Exemple #1
0
  // function to do the join use case
  public static void share() throws Exception {
    HttpPost method = new HttpPost(url + "/share");
    String ipAddress = null;

    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) en.nextElement();
      if (ni.getName().equals("eth0")) {
        Enumeration<InetAddress> en2 = ni.getInetAddresses();
        while (en2.hasMoreElements()) {
          InetAddress ip = (InetAddress) en2.nextElement();
          if (ip instanceof Inet4Address) {
            ipAddress = ip.getHostAddress();
            break;
          }
        }
        break;
      }
    }

    method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8"));
    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    // get present time
    date = new Date();
    long start = date.getTime();

    // Execute the vishwa share process
    Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp);

    String ch = "alive";
    System.out.println("Type kill to unjoin from the grid");

    while (!ch.equals("kill")) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      ch = in.readLine();
    }

    p.destroy();

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/shareAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
Exemple #2
0
  // function to do the compute use case
  public static void compute() throws Exception {
    HttpPost method = new HttpPost(url + "/compute");

    method.setEntity(new StringEntity(username, "UTF-8"));

    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    System.out.println("Give the file name which has to be put in the grid for computation");

    // input of the file name to be computed
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String name = in.readLine();

    // get the absolute path of the current working directory
    File directory = new File(".");
    String pwd = directory.getAbsolutePath();

    // get present time
    date = new Date();
    long start = date.getTime();

    String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp;
    System.out.println(cmd);

    // Execute the vishwa compute process
    Process p = Runtime.getRuntime().exec(cmd);

    // wait till the compute process is completed
    // check for the status code (0 for successful termination)
    int status = p.waitFor();

    if (status == 0) {
      System.out.println("Compute operation successful. Check the directory for results");
    }

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/computeAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
 public String readTwitterFeed() {
   StringBuilder builder = new StringBuilder();
   HttpClient client = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet("http:'//twitter.com/users/show/vogella.json");
   try {
     HttpResponse response = client.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content));
       String line;
       while ((line = reader.readline()) != null) {
         builder.append(line);
       }
     } else {
       Log.e(MainActivity2.class.toString(), "Failed to download file");
     }
   } catch (ClientProtocolExpcetion e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return builder.toString();
 }
 /**
  * this is the primary method that sends a query to the CIPRes REST service. It expects to receive
  * an XML file, which it returns in Document if the root tag matc hes xmlRootTag
  */
 public Document cipresQuery(HttpClient httpclient, String URL, String xmlRootTag) {
   if (StringUtil.blank(URL)) return null;
   try {
     HttpGet httpget = new HttpGet(URL);
     httpget.addHeader("cipres-appkey", CIPRESkey);
     try {
       HttpResponse response = httpclient.execute(httpget);
       HttpEntity responseEntity = response.getEntity();
       InputStream instream = responseEntity.getContent();
       BufferedReader br = new BufferedReader(new InputStreamReader(instream));
       String line = "";
       StringBuffer sb = new StringBuffer();
       while ((line = br.readLine()) != null) {
         sb.append(line + StringUtil.lineEnding());
       }
       Document cipresResponseDoc = loadXMLFile(xmlRootTag, sb.toString());
       if (cipresResponseDoc != null && verbose) {
         ownerModule.logln(sb.toString());
       }
       if (cipresResponseDoc == null) {
         Document errorDoc = loadXMLFile(sb.toString());
         if (errorDoc != null) reportError(errorDoc, "Error in communicating with CIPRes", true);
       }
       EntityUtils.consume(response.getEntity());
       return cipresResponseDoc;
     } catch (IOException e) {
       Debugg.printStackTrace(e);
     } catch (Exception e) {
       Debugg.printStackTrace(e);
     }
   } catch (Exception e) {
     Debugg.printStackTrace(e);
   }
   return null;
 }
 /*.................................................................................................................*/
 public void deleteJob(HttpClient httpclient, String URL) {
   HttpDelete httpdelete = new HttpDelete(URL);
   httpdelete.addHeader("cipres-appkey", CIPRESkey);
   try {
     HttpResponse response = httpclient.execute(httpdelete);
   } catch (IOException e) {
     Debugg.printStackTrace(e);
   }
 }
Exemple #6
0
 public String getData(String url) {
   HttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   String response = "";
   try {
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
     response = client.execute(get, responseHandler);
   } catch (Exception e) {
     debug(e.toString());
   }
   return response;
 }
 public Result<InputStream> getInputStream(String endpoint) throws IOException {
   HttpClient cli = createClient();
   HttpGet get = createGet(endpoint);
   HttpResponse res = cli.execute(get);
   Object result = null;
   if (res.getStatusLine().getStatusCode() == 200) result = res.getEntity().getContent();
   else {
     RestResponse resp = new RestResponse(res);
     result = unmarshalPOJO(resp, InputStream.class);
     cli.getConnectionManager().shutdown();
   }
   return new Result<InputStream>(result);
 }
    @Override
    protected Void doInBackground(String... params) {
      // TODO Auto-generated method stub

      InputStream is = null;

      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("username", _username.getText().toString()));
      nameValuePairs.add(new BasicNameValuePair("password", _password.getText().toString()));

      // http post
      try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httppost = new HttpPost("http://trainingbuddy.comuv.com/login.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        conSuccess = true;

      } catch (Exception e) {
        e.printStackTrace();
        this.progressDialog.dismiss();
      }

      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = "";

        while ((line = br.readLine()) != null) {
          sb.append(line + "\n");
        }
        is.close();
        result = sb.toString().substring(0, 1);
        userDetails = sb.toString().substring(1);

      } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
      }

      return null;
    }
