List of usage examples for java.util Date toString
public String toString()
where:dow mon dd hh:mm:ss zzz yyyy
From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java
/** * Submit comment for a package./* www . java 2s. co m*/ * * @param dataSetId * the id of the dataset. * @param userId * the user ID. * @param date * the date of the commenting * @param comment * the comment. * @return true if everything is fine, false otherwise. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static boolean postDatasetComment(String dataSetId, String userId, Date date, String comment) { // check the parameters if (dataSetId == null || dataSetId.equals("") || userId == null || userId.equals("") || comment == null || comment.equals("")) { return false; } // get the package details Object obj = CKANGatewayCore.getDataSetDetails(dataSetId); if (obj == null) { return false; } // prepare the extras string // pick the extras Map mMap = (Map) obj; String resource = mMap.get("resources").toString(); Map eMap = (Map) mMap.get("extras"); JSONArray tArray = (JSONArray) mMap.get("tags"); JSONArray gArray = (JSONArray) mMap.get("groups"); // check weather extras is defined if (eMap != null) { JSONArray comments = null; try { if (eMap.get("comments") instanceof java.lang.String) { JSONParser parser = new JSONParser(); comments = (JSONArray) parser.parse((String) eMap.get("comments")); } else { comments = (JSONArray) eMap.get("comments"); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse result" + (String) eMap.get("comments")); } if (comments == null) { comments = new JSONArray(); } Map<String, String> toadd = new HashMap<String, String>(); toadd.put("userId", userId); toadd.put("comment", comment); toadd.put("date", date.toString()); comments.add(toadd); eMap.put("comments", comments); } // prepare the hash map for the update method HashMap<String, String> hm = new HashMap<String, String>(); hm.put("extras", eMap.toString()); hm.put("resources", resource); hm.put("tags", tArray.toJSONString()); hm.put("groups", gArray.toJSONString()); // update the meta data set HashMap<String, HashMap> res = CKANGatewayCore.updateDataSet(dataSetId, hm); boolean toreturn = (res != null); return toreturn; }
From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java
/** * Submit rating for a package [rating: number of stars, 1..5] * //w w w.jav a 2 s . c om * @param dataSetId * the id of the dataset to rate. * @param userId * the ID of the user submitting the rating. * @param date * the date at which the rating takes place. * @param rating * the rating value. * @return true in case of success, false otherwise. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static boolean postDataSetRating(String dataSetId, String userId, Date date, int rating) { // check the parameters if (dataSetId == null || dataSetId.equals("") || userId == null || userId.equals("") || rating < 0 || rating > 5) { return false; } // get the package details Object obj = CKANGatewayCore.getDataSetDetails(dataSetId); if (obj == null) { return false; } // prepare the extras string // pick the extras Map mMap = (Map) obj; Map eMap = (Map) mMap.get("extras"); String resource = mMap.get("resources").toString(); JSONArray tArray = (JSONArray) mMap.get("tags"); JSONArray gArray = (JSONArray) mMap.get("groups"); // check weather extras is defined if (eMap != null) { JSONArray ratings = null; try { if (eMap.get("ratings") instanceof java.lang.String) { JSONParser parser = new JSONParser(); ratings = (JSONArray) parser.parse((String) eMap.get("ratings")); } else { ratings = (JSONArray) eMap.get("ratings"); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse result" + (String) eMap.get("ratings")); } if (ratings == null) { ratings = new JSONArray(); } Map<String, String> toadd = new HashMap<String, String>(); toadd.put("userId", userId); toadd.put("ratingValue", Integer.valueOf(rating).toString()); toadd.put("date", date.toString()); ratings.add(toadd); eMap.put("ratings", ratings); } // prepare the hash map for the update method HashMap<String, String> hm = new HashMap<String, String>(); hm.put("extras", eMap.toString()); hm.put("resources", resource); hm.put("tags", tArray.toJSONString()); hm.put("groups", gArray.toJSONString()); // update the meta data set HashMap<String, HashMap> res = CKANGatewayCore.updateDataSet(dataSetId, hm); boolean toreturn = (res != null); return toreturn; }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * We check this to reduce replay attacks. * /*from w ww. j a v a 2s . c o m*/ * @param timeStamp * @return true - if the request is not longer valid, false otherwise * @throws ParseException */ private boolean hasSignatureExpired(String timeStamp) { Calendar cal = EC2RestAuth.parseDateString(timeStamp); if (null == cal) return false; Date expiredTime = cal.getTime(); Date today = new Date(); // -> gets set to time of creation if (0 >= expiredTime.compareTo(today)) { logger.debug("timestamp given: [" + timeStamp + "], now: [" + today.toString() + "]"); return true; } else return false; }
From source file:mom.trd.opentheso.bdd.helper.GroupHelper.java
/** * Cette fonction permet de rcuprer l'historique d'un groupe une date * prcise// ww w .jav a 2 s . com * * @param ds * @param idConcept * @param idThesaurus * @param date * @return */ public ArrayList<NodeGroup> getGroupHistoriqueFromDate(HikariDataSource ds, String idConcept, String idThesaurus, Date date) { Connection conn; Statement stmt; ArrayList<NodeGroup> nodeGroupList = null; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "select idgroup, id_ark, idtypecode, idparentgroup, notation, modified, username from concept_group_historique, users " + "where idconcept = '" + idConcept + "'" + " and idthesaurus = '" + idThesaurus + "'" + " and concept_group_historique.id_user=users.id_user" + " and modified <= '" + date.toString() + "' order by modified DESC"; ResultSet resultSet = stmt.executeQuery(query); if (resultSet != null) { nodeGroupList = new ArrayList<>(); while (resultSet.next()) { NodeGroup nodeGroup = new NodeGroup(); nodeGroup.setIdUser(resultSet.getString("username")); nodeGroup.setModified(resultSet.getDate("modified")); nodeGroup.getConceptGroup().setId(resultSet.getInt("idgroup")); nodeGroup.getConceptGroup().setIdARk(resultSet.getString("id_ark")); nodeGroup.getConceptGroup().setIdthesaurus(idThesaurus); nodeGroup.getConceptGroup().setIdtypecode(resultSet.getString("idtypecode")); nodeGroup.getConceptGroup().setIdparentgroup(resultSet.getString("idparentgroup")); nodeGroup.getConceptGroup().setNotation(resultSet.getString("notation")); nodeGroup.getConceptGroup().setIdconcept(resultSet.getString("idconcept")); nodeGroupList.add(nodeGroup); } } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while getting date historique group of concept : " + idConcept, sqle); } return nodeGroupList; }
From source file:mom.trd.opentheso.bdd.helper.GroupHelper.java
/** * Cette fonction permet de rcuprer l'historique des traductions d'un * groupe une date prcise//from ww w.j a v a2s .co m * * @param ds * @param idGroup * @param idThesaurus * @param lang * @return */ public ArrayList<NodeGroup> getGroupTraductionsHistoriqueFromDate(HikariDataSource ds, String idGroup, String idThesaurus, String lang, Date date) { Connection conn; Statement stmt; ArrayList<NodeGroup> nodeGroupList = null; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "select lexicalvalue, modified, idgroup, username from concept_group_label_historique, users " + "where id = '" + idGroup + "'" + " and lang = '" + lang + "'" + " and idthesaurus = '" + idThesaurus + "'" + " and concept_group_label_historique.id_user=users.id_user" + " and modified <= '" + date.toString() + "' order by modified DESC"; ResultSet resultSet = stmt.executeQuery(query); if (resultSet != null) { nodeGroupList = new ArrayList<>(); while (resultSet.next()) { NodeGroup nodeGroup = new NodeGroup(); nodeGroup.getConceptGroup().setIdgroup(idGroup); nodeGroup.setIdUser(resultSet.getString("username")); nodeGroup.setModified(resultSet.getDate("modified")); nodeGroup.getConceptGroup().setId(resultSet.getInt("idgroup")); nodeGroup.getConceptGroup().setIdthesaurus(idThesaurus); nodeGroup.setLexicalValue(resultSet.getString("lexicalvalue")); nodeGroup.setIdLang(lang); nodeGroupList.add(nodeGroup); } } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while getting date traductions historique of group : " + idGroup, sqle); } return nodeGroupList; }
From source file:com.att.aro.diagnostics.GraphPanel.java
/** * Creating Alarm triggered data for graph plot */// ww w. j a v a2 s .com private static void populateAlarmPlot(XYPlot plot, TraceData.Analysis analysis) { final XYIntervalSeriesCollection alarmDataCollection = new XYIntervalSeriesCollection(); if (analysis != null) { // Remove old annotation from previous plots Iterator<XYPointerAnnotation> pointers = pointerAnnotation.iterator(); while (pointers.hasNext()) { plot.removeAnnotation(pointers.next()); } pointerAnnotation.clear(); final Map<AlarmType, XYIntervalSeries> seriesMap = new EnumMap<AlarmType, XYIntervalSeries>( AlarmType.class); for (AlarmType eventType : AlarmType.values()) { XYIntervalSeries series = new XYIntervalSeries(eventType); seriesMap.put(eventType, series); alarmDataCollection.addSeries(series); } final List<AlarmInfo> alarmInfos = analysis.getAlarmInfos(); final Map<Double, AlarmInfo> eventMap = new HashMap<Double, AlarmInfo>(); final Map<Double, ScheduledAlarmInfo> eventMapPending = new HashMap<Double, ScheduledAlarmInfo>(); List<ScheduledAlarmInfo> pendingAlarms = getHasFiredAlarms(analysis.getScheduledAlarms()); Iterator<ScheduledAlarmInfo> iterPendingAlarms = pendingAlarms.iterator(); double firedTime = 0; while (iterPendingAlarms.hasNext()) { ScheduledAlarmInfo scheduledEvent = iterPendingAlarms.next(); AlarmType pendingAlarmType = scheduledEvent.getAlarmType(); if (pendingAlarmType != null) { firedTime = (scheduledEvent.getTimeStamp() - scheduledEvent.getRepeatInterval()) / 1000; seriesMap.get(pendingAlarmType).add(firedTime, firedTime, firedTime, 1, 0.8, 1); eventMapPending.put(firedTime, scheduledEvent); logger.fine("populateAlarmScheduledPlot type:\n" + pendingAlarmType + "\ntime " + scheduledEvent.getTimeStamp() + "\nrepeating " + firedTime); } } Iterator<AlarmInfo> iter = alarmInfos.iterator(); while (iter.hasNext()) { AlarmInfo currEvent = iter.next(); if (currEvent != null) { AlarmType alarmType = currEvent.getAlarmType(); if (alarmType != null) { firedTime = currEvent.getTimeStamp() / 1000; /* * Catching any alarms align to quanta as being * inexactRepeating alarms */ if ((currEvent.getTimestampElapsed() / 1000) % 900 < 1) { seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.7); // Adding an arrow to mark these inexactRepeating alarms XYPointerAnnotation xypointerannotation = new XYPointerAnnotation(alarmType.name(), firedTime, 0.6, 3.92699082D); xypointerannotation.setBaseRadius(20D); xypointerannotation.setTipRadius(1D); pointerAnnotation.add(xypointerannotation); plot.addAnnotation(xypointerannotation); logger.info("SetInexactRepeating alarm type: " + alarmType + " time " + firedTime + " epoch " + currEvent.getTimestampEpoch() + " elapsed:\n" + currEvent.getTimestampElapsed() / 1000); } else { seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.5); } eventMap.put(firedTime, currEvent); } } } XYItemRenderer renderer = plot.getRenderer(); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC_WAKEUP), Color.red); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC), Color.pink); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME_WAKEUP), Color.blue); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME), Color.cyan); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.UNKNOWN), Color.black); // Assign ToolTip to renderer renderer.setBaseToolTipGenerator(new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { AlarmInfo info = eventMap.get(dataset.getX(series, item)); Date epochTime = new Date(); if (info != null) { epochTime.setTime((long) info.getTimestampEpoch()); StringBuffer displayInfo = new StringBuffer(rb.getString("alarm.tooltip.prefix")); displayInfo.append(MessageFormat.format(rb.getString("alarm.tooltip.content"), info.getAlarmType(), info.getTimeStamp() / 1000, epochTime.toString())); if ((info.getTimestampElapsed() / 1000) % 900 < 1) { displayInfo.append(rb.getString("alarm.tooltip.setInexactRepeating")); } displayInfo.append(rb.getString("alarm.tooltip.suffix")); return displayInfo.toString(); } ScheduledAlarmInfo infoPending = eventMapPending.get(dataset.getX(series, item)); if (infoPending != null) { epochTime.setTime( (long) (infoPending.getTimestampEpoch() - infoPending.getRepeatInterval())); StringBuffer displayInfo = new StringBuffer(rb.getString("alarm.tooltip.prefix")); displayInfo.append(MessageFormat.format(rb.getString("alarm.tooltip.contentWithName"), infoPending.getAlarmType(), (infoPending.getTimeStamp() - infoPending.getRepeatInterval()) / 1000, epochTime.toString(), infoPending.getApplication(), infoPending.getRepeatInterval() / 1000)); displayInfo.append(rb.getString("alarm.tooltip.suffix")); return displayInfo.toString(); } return null; } }); } plot.setDataset(alarmDataCollection); }
From source file:fr.gael.dhus.service.job.SendLogsJob.java
@Override protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { if (!configurationManager.getSendLogsCronConfiguration().isActive()) return;//from w w w .j a va 2 s .c o m long start = System.currentTimeMillis(); logger.info("SCHEDULER : Send Administrative logs."); if (!DHuS.isStarted()) { logger.warn("SCHEDULER : Not run while system not fully initialized."); return; } String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(","); // Case of no addresses available: use system support if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) { String email = configurationManager.getSupportConfiguration().getMail(); if ((email == null) || "".equals(email)) { throw new MailException("Support e-mail not configured, " + "system logs will not be send"); } addresses = new String[] { email }; } RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager .getRootLogger()).getAppenders().get("RollingFile"); if (rollingFileAppender == null) { throw new MailException("No rolling log file defined"); } String logPath = rollingFileAppender.getFileName(); if ((logPath == null) || logPath.trim().equals("")) { throw new MailException("Log file not defined"); } File logs = new File(logPath); if (!logs.exists()) { throw new MailException("Log file not present : " + logs.getPath()); } Date now = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-" + df.format(now); File zipLogs; try { zipLogs = File.createTempFile(docFilename, ".zip"); } catch (IOException e) { throw new MailException("Cannot create temporary zip log file.", e); } // compress logs file to zip format FileOutputStream fos; ZipOutputStream zos = null; FileInputStream fis = null; try { int length; byte[] buffer = new byte[1024]; ZipEntry entry = new ZipEntry(docFilename + ".txt"); fos = new FileOutputStream(zipLogs); zos = new ZipOutputStream(fos); fis = new FileInputStream(logs); zos.setLevel(Deflater.BEST_COMPRESSION); zos.putNextEntry(entry); while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } catch (IOException e) { throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e); } finally { try { if (fis != null) { fis.close(); } if (zos != null) { zos.closeEntry(); zos.close(); } } catch (IOException e) { throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e); } } EmailAttachment attachment = new EmailAttachment(); attachment.setDescription( configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString()); attachment.setPath(zipLogs.getPath()); attachment.setName(zipLogs.getName()); // Prepare the addresses List<String> ads = new ArrayList<String>(); for (String email : addresses) { StringTokenizer tk = new StringTokenizer(email, ", "); while (tk.hasMoreTokens()) { String token = tk.nextToken().trim(); if (!token.isEmpty()) ads.add(token); } } for (String email : ads) { try { String server = configurationManager.getServerConfiguration().getExternalHostname(); String url = configurationManager.getServerConfiguration().getExternalUrl(); mailServer.send(email, null, null, "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@" + server + "] logs of " + df.format(now), "Here is attached " + configurationManager.getNameConfiguration().getShortName() + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe " + configurationManager.getNameConfiguration().getShortName() + " Team.", attachment); logger.info("Logs Sent to " + email); } catch (EmailException e) { throw new MailException("Cannot send logs to " + email, e); } } if (!zipLogs.delete()) { logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath()); } logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms"); }
From source file:cms.service.app.ServiceController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, String> userdata; AccessToken access = null;// w w w . ja v a 2s.com AccessToken regaccess = null; RequestDispatcher rd; String strNextPage = null; boolean isvalidtoken = false; boolean subscription = false; String reguser = "registration"; String regpassword = "reg$56*123"; String baseurl = request.getRequestURL().toString().split("/service")[0]; String remotehost = request.getRemoteHost(); String remoteaddress = request.getRemoteAddr(); String username = request.getParameter("username"); String password = request.getParameter("password"); String useraction = request.getParameter("useraction"); String adminuser = request.getParameter("adminuser"); String usertoken = request.getParameter("usertoken"); String servicekey = request.getParameter("servicekey"); String amount = request.getParameter("amount"); String objid = request.getParameter("refobjid"); String description = request.getParameter("description"); String leadactions = "campaign whitepapers contactus training"; String sendreference = request.getParameter("sendreference"); ; Date date = new Date(); //set remote address request.setCharacterEncoding("UTF-8"); /*if(custom!=null&&!custom.equals("")){ custom="dan@softlean.com#-1624640437#127.0.0.1"; item_name="xyx"; item_number="899"; } subscription=(custom!=null&&!custom.equals(""))?true:false; logger.info(date.toString()+":-subscription="+subscription+" custom="+custom); if(subscription){ custret=custom.split("-"); if(custret.length==6) username=custret[3]; usertoken=custret[4]; tu.updatePayment(custret); } */ //first verify remote client whether the request is from same client if (!tu.isEmptyValue(servicekey)) { try { String val = new String(Base64Util.decode(servicekey.getBytes())); logger.info("servicekey=" + val); if (!tu.isEmptyValue(val)) { String[] items = val.split(CONST.IPSEPERATOR); if (items.length >= 2) { username = items[0]; password = items[1]; } if (items.length == 3) { useraction = items[2]; if (useraction.equalsIgnoreCase("campaign") && tu.isEmptyValue(sendreference)) { sendreference = "2"; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //logger.info("\n"+date.toString()+":-username="+username+ " password="+password+" useraction="+useraction); if (CONST.GENERATE_LOG) { logger.info("\n" + date.toString() + ":-URI=" + request.getRequestURI()); logger.info("\n" + date.toString() + ":-Request Remote address=" + remoteaddress + " Remote Host=" + remotehost); } //Identify the current page as login page if (!tu.isEmptyValue(username) && !tu.isEmptyValue(password)) { //Do not check license for hosting solution access = m_service.verifyLogin(username, password, remoteaddress); } else { regaccess = m_service.verifyLogin(reguser, regpassword, remoteaddress); } if (access != null && tu.isEmptyValue(useraction)) { logger.info("\n" + date.toString() + " Loged in User:=" + username + " " + ":-Assigned Token=" + access.getToken() + ":-Assigned Modules=" + access.getModules()); //access token is appended with Client IP in the indexpage strNextPage = "/src/index.jsp?username=" + username + "&firstname=" + access.getFirstname() + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + username + "&baseurl=" + baseurl + "&modules=" + access.getModules(); } else if (access != null && !tu.isEmptyValue(useraction) && leadactions.toLowerCase().contains(useraction.toLowerCase())) { strNextPage = "/src/campaign/" + useraction + ".jsp?username=" + username + "&firstname=" + access.getFirstname() + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + username + "&baseurl=" + baseurl + "&campaignid=" + objid + "&sendreference=" + sendreference; //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage); //}else if(access!=null && !tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("whitepapers")){ //strNextPage="/src/campaign/white_paper.jsp?username="+username+"&firstname="+access.getFirstname()+"&usertoken="+access.getToken()+CONST.IPSEPERATOR+remoteaddress+CONST.IPSEPERATOR+username+"&baseurl=" // +baseurl+"&campaignid="+objid; //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage); } else if (subscription) { userdata = m_service.verifyUserToken(usertoken); isvalidtoken = usertoken != null && !usertoken.equals("") && userdata != null; if (isvalidtoken) { strNextPage = "/src/index.jsp?username=" + username + "&usertoken=" + usertoken + "&baseurl=" + baseurl; } } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("missingpassword")) { strNextPage = "/src/password.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("demoregistration")) { strNextPage = "/src/demologin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(adminuser) && adminuser.equals("sa")) { strNextPage = "/src/admin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else if (!tu.isEmptyValue(amount) && !tu.isEmptyValue(objid)) { userdata = m_service.verifyUserToken(usertoken); if (userdata != null && !userdata.isEmpty()) { strNextPage = "/src/java_sim/payment.jsp?email=" + username + "&objid=" + objid + "&amount=" + amount + "&description=" + description; } } else if (regaccess != null) { strNextPage = "/src/login.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } else { strNextPage = "/src/error.jsp?token=null" + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl; } if (CONST.GENERATE_LOG) { logger.info("\n" + date.toString() + ":-Mapped Filename : " + strNextPage); } if (!strNextPage.equals("")) { rd = m_autoContext.getRequestDispatcher(strNextPage); // Forward the request to the target page try { if (rd != null) { rd.forward(request, response); } } catch (Exception e) { logger.info("ControllerServlet.doPost(): error in rd.forward"); e.printStackTrace(); } } else { // This should be logged. logger.info("Next Page is null"); super.doPost(request, response); } }
From source file:org.apache.slider.providers.agent.AgentProviderService.java
/** * Format the folder locations and publish in the registry service * * @param folders//from w ww . j a va 2 s. co m * @param containerId * @param hostFqdn * @param componentName */ protected void publishFolderPaths(Map<String, String> folders, String containerId, String componentName, String hostFqdn) { Date now = new Date(); for (Map.Entry<String, String> entry : folders.entrySet()) { ExportEntry exportEntry = new ExportEntry(); exportEntry.setValue(String.format(HOST_FOLDER_FORMAT, hostFqdn, entry.getValue())); exportEntry.setContainerId(containerId); exportEntry.setLevel(COMPONENT_TAG); exportEntry.setTag(componentName); exportEntry.setUpdatedTime(now.toString()); if (entry.getKey().equals("AGENT_LOG_ROOT")) { synchronized (logFolderExports) { getLogFolderExports().put(containerId, exportEntry); } } else { synchronized (workFolderExports) { getWorkFolderExports().put(containerId, exportEntry); } } log.info("Updating log and pwd folders for container {}", containerId); } PublishedExports exports = new PublishedExports(CONTAINER_LOGS_TAG); exports.setUpdated(now.getTime()); synchronized (logFolderExports) { updateExportsFromList(exports, getLogFolderExports()); } getAmState().getPublishedExportsSet().put(CONTAINER_LOGS_TAG, exports); exports = new PublishedExports(CONTAINER_PWDS_TAG); exports.setUpdated(now.getTime()); synchronized (workFolderExports) { updateExportsFromList(exports, getWorkFolderExports()); } getAmState().getPublishedExportsSet().put(CONTAINER_PWDS_TAG, exports); }
From source file:org.apache.manifoldcf.crawler.connectors.amazons3.AmazonS3Connector.java
@Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { AmazonS3 amazons3Client = getClient(); if (amazons3Client == null) throw new ManifoldCFException("Amazon client can not connect at the moment"); String[] acls = null;//from w w w. jav a 2 s. c om // loop documents and process for (String documentIdentifier : documentIdentifiers) { try { if (documentIdentifier != null && StringUtils.isNotEmpty(documentIdentifier)) { String versionString; String[] aclsToUse; if (documentIdentifier.split(STD_SEPARATOR_BUCKET_AND_KEY) == null && documentIdentifier.length() < 1) { continue; } S3Artifact s3Artifact = getS3Artifact(documentIdentifier); S3Object s3Obj = amazons3Client .getObject(new GetObjectRequest(s3Artifact.getBucketName(), s3Artifact.getKey())); if (s3Obj == null) { // no such document in the bucket now // delete document activities.deleteDocument(documentIdentifier); continue; } Logging.connectors.info("Content-Type: " + s3Obj.getObjectMetadata().getContentType()); ObjectMetadata objectMetadata = s3Obj.getObjectMetadata(); Date lastModified = objectMetadata.getLastModified(); StringBuilder sb = new StringBuilder(); if (lastModified == null) { // remove the content activities.deleteDocument(documentIdentifier); continue; } aclsToUse = new String[0]; AccessControlList objectAcl = amazons3Client.getObjectAcl(s3Artifact.getBucketName(), s3Artifact.getKey()); Set<Grant> grants = objectAcl.getGrants(); String[] users = getUsers(grants); // sort aclsToUse = users; Arrays.sort(aclsToUse); packList(sb, aclsToUse, '+'); if (aclsToUse.length > 0) { sb.append('+'); pack(sb, AmazonS3Config.defaultAuthorityDenyToken, '+'); } else sb.append('-'); // sb.append(lastModified.toString()); versionString = sb.toString(); Logging.connectors.debug("version string : " + versionString); if (versionString.length() > 0 && !activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) { Logging.connectors.info("Document need not to be reindexed : " + documentIdentifier); continue; } Logging.connectors.debug("JIRA: Processing document identifier '" + documentIdentifier + "'"); long startTime = System.currentTimeMillis(); String errorCode = null; String errorDesc = null; Long fileSize = null; try { String mimeType = "text/plain";// default // tika works starts InputStream in = null; String document = null; try { in = s3Obj.getObjectContent(); parser.parse(in, handler, metadata, context); mimeType = tika.detect(in); document = handler.toString(); if (document == null) continue; metadata.set(Metadata.CONTENT_TYPE, mimeType); } catch (Exception e) { Logging.connectors.error("Error while parsing tika contents", e); } finally { if (in != null) IOUtils.closeQuietly(in); } String documentURI = getDocumentURI(s3Artifact); Logging.connectors.debug("document : " + documentURI); // need some investigation if (!activities.checkURLIndexable(documentURI)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + documentURI + "')"; activities.noDocument(documentIdentifier, versionString); continue; } if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_MIMETYPE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(documentIdentifier, versionString); continue; } if (!activities.checkDateIndexable(lastModified)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + lastModified + ")"; activities.noDocument(documentIdentifier, versionString); continue; } // otherwise process RepositoryDocument rd = new RepositoryDocument(); // Turn into acls and add into // description String[] denyAclsToUse; if (aclsToUse.length > 0) denyAclsToUse = new String[] { AmazonS3Config.defaultAuthorityDenyToken }; else denyAclsToUse = new String[0]; rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT, aclsToUse, denyAclsToUse); rd.setMimeType(mimeType); if (lastModified != null) rd.setModifiedDate(lastModified); // set all meta-data fields addAllMetaData(rd, metadata); // get document try { byte[] documentBytes = document.getBytes(StandardCharsets.UTF_8); long fileLength = documentBytes.length; if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of document length (" + fileLength + ")"; activities.noDocument(documentIdentifier, versionString); continue; } InputStream is = new ByteArrayInputStream(documentBytes); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(documentIdentifier, versionString, documentURI, rd); errorCode = "OK"; fileSize = new Long(fileLength); } finally { if (is != null) IOUtils.closeQuietly(is); } } catch (Exception e) { Logging.connectors.error(e); } } catch (Exception e) { Logging.connectors.error(e); } } } catch (AmazonServiceException e) { Logging.connectors.error(e); } catch (AmazonClientException e) { Logging.connectors.error(e); } } }