Exemplo n.º 1
0
  // TODO:  Make this more decoupled and unit testable
  public static void resolveHerdDependency(Long id, String name, String version)
      throws IOException {
    models.Upload upload = getUpload(id);

    HerdDependency hd = getHerdDependency(upload, name, version);
    // check that we didn't already resolve it from Herd
    if (hd != null) {
      Validation.addError(null, "Module already resolved from Herd");
      prepareForErrorRedirect();
      view(id);
    }

    String url = "http://modules.ceylon-lang.org/modules/" + name + "/" + version;

    Logger.info("Looking up module in Herd at: %s", url);
    HttpResponse response = WS.url(url).head();
    if (response.getStatus() == HttpURLConnection.HTTP_OK) {
      hd = new HerdDependency(name, version, upload);
      hd.create();
      flash("message", "Found in Herd");
    } else if (response.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
      flash("message", "Module could not be found in Herd");
    } else {
      flash(
          "message",
          "Module could not be found in Herd: "
              + response.getStatus()
              + ": "
              + response.getString());
    }

    view(id);
  }
Exemplo n.º 2
0
  public static void resolveMavenDependency(Long id, String name, String version)
      throws IOException {
    models.Upload upload = getUpload(id);

    MavenDependency md = getMavenDependency(upload, name, version);
    // check that we didn't already resolve it from Maven
    if (md != null) {
      Validation.addError(null, "Module already resolved from Maven");
      prepareForErrorRedirect();
      view(id);
    }

    // check if the module in question is really in maven
    // ex: http://repo1.maven.org/maven2/io/vertx/vertx-core/2.0.0-beta5/vertx-core-2.0.0-beta5.jar
    int idSep = name.lastIndexOf(':');
    if (idSep == -1) idSep = name.lastIndexOf('.');
    if (idSep == -1) {
      Validation.addError(
          null,
          "Module name does not contain any ':' or '.' (used to separate the artifact group and ID)");
      prepareForErrorRedirect();
      view(id);
    }
    String mavenUrl = Play.configuration.getProperty("maven.url", "http://repo1.maven.org/maven2");
    String groupId = name.substring(0, idSep);
    String groupIdPath = groupId.replace('.', '/');
    String artifactId = name.substring(idSep + 1);
    String url =
        mavenUrl
            + "/"
            + groupIdPath
            + "/"
            + artifactId
            + "/"
            + version
            + "/"
            + artifactId
            + "-"
            + version
            + ".jar";

    Logger.info("Looking up module in Maven Central at: %s", url);
    HttpResponse response = WS.url(url).head();
    if (response.getStatus() == HttpURLConnection.HTTP_OK) {
      md = new MavenDependency(name, version, upload);
      md.create();
      flash("message", "Found in Maven central");
    } else if (response.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
      flash("message", "Module could not be found in Maven central");
    } else {
      flash(
          "message",
          "Module could not be found in Maven central: "
              + response.getStatus()
              + ": "
              + response.getString());
    }

    view(id);
  }
