public String getSignature(String baseString, OAuthParameters oauthParameters)
     throws OAuthException {
   try {
     if (oauthParameters == null) {
       throw new OAuthException("OAuth parameters cannot be null");
     }
     String keyString = getKey(oauthParameters);
     SecretKey key = new SecretKeySpec(keyString.getBytes("UTF-8"), "HmacSHA1");
     Mac mac = Mac.getInstance("HmacSHA1");
     mac.init(key);
     return Base64.encode(mac.doFinal(baseString.getBytes("UTF-8")));
   } catch (UnsupportedEncodingException e) {
     throw new OAuthException(e);
   } catch (NoSuchAlgorithmException e) {
     throw new OAuthException(e);
   } catch (InvalidKeyException e) {
     throw new OAuthException(e);
   }
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      if (HttpUtils.isEmptyAny(request, "type")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      } else {
        String type = request.getParameter("type");
        int appId = NumberUtils.getInt(request.getHeader(Commons.APP_HEADER), -1);
        JSONObject reply = new JSONObject();

        String latStr = request.getParameter("lat");
        String lngStr = request.getParameter("lng");
        if (StringUtils.isNotEmpty(latStr) && StringUtils.isNotEmpty(lngStr)) {
          try {
            Landmark l = new Landmark();
            l.setLatitude(GeocodeUtils.getLatitude(latStr));
            l.setLongitude(GeocodeUtils.getLongitude(lngStr));
            logger.log(Level.INFO, "User location is " + latStr + "," + lngStr);
            // persist location

            l.setName(Commons.MY_POSITION_LAYER);
            boolean isSimilarToNewest = LandmarkPersistenceWebUtils.isSimilarToNewest(l);
            if (!isSimilarToNewest) {
              String u =
                  StringUtil.getUsername(
                      request.getAttribute("username"), request.getParameter("username"));
              if (u != null && u.length() % 4 == 0) {
                try {
                  u = new String(Base64.decode(u));
                } catch (Exception e) {
                  // from version 1086, 86 username is Base64 encoded string
                }
              }
              l.setUsername(u);
              String socialIds = request.getParameter("socialIds");

              LandmarkPersistenceWebUtils.setFlex(l, request);
              l.setLayer(Commons.MY_POS_CODE);

              LandmarkPersistenceUtils.persistLandmark(l, GoogleCacheProvider.getInstance());

              if (l.getId() > 0) {
                LandmarkPersistenceWebUtils.notifyOnLandmarkCreation(
                    l, request.getHeader("User-Agent"), socialIds);
              }
            }
          } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
          }
        } else {
          logger.log(Level.INFO, "No user location provided");
        }

        if (StringUtils.equals(type, "v")) {
          // check for version
          reply.put("type", type);
          if (appId == 0) {
            // LM
            String version =
                ConfigurationManager.getParam(
                    net.gmsworld.server.config.ConfigurationManager.LM_VERSION, "0");
            reply.put("value", version);
          } else if (appId == 1) {
            // DA
            String version =
                ConfigurationManager.getParam(
                    net.gmsworld.server.config.ConfigurationManager.DA_VERSION, "0");
            reply.put("value", version);
          }
        } else if (StringUtils.equals(type, "u")) {
          // engagement
          String email = request.getParameter("e");
          long lastStartupTime = NumberUtils.getLong(request.getParameter("lst"), -1);
          String useCount = request.getParameter("uc");
          Calendar cal = Calendar.getInstance();
          cal.setTimeInMillis(lastStartupTime);
          logger.log(
              Level.INFO,
              "Received usage notification from "
                  + (email != null ? email : "guest")
                  + " last startup time: "
                  + DateFormat.getDateTimeInstance().format(cal.getTime())
                  + ", use count: "
                  + useCount);
          int minInterval =
              NumberUtils.getInt(
                  ConfigurationManager.getParam(
                      net.gmsworld.server.config.ConfigurationManager.NOTIFICATIONS_INTERVAL, "14"),
                  14);
          int maxInterval = 31;
          long interval = System.currentTimeMillis() - lastStartupTime;
          if (interval > (minInterval * ONE_DAY)
              && interval < (maxInterval * ONE_DAY)
              && email != null) {
            // send email notification if lastStartupTime > week ago
            // send not more that once a week
            logger.log(Level.WARNING, email + " should be engaged to run Landmark Manager!");
            MailUtils.sendEngagementMessage(email, getServletContext());
            reply =
                new JSONObject()
                    .put("status", "engaged")
                    .put("timestamp", System.currentTimeMillis());
          } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            reply = new JSONObject().put("status", "accepted");
          }
        }
        out.print(reply.toString());
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
      out.close();
    }
  }
Ejemplo n.º 3
0
  public static ArrayList<String> extractDataFromZip(ZipInputStream zis)
      throws IOException, SignedDataException {
    ArrayList<String> lines = new ArrayList<String>();
    String line = null;
    String surveyDataOnly = null;
    String dataSig = null;
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
      log.info("Unzipping: " + entry.getName());
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buffer = new byte[2048];
      int size;
      while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
        out.write(buffer, 0, size);
      }
      line = out.toString("UTF-8");

      if (entry.getName().endsWith("txt")) {
        if (entry.getName().equals("regions.txt")) {
          lines.add("regionFlag=true");
        } else {
          surveyDataOnly = line;
        }
        String[] linesSplit = line.split("\n");
        for (String s : linesSplit) {
          if (s.contains("\u0000")) {
            s = s.replaceAll("\u0000", "");
          }
          lines.add(s);
        }
      } else if (entry.getName().endsWith(".sig")) {
        dataSig = line.trim();
      } else {
        S3Driver s3 = new S3Driver();
        String[] imageParts = entry.getName().split("/");
        // comment out while testing locally
        try {
          // GAEImageAdapter gaeIA = new GAEImageAdapter();
          // byte[] resizedImage =
          // gaeIA.resizeImage(out.toByteArray(), 500, 500);
          // s3.uploadFile("dru-test", imageParts[1], resizedImage);
          GAEImageAdapter gaeImg = new GAEImageAdapter();
          byte[] newImage = gaeImg.resizeImage(out.toByteArray(), 500, 500);
          s3.uploadFile("dru-test", imageParts[1], newImage);
          // add queue call to resize
          Queue queue = QueueFactory.getDefaultQueue();

          queue.add(TaskOptions.Builder.withUrl("imageprocessor").param("imageURL", imageParts[1]));
          log.info("submiting image resize for imageURL: " + imageParts[1]);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
        out.close();
      }
      zis.closeEntry();
    }
    // check the signature if we have it
    if (surveyDataOnly != null && dataSig != null) {
      try {
        MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        byte[] digest = sha1Digest.digest(surveyDataOnly.getBytes("UTF-8"));
        SecretKeySpec signingKey =
            new SecretKeySpec(
                PropertyUtil.getProperty(SIGNING_KEY).getBytes("UTF-8"), SIGNING_ALGORITHM);
        Mac mac = Mac.getInstance(SIGNING_ALGORITHM);
        mac.init(signingKey);
        byte[] hmac = mac.doFinal(digest);

        String encodedHmac = com.google.gdata.util.common.util.Base64.encode(hmac);
        if (!encodedHmac.trim().equals(dataSig.trim())) {
          String allowUnsigned = PropertyUtil.getProperty(ALLOW_UNSIGNED);
          if (allowUnsigned != null && allowUnsigned.trim().equalsIgnoreCase("false")) {
            throw new SignedDataException(
                "Computed signature does not match the one submitted with the data");
          } else {
            log.warning("Signatures don't match. Processing anyway since allow unsigned is true");
          }
        }
      } catch (GeneralSecurityException e) {
        throw new SignedDataException("Could not calculate signature", e);
      }

    } else if (surveyDataOnly != null) {
      // if there is no signature, check the configuration to see if we
      // are allowed to proceed
      String allowUnsigned = PropertyUtil.getProperty(ALLOW_UNSIGNED);
      if (allowUnsigned != null && allowUnsigned.trim().equalsIgnoreCase("false")) {
        throw new SignedDataException("Datafile does not have a signature");
      }
    }

    return lines;
  }