so im trying to generate Views on a personal page for some hours now. Im not getting why it isnt working. So my current code: (Yes im using the spigot API but that does not matter now).
#Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if(args.length == 2){
String link = args[0];
String views = args[1];
int view = 0;
try{
view = Integer.parseInt(views);
}catch(Exception ex){
ex.printStackTrace();
cs.sendMessage("" + views + " is not a number.");
}
execute(link, view);
}else{
System.out.println("More arguments");
}
return true;
}
private int o = 1;
private void execute(String link, int views){
new BukkitRunnable() {
int i = views;
#Override
public void run() {
i--;
try{
String fullProxy = Viewbot.getInstance().getProxys().get(i);
String proxy, port;
String[] fullProx;
fullProx = fullProxy.split(":");
proxy = fullProx[0];
port = fullProx[1];
/* Proxy proxyCon = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, Integer.parseInt(port)));
HttpURLConnection connection =(HttpURLConnection)new URL(link).openConnection(proxyCon);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "text/xml");
connection.setRequestProperty("Accept", "text/xml, application/xml");
connection.setRequestMethod("POST");
*/
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
systemProperties.setProperty("https.proxyHost",proxy);
systemProperties.setProperty("https.proxyPort",port);
URL server = new URL(link);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setUseCaches(false);
connection.connect();
System.out.println("Respone: "+ connection.getResponseMessage());
System.out.println("View #" + o + " gesendet!");
o++;
connection.disconnect();
System.out.println("Proxy: " + proxy + " Port: " + port);
System.out.println("System using: " + systemProperties.getProperty("http.proxyHost") + ":" + systemProperties.getProperty("http.proxyPort"));
System.out.println("Proxy: " + connection.usingProxy());
}catch(Exception ex){
Properties systemProperties = System.getProperties();
ex.printStackTrace();
Viewbot.getInstance().failProxys.add(systemProperties.getProperty("http.proxyHost") + ":" + systemProperties.getProperty("http.proxyPort"));
}
if(i == 5){
for(int i = 0; i < Viewbot.getInstance().failProxys.size(); i++){
String failed = Viewbot.getInstance().failProxys.get(i);
Viewbot.getInstance().getProxys().remove(failed);
}
Path file = Paths.get(Viewbot.getInstance().getDataFolder() + "/HTTPS.txt");
try {
Files.write(file, Viewbot.getInstance().getProxys(), Charset.forName("UTF-8"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File saved");
}
if(i == 0){
cancel();
}
}
}.runTaskTimerAsynchronously(Viewbot.getInstance(), 0, 2);
}
A sample output of that whole thing:
[00:34:45 INFO]: Response: OK
[00:34:45 INFO]: View #430 sent!
[00:34:45 INFO]: Proxy: 41.76.44.76 Port: 3128
[00:34:45 INFO]: System using: 45.63.16.86:8080
[00:34:45 INFO]: Proxy: false
The output now is:
[00:57:58 INFO]: Proxy: 36.80.34.225 Port: 3128
[00:57:58 INFO]: System using: 113.18.193.26:8000
[00:57:58 INFO]: Proxy: true
[00:57:58 INFO]: Respone: OK
But when you look here: http://84.200.122.107/ It does not add views..
So its using a different IP Address to connect. Whats the error than?
It also shows that it isn't using a proxy, which should be wrong..
Thanks for any help.
I think you iterate over the list of proxy, each call to BukkitRunnable will take a new one.
So if call to BukkitRunnable in different threads overlap, one set the value and the other reads it.
To use one proxy per connection you should use common http client that is able to do it :
Common HTTPclient and proxy
Related
I am currently trying to connect to an amazon RDS from a lambda function. The problem I am facing is that I do not get an error but neither I manage to get a connection, so I am not sure how to proceed. I do not have a timeout, or an error with the parameters, but the object "con" is always null.
To do this I am doing the following:
Connection con = null;
String jdbcUrl2 = "jdbc:mysql://" + "connectionValueExample-zone.rds.amazonaws.com" + ":" + "3306" + "/" + "botdb" + "?user=" + "bot" + "&password=" + "PWvalueExample";
con = DriverManager.getConnection(jdbcUrl2);
After every step I check with prints() how it's going. After I try to stablish the connection I try to catch it, because while I am not getting exceptions right now, the object con never stops being null, so I do not stablish a connection.
catch (SQLException e) {
e.toString();
log.warn(e.toString());
} catch (Exception e) {
System.out.println("excepcion no capturada ");
e.toString();
}
The second catch is just in case I was missing something, originally it was not there.
All in all, the code looks something like:
#Override
public String handleRequest(Object input, Context context) {
context.getLogger().log("Input: " + input);
Connection con = null;
try {
String jdbcUrl2 = "jdbc:mysql://" + "value-zone.rds.amazonaws.com" + ":" + "3306" + "/" + "botdb" + "?user=" + "bot" + "&password=" + "PW";
con = DriverManager.getConnection(jdbcUrl2);
} catch (SQLException e) {
e.toString();
log.warn(e.toString());
} catch (Exception e) {
System.out.println("excepcion no capturada ");
e.toString();
}
String status = null;
if (con != null) {
status = "conexion establecida";
System.out.println("connection stablished");
} else status = "connection failed";
return status;
}
Edit:
I am now capturing slightly better the exceptions and get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
At this point I am unsure if the Strin jdbcURL is not properly formed OR why is the connection failing.
I am scheduling tasks on servers but I have no idea how to know if any server is currently doing the task. I am looping over servers like this:
for(int i = 0; i < tasksList.size(); i++){
for(URL url : serverURLsList){
if(InetAddress.getByName(url.toString()).isReachable(0)){ //this gives me exception
HttpURLConnection availableServer = (HttpURLConnection) url.openConnection();
availableServer.setDoOutput(true);
ObjectOutputStream oos = new ObjectOutputStream(availableServer.getOutputStream());
oos.writeObject(tasksList.get(i));
oos.close();
tasksList.remove(i);
break;
}
}
}
This is my server for task handling:
public class Serv{
public static void main(String[] args) throws IOException {
int port = 8080;
String host = "192.168.1.116";
System.out.println("Server 1 is up. Host: " + host + " port: " + port);
HttpServer s= HttpServer.create(new InetSocketAddress(host, port), 0);
s.createContext("/", new RootHandler());
s.setExecutor(null);
s.start();
}
}
class RootHandler implements HttpHandler{
private static int clientCounter = 1;
#Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("\nRoot handler; \n\tclient no. " + clientCounter++);
Task t;
ObjectInputStream ois = new ObjectInputStream(exchange.getRequestBody());
try {
System.out.println("Recieved object:");
t = (Task) ois.readObject();
ois.close();
System.out.println("Array not sorted:");
int[] arr = (int[]) t.getData();
for (int anArr : arr) {
System.out.print(anArr + " ");
}
TaskSolver.solve(t); // need to check if this is runned on the server or server is doing nothing
System.out.println("\nArray sorted!");
for (int anArr : (int[])t.getData()) {
System.out.print(anArr + " ");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String response = "<h1>Server up!</h1>";
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
What I really want to achieve is have the information if any server in the list is currently solving the task (the comment in the snippet above shows that place). No idea why getting the exception mentioned in the title because I can reach the server from the web browser. I suppose the method isReachable() is not good for that purpose (because it should tell if the host given is up or not while I want to know if the proper method on the server is currently running). Does somebody know a good solution to do so?
#Edit
According to the comment I need to say that each of my servers (I will have plenty of them) should be doing only one task, that is the purpose of my simulation.
InetAddress.getByName(url.toString()).isReachable(0)){ //this gives me exception
Of course it does. The argument to InetAddress.getByName() is not a URL. Check the Javadoc. It is a hostname.
I need to load webpage after basic auth, but the sessionid in my code is not concatenated to url (I get this 10-08 10:17:27.424 20143-20143/com.example.marco.bella D/WebView: loadUrl=https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid=
)...i don't know why...i show you my code!
variable cookie get the correct sessionID.
Thanks in advance!
URL url = null;
try {
url = new URL("https://unimol.esse3.cineca.it/auth/Logon.do");
} catch (MalformedURLException e) {
}
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
httpRequest.setRequestMethod("GET");
} catch (ProtocolException e) {
}
String cookie = "";
httpRequest.setDoInput(true);
String authString = "user" + ":" + "pass";
byte[] authEncBytes = android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
httpRequest.addRequestProperty("Authorization", "Basic " + authStringEnc);
System.out.println("auth:" + "" + authStringEnc);
DefaultHttpClient httpclient = new DefaultHttpClient();
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie=cookies.get(i).toString();
}
}
webView.loadUrl("https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid="+cookie);
(I get this 10-08 10:17:27.424 20143-20143/com.example.marco.bella
D/WebView:
loadUrl=https://unimol.esse3.cineca.it/auth/Logon.do;jsessionid= )...i
don't know why
The problem I can think of by looking only the portion you have posted here is that you are Overriding cookie variable inside your for loop and there is a high possibility on any iteration of cookies, one or more than 1 cookie exist whose value is blank.
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
cookie=cookies.get(i).toString(); // This line is the culprit
}
You should check if the value of the cookie is null or empty.
Replace the culprit line with below line
I am using a utility of Strings class (isNullOrEmpty) of Guava library to check if value is null or empty, you can use your own implementation for this,
if(Strings.isNullOrEmpty(cookies.get(i).toString())) {
continue;
} else {
cookie=cookies.get(i).toString();
}
Now if during iteration you get id which you confirmed that you are getting in console statement then it will definitely get loaded up.
I have the following java code to create a connection to a SMTP server to send an email. If "distList#mydomain.com" is a single receiver, it works. However, if it is a distribution list, like I would like it to be, it does not.
public static void main(String[] args){
SendEmail send = new SendEmail();
send.sendEmail();
}
private void sendEmail(){
try {
smtpSocket = new Socket(host, port);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
if(smtpSocket != null && os != null && is != null)
{
try
{ os.writeBytes("HELO\r\n");
os.writeBytes("MAIL From: <mySender#mydomain.com>\r\n");
os.writeBytes("RCPT To: <distList#mydomain.com>\r\n");
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("DATE: " + dFormat.format(dDate) + "\r\n");
os.writeBytes("From: Me <mySender#mydomain.com>\r\n");
os.writeBytes("To: You <distList#mydomain.com>\r\n");
String sMessage = "This is the body of the message.";
os.writeBytes("Subject: Your subjectline here\r\n\r\n");
os.writeBytes(sMessage + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
String responseline;
while((responseline = is.readLine())!=null)
{
System.out.println(responseline);
if(responseline.indexOf("Ok") != -1)
break;
}
}
catch(Exception e)
{ System.out.println("Cannot send email as an error occurred."); }
}
}
catch(Exception e)
{ System.out.println("Host " + m_sHostName + " unknown"); }
}
}
The response from the server is the same regardless of if its a single recipient or the desired distribution list:
220 host Microsoft ESMTP MAIL Service ready at currentTimestamp
250 host Hello [myIP]
250 2.1.0 Sender OK
250 2.1.5 Recipient OK
354 Please start mail input.
250 Mail queued for delivery.
221 Closing connection. Good bye.
Does anyone know why I can successfully send to a single person, but not a distribution list?
I'm busy writing a Program that Transmits GPS Coordinates to a Server from a mobile phone where the coordinates are then used for calculations. But I'm constantly hitting a wall with blackberry. I have built the Android App and it works great but can't seem to contact the server on a real blackberry device. I have tested the application in a simulator and it works perfectly but when I install it on a real phone I get no request the phone.
I have read quite a bit about the secret strings to append at the end of the url so I adapted some demo code to get me the first available transport but still nothing ...
The Application is Signed and I normally then either install it by debugging through eclipse or directly on the device from the .jad file and allow the application the required permissions.
The current code was adapted from the HTTP Connection Demo in the Blackberry SDK.
Could you have a look and give me some direction. I'm losing too much hair here ...
The Backend Service that keeps running:
public void run() {
System.out.println("Starting Loop");
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
cr.setPreferredResponseTime(1000);
LocationProvider lp = null;
try {
lp = LocationProvider.getInstance(cr);
} catch (LocationException e) {
System.out.println("*****************Exception" + e);
}
if (lp == null) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS not supported!");
return;
}
});
} else {
System.out
.println(lp.getState() + "-" + LocationProvider.AVAILABLE);
switch (lp.getState()) {
case LocationProvider.AVAILABLE:
// System.out.println("Provider is AVAILABLE");
while (true) {
Location l = null;
int timeout = 120;
try {
l = lp.getLocation(timeout);
final Location fi = l;
System.out.println("Got a Coordinate "
+ l.getQualifiedCoordinates().getLatitude()
+ ", "
+ l.getQualifiedCoordinates().getLongitude());
System.out.println("http://" + Constants.website_base
+ "/apis/location?device_uid=" + Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates().getLongitude());
if (!_connectionThread.isStarted()) {
fetchPage("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
} else {
createNewFetch("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
}
Thread.sleep(1000 * 60);
} catch (LocationException e) {
System.out.println("Location timeout");
} catch (InterruptedException e) {
System.out.println("InterruptedException"
+ e.getMessage());
} catch (Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
}
My Connection is Made with:
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc = connFact.getConnection(getUrl());
// Open the connection and extract the data.
try {
// StreamConnection s = null;
// s = (StreamConnection) Connector.open(getUrl());
HttpConnection httpConn = (HttpConnection) connDesc.getConnection();
/* Data is Read here with a Input Stream */
Any Ideas ?
Figured it out!
Using a function I found online to determine which ; extension to use when connecting by using numerous Try / Catch. Then had to set the Internet APN settings. I'm in South-Africa using Vodacom so the APN is "Internet" with no Password.
Barely have hair left ....