private void loadCalendarEvents(
     final Calendar calendar,
     final CalendarListEntry calendarEntry,
     final UpdateInfo updateInfo,
     final Long since)
     throws IOException {
   String pageToken = null;
   do {
     long then = System.currentTimeMillis();
     final Calendar.Events.List eventsApiCall = calendar.events().list(calendarEntry.getId());
     final String uriTemplate = eventsApiCall.getUriTemplate();
     try {
       eventsApiCall.setPageToken(pageToken);
       eventsApiCall.setShowHiddenInvitations(true);
       eventsApiCall.setSingleEvents(true);
       eventsApiCall.setTimeMax(new DateTime(System.currentTimeMillis()));
       if (since != null) eventsApiCall.setTimeMin(new DateTime(since));
       final Events events = eventsApiCall.execute();
       countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, uriTemplate);
       final List<Event> eventList = events.getItems();
       storeEvents(updateInfo, calendarEntry, eventList);
       pageToken = events.getNextPageToken();
     } catch (Throwable e) {
       countFailedApiCall(
           updateInfo.apiKey,
           updateInfo.objectTypes,
           then,
           uriTemplate,
           ExceptionUtils.getStackTrace(e),
           eventsApiCall.getLastStatusCode(),
           eventsApiCall.getLastStatusMessage());
       throw (new RuntimeException(e));
     }
   } while (pageToken != null);
 }
예제 #2
0
    public void run() {
      try {
        if (reconnect) {
          reconnect = false;
          mysqlConnection.reconnect();
        } else if (!mysqlConnection.isConnected()) {
          mysqlConnection.connect();
        }
        Long startTime = System.currentTimeMillis();

        // 可能心跳sql为select 1
        if (StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "select")) {
          mysqlConnection.query(detectingSQL);
        } else {
          mysqlConnection.update(detectingSQL);
        }

        Long costTime = System.currentTimeMillis() - startTime;
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onSuccess(costTime);
        }
      } catch (SocketTimeoutException e) {
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onFailed(e);
        }
        reconnect = true;
        logger.warn("connect failed by " + ExceptionUtils.getStackTrace(e));
      } catch (IOException e) {
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onFailed(e);
        }
        reconnect = true;
        logger.warn("connect failed by " + ExceptionUtils.getStackTrace(e));
      }
    }
예제 #3
0
 public static void inlinePic(HttpServletResponse res, String path) {
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   if (path != null) {
     if (path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".jpeg")) {
       res.setContentType("image/jpeg");
       res.setHeader("Content-disposition", "inline; filename=\"license.jpg\";");
     } else if (path.toLowerCase().endsWith(".gif")) {
       res.setContentType("image/gif");
       res.setHeader("Content-disposition", "inline; filename=\"license.gif\";");
     } else if (path.toLowerCase().endsWith(".png")) {
       res.setContentType("image/png");
       res.setHeader("Content-disposition", "inline; filename=\"license.png\";");
     }
     res.setHeader("Content-Length", String.valueOf(new File(path).length()));
     try {
       bis = new BufferedInputStream(new FileInputStream(path));
       bos = new BufferedOutputStream(res.getOutputStream());
       IOUtils.copy(bis, bos);
     } catch (IOException e) {
       logger.error(ExceptionUtils.getStackTrace(e));
       throw new RuntimeException(e);
     } finally {
       IOUtils.closeQuietly(bis);
       IOUtils.closeQuietly(bos);
     }
   }
 }
 protected void logHasPermissionCheck(
     String checkType,
     String principalId,
     String namespaceCode,
     String permissionName,
     Map<String, String> permissionDetails) {
   StringBuilder sb = new StringBuilder();
   sb.append('\n');
   sb.append("Has Perm for ")
       .append(checkType)
       .append(": ")
       .append(namespaceCode)
       .append("/")
       .append(permissionName)
       .append('\n');
   sb.append("             Principal:  ").append(principalId);
   if (principalId != null) {
     Principal principal = getPrincipal(principalId);
     if (principal != null) {
       sb.append(" (").append(principal.getPrincipalName()).append(')');
     }
   }
   sb.append('\n');
   sb.append("             Details:\n");
   if (permissionDetails != null) {
     sb.append(permissionDetails);
   } else {
     sb.append("                         [null]\n");
   }
   if (LOG.isTraceEnabled()) {
     LOG.trace(sb.append(ExceptionUtils.getStackTrace(new Throwable())));
   } else {
     LOG.debug(sb.toString());
   }
 }
  public Map<String, List<RDFNode>> queryModel(
      String queryString, List<String> queryVariables, VirtDataset virtDataset) {
    Map<String, List<RDFNode>> solution = new HashMap<String, List<RDFNode>>();
    QueryExecution qexec = null;
    try {
      qexec = QueryExecutionFactory.create(queryString, virtDataset);
      // ResultSet rs = executeQuery(sb.toString(), virtDataset);
    } catch (com.hp.hpl.jena.query.QueryParseException e) {
      System.err.println(ExceptionUtils.getStackTrace(e) + "\n Will return an empty map...");
      return Collections.EMPTY_MAP;
    }

    ResultSet results = qexec.execSelect();
    while (results.hasNext()) {
      QuerySolution sol = results.next();
      for (String variable : queryVariables) {

        RDFNode nodeVar = sol.get(variable);
        if (nodeVar != null) {
          if (solution.get(variable) == null) {
            solution.put(variable, new ArrayList<RDFNode>());
          }
          solution.get(variable).add(nodeVar);
        }
      }
    }

    return solution;
  }
  public String registerStudy(String studyOid, String hostName) {
    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl =
        CoreResources.getField("portalURL")
            + "/app/rest/oc/authorizations?studyoid="
            + studyOid
            + "&instanceurl="
            + ocUrl;
    Authorization authRequest = new Authorization();
    Study authStudy = new Study();
    authStudy.setStudyOid(studyOid);
    authStudy.setInstanceUrl(ocUrl);
    authStudy.setHost(hostName);
    authRequest.setStudy(authStudy);

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);

    try {
      Authorization response = rest.postForObject(pManageUrl, authRequest, Authorization.class);
      if (response != null && response.getAuthorizationStatus() != null)
        return response.getAuthorizationStatus().getStatus();
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
예제 #7
0
 public List<ClientListInfo> getClientsDataTable(
     int startRecord, int recordsToShow, String clientNameKey) {
   try {
     Session session = sessionFactory.getCurrentSession();
     CallableStatement cstmt =
         session.connection().prepareCall("{call ADMIN_CLIENT_MANAGEMENT(?,?,?)}");
     List<ClientListInfo> clientListInfo = new ArrayList<ClientListInfo>();
     cstmt.setInt(1, startRecord);
     cstmt.setInt(2, recordsToShow);
     cstmt.setString(3, clientNameKey.trim());
     ResultSet rs = cstmt.executeQuery();
     if (rs != null) {
       while (rs.next()) {
         ClientListInfo clientInfo = new ClientListInfo();
         clientInfo.setIndex(rs.getInt(1));
         clientInfo.setClientId(rs.getInt(2));
         clientInfo.setClientName(rs.getString(3));
         clientInfo.setBusinessType(rs.getString(4));
         clientInfo.setContactPerson(rs.getString(5));
         clientInfo.setWorkPhone(rs.getString(6));
         clientInfo.setMobileNumber(rs.getString(7));
         clientInfo.setIsActive(rs.getBoolean(9));
         clientInfo.setEdit(rs.getInt(2));
         clientInfo.setDelete(rs.getInt(2));
         clientInfo.setTotalRows(rs.getInt(10));
         clientListInfo.add(clientInfo);
       }
     }
     return clientListInfo;
   } catch (Exception e) {
     log.error("Exception in get Client Data Table : DAO :" + ExceptionUtils.getStackTrace(e));
   }
   return null;
 }
  public String getStudyHost(String studyOid) throws Exception {

    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl = CoreResources.getField("portalURL");
    String pManageUrlFull =
        pManageUrl + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl;

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);
    try {
      Authorization[] response = rest.getForObject(pManageUrlFull, Authorization[].class);
      if (response.length > 0
          && response[0].getStudy() != null
          && response[0].getStudy().getHost() != null
          && !response[0].getStudy().getHost().equals("")) {
        URL url = new URL(pManageUrl);
        String port = "";
        if (url.getPort() > 0) port = ":" + String.valueOf(url.getPort());
        return url.getProtocol()
            + "://"
            + response[0].getStudy().getHost()
            + "."
            + url.getHost()
            + port
            + "/#/login";
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
예제 #9
0
  /**
   * This method is to get the roleId and roleName.
   *
   * @param roleLevel
   * @param tenantId
   * @param subTenantId
   * @param response
   * @return
   */
  @RequestMapping(value = "/getRoleInfo", method = RequestMethod.GET)
  public @ResponseBody String getRoleInfo(
      int roleLevel, int tenantId, int subTenantId, HttpServletResponse response) {
    try {
      ArrayList arrayObj = new ArrayList();
      List<Roles> roleInfoList = userService.getRoleInfo();

      for (int i = 0; i < roleInfoList.size(); i++) {
        Roles roleInfo = roleInfoList.get(i);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roleId", roleInfo.getRoleId());
        jsonObject.put("roleName", roleInfo.getRoleName());

        arrayObj.add(jsonObject);
      }

      JSONObject myObj = new JSONObject();
      myObj.put("total", roleInfoList.size());
      myObj.put("success", true);
      myObj.put("roleInfo", arrayObj);

      return myObj.toString();

    } catch (Exception e) {
      log.error("Exception in getRoleInfo::" + ExceptionUtils.getStackTrace(e));
    }

    return "";
  }
예제 #10
0
  public int updateUser(User user) throws RuntimeException {
    logger.info("--> cs.simple.console.service.impl.UserServiceImpl.updateUser");
    int affected = 0;
    try {
      List<Object> args = new ArrayList<Object>();

      String password = user.getPassword();
      StringBuffer b = new StringBuffer();
      b.append("update tb_user set viewname = ? ");
      args.add(user.getViewname());

      if (StringUtils.hasText(password)) {
        b.append(", password = ? ");
        args.add(password(user.getPassword()));
      }

      b.append("where user_id = ?");
      args.add(user.getUserId());

      affected = jdbcTemplate.update(b.toString(), args.toArray());
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      throw new RuntimeException(e);
    }
    logger.info("<-- cs.simple.console.service.impl.UserServiceImpl.updateUser");
    return affected;
  }
  public void onFailure(ITestResult result) {
    if (getWebDriver() == null) {
      System.out.println(
          "Can't take a screenshot and save HTML, because there is no driver available.");
      return;
    }

    Throwable throwable = result.getThrowable();
    String stacktrace = null;

    if (throwable != null) {
      stacktrace = ExceptionUtils.getStackTrace(throwable);
    }

    String filenameIdentification = getFilenameIdentification(result);

    // TODO traffic can be captured using BrowserMob Proxy
    // String traffic;
    // try {
    // traffic = selenium.captureNetworkTraffic(NetworkTrafficType.PLAIN).getTraffic();
    // } catch (SeleniumException e) {
    // traffic = ExceptionUtils.getFullStackTrace(e);
    // }

    try {
      File screenshot = null;
      if (((GrapheneProxyInstance) getWebDriver()).unwrap() instanceof TakesScreenshot) {
        screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.FILE);
      }

      String htmlSource = getWebDriver().getPageSource();

      File stacktraceOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/stacktrace.txt");
      File imageOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/screenshot.png");
      // File trafficOutputFile = new File(failuresOutputDir, filenameIdentification +
      // "/network-traffic.txt");
      // File logOutputFile = new File(failuresOutputDir, filenameIdentification +
      // "/selenium-log.txt");
      File htmlSourceOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/html-source.html");

      File directory = imageOutputFile.getParentFile();
      FileUtils.forceMkdir(directory);

      FileUtils.writeStringToFile(stacktraceOutputFile, stacktrace);
      if (!HtmlUnitDriver.class.isInstance(getWebDriver())) {
        FileUtils.copyFile(screenshot, imageOutputFile);
      }

      // FileUtils.writeStringToFile(trafficOutputFile, traffic);
      // FileUtils.writeLines(logOutputFile, methodLog);
      FileUtils.writeStringToFile(htmlSourceOutputFile, htmlSource);
    } catch (Exception e) {
      System.err.println("Can't take a screenshot/save HTML source: " + e.getMessage());
      e.printStackTrace(System.err);
      // LOGGER.log(Level.WARNING, "Can't take a screenshot/save HTML source.", e);
    }
  }
예제 #12
0
  private String writeError(Throwable error, String errorMsg) {
    StringBuffer errorBlock = new StringBuffer("\"error\":");
    errorBlock.append("\"");
    if (error != null) {
      JsonStringEncoder inst = JsonStringEncoder.getInstance();
      errorBlock.append(inst.quoteAsString("" + error.getClass() + ": "));
      errorBlock.append(inst.quoteAsString("" + error.getMessage()));
      String mode = Play.configuration.getProperty("application.mode");
      if (!"prod".equals(mode)) {
        inst = JsonStringEncoder.getInstance();
        errorBlock.append(inst.quoteAsString("" + ExceptionUtils.getStackTrace(error)));
      }
    }

    if (errorMsg != null) {
      errorBlock.append(errorMsg);
    }

    for (int i = 0; i < errors.size(); i++) {
      String err = errors.get(i);
      errorBlock.append(err);
      if (i < errors.size()) errorBlock.append(", ");
    }

    errorBlock.append("\"");
    return "" + errorBlock;
  }
예제 #13
0
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    logger.error(
        "something goes wrong with channel:{}, exception={}",
        ctx.getChannel(),
        ExceptionUtils.getStackTrace(e.getCause()));

    ctx.getChannel().close();
  }
예제 #14
0
 public static void sendError(Throwable exception, Request request) {
   setContentType("text/html");
   setSubject("An OpenSeedbox error occured!");
   addRecipient(Config.getErrorEmailAddress());
   setFrom(Config.getErrorFromEmailAddress());
   String stackTrace = ExceptionUtils.getStackTrace(exception);
   send("mails/sendError", exception, stackTrace, request);
 }
예제 #15
0
 private static String fullMessage(String message, Throwable t) {
   if (message == null) {
     message = "";
   }
   if (t == null) {
     return message;
   }
   return message + "\n" + ExceptionUtils.getStackTrace(t);
 }
예제 #16
0
 public boolean deleteClient(Clients clients) {
   try {
     clients.setIsDeleted(true);
     sessionFactory.getCurrentSession().saveOrUpdate(clients);
     return true;
   } catch (Exception e) {
     log.error("Exception in delete client : DAO :" + ExceptionUtils.getStackTrace(e));
   }
   return false;
 }
예제 #17
0
 public HCatClient getHCatClient() {
   if (null == this.hCatClient) {
     try {
       this.hCatClient = HCatUtil.getHCatClient(hcatEndpoint, hiveMetaStorePrincipal);
     } catch (HCatException e) {
       Assert.fail(
           "Unable to create hCatClient because of exception:\n"
               + ExceptionUtils.getStackTrace(e));
     }
   }
   return this.hCatClient;
 }
예제 #18
0
 public static void nodeDown(Node node, Throwable exactError) {
   setContentType("text/html");
   setSubject("Node '" + node.getName() + "' is down!");
   addRecipient(Config.getErrorEmailAddress());
   setFrom(Config.getErrorFromEmailAddress());
   String stackTrace = "Node wont respond to pings.";
   if (exactError != null) {
     stackTrace = ExceptionUtils.getStackTrace(exactError);
   }
   String status = "down";
   send("mails/nodeDown", node, stackTrace, status);
 }
예제 #19
0
 public Clients getClientById(int clientId) {
   Clients client = null;
   try {
     String queryString = "FROM Clients WHERE isDeleted = 'false' AND clientId = " + clientId;
     Query query = sessionFactory.getCurrentSession().createQuery(queryString);
     client = (Clients) query.list().get(0);
     return client;
   } catch (Exception e) {
     log.error("Exception in get client By clientId : DAO :" + ExceptionUtils.getStackTrace(e));
   }
   return client;
 }
    @SuppressWarnings("unchecked")
    public synchronized void launch(NMCommunicatorLaunchRequestEvent event) {
      LOG.info("Launching Container with Id: " + event.getContainerId());
      if (this.state == ContainerState.KILLED_BEFORE_LAUNCH) {
        state = ContainerState.DONE;
        sendContainerLaunchFailedMsg(
            event.getContainerId(), "Container was killed before it was launched");
        return;
      }

      ContainerManagementProtocolProxyData proxy = null;
      try {

        proxy = getCMProxy(containerID, containerMgrAddress, containerToken);

        // Construct the actual Container
        ContainerLaunchContext containerLaunchContext = event.getContainerLaunchContext();

        // Now launch the actual container
        StartContainerRequest startRequest = Records.newRecord(StartContainerRequest.class);
        startRequest.setContainerToken(event.getContainerToken());
        startRequest.setContainerLaunchContext(containerLaunchContext);

        StartContainersResponse response =
            proxy
                .getContainerManagementProtocol()
                .startContainers(
                    StartContainersRequest.newInstance(Collections.singletonList(startRequest)));
        if (response.getFailedRequests() != null && !response.getFailedRequests().isEmpty()) {
          throw response.getFailedRequests().get(containerID).deSerialize();
        }

        // after launching, send launched event to task attempt to move
        // it from ASSIGNED to RUNNING state
        context.getEventHandler().handle(new AMContainerEventLaunched(containerID));
        ContainerLaunchedEvent lEvt =
            new ContainerLaunchedEvent(
                containerID, clock.getTime(), context.getApplicationAttemptId());
        context.getHistoryHandler().handle(new DAGHistoryEvent(null, lEvt));

        this.state = ContainerState.RUNNING;
      } catch (Throwable t) {
        String message =
            "Container launch failed for " + containerID + " : " + ExceptionUtils.getStackTrace(t);
        this.state = ContainerState.FAILED;
        sendContainerLaunchFailedMsg(containerID, message);
      } finally {
        if (proxy != null) {
          cmProxy.mayBeCloseProxy(proxy);
        }
      }
    }
예제 #21
0
  /**
   * This method used to show the userList in Datatable.
   *
   * @param levelIdParam
   * @param tenantIdParam
   * @param subTenantIdParam
   * @param userNameKey
   * @param model
   * @param session
   * @param request
   * @return
   */
  @RequestMapping(value = "/userListInfo", method = RequestMethod.GET)
  public @ResponseBody String getUsersDataTable(
      String levelIdParam,
      String tenantIdParam,
      String subTenantIdParam,
      String userNameKey,
      Model model,
      HttpSession session,
      HttpServletRequest request) {
    try {
      int startRecord = 0;
      int recordsToShow = 0;

      String sEcho = request.getParameter("sEcho");

      if (request.getParameter("iDisplayStart") != null) {
        startRecord = Integer.parseInt(request.getParameter("iDisplayStart"));
        startRecord = startRecord + 1;
      }

      if (request.getParameter("iDisplayLength") != null) {
        recordsToShow = Integer.parseInt(request.getParameter("iDisplayLength"));
      }

      ArrayList arrayObj = new ArrayList();
      List<UserListInfo> userList = new ArrayList<UserListInfo>();
      JSONObject itemObj = new JSONObject();
      UserSessionInfo userSessionInfo =
          (UserSessionInfo) session.getAttribute(ApplicationConstants.USER_SESSION_KEY);

      userList = userService.getUsersDataTable(startRecord, recordsToShow, userNameKey);

      int totalRows = 0;
      for (int i = 0; i < userList.size(); i++) {
        UserListInfo userListInfo = userList.get(i);
        totalRows = userListInfo.getTotalRows();
        itemObj = JSONObject.fromObject(userListInfo);
        arrayObj.add(itemObj);
      }
      JSONObject myObj = new JSONObject();
      myObj.put("sEcho", sEcho);
      myObj.put("iTotalRecords", totalRows);
      myObj.put("iTotalDisplayRecords", totalRows);
      myObj.put("aaData", arrayObj);

      // convert the JSON object to string and send the response back
      return myObj.toString();
    } catch (Exception e) {
      log.error("Exception in getUsersDataTable::" + ExceptionUtils.getStackTrace(e));
      return "";
    }
  }
예제 #22
0
 /**
  * This method is to save the client object.
  *
  * @param clients
  * @return saved client Id else 0.
  */
 public long saveClients(Clients clients) {
   try {
     if (clients.getClientId() == 0) {
       return (Long) sessionFactory.getCurrentSession().save(clients);
     } else {
       sessionFactory.getCurrentSession().saveOrUpdate(clients);
       return 1;
     }
   } catch (Exception e) {
     log.error("Exception in save client: DAO : " + ExceptionUtils.getStackTrace(e));
   }
   return 0;
 }
  @ExceptionHandler(Exception.class)
  public void handleBundleException(HttpServletResponse response, Exception ex) throws IOException {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    Throwable rootEx = (ex.getCause() == null ? ex : ex.getCause());

    String msg =
        (StringUtils.isNotBlank(rootEx.getMessage())) ? rootEx.getMessage() : rootEx.toString();
    statusMessageService.error(msg);

    try (Writer writer = response.getWriter()) {
      writer.write(ExceptionUtils.getStackTrace(ex));
    }
  }
예제 #24
0
 /**
  * 获取queryStr,系统中使用该参数记录列表页面的参数,执行修改或者删除之后将回到原参数页面,注意排除了参数success,fail
  *
  * @param req HttpServletRequest object
  * @param prefix 前缀
  * @return 编码之后的查询字符串,排除了success,fail,还可以添加前缀
  */
 public static String getQueryStr(HttpServletRequest req, String prefix) {
   String queryStr = getQueryString(req, query_str_exclude_params);
   if (queryStr.length() > 0) {
     try {
       return URLEncoder.encode(prefix + "?" + queryStr, "UTF-8");
     } catch (UnsupportedEncodingException e) {
       logger.warn(ExceptionUtils.getStackTrace(e));
       throw new RuntimeException(e);
     }
   } else {
     return prefix;
   }
 }
예제 #25
0
  @GET
  @Path("/{studyOID}/getSchedule")
  @Produces(MediaType.APPLICATION_XML)
  public String getSchedule(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response,
      @Context ServletContext context,
      @PathParam("studyOID") String studyOID,
      @RequestHeader("Authorization") String authorization)
      throws Exception {

    String ssoid = request.getParameter("studySubjectOID");
    StudySubjectDAO ssdao = new StudySubjectDAO<String, ArrayList>(dataSource);
    StudySubjectBean ssBean = ssdao.findByOid(ssoid);
    if (!mayProceedSubmission(studyOID, ssBean)) return null;

    HashMap<String, String> urlCache =
        (HashMap<String, String>) context.getAttribute("pformURLCache");
    context.getAttribute("subjectContextCache");
    if (ssoid == null) {
      return "<error>studySubjectOID is null :(</error>";
    }

    try {
      // Need to retrieve crf's for next event
      StudyEventDAO eventDAO = new StudyEventDAO(getDataSource());
      StudyEventBean nextEvent = (StudyEventBean) eventDAO.getNextScheduledEvent(ssoid);
      CRFVersionDAO versionDAO = new CRFVersionDAO(getDataSource());
      ArrayList<CRFVersionBean> crfs =
          versionDAO.findDefCRFVersionsByStudyEvent(nextEvent.getStudyEventDefinitionId());
      PFormCache cache = PFormCache.getInstance(context);
      for (CRFVersionBean crfVersion : crfs) {
        String enketoURL = cache.getPFormURL(studyOID, crfVersion.getOid());
        String contextHash =
            cache.putSubjectContext(
                ssoid,
                String.valueOf(nextEvent.getStudyEventDefinitionId()),
                String.valueOf(nextEvent.getSampleOrdinal()),
                crfVersion.getOid());
      }
    } catch (Exception e) {
      LOGGER.debug(e.getMessage());
      LOGGER.debug(ExceptionUtils.getStackTrace(e));
      return "<error>" + e.getMessage() + "</error>";
    }

    response.setHeader("Content-Type", "text/xml; charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"schedule.xml\";");
    response.setContentType("text/xml; charset=utf-8");
    return "<result>success</result>";
  }
예제 #26
0
 private void checkSpillException() throws IOException {
   final Throwable lspillException = sortSpillException;
   if (lspillException != null) {
     if (lspillException instanceof Error) {
       final String logMsg =
           "Task "
               + outputContext.getUniqueIdentifier()
               + " failed : "
               + ExceptionUtils.getStackTrace(lspillException);
       outputContext.fatalError(lspillException, logMsg);
     }
     throw new IOException("Spill failed", lspillException);
   }
 }
 private void updateCalendarEvents(
     final Calendar calendar,
     final CalendarListEntry calendarEntry,
     final UpdateInfo updateInfo,
     long since)
     throws IOException {
   // In the unlikely case where the server was down or disconnected more than 20 days and thus
   // wasn't able to
   // check for updated items during this period, we need to constrain the updatedMin parameter to
   // a maximum
   // of 20 days in the past, at the risk of getting an error from Google
   since = Math.max(since, System.currentTimeMillis() - 20 * DateTimeConstants.MILLIS_PER_DAY);
   String pageToken = null;
   do {
     long then = System.currentTimeMillis();
     final Calendar.Events.List eventsApiCall = calendar.events().list(calendarEntry.getId());
     final String uriTemplate = eventsApiCall.getUriTemplate();
     try {
       eventsApiCall.setPageToken(pageToken);
       eventsApiCall.setShowHiddenInvitations(true);
       eventsApiCall.setSingleEvents(true);
       eventsApiCall.setTimeMax(new DateTime(System.currentTimeMillis()));
       eventsApiCall.setUpdatedMin(new DateTime(since));
       final Events events = eventsApiCall.execute();
       countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, uriTemplate);
       final List<Event> eventList = events.getItems();
       storeEvents(updateInfo, calendarEntry, eventList);
       pageToken = events.getNextPageToken();
     } catch (Throwable e) {
       logger.warn(
           "updateCalendarEvents unexpected httpCode="
               + eventsApiCall.getLastStatusCode()
               + " reason="
               + eventsApiCall.getLastStatusMessage()
               + " since="
               + since
               + " message="
               + e.getMessage());
       countFailedApiCall(
           updateInfo.apiKey,
           updateInfo.objectTypes,
           then,
           uriTemplate,
           ExceptionUtils.getStackTrace(e),
           eventsApiCall.getLastStatusCode(),
           eventsApiCall.getLastStatusMessage());
       throw (new RuntimeException(e));
     }
   } while (pageToken != null);
 }
예제 #28
0
 public Connection getHiveJdbcConnection() {
   if (null == hiveJdbcConnection) {
     try {
       hiveJdbcConnection =
           HiveUtil.getHiveJdbcConnection(
               hiveJdbcUrl, hiveJdbcUser, hiveJdbcPassword, hiveMetaStorePrincipal);
     } catch (ClassNotFoundException | SQLException | InterruptedException | IOException e) {
       Assert.fail(
           "Unable to create hive jdbc connection because of exception:\n"
               + ExceptionUtils.getStackTrace(e));
     }
   }
   return hiveJdbcConnection;
 }
예제 #29
0
 public int removeUser(User user) throws RuntimeException {
   logger.info("--> cs.simple.console.service.impl.UserServiceImpl.removeUser");
   int affected = 0;
   try {
     affected =
         jdbcTemplate.update(
             "update tb_user set deleted = ? where user_id = ?", Constant.Y, user.getUserId());
     // TODO remove groupMember
   } catch (Exception e) {
     logger.error(ExceptionUtils.getStackTrace(e));
     throw new RuntimeException(e);
   }
   logger.info("<-- cs.simple.console.service.impl.UserServiceImpl.removeUser");
   return affected;
 }
예제 #30
0
  /**
   * Handle exception.
   *
   * @param exception the exception
   * @return the response
   */
  public static Response handleException(Exception exception) {
    ResponseBuilder builder = null;
    ObjectFactory factory = new ObjectFactory();

    /* Construct error response jaxb */
    ApiErrorResponse errResponse = factory.createApiErrorResponse();
    errResponse.setMessage(exception.getMessage());
    errResponse.setTrace(ExceptionUtils.getStackTrace(exception));
    errResponse.setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode());

    /* Build the error response */
    builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errResponse);

    /* Return the response */
    return builder.build();
  }