Exemplo n.º 3
0
  public final void doProcess(String queryBody) {

    ArrayList<WaveSegmentArray> arrayOfResponses = new ArrayList<WaveSegmentArray>();
    QueryRequest queryRequest = gson.fromJson(queryBody, QueryRequest.class);

    String usertype = session.get(Const.USERTYPE);
    String secretkey = null;
    String vpdsURL = null;
    HttpResponse responseFromServer = null;

    if (usertype.equals(Const.USER)) {

      /* Get accesskey from Broker */

      // From Json - vpdsname and secretkey
      String usersecretkey = new SecretKey().getSecretKeyFromHashMap(session.get(Const.USERNAME));
      String jsonGetAccessKey =
          "{\"secretkey\" : \""
              + usersecretkey
              + "\",\"vpdsname\": \""
              + queryRequest.vpdsname
              + "\"}";
      logger.info(Const.API_QUERYDATA, "For " + usertype + " " + jsonGetAccessKey);

      // Make request
      responseFromServer =
          new SendHTTPRequest()
              .sendPostRequest(
                  Const.URL_BROKER_GET_ACCESS_KEY,
                  Const.MIME_TYPE_JSON,
                  Const.API_QUERYDATA,
                  jsonGetAccessKey);
      System.out.println("Get access key " + responseFromServer.getString());
      GetAccessKeyResponseFormat response =
          gson.fromJson(responseFromServer.getString(), GetAccessKeyResponseFormat.class);

      // Set secretkey as accesskey
      secretkey = userkey = response.accesskey;
      vpdsURL = response.vpdsurl;
    } else if (usertype.equals(Const.OWNER)) {
      // Set secretkey as owner key
      secretkey = userkey = Global.VPDS_OWNER_KEY;
    }

    int numberOfDevicesRequest = queryRequest.devicesArray.size();

    for (int i = 0; i < numberOfDevicesRequest; i++) {

      String devicename = queryRequest.devicesArray.get(i).device;
      int numberOfSensorsInDevice = queryRequest.devicesArray.get(i).sensorsArray.size();
      for (int j = 0; j < numberOfSensorsInDevice; j++) {
        QueryToRepo queryToRepo =
            new QueryToRepo(
                queryRequest.conditions,
                devicename,
                queryRequest.devicesArray.get(i).sensorsArray.get(j).sensorname,
                queryRequest.devicesArray.get(i).sensorsArray.get(j).sensorid,
                queryRequest.username,
                secretkey);
        String queryBodyWithSecretKey = gson.toJson(queryToRepo);
        logger.info(Const.API_QUERYDATA, "------Sending Request to VPDS--------");
        if (usertype.equals(Const.USER)) {
          responseFromServer =
              new SendHTTPRequest()
                  .sendPostRequest(
                      vpdsURL + "data/query",
                      Const.MIME_TYPE_JSON,
                      Const.API_QUERYDATA,
                      queryBodyWithSecretKey);
        } else {
          responseFromServer =
              new SendHTTPRequest()
                  .sendPostRequest(
                      Global.URL_REPOSITORY_QUERY_DATA,
                      Const.MIME_TYPE_JSON,
                      Const.API_QUERYDATA,
                      queryBodyWithSecretKey);
        }
        logger.info(Const.API_QUERYDATA, "------Finished Receiving Data--------");
        // System.out.println("Data response: "+responseFromServer.getString());

        try {

          WaveSegmentArray wa =
              gson.fromJson(responseFromServer.getString(), WaveSegmentArray.class);
          /*
           * If the size of WaveSegmentArray is 0, that is no data is found, then in that
           * case, it is not to be added to arrayOfResponses
           */
          if (wa.wavesegmentArray.size() > 0) {
            arrayOfResponses.add(wa);
          }
        } catch (NullPointerException e) {
          e.printStackTrace();
          renderJSON(
              gson.toJson(new APIResponse(Const.API_QUERYDATA, 1, "Error retrieving data!")));
        } catch (Exception e) {
          e.printStackTrace();
          renderJSON(
              gson.toJson(new APIResponse(Const.API_QUERYDATA, 1, "Error retrieving data!")));
        }
      }
    }

    if (arrayOfResponses.size() == 0) {
      renderText("No Data Found");
    }

    /*
     * @TODO : Automatically do mode checking based on size of data
     */
    if (queryRequest.interactive.equals("false")) {

      processNonInteractive(arrayOfResponses, vpdsURL);
    } else {
      processInteractive(arrayOfResponses, vpdsURL);
    }
  }
Exemplo n.º 4
0
  public XYDataset createDataset(ArrayList<WaveSegmentArray> arrayOfResponses, String vpdsURL) {
    TimeSeriesCollection dataset = new TimeSeriesCollection();

    // Number of sensor specific wavesegment array
    int numberOfResponses = arrayOfResponses.size();
    String usertype = session.get(Const.USERTYPE);
    HttpResponse responseFromServer = null;

    if (numberOfResponses > 0)
      for (int i = 0; i < numberOfResponses; i++) {
        WaveSegmentArray wa = arrayOfResponses.get(i);

        String devicename = wa.wavesegmentArray.get(0).data.dname;
        // Get device details

        String getDeviceProfile =
            "{\"secretkey\" : \"" + userkey + "\", \"devicename\": \"" + devicename + "\" }";
        System.out.println("Get device request" + getDeviceProfile);
        if (usertype.equals(Const.USER)) {
          responseFromServer =
              new SendHTTPRequest()
                  .sendPostRequest(
                      vpdsURL + "device/get",
                      Const.MIME_TYPE_JSON,
                      Const.API_GETDEVICE,
                      getDeviceProfile);
        } else {
          responseFromServer =
              new SendHTTPRequest()
                  .sendPostRequest(
                      Global.URL_REPOSITORY_GET_DEVICE,
                      Const.MIME_TYPE_JSON,
                      Const.API_GETDEVICE,
                      getDeviceProfile);
        }

        DeviceProfileFormat device =
            gson.fromJson(responseFromServer.getString(), DeviceProfileFormat.class);
        System.out.println("Get device response" + responseFromServer.getString());

        int numberOfSeries = wa.wavesegmentArray.get(0).data.channels.size();
        int numberOfWavesegs = wa.wavesegmentArray.size();
        String sensorname = wa.wavesegmentArray.get(0).data.sname;

        TimeSeries s1[] = new TimeSeries[numberOfSeries];

        for (int j = 0; j < numberOfSeries; j++) {
          s1[j] =
              new TimeSeries(
                  wa.wavesegmentArray.get(0).data.channels.get(j).cname
                      + " "
                      + wa.wavesegmentArray.get(0).data.sname
                      + " "
                      + wa.wavesegmentArray.get(0).data.dname,
                  Millisecond.class);
        }

        // Get sensor index of the sensor whose data is being processed
        // to compare it to the device profile retrieved from the VPDS

        int sindex = 0;
        for (int idx = 0; idx < device.sensors.size(); idx++) {
          if (device.sensors.get(idx).name.equals(sensorname)) {
            sindex = idx;
            break;
          }
        }
        // System.out.println("Sindex: " + sindex);
        for (int a = 0; a < numberOfWavesegs; a++) {

          long timestamp = wa.wavesegmentArray.get(a).data.timestamp * 1000;
          // System.out.println(timestamp);
          // initialization of sampling period
          int samplingPeriod = 1;

          for (int j = 0; j < numberOfSeries; j++) {

            try {

              int numberOfReadings =
                  wa.wavesegmentArray.get(a).data.channels.get(j).readings.size();
              String channelname = wa.wavesegmentArray.get(a).data.channels.get(j).cname;
              if (device.sensors.get(sindex).channels.get(j).name.equals(channelname))
                samplingPeriod = device.sensors.get(sindex).channels.get(j).samplingperiod;
              // System.out.println("sampling period:" + samplingPeriod + "number of readings" +
              // numberOfReadings);
              for (int k = 0; k < numberOfReadings; k++) {

                Millisecond x =
                    new Millisecond(
                        new Date(new Double((timestamp + k * samplingPeriod * 1000)).longValue()));
                // double x = (timestamp + k * samplingPeriod)* 1000;

                double y = wa.wavesegmentArray.get(a).data.channels.get(j).readings.get(k);

                // System.out.println("d[0]: " + x + " d[1]:" + y);

                s1[j].addOrUpdate(x, y);
              }
            } catch (NullPointerException e) {
              logger.error(
                  Const.API_QUERYDATA
                      + ": Null Pointer: Check packet. Possible error - readings missing");
            }
          }
        }
        for (int j = 0; j < numberOfSeries; j++) {
          dataset.addSeries(s1[j]);
        }
      } // arrayOfResponses loop ended

    // TODO Auto-generated method stub
    return dataset;
  }
Exemplo n.º 5
0
  private void processInteractive(ArrayList<WaveSegmentArray> arrayOfResponses, String vpdsURL) {
    long t1 = new Date().getTime();
    int size = arrayOfResponses.size(); // Number of sensors
    int seriesOffset = 0;
    String usertype = session.get(Const.USERTYPE);
    HttpResponse responseFromServer = null;

    ChartSeriesArray ca = new ChartSeriesArray();
    logger.info(Const.API_QUERYDATA, "Interactive:: Data Size:" + size);

    // Loop through the wavesegment array for 'a' requested sensors
    for (int a = 0; a < size; a++) {
      // System.out.println("For waveseg " + Integer.toString(a) + " ");
      WaveSegmentArray wa = arrayOfResponses.get(a);

      String devicename = wa.wavesegmentArray.get(0).data.dname;
      // Get device details

      String getDeviceProfile =
          "{\"secretkey\" : \"" + userkey + "\", \"devicename\": \"" + devicename + "\" }";
      // System.out.println("Get device request" + getDeviceProfile);
      if (usertype.equals(Const.USER)) {
        responseFromServer =
            new SendHTTPRequest()
                .sendPostRequest(
                    vpdsURL + "device/get",
                    Const.MIME_TYPE_JSON,
                    Const.API_GETDEVICE,
                    getDeviceProfile);
      } else {
        responseFromServer =
            new SendHTTPRequest()
                .sendPostRequest(
                    Global.URL_REPOSITORY_GET_DEVICE,
                    Const.MIME_TYPE_JSON,
                    Const.API_GETDEVICE,
                    getDeviceProfile);
      }

      DeviceProfileFormat device =
          gson.fromJson(responseFromServer.getString(), DeviceProfileFormat.class);
      // System.out.println("Get device response" + responseFromServer.getString());

      int numberOfWavesegs = wa.wavesegmentArray.size();
      int numberOfSeries = wa.wavesegmentArray.get(0).data.channels.size();
      String sensorname = wa.wavesegmentArray.get(0).data.sname;

      for (int i = 0; i < numberOfSeries; i++) {
        ca.chartSeries.add(
            new ChartSeries(
                wa.wavesegmentArray.get(0).data.channels.get(i).cname
                    + " "
                    + wa.wavesegmentArray.get(0).data.sname
                    + " "
                    + wa.wavesegmentArray.get(0).data.dname));

        ca.chartSeriesStats.add(
            new ChartSeriesStats(
                wa.wavesegmentArray.get(0).data.channels.get(i).cname
                    + " "
                    + wa.wavesegmentArray.get(0).data.sname
                    + " "
                    + wa.wavesegmentArray.get(0).data.dname));
      }
      // Get sensor index of the sensor whose data is being processed
      // to compare it to the device profile retrieved from the VPDS

      int sindex = 0;
      for (int i = 0; i < device.sensors.size(); i++)
        if (device.sensors.get(i).name.equals(sensorname)) sindex = i;

      for (int i = 0; i < numberOfWavesegs; i++) {
        long timestamp = wa.wavesegmentArray.get(i).data.timestamp;

        // initialization of sampling period
        int samplingPeriod = 1;
        // System.out.println(timestamp);

        for (int j = 0; j < numberOfSeries; j++) {
          try {

            int numberOfReadings = wa.wavesegmentArray.get(i).data.channels.get(j).readings.size();
            String channelname = wa.wavesegmentArray.get(i).data.channels.get(j).cname;

            Double min = wa.wavesegmentArray.get(i).data.channels.get(j).readings.get(0);
            Double max = wa.wavesegmentArray.get(i).data.channels.get(j).readings.get(0);
            Double avg = 0.0;
            if (device.sensors.get(sindex).channels.get(j).name.equals(channelname))
              samplingPeriod = device.sensors.get(sindex).channels.get(j).samplingperiod;

            // System.out.println("sampling period:" + samplingPeriod);

            for (int k = 0; k < numberOfReadings; k++) {
              double[] d = new double[2];
              d[0] = (timestamp + k * samplingPeriod) * 1000;
              d[1] = wa.wavesegmentArray.get(i).data.channels.get(j).readings.get(k);
              // System.out.println("d[0]: " + d[0] + " d[1]:" + d[1]);

              ca.chartSeries.get(j + seriesOffset).data.add(d);
              // Min Value
              if (min > d[1]) min = d[1];

              // Max Value
              if (max < d[1]) max = d[1];

              // Avg Value
              avg += d[1];
            }

            ca.chartSeriesStats.get(j + seriesOffset).min = min;
            ca.chartSeriesStats.get(j + seriesOffset).max = max;
            ca.chartSeriesStats.get(j + seriesOffset).avg = avg / numberOfReadings;
          } catch (NullPointerException e) {
            logger.error(
                Const.API_QUERYDATA
                    + ": NullPointerError: Check packet. Possible error - readings missing");
          }
        }
      }
      seriesOffset += numberOfSeries;
    }
    // System.out.println(gson.toJson(ca));
    long t2 = new Date().getTime();
    logger.info(
        Const.API_QUERYDATA, "Time to create interactive graph:" + (t2 - t1) / 1000 + " seconds");
    renderJSON(gson.toJson(ca));
  }
Exemplo n.º 6
0
  public boolean verify() {
    try {
      // Normalize
      String claimedId = normalize(id);
      String server = null;
      String delegate = null;

      // Discover
      HttpResponse response = WS.url(claimedId).get();

      // Try HTML (I know it's bad)
      String html = response.getString();
      server = discoverServer(html);

      if (server == null) {

        // Try YADIS
        Document xrds = null;

        if (response.getContentType().contains("application/xrds+xml")) {
          xrds = getXml(html, response.getEncoding());
        } else if (response.getHeader("X-XRDS-Location") != null) {
          xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml();
        } else {
          return false;
        }

        // Ok we have the XRDS file
        server =
            XPath.selectText(
                "//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()",
                xrds);
        claimedId =
            XPath.selectText(
                "//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()",
                xrds);
        if (claimedId == null) {
          claimedId = "http://specs.openid.net/auth/2.0/identifier_select";
        } else {
          server =
              XPath.selectText(
                  "//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()",
                  xrds);
        }

        if (server == null) {
          return false;
        }

      } else {

        // Delegate
        Matcher openid2Localid =
            Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE)
                .matcher(html);
        Matcher openidDelegate =
            Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE)
                .matcher(html);
        if (openid2Localid.find()) {
          delegate = extractHref(openid2Localid.group());
        } else if (openidDelegate.find()) {
          delegate = extractHref(openidDelegate.group());
        }
      }

      // Redirect
      String url = server;
      if (!server.contains("?")) {
        url += "?";
      }
      if (!url.endsWith("?") && !url.endsWith("&")) {
        url += "&";
      }

      url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8");
      url += "&openid.mode=checkid_setup";
      url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8");
      url +=
          "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8");

      if (returnAction != null
          && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) {
        url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8");
      } else {
        url +=
            "&openid.return_to="
                + URLEncoder.encode(
                    Request.current().getBase() + Router.reverse(returnAction), "utf8");
      }
      if (realmAction != null
          && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) {
        url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8");
      } else {
        url +=
            "&openid.realm="
                + URLEncoder.encode(
                    Request.current().getBase() + Router.reverse(realmAction), "utf8");
      }

      if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) {
        url +=
            "&openid.ns.sreg="
                + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8");
      }
      String sregO = "";
      for (String a : sregOptional) {
        sregO += URLEncoder.encode(a, "UTF-8") + ",";
      }
      if (!StringUtils.isEmpty(sregO)) {
        url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1);
      }
      String sregR = "";
      for (String a : sregRequired) {
        sregR += URLEncoder.encode(a, "UTF-8") + ",";
      }
      if (!StringUtils.isEmpty(sregR)) {
        url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1);
      }

      if (!axRequired.isEmpty() || !axOptional.isEmpty()) {
        url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0";
        url += "&openid.ax.mode=fetch_request";
        for (String a : axOptional.keySet()) {
          url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8");
        }
        for (String a : axRequired.keySet()) {
          url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8");
        }
        if (!axRequired.isEmpty()) {
          String r = "";
          for (String a : axRequired.keySet()) {
            r += "," + a;
          }
          r = r.substring(1);
          url += "&openid.ax.required=" + r;
        }
        if (!axOptional.isEmpty()) {
          String r = "";
          for (String a : axOptional.keySet()) {
            r += "," + a;
          }
          r = r.substring(1);
          url += "&openid.ax.if_available=" + r;
        }
      }

      if (Logger.isTraceEnabled()) {
        // Debug
        Logger.trace("Send request %s", url);
      }

      throw new Redirect(url);
    } catch (Redirect e) {
      throw e;
    } catch (PlayException e) {
      throw e;
    } catch (Exception e) {
      return false;
    }
  }