/**
   * Makes an asynchronous call.
   *
   * @param method the method on the API to call
   * @param request the request to forward to the API
   * @param responseBuilder the response builder used to fill the response
   * @param deadline the deadline of the call. if it is null, the default api deadline will be used
   */
  private <T extends GeneratedMessage.Builder<T>> Future<T> makeAsyncCall(
      String method, GeneratedMessage request, final T responseBuilder, Double deadline) {
    Future<byte[]> response;
    if (deadline == null) {
      response = ApiProxy.makeAsyncCall(PACKAGE, method, request.toByteArray());
    } else {
      ApiProxy.ApiConfig apiConfig = new ApiProxy.ApiConfig();
      apiConfig.setDeadlineInSeconds(deadline);
      response = ApiProxy.makeAsyncCall(PACKAGE, method, request.toByteArray(), apiConfig);
    }
    return new FutureWrapper<byte[], T>(response) {
      @Override
      protected T wrap(byte[] responseBytes) {
        if (responseBytes != null) {
          try {
            responseBuilder.mergeFrom(responseBytes);
          } catch (InvalidProtocolBufferException e) {
            throw new SearchServiceException(e.toString());
          }
        }
        return responseBuilder;
      }

      @Override
      protected Throwable convertException(Throwable cause) {
        return cause;
      }
    };
  }
 public String getEmail() {
   // The test below just makes sure we didn't miss the lines in web.xml that
   // ensure the user has to be logged in. If this exception is thrown, web.xml
   // needs fixing.
   if (!ApiProxy.getCurrentEnvironment().isLoggedIn()) {
     throw new IllegalStateException("not logged in");
   }
   // In the same way, ApiProxy.getCurrentEnvironment().isAdmin() could be used to
   // determine whether the currently logged in user is known to AppEngine as an
   // administrator of this application. I can't think of any reason to demonstrate
   // thatin the Land of Gack.
   return ApiProxy.getCurrentEnvironment().getEmail();
 }
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    final long firstCall = ApiProxy.getCurrentEnvironment().getRemainingMillis();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while sleeping.");
    }
    final long secondCall = ApiProxy.getCurrentEnvironment().getRemainingMillis();
    if (secondCall >= firstCall) {
      throw new RuntimeException(
          "Time is not moving (or moving backwards): initial call = '"
              + firstCall
              + "', subsequent call = '"
              + secondCall
              + "'.");
    }

    res.setContentType("text/plain");
    res.getWriter()
        .println("You are the bread and the knife, " + "the crystal goblet and the wine.");

    // Unfortunately, if we're using this servlet to test the DevAppServer we can't continue
    // because it does not ever time out requests.
    if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) {
      return;
    }

    try {
      Thread.sleep(600000); // Sleep 10 minutes, this should guarantee an exception is thrown.
      throw new RuntimeException(
          "Expected the DeadlineExceededException to be thrown after" + "sleeping for 10mins");
    } catch (DeadlineExceededException e) {
      // There is an inherent race condition here that exists in the java runtime in general.
      // The problem that users run into here, is that they end up having to write code that
      // is gauranteed to complete in a specific amount of wall clock time.  In production,
      // this time is represented by a sleep that occurs in deadline_manager.cc and has little
      // to do with the java runtime itself.  Therefore, this segment of the test is always going
      // to be potentially flaky, we just try to do as much work before we get into this
      // exception handler as possible so that we don't run over our allocated cleanup time.
      if (ApiProxy.getCurrentEnvironment().getRemainingMillis() > 0) {
        throw new RuntimeException(
            "getRemainingMillis returned a result indicating there was time "
                + "remaining after DeadlineExceededException was thrown");
      }
      return;
    } catch (InterruptedException e) {
      throw new RuntimeException("The serving thread was interrupted before the deadline");
    }
  }
  @Test(expected = CallNotFoundException.class)
  public void testCallRunCompiledQueryRequest() {
    com.google.apphosting.api.DatastorePb.Query query =
        new com.google.apphosting.api.DatastorePb.Query();
    query.setApp(ApiProxy.getCurrentEnvironment().getAppId());
    query.setKind("Foo");

    RunCompiledQueryRequest request = new RunCompiledQueryRequest();
    request.setApp(ApiProxy.getCurrentEnvironment().getAppId());
    request.setOriginalQuery(query);

    QueryResult response = DatastoreOperations.RUN_COMPILES_QUERY.call(request);

    assertThat(response, is(not(nullValue())));
  }
