localhost take directory or path after / - url

As I am running the code in localhost mode and I have localhost:8080/url/hello. Is the value after / is the directory or the path Because I am getting the result as HTTP STATUS 404.
public void onValueChange(ValueChangeEvent<String> event)
{
String a=Window.Location.getHref();
Window.alert(a);
if(Window.Location.getHash().equals("") || Window.Location.getHash().equals(null) || Window.Location.getHash()== null)
{
String SUBURL=a.substring(a.lastIndexOf("/")+1;
String a1=SUBURL;
Window.alert("LINK :: "+a1);
if(!a1.isEmpty())
{
greetingService.shrturl(a1,new AsyncCallback<String>()
{
#Override
public void onFailure(Throwable caught)
{
Window.alert("fail");
}
#Override
public void onSuccess(String h)
{
System.out.print("return value :: "+h);
if(h.equals(null))
{
Window.Location.replace("ERROR:PAGE NOT FOUND");
}
else
{
Window.Location.replace(h);
}
}
});
}
else
{
new shorturl();
}
}

Localhost: is telling the server to loop back on itself, so instead of sending a HTTP request to a forgien server to send it to a local server,
8080:, refers to the port number,
/url/hello/ refers to the directory structure within the local server
so yes if you are migrating your code from local to live then
http://localhost:8080/url/hello
will become
http://www.mywebsite.ie/url/hello

Related

how to resolver 502 - Web server received an invalid response while acting as a gateway or proxy server

I am getting the following error after publsishing my web application.
502 - Web server received an invalid response while acting as a gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.
Before the project was working fine on live one but when I have published this version of the project I am getting this error in uploading the image. Project is also working fine on local server.
Uploading image is also working fine when i first time upload the image but after i want to edit the image i am getting this error.I have done the follwong code for uploading the image
if (picture?.Length > 0)
{
var fileName = Common.GetUniqueName(picture.FileName, _env);
Common.FileResponse response = Common.SaveImageFile(picture, _env, fileName);
if (response.Equals(Common.FileResponse.Ok))
{
article.Picture = fileName;
if (article.Id>0)
{
var oldFileName = _context.userCvs.Where(x => x.Id == article.Id).Select(x => x.Picture).FirstOrDefault();
if (!string.IsNullOrEmpty(oldFileName))
{
Common.RemoveUploadedFiles(oldFileName, _env);
}
}
}
else
{
ModelState.AddModelError("Picture", response.ToString());
}
}
The following function for saving uploaded file
public static FileResponse SaveUploadedFile(Microsoft.AspNetCore.Http.IFormFile file, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, string uploadedFileName = "", bool isCvs = false, bool isContent = false, bool IsProfile=false)
{
if (file == null || file.Length <= 0) return FileResponse.Nothing;
// limit 5mb file size 5242880
if (file.Length > 124288000) return FileResponse.ExceedFileSize;
if (!IsAllowedExt(Path.GetExtension(file.FileName)))
{
return FileResponse.ExtNotAllowed;
}
var fileName = uploadedFileName == "" ? file.FileName : uploadedFileName;
var directory = Path.Combine( env.WebRootPath, isCvs ? UploadCvsDirectory : isContent? UploadContentDirectory :IsProfile ? UploadprofileDirectory: UploadDirectory);
if (File.Exists(Path.Combine(directory, fileName)))
{
return FileResponse.FileExists;
}
using (var fileStream = new FileStream(Path.Combine(directory, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
return FileResponse.Ok;
}
THe following function for removing upload file
public static void RemoveUploadedFiles(string fileName, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, bool isCvs = false, bool isContent = false)
if (fileName == null) return;
try
{
var directory = Path.Combine(env.WebRootPath, isCvs ? UploadCvsDirectory : isContent ? UploadContentDirectory : UploadDirectory);
if (File.Exists(Path.Combine(directory, fileName)))
{
File.Delete(Path.Combine(directory, fileName));
}
}
catch (Exception)
{
}
}

How use weboptimizer to with multiple virtual directories and single wwwroot

ASP.NET 5 MVC Core application serves multiple sites using LigerShark WebOptimizer ( https://github.com/ligershark/WebOptimizer )
https://example.com/store1
https://example.com/store2
https://example2.com
All those sites should served from wwwroot directory containing same files for those urls.
Sites are defined in hosts.json file:
{
"EevaHosts": {
"example.com/store1": {}
"example.com/store2": {}
"example2.com": {}
}
}
I tried code below to force WebOptimizer to use same wwwwroot directory for every site in Debian Linux but got exception for https://example.com/store1/site.js
No files found matching "/store1/js/site.js" exist in
"/var/www/appbasedir/wwwroot/"
How to force web optimizer to use same wwwwroot directory for all sites ?
If Weboptimizer middleware is removed, static files are serverd properly.
In StartUp.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ ...
var eevakonf = new ConfigurationBuilder().AddJsonFile("hosts.json").Build();
foreach (var host1 in eevakonf.GetSection("EevaHosts").GetChildren())
{
if (!host1.Key.Contains("/"))
app.UseWebOptimizer();
else
app.UseWebOptimizer(env, new FileProviderOptions[] { new FileProviderOptions()
{
// example.com/store1 -> /store1
RequestPath = new PathString(RequestPathExtract(host1)),
FileProvider = env.WebRootFileProvider
}
});
}
// Using single call causes the same exception:
//HashSet<FileProviderOptions> fp = new();
//foreach (var host1 in eevakonf.GetSection("EevaHosts").GetChildren())
//{
// if (host1.Key.Contains("/"))
// fp.Add(new FileProviderOptions() {
// RequestPath = new PathString(RequestPathExtract(host1)) ,
// FileProvider = env.WebRootFileProvider
// });
//}
//app.UseWebOptimizer(env, fp.ToArray());
foreach (var host in eevakonf.GetSection("EevaHosts").GetChildren())
{
if (!host.Key.Contains("/"))
app.UseStaticFiles();
else
{
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = new PathString(RequestPathExtract(host))
});
}
}
}
static string RequestPathExtract(IConfigurationSection host)
{
return "/" + StrExtract(host.Key, "/");
}
static string StrExtract(string cSearchExpression, string cBeginDelim)
{
int nbpos = At(cBeginDelim, cSearchExpression);
return cSearchExpression[(nbpos + cBeginDelim.Length - 1)..];
}

401:Authentication credentials were invalid - Invalid or expired token. code - 89

This is the code and I am recieving the error 401: Authentication Error
public class Server {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public void tweet() throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDaemonEnabled(true).setOAuthConsumerKey("......")
.setOAuthConsumerSecret("......")
.setOAuthAccessToken("......")
.setOAuthAccessTokenSecret(".....");
TwitterFactory tf = new TwitterFactory();
twitter4j.Twitter twitter = tf.getInstance();
List status = twitter.getHomeTimeline();
for (Status st : status) {
System.out.println(st.getUser().getName() + "---- Tweets----" + st.getText());
}
}
// constructor with port
public Server(int port) throws TwitterException {
// starts server and waits for a connection
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
if (line.equalsIgnoreCase("Data")) {
tweet();
}
} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) throws TwitterException {
Server server = new Server(5000);
}
}
Please make sure that the tokens are valid.
Then, you could try enabling system proxies like so:
System.setProperty("java.net.useSystemProxies", "true");