Exemple #9
0
 private String getJsonResponse(String jsonUrl) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method CIManagerImpl.getJsonResponse(String jsonUrl)");
     S_LOGGER.debug("getJsonResponse() JSonUrl = " + jsonUrl);
   }
   try {
     HttpClient httpClient = new DefaultHttpClient();
     HttpGet httpget = new HttpGet(jsonUrl);
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
     return httpClient.execute(httpget, responseHandler);
   } catch (IOException e) {
     throw new PhrescoException(e);
   }
 }
Exemple #10
0
  // function to check login
  public static boolean login(String pass) throws Exception {
    HttpPost method = new HttpPost(url + "/login");

    method.setEntity(new StringEntity(username + ';' + pass, "UTF-8"));

    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    return connIp.equals("true");
  }
 /*.................................................................................................................*/
 public void cipresDownload(HttpClient httpclient, String URL, String filePath) {
   HttpGet httpget = new HttpGet(URL);
   httpget.addHeader("cipres-appkey", CIPRESkey);
   try {
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity responseEntity = response.getEntity();
     BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
     int inByte;
     while ((inByte = bis.read()) != -1) bos.write(inByte);
     bis.close();
     bos.close();
     EntityUtils.consume(response.getEntity());
   } catch (IOException e) {
     Debugg.printStackTrace(e);
   }
 }
Exemple #12
0
  public String getRequest(String url, String queryString) {
    String responseText = "";

    try {
      httpGet.setURI(new URI(url + "?" + queryString));
      httpGet.addHeader("Accept", "application/json");

      HttpResponse response = httpClient.execute(httpGet);
      responseText = EntityUtils.toString(response.getEntity());

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } catch (URISyntaxException e1) {
    }

    return responseText;
  }
  /** The core method that initiates a job on CIPRes. */
  public boolean postJob(
      HttpClient httpclient, MultipartEntityBuilder builder, MesquiteString jobURL) {
    if (builder == null) return false;
    String URL = baseURL + "/job/" + username;
    HttpPost httppost = new HttpPost(URL);
    httppost.addHeader("cipres-appkey", CIPRESkey);

    // some of this from
    // http://stackoverflow.com/questions/18964288/upload-a-file-through-an-http-form-via-multipartentitybuilder-with-a-progress
    HttpEntity cipresEntity = builder.build();

    httppost.setEntity(cipresEntity);

    try {
      HttpResponse response = httpclient.execute(httppost);

      HttpEntity responseEntity = response.getEntity();
      InputStream instream = responseEntity.getContent();
      BufferedReader br = new BufferedReader(new InputStreamReader(instream));
      StringBuffer sb = new StringBuffer();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line + StringUtil.lineEnding());
      }

      Document cipresResponseDoc = loadXMLFile("jobstatus", sb.toString()); // let's see how it went
      boolean success = false;
      if (cipresResponseDoc != null) {
        processJobSubmissionResponse(cipresResponseDoc, jobURL);
        if (verbose) ownerModule.logln(sb.toString());
        if (jobURL != null) success = StringUtil.notEmpty(jobURL.getValue());
        else success = true;
      } else {
        cipresResponseDoc = loadXMLFile(sb.toString());
        reportError(cipresResponseDoc, "Error with CIPRes run", false);
      }
      EntityUtils.consume(response.getEntity());
      return success;
    } catch (IOException e) {
      Debugg.printStackTrace(e);
    }
    return false;
  }
Exemple #14
0
  public String postRequest(String url, List<NameValuePair> entity) {
    String responseText = "";

    try {
      httpPost.setURI(new URI(url));
      httpPost.addHeader("Accept", "application/json");
      httpPost.setEntity(new UrlEncodedFormEntity(entity));

      HttpResponse response = httpClient.execute(httpPost);
      responseText = EntityUtils.toString(response.getEntity());

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } catch (URISyntaxException e1) {
    }

    return responseText;
  }
  public static String apiRequest(Request request, String... paramValues) {
    if (httpClient == null) {
      httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }
    RequestBuilder reqBuilder;
    HttpUriRequest get, post;
    switch (request.type) {
      case GET:
        reqBuilder = RequestBuilder.get("http://naturesnap.net/" + request.getEndpoint());
        for (int i = 0; i < request.getParams().length; i++) {
          reqBuilder.addParameter(request.getParams()[i], paramValues[i]);
        }
        get = reqBuilder.build();
        try {
          CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(get);
          HttpEntity entity = response.getEntity();
          String content = IOUtils.toString(entity.getContent(), "UTF-8");
          response.close();
          return content;
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        break;
      case POST:
        reqBuilder = RequestBuilder.post().setUri("http://naturesnap.net/" + request.getEndpoint());
        for (int i = 0; i < request.getParams().length; i++) {
          reqBuilder.addParameter(request.getParams()[i], paramValues[i]);
        }
        post = reqBuilder.build();
        try {
          CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(post);
          HttpEntity entity = response.getEntity();
          String content = IOUtils.toString(entity.getContent(), "UTF-8");
          response.close();
          return content;
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        break;
      case FILE:
        HttpPost postFile = new HttpPost("http://naturesnap.net/" + request.getEndpoint());
        File file = new File(request.getParams()[0]);
        FileBody fileBody = new FileBody(file);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("filename", fileBody);
        builder.addTextBody("uploadForm", "Upload");
        builder.addTextBody("latitude", request.getParams()[1]);
        builder.addTextBody("longitude", request.getParams()[2]);
        builder.addTextBody("groupName", "");
        builder.addTextBody("description", "");
        HttpEntity entity = builder.build();
        postFile.setEntity(entity);
        try {
          HttpResponse response = httpClient.execute(postFile);
          return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } catch (Exception e) {

        }
        break;
      default:
        // Error
        break;
    }

    return "";
  }