Esempio n. 5
0
  @Before
  public void setUp() throws Exception {
    super.setUp();
    ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment());
    // ApiProxyLocalImpl apiProxyLocalImpl = new ApiProxyLocalImpl(new File(".")){};
    // ApiProxy.setDelegate(apiProxyLocalImpl);

    /*	ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment());
    ApiProxyLocalFactory factory = new ApiProxyLocalFactory();
    LocalServerEnvironment localServerEnvironment = new LocalServerEnvironment() {
    	@Override
    	public void waitForServerToStart() throws InterruptedException {
    		// TODO Auto-generated method stub
    	}

    	@Override
    	public int getPort() {
    		return 8080;
    	}

    	@Override
    	public File getAppDir() {
    		return new File(".");
    	}

    	@Override
    	public String getAddress() {
    		return "127.0.0.1";
    	}
    };
          ApiProxy.setDelegate(factory.create(localServerEnvironment));*/
  }
  @Override
  public GetAccessTokenResult getAccessTokenUncached(Iterable<String> scopes) {
    GetAccessTokenRequest.Builder requestBuilder = GetAccessTokenRequest.newBuilder();
    for (String scope : scopes) {
      requestBuilder.addScope(scope);
    }
    if (requestBuilder.getScopeCount() == 0) {
      throw new AppIdentityServiceFailureException("No scopes specified.");
    }
    GetAccessTokenResponse.Builder responseBuilder = GetAccessTokenResponse.newBuilder();
    try {
      responseBuilder.mergeFrom(
          ApiProxy.makeSyncCall(
              getAccessTokenPackageName(),
              GET_ACCESS_TOKEN_METHOD_NAME,
              requestBuilder.build().toByteArray()));
    } catch (ApiProxy.ApplicationException e) {
      handleApplicationError(e);
    } catch (InvalidProtocolBufferException e) {
      throw new AppIdentityServiceFailureException(e.getMessage());
    }

    GetAccessTokenResponse response = responseBuilder.build();
    return new GetAccessTokenResult(
        response.getAccessToken(), new Date(response.getExpirationTime() * 1000));
  }
 @Override
 public TaskQueueQueryTasksResponse call(TaskQueueQueryTasksRequest request) {
   TaskQueueQueryTasksResponse response = new TaskQueueQueryTasksResponse();
   response.mergeFrom(
       ApiProxy.makeSyncCall(
           taskqueue.packageName, taskqueue.methodName.QueryTasks, request.toByteArray()));
   return response;
 }
  @Test(expected = ExecutionException.class)
  public void testCallAsyncRunCompiledQueryRequestApiConfig()
      throws InterruptedException, ExecutionException {
    com.google.apphosting.api.DatastorePb.Query query =
        new com.google.apphosting.api.DatastorePb.Query();
    query.setApp(ApiProxy.getCurrentEnvironment().getAppId());
    query.setKind("Foo");

    RunCompiledQueryRequest request = new RunCompiledQueryRequest();
    request.setApp(ApiProxy.getCurrentEnvironment().getAppId());
    request.setOriginalQuery(query);

    Future<QueryResult> response =
        DatastoreOperations.RUN_COMPILES_QUERY.callAsync(request, new ApiConfig());

    assertThat(response, is(not(nullValue())));
    assertThat(response.get(), is(not(nullValue())));
  }
 static {
   if (ApiProxy.getCurrentEnvironment() != null) {
     Logger.forceJuli = true;
     Logger.setUp("DEBUG");
     Logger.info("Play! is running in Google App Engine");
     Play.readOnlyTmp = true;
     Play.usePrecompiled = true;
   } else {
     Logger.redirectJuli = true;
   }
 }
 @Override
 public Future<TaskQueueQueryTasksResponse> callAsync(
     TaskQueueQueryTasksRequest request, ApiConfig apiConfig) {
   TaskQueueQueryTasksResponse response = new TaskQueueQueryTasksResponse();
   return new ProtocolMessageFuture<TaskQueueQueryTasksResponse>(
       ApiProxy.makeAsyncCall(
           taskqueue.packageName,
           taskqueue.methodName.QueryTasks,
           request.toByteArray(),
           apiConfig),
       response);
 }
Esempio n. 11
0
  /** setup with spedified user */
  @Override
  protected void before() throws Throwable {
    if (AppEngineUtil.isProduction()) {
      // not loaded TestEnvironment on production
      return;
    }

    TestEnvironment environment = (TestEnvironment) ApiProxy.getCurrentEnvironment();
    if (environment == null) {
      throw new NullPointerException("Not initialized TestEnvironment. please use RuleChain");
    }
    environment.setEmail(email);
    environment.setAdmin(admin);
    if (authDomain != null) {
      environment.setAuthDomain(authDomain);
    }
  }
  @Test
  public void testParseFullAppId() {
    // [(partition)~][(domain):](display-app-id)
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    String hostname =
        (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname");
    AppIdentityService.ParsedAppId parsed = appIdentity.parseFullAppId(hostname);

    String message = createParsed(parsed);
    Assert.assertEquals(
        message,
        property("testParseFullAppId_partition").getPropertyValue(),
        parsed.getPartition());
    Assert.assertEquals(
        message, getExpectedAppHostname("testParseFullAppId_domain"), parsed.getDomain());
    Assert.assertEquals(message, getExpectedAppId("testParseFullAppId_id"), parsed.getId());
  }
  @Override
  public SigningResult signForApp(byte[] signBlob) {
    SignForAppRequest.Builder requestBuilder = SignForAppRequest.newBuilder();
    requestBuilder.setBytesToSign(ByteString.copyFrom(signBlob));
    SignForAppResponse.Builder responseBuilder = SignForAppResponse.newBuilder();
    try {
      responseBuilder.mergeFrom(
          ApiProxy.makeSyncCall(
              PACKAGE_NAME, SIGN_FOR_APP_METHOD_NAME, requestBuilder.build().toByteArray()));
    } catch (ApiProxy.ApplicationException e) {
      handleApplicationError(e);
    } catch (InvalidProtocolBufferException e) {
      throw new AppIdentityServiceFailureException(e.getMessage());
    }

    SignForAppResponse response = responseBuilder.build();
    return new SigningResult(response.getKeyName(), response.getSignatureBytes().toByteArray());
  }
 public static CapedwarfEnvironment setThreadLocalInstance(
     final CapedwarfEnvironment environment) {
   SecurityManager sm = System.getSecurityManager();
   if (sm == null) {
     CapedwarfEnvironment previous = getThreadLocalInstanceInternal();
     ApiProxy.setEnvironmentForCurrentThread(environment);
     return previous;
   } else {
     return AccessController.doPrivileged(
         new PrivilegedAction<CapedwarfEnvironment>() {
           public CapedwarfEnvironment run() {
             CapedwarfEnvironment previous = getThreadLocalInstanceInternal();
             ApiProxy.setEnvironmentForCurrentThread(environment);
             return previous;
           }
         });
   }
 }
  @Override
  public String getServiceAccountName() {
    GetServiceAccountNameRequest.Builder requestBuilder = GetServiceAccountNameRequest.newBuilder();
    GetServiceAccountNameResponse.Builder responseBuilder =
        GetServiceAccountNameResponse.newBuilder();
    try {
      responseBuilder.mergeFrom(
          ApiProxy.makeSyncCall(
              getAccessTokenPackageName(),
              GET_SERVICE_ACCOUNT_NAME_METHOD_NAME,
              requestBuilder.build().toByteArray()));
    } catch (ApiProxy.ApplicationException e) {
      handleApplicationError(e);
    } catch (InvalidProtocolBufferException e) {
      throw new AppIdentityServiceFailureException(e.getMessage());
    }

    GetServiceAccountNameResponse response = responseBuilder.build();
    return response.getServiceAccountName();
  }
  /*
   * Retrieve the default Google Cloud Storage bucket name.
   */
  @Test
  public void testGetDefaultGcsBucketName() {
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    String expectedBucketName;
    Property property = property("testGetDefaultGcsBucketName");
    if (property.exists()) {
      expectedBucketName = property.getPropertyValue();
    } else {
      expectedBucketName =
          (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname");
    }

    try {
      String bucketName = appIdentity.getDefaultGcsBucketName();
      Assert.assertEquals(expectedBucketName, bucketName);
    } catch (AppIdentityServiceFailureException aisfe) {
      // TODO: This means that there is no default bucket setup for this project.  Have a better way
      // to verify this.
    }
  }
  @Override
  public List<PublicCertificate> getPublicCertificatesForApp() {
    GetPublicCertificateForAppRequest.Builder requestBuilder =
        GetPublicCertificateForAppRequest.newBuilder();
    GetPublicCertificateForAppResponse.Builder responseBuilder =
        GetPublicCertificateForAppResponse.newBuilder();

    try {
      responseBuilder.mergeFrom(
          ApiProxy.makeSyncCall(
              PACKAGE_NAME, GET_CERTS_METHOD_NAME, requestBuilder.build().toByteArray()));
    } catch (ApiProxy.ApplicationException e) {
      handleApplicationError(e);
    } catch (InvalidProtocolBufferException e) {
      throw new AppIdentityServiceFailureException(e.getMessage());
    }
    GetPublicCertificateForAppResponse response = responseBuilder.build();

    List<PublicCertificate> certs = Lists.newArrayList();
    for (AppIdentityServicePb.PublicCertificate cert : response.getPublicCertificateListList()) {
      certs.add(new PublicCertificate(cert.getKeyName(), cert.getX509CertificatePem()));
    }
    return certs;
  }
 public static CapedwarfEnvironment createThreadLocalInstance() {
   CapedwarfEnvironment environment = new CapedwarfEnvironment();
   ApiProxy.setEnvironmentForCurrentThread(environment);
   return environment;
 }
 /**
  * This one doesn't make any check if env is null.
  *
  * @return env or null if not set
  */
 public static CapedwarfEnvironment getThreadLocalInstanceInternal() {
   return (CapedwarfEnvironment) ApiProxy.getCurrentEnvironment();
 }
 public static void clearThreadLocalInstance() {
   ApiProxy.clearEnvironmentForCurrentThread();
 }
 protected void setDelegateForThread(ApiProxy.Delegate delegate) {
   ApiProxy.setDelegate(delegate);
   //    CloudCoverLocalServiceTestHelper.setDelegate(delegate);
 }
  public JSONArray employeeBalanceLeave(Object employeeid, Object requestdate) {

    String applicationVersionId =
        ApiProxy.getCurrentEnvironment()
            .getVersionId()
            .substring(0, ApiProxy.getCurrentEnvironment().getVersionId().indexOf("."));
    if (applicationVersionId.equalsIgnoreCase("testviews")) {
      JSONArray balanceLeaveArray =
          com.applane.resourceoriented.hris.BalanceLeaves.employeeBalanceLeave(
              employeeid, requestdate);
      return balanceLeaveArray;
    } else {
      try {
        // GET EMPLOYEEID FROM KEY
        Object employeeId;
        if ((employeeid instanceof JSONObject)) {
          employeeId = ((JSONObject) employeeid).get(Data.Query.KEY);
        } else {
          employeeId = employeeid;
        }

        // get designationid from hris_employees where employeeId is above

        JSONObject query = new JSONObject();
        query.put(Data.Query.RESOURCE, "hris_employees");
        JSONArray array = new JSONArray();
        array.put("designationid");
        query.put(Data.Query.COLUMNS, array);
        query.put(Data.Query.FILTERS, "__key__= " + employeeId);
        JSONObject designationObject;
        designationObject = ResourceEngine.query(query);
        JSONArray designationArray = designationObject.getJSONArray("hris_employees");

        int designationArrayCount = designationArray == null ? 0 : designationArray.length();

        if (designationArrayCount > 0) {
          Object designationId = designationArray.getJSONObject(0).opt("designationid");
          if (designationId != null) {

            // GET leavepolicyid from hris_leavepolicy__designationid where designationid is above
            JSONObject leavePolicyQuery = new JSONObject();
            leavePolicyQuery.put(Data.Query.RESOURCE, "hris_designations__leavepolicyid");
            JSONArray policyArray = new JSONArray();
            policyArray.put("leavepolicyid");
            policyArray.put("leavepolicyid.fromdate");
            policyArray.put("leavepolicyid.todate");
            leavePolicyQuery.put(Data.Query.COLUMNS, policyArray);
            leavePolicyQuery.put(Data.Query.FILTERS, "hris_designations= " + designationId);
            JSONObject leavePolicyObject;
            leavePolicyObject = ResourceEngine.query(leavePolicyQuery);
            JSONArray leavePolicyArray =
                leavePolicyObject.getJSONArray("hris_designations__leavepolicyid");

            int leavePolicyArrayCount = leavePolicyArray == null ? 0 : leavePolicyArray.length();
            if (leavePolicyArrayCount > 0) {
              Object leavePolicyId = leavePolicyArray.getJSONObject(0).opt("leavepolicyid");
              Object leavePolicyFromDateObject =
                  leavePolicyArray.getJSONObject(0).opt("leavepolicyid.fromdate");
              Object leavePolicyToDateObject =
                  leavePolicyArray.getJSONObject(0).opt("leavepolicyid.todate");

              SimpleDateFormat queryDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              SimpleDateFormat updateDateFormat = new SimpleDateFormat("yyyy-MM-dd");

              Date leavePolicyFromDate = null;
              Date leavePolicyToDate = null;
              Date requestDate = null;

              if (leavePolicyFromDateObject != null
                  && leavePolicyToDateObject != null
                  && requestdate != null) {
                // parse leave policy from date
                try {
                  leavePolicyFromDate = queryDateFormat.parse("" + leavePolicyFromDateObject);
                } catch (ParseException e) {
                  e.printStackTrace();
                  try {
                    leavePolicyFromDate = updateDateFormat.parse("" + leavePolicyFromDateObject);
                  } catch (ParseException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    throw new RuntimeException(
                        "LEAVE POLICY from date is not parsable" + e.getMessage());
                  }
                }

                // parse leave policy to date
                try {
                  leavePolicyToDate = queryDateFormat.parse("" + leavePolicyToDateObject);
                } catch (ParseException e) {
                  e.printStackTrace();
                  try {
                    leavePolicyToDate = updateDateFormat.parse("" + leavePolicyToDateObject);
                  } catch (ParseException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    throw new RuntimeException(
                        "LEAVE POLICY to date is not parsable" + e.getMessage());
                  }
                }

                // parse request date
                try {
                  requestDate = queryDateFormat.parse("" + requestdate);
                } catch (ParseException e) {
                  e.printStackTrace();
                  try {
                    requestDate = updateDateFormat.parse("" + requestdate);
                  } catch (ParseException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    throw new RuntimeException("REQUEST date is not parsable" + e.getMessage());
                  }
                }
              } else {
                LogUtility.writeLog("one or more  than one dates are null");
              }

              if (leavePolicyFromDate.before(requestDate)
                  && requestDate.before(leavePolicyToDate)) {
                // GET leaveruleid, leavetypeid, and noofleaves from hris_leaverules where
                // leavepolicyid is above
                JSONObject leaveRuleQuery = new JSONObject();
                leaveRuleQuery.put(Data.Query.RESOURCE, "hris_leaverule");
                JSONArray ruleArray = new JSONArray();
                ruleArray.put("__key__");
                ruleArray.put("leavetypeid");
                ruleArray.put("leavetypeid.name");
                ruleArray.put("noofleaves");
                ruleArray.put("maxallowed");
                leaveRuleQuery.put(Data.Query.COLUMNS, ruleArray);
                leaveRuleQuery.put(Data.Query.FILTERS, "leavepolicyid= " + leavePolicyId);
                JSONObject leaveRuleObject;
                leaveRuleObject = ResourceEngine.query(leaveRuleQuery);
                JSONArray leaveRuleArray = leaveRuleObject.getJSONArray("hris_leaverule");

                int leaveCount =
                    (leaveRuleArray == null || leaveRuleArray.length() == 0)
                        ? 0
                        : leaveRuleArray.length();
                JSONArray categoryTypeArray = new JSONArray();
                if (leaveCount > 0) {
                  for (int leaveCounter = 0; leaveCounter < leaveCount; leaveCounter++) {
                    Object key = leaveRuleArray.getJSONObject(leaveCounter).opt("__key__");

                    Object leaveTypeId =
                        leaveRuleArray.getJSONObject(leaveCounter).opt("leavetypeid");
                    Object leaveType =
                        leaveRuleArray.getJSONObject(leaveCounter).opt("leavetypeid.name");
                    Double noofLeaves =
                        leaveRuleArray.getJSONObject(leaveCounter).getDouble("noofleaves");
                    Object maxAllowedLeavesInMonth =
                        leaveRuleArray.getJSONObject(leaveCounter).opt("maxallowed");

                    JSONObject typeobject = new JSONObject();

                    JSONObject leaveTypeObject = new JSONObject();
                    leaveTypeObject.put("__key__", leaveTypeId);
                    leaveTypeObject.put("name", leaveType);
                    typeobject.put("leavetypeid", leaveTypeObject);
                    typeobject.put("totalleaves", noofLeaves);
                    Double takenLeaves =
                        calculateLeaveTaken(
                            employeeId,
                            leaveTypeId,
                            leavePolicyFromDateObject,
                            leavePolicyToDateObject);
                    typeobject.put("takenleaves", takenLeaves);
                    Double balanceLeave = noofLeaves - takenLeaves;
                    String balanceMessage = "";
                    if (balanceLeave >= 0) {
                      balanceMessage = balanceLeave + " leaves pending";
                    } else {
                      balanceMessage = (balanceLeave * (-1.0)) + " leaves overdue";
                    }
                    typeobject.put("balanceleaves", balanceMessage);
                    categoryTypeArray.put(leaveCounter, typeobject);
                  }
                }
                return categoryTypeArray;
              } else {
                WarningCollector.collect("Your leave policy is outdated.");
              }
            }
          }
        }
        return null;
      } catch (Exception e) {
        e.printStackTrace();
        throw new BusinessLogicException(
            "Error while generating leave balance report" + e.getMessage());
      }
    }
  }
  public JSONArray populateEmployeeBalanceLeavesDARCL(Object employeeid, Object requestdate) {

    String applicationVersionId =
        ApiProxy.getCurrentEnvironment()
            .getVersionId()
            .substring(0, ApiProxy.getCurrentEnvironment().getVersionId().indexOf("."));
    if (applicationVersionId.equalsIgnoreCase("testviews")) {
      JSONArray balanceLeaveArray =
          com.applane.resourceoriented.hris.BalanceLeaves.employeeBalanceLeave(
              employeeid, requestdate);
      return balanceLeaveArray;
    } else {
      try {
        // GET EMPLOYEEID FROM KEY
        if ((employeeid instanceof JSONArray)) {
          employeeid = ((JSONArray) employeeid).getJSONObject(0).get(Data.Query.KEY);
        }

        if ((employeeid instanceof JSONObject)) {
          employeeid = ((JSONObject) employeeid).get(Data.Query.KEY);
        }

        JSONArray employeeLeavePolicyArray = getEmployeeLeavePolicyId(employeeid);
        if (employeeLeavePolicyArray != null && employeeLeavePolicyArray.length() > 0) {
          Object leavePolicyId = employeeLeavePolicyArray.getJSONObject(0).opt("leavepolicyid");
          Object leavePolicyFromDate =
              employeeLeavePolicyArray.getJSONObject(0).opt("leavepolicyid.fromdate");
          Object leavePolicyToDate =
              employeeLeavePolicyArray.getJSONObject(0).opt("leavepolicyid.todate");
          JSONArray employeeLeaveRuleArray = getEmployeeLeaveRule(employeeid, leavePolicyId);
          if (employeeLeaveRuleArray != null && employeeLeaveRuleArray.length() > 0) {
            JSONArray categoryTypeArray = new JSONArray();
            for (int counter = 0; counter < employeeLeaveRuleArray.length(); counter++) {
              Object leaveTypeId = employeeLeaveRuleArray.getJSONObject(counter).opt("leavetypeid");
              Object leaveTypeName =
                  employeeLeaveRuleArray.getJSONObject(counter).opt("leavetypeid.name");
              Object openingBalance =
                  employeeLeaveRuleArray.getJSONObject(counter).opt("openingbalance");
              Object assignedLeave =
                  employeeLeaveRuleArray.getJSONObject(counter).opt("assignedleaves");
              double totalMonthBetweenFromDateAneToDate =
                  getTotalMonthBetweenFromDateAneToDate(
                      Translator.dateValue(leavePolicyFromDate),
                      Translator.dateValue(leavePolicyToDate));
              double takenLeaves =
                  calculateLeaveTaken(
                      employeeid, leaveTypeId, leavePolicyFromDate, leavePolicyToDate);
              double totalAssignedLeaves =
                  Translator.doubleValue(openingBalance)
                      + (Translator.doubleValue(assignedLeave)
                          / totalMonthBetweenFromDateAneToDate);
              double balance = totalAssignedLeaves - takenLeaves;

              JSONObject leaveTypeObject = new JSONObject();
              JSONObject typeobject = new JSONObject();

              leaveTypeObject.put("__key__", leaveTypeId);
              leaveTypeObject.put("name", leaveTypeName);

              typeobject.put("leavetypeid", leaveTypeObject);
              typeobject.put("totalleaves", totalAssignedLeaves);
              typeobject.put("takenleaves", takenLeaves);
              String balanceMessage = "";
              if (balance >= 0) {
                balanceMessage = new DecimalFormat("0.#").format(balance) + " leaves pending";
              } else {
                balanceMessage =
                    new DecimalFormat("0.#").format((balance * (-1.0))) + " leaves overdue";
              }
              typeobject.put("balanceleaves", balanceMessage);
              categoryTypeArray.put(counter, typeobject);
            }
            return categoryTypeArray;
          }
        }

      } catch (Exception e) {
        LogUtility.writeLog(
            "BalanceLeaves >> populateEmployeeBalanceLeavesDARCL Exception  >> : ["
                + ExceptionUtils.getExceptionTraceMessage(getClass().getName(), e)
                + "]");
        throw new RuntimeException("Some Error Occured while Generating Leave Balance");
      }
    }
    return null;
  }
Esempio n. 24
0
  private void handleMail(
      HttpServletRequest request, HttpServletResponse response, BlogAuthor blogAuthor)
      throws IOException, ServletException, EntityNotFoundException, MessagingException,
          HttpException {
    DS ds = DS.get();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session, request.getInputStream());
    String messageId = getMessageId(message);
    String contentType = message.getContentType();

    if (messageId == null) {
      log("messageID missing");
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    log("Message-ID=" + messageId);
    // TODO authorization
    if (handleSpot(message)) {
      return;
    }
    InternetAddress sender = (InternetAddress) message.getSender();
    log("sender=" + sender);
    if (sender == null) {
      Address[] from = message.getFrom();
      if (from != null && from.length != 0) {
        sender = (InternetAddress) from[0];
      }
    }
    if (sender == null) {
      log("Sender missing");
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    Email senderEmail = new Email(sender.getAddress());
    Settings settings = ds.getSettingsFor(senderEmail);
    if (settings == null) {
      log(senderEmail.getEmail() + " not allowed to send blogs");
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
    String[] ripperDate = message.getHeader(BlogRipper + "Date");
    boolean ripping = ripperDate != null && ripperDate.length > 0;
    Object content = message.getContent();
    if (content instanceof Multipart) {
      Multipart multipart = (Multipart) message.getContent();
      List<BodyPart> bodyPartList = findParts(multipart);
      try {
        Entity blog = null;
        String htmlBody = getHtmlBody(bodyPartList);
        if (htmlBody != null && htmlBody.length() > 10) {
          boolean publishImmediately = settings.isPublishImmediately();
          blog = updateBlog(messageId, message, htmlBody, publishImmediately, senderEmail);
          if (!ripping) {
            if (blog != null) {
              sendMail(request, blogAuthor, blog, settings);
            }
          } else {
            log("not sending email because ripping");
          }
        } else {
          log("no html body");
        }
        List<Future<HTTPResponse>> futureList = new ArrayList<Future<HTTPResponse>>();
        for (BodyPart bodyPart : bodyPartList) {
          Collection<Future<HTTPResponse>> futures =
              handleBodyPart(request, blog, bodyPart, settings);
          if (futures != null) {
            futureList.addAll(futures);
          }
        }
        long remainingMillis = ApiProxy.getCurrentEnvironment().getRemainingMillis();
        log("remainingMillis=" + remainingMillis);
        for (Future<HTTPResponse> res : futureList) {
          try {
            HTTPResponse hr = res.get();
            log("code=" + hr.getResponseCode());
            if (hr.getResponseCode() != HttpServletResponse.SC_OK) {
              throw new ServletException("blob upload failed code=" + hr.getResponseCode());
            }
          } catch (InterruptedException ex) {
            throw new IOException(ex);
          } catch (ExecutionException ex) {
            throw new IOException(ex);
          }
        }
      } catch (MessagingException ex) {
        throw new IOException(ex);
      }
    } else {
      if (content instanceof String) {
        String bodyPart = (String) content;
        if (contentType.startsWith("text/plain")) {
          bodyPart = textPlainToHtml(bodyPart);
        }
        boolean publishImmediately = settings.isPublishImmediately();
        Entity blog = updateBlog(messageId, message, bodyPart, publishImmediately, senderEmail);
        if (blog != null) {
          sendMail(request, blogAuthor, blog, settings);
        }
      } else {
        log("body not MultiPart of String");
      }
    }
  }
 protected ApiProxy.Delegate getDelegateForThread() {
   return ApiProxy.getDelegate();
   //    return CloudCoverLocalServiceTestHelper.getDelegate();
 }