calling a webservice from scheduled task agent class in windows phone 7.1

Can we call a webservice from the scheduled periodic task class firstly, if yes,
Am trying to call a webservice method with parameters in scheduled periodic task agent class in windows phone 7.1. am getting a null reference exception while calling the method though am passing the expected values to the parameters for the webmethod.
am retrieving the id from the isolated storage.
the following is my code.
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
string Name = IName;
string Desc = IDesc;
updateinfo(Name, Desc);
}
}
public void updateinfo(string name, string desc)
{
AppSettings tmpSettings = Tr.AppSettings.Load();
id = tmpSettings.myString;
if (name == "" && desc == "")
{
name = "No Data";
desc = "No Data";
}
tservice.UpdateLogAsync(id, name,desc);
tservice.UpdateLogCompleted += new EventHandler<STservice.UpdateLogCompletedEventArgs>(t_UpdateLogCompleted);
}
Someone please help me resolve the above issue.
I've done this before without a problem. The one thing you need to make sure of is that you wait until your async read processes have completed before you call NotifyComplete();.
Here's an example from one of my apps. I had to remove much of the logic, but it should show you how the flow goes. This uses a slightly modified version of WebClient where I added a Timeout, but the principles are the same with the service that you're calling... Don't call NotifyComplete() until the end of t_UpdateLogCompleted
Here's the example code:
private void UpdateTiles(ShellTile appTile)
{
try
{
var wc = new WebClientWithTimeout(new Uri("URI Removed")) { Timeout = TimeSpan.FromSeconds(30) };
wc.DownloadAsyncCompleted += (src, e) =>
{
try
{
//process response
}
catch (Exception ex)
{
// Handle exception
}
finally
{
FinishUp();
}
};
wc.StartReadRequestAsync();
}
private void FinishUp()
{
#if DEBUG
try
{
ScheduledActionService.LaunchForTest(_taskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("relaunching in 30 seconds");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
NotifyComplete();
}

how to check internet connection in java in blackberry

I want to check whether internet connection is there or not in blackberry device so that depending on the result I can call webservices to get data or upload data from my application
I have tried this one
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS))) ||
(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) != false
If you want to check the internet connection, then send any url to the web service and check the HTTP Response. If HTTPResponse is 200 then only you are having internet connection. Do like this.......
try
{
factory = new HttpConnectionFactory();
url="Here put any sample url or any of your web service to check network connection.";
httpConnection = factory.getHttpConnection(url);
response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
callback(response);
}else
{
callback(response);
}
} catch (Exception e)
{
System.out.println(e.getMessage());
callback(0);
}
Here "response"=200 then you have an internet connection. otherwise it is a connection problem. You can check this like below...........
public void callback(int i)
{
if(i==200)
{
//You can do what ever you want.
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
int k=Dialog.ask(Dialog.D_OK,"Connection error,please check your network connection..");
if(k==Dialog.D_OK)
{
System.exit(0);
}
}
});
}
}
Here System.exit(0); exit the application where ever you are.
Take these two classes
1)HttpConnectionFactory.java
2)HttpConnectionFactoryException.java
from this link:HttpConnection Classes

Resources