List of usage examples for java.text ParseException getMessage
public String getMessage()
From source file:uk.ac.bbsrc.tgac.miso.core.manager.ERASubmissionManager.java
public String prettifySubmissionMetadata(Submission submission) throws SubmissionException { StringBuilder sb = new StringBuilder(); try {/*from w w w .j a va2s .co m*/ Collection<File> files = misoFileManager.getFiles(Submission.class, submission.getName()); Date latestDate = null; //get latest submitted xmls try { for (File f : files) { if (f.getName().contains("submission_")) { String d = f.getName().substring(f.getName().lastIndexOf("_") + 1, f.getName().lastIndexOf(".")); Date test = df.parse(d); if (latestDate == null || test.after(latestDate)) { latestDate = test; } } } } catch (ParseException e) { log.error("No timestamped submission metadata documents. Falling back to simple names: " + e.getMessage()); } String dateStr = ""; if (latestDate != null) { dateStr = "_" + df.format(latestDate); } InputStream in = null; for (File f : files) { if (f.getName().contains("submission" + dateStr)) { in = ERASubmissionManager.class.getResourceAsStream("/submission/xsl/eraSubmission.xsl"); if (in != null) { String xsl = LimsUtils.inputStreamToString(in); sb.append(SubmissionUtils.xslTransform(SubmissionUtils.transform(f, true), xsl)); } } } for (File f : files) { if (f.getName().contains("study" + dateStr)) { in = ERASubmissionManager.class.getResourceAsStream("/submission/xsl/eraStudy.xsl"); if (in != null) { String xsl = LimsUtils.inputStreamToString(in); sb.append(SubmissionUtils.xslTransform(SubmissionUtils.transform(f, true), xsl)); } } } for (File f : files) { if (f.getName().contains("sample" + dateStr)) { in = ERASubmissionManager.class.getResourceAsStream("/submission/xsl/eraSample.xsl"); if (in != null) { String xsl = LimsUtils.inputStreamToString(in); sb.append(SubmissionUtils.xslTransform(SubmissionUtils.transform(f, true), xsl)); } } } for (File f : files) { if (f.getName().contains("experiment" + dateStr)) { in = ERASubmissionManager.class.getResourceAsStream("/submission/xsl/eraExperiment.xsl"); if (in != null) { String xsl = LimsUtils.inputStreamToString(in); sb.append(SubmissionUtils.xslTransform(SubmissionUtils.transform(f, true), xsl)); } } } for (File f : files) { if (f.getName().contains("run" + dateStr)) { in = ERASubmissionManager.class.getResourceAsStream("/submission/xsl/eraRun.xsl"); if (in != null) { String xsl = LimsUtils.inputStreamToString(in); sb.append(SubmissionUtils.xslTransform(SubmissionUtils.transform(f, true), xsl)); } } } } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return sb.toString(); }
From source file:com.hp.mqm.atrf.App.java
private List<TestRunResultEntity> prepareRunsForInjection(int bulkId, List<Run> runs) { List<TestRunResultEntity> list = new ArrayList<>(); List<String> skippedRunIds = new ArrayList<>(); for (Run run : runs) { //preparation Test test = almWrapper.getTest(run.getTestId()); TestFolder testFolder = almWrapper.getTestFolder(test.getTestFolderId()); TestSet testSet = almWrapper.getTestSet(run.getTestSetId()); TestConfiguration testConfiguration = almWrapper.getTestConfiguration(run.getTestConfigId()); if (testSet == null) { //testSet was deleted skippedRunIds.add(run.getId()); continue; }//ww w .ja v a 2 s . c om TestRunResultEntity injectionEntity = new TestRunResultEntity(); injectionEntity.setRunId(run.getId()); //TEST FIELDS //test name + test configuration, if Test name =Test configuration, just keep test name String testName = String.format("AlmTestId #%s : %s", test.getId(), sanitizeForXml(test.getName())); if (!testConfiguration.getName().equals(test.getName())) { testName = String.format("AlmTestId #%s, ConfId #%s : %s - %s", test.getId(), testConfiguration.getId(), sanitizeForXml(test.getName()), sanitizeForXml(testConfiguration.getName())); } injectionEntity.setTestName(restrictTo255(testName)); injectionEntity.setTestingToolType(alm2OctaneTestingToolMapper.get(test.getSubType())); injectionEntity.setPackageValue(almWrapper.getProject()); injectionEntity.setModule(almWrapper.getDomain()); injectionEntity.setClassValue(restrictTo255(sanitizeForXml(testFolder.getName()))); //RUN FIELDS injectionEntity.setDuration(run.getDuration()); injectionEntity.setRunName(restrictTo255( String.format("AlmTestSet #%s : %s", testSet.getId(), sanitizeForXml(testSet.getName())))); injectionEntity.setExternalReportUrl(almWrapper.generateALMReferenceURL(run)); Date startedDate = null; try { startedDate = DATE_TIME_FORMAT.parse(run.getExecutionDate() + " " + run.getExecutionTime()); } catch (ParseException e) { try { startedDate = DATE_FORMAT.parse(run.getExecutionDate()); } catch (ParseException e1) { throw new RuntimeException( String.format("Failed to convert run execution date '%s' to Java Date : %s", run.getExecutionDate(), e1.getMessage())); } } injectionEntity.setStartedTime(Long.toString(startedDate.getTime())); String status = OCTANE_RUN_VALID_STATUS.contains(run.getStatus()) ? run.getStatus() : OCTANE_RUN_SKIPPED_STATUS; injectionEntity.setStatus(status); injectionEntity.validateEntity(); list.add(injectionEntity); } if (!skippedRunIds.isEmpty()) { List subList = skippedRunIds; int showCount = 20; String firstNMessage = ""; if (skippedRunIds.size() > showCount) { subList = skippedRunIds.subList(0, showCount); firstNMessage = String.format(", first %s runs are", showCount); } logger.info(String.format("Bulk #%s : %s runs are skipped as their testsets are deleted %s : %s", bulkId, skippedRunIds.size(), firstNMessage, StringUtils.join(subList, ","))); } return list; }
From source file:br.org.funcate.dynamicforms.FragmentDetail.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.details, container, false); LinearLayout mainView = (LinearLayout) view.findViewById(R.id.form_linear); FragmentDetailActivity fragmentDetailActivity; try {// ww w . j a v a 2s .c o m FragmentActivity activity = getActivity(); if (selectedFormName == null || sectionObject == null) { FragmentList fragmentList = (FragmentList) getFragmentManager().findFragmentById(R.id.listFragment); if (fragmentList != null) { selectedFormName = fragmentList.getSelectedItemName(); sectionObject = fragmentList.getSectionObject(); noteId = fragmentList.getNoteId(); } else { if (activity instanceof FragmentDetailActivity) { // case of portrait mode fragmentDetailActivity = (FragmentDetailActivity) activity; selectedFormName = fragmentDetailActivity.getFormName(); sectionObject = fragmentDetailActivity.getSectionObject(); noteId = fragmentDetailActivity.getNoteId(); workingDirectory = fragmentDetailActivity.getWorkingDirectory(); existingFeatureData = fragmentDetailActivity.getFeatureData(); } } } if (selectedFormName != null) { JSONObject formObject = TagsManager.getForm4Name(selectedFormName, sectionObject); key2WidgetMap.clear(); requestCodes2WidgetMap.clear(); int requestCode = 666; keyList.clear(); key2ConstraintsMap.clear(); if (formObject != null) {// Test to get form configuration to this layer JSONArray formItemsArray = TagsManager.getFormItems(formObject); int length = ((formItemsArray != null) ? (formItemsArray.length()) : (0)); for (int i = 0; i < length; i++) { JSONObject jsonObject = formItemsArray.getJSONObject(i); String key = "-"; //$NON-NLS-1$ if (jsonObject.has(TAG_KEY)) key = jsonObject.getString(TAG_KEY).trim(); String label = key; if (jsonObject.has(TAG_LABEL)) label = jsonObject.getString(TAG_LABEL).trim(); String type = FormUtilities.TYPE_STRING; if (jsonObject.has(TAG_TYPE)) { type = jsonObject.getString(TAG_TYPE).trim(); } boolean readonly = false; if (jsonObject.has(TAG_READONLY)) { String readonlyStr = jsonObject.getString(TAG_READONLY).trim(); readonly = Boolean.parseBoolean(readonlyStr); } // if attribute has a non printable char, force readonly mode. if (Utilities.existUnprintableCharacters(key)) { readonly = true; } Constraints constraints = new Constraints(); FormUtilities.handleConstraints(jsonObject, constraints); key2ConstraintsMap.put(key, constraints); String constraintDescription = constraints.getDescription(); Object o; GView addedView = null; if (type.equals(TYPE_STRING)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addEditText(activity, mainView, label, value, 0, 0, constraintDescription, readonly); } else if (type.equals(TYPE_STRINGAREA)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addEditText(activity, mainView, label, value, 0, 7, constraintDescription, readonly); } else if (type.equals(TYPE_DOUBLE)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addEditText(activity, mainView, label, value, 1, 0, constraintDescription, readonly); } else if (type.equals(TYPE_INTEGER)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addEditText(activity, mainView, label, value, 4, 0, constraintDescription, readonly); } else if (type.equals(TYPE_DATE)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addDateView(FragmentDetail.this, mainView, label, value, constraintDescription, readonly); } else if (type.equals(TYPE_TIME)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addTimeView(FragmentDetail.this, mainView, label, value, constraintDescription, readonly); } else if (type.equals(TYPE_LABEL)) { String size = "20"; //$NON-NLS-1$ if (jsonObject.has(TAG_SIZE)) size = jsonObject.getString(TAG_SIZE); String url = null; if (jsonObject.has(TAG_URL)) url = jsonObject.getString(TAG_URL); o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addTextView(activity, mainView, value, size, false, url); } else if (type.equals(TYPE_LABELWITHLINE)) { String size = "20"; //$NON-NLS-1$ if (jsonObject.has(TAG_SIZE)) size = jsonObject.getString(TAG_SIZE); String url = null; if (jsonObject.has(TAG_URL)) url = jsonObject.getString(TAG_URL); o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addTextView(activity, mainView, value, size, true, url); } else if (type.equals(TYPE_BOOLEAN)) { o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addBooleanView(activity, mainView, label, value, constraintDescription, readonly); } else if (type.equals(TYPE_STRINGCOMBO)) { JSONArray comboItems = TagsManager.getComboItems(jsonObject); String[] itemsArray = TagsManager.comboItems2StringArray(comboItems); o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addComboView(activity, mainView, label, value, itemsArray, constraintDescription); } else if (type.equals(TYPE_CONNECTEDSTRINGCOMBO)) { LinkedHashMap<String, List<String>> valuesMap = TagsManager .extractComboValuesMap(jsonObject); o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addConnectedComboView(activity, mainView, label, value, valuesMap, constraintDescription); } else if (type.equals(TYPE_STRINGMULTIPLECHOICE)) { JSONArray comboItems = TagsManager.getComboItems(jsonObject); String[] itemsArray = TagsManager.comboItems2StringArray(comboItems); o = getValueFromExtras(jsonObject, key); String value = ((String) o).trim(); addedView = FormUtilities.addMultiSelectionView(activity, mainView, label, value, itemsArray, constraintDescription); } else if (type.equals(TYPE_PICTURES)) { o = getValueFromExtras(jsonObject, FormUtilities.IMAGE_MAP); Map<String, Map<String, String>> value = null; String clazz = o.getClass().getSimpleName(); if (("bundle").equalsIgnoreCase(clazz)) { Bundle imageMapBundle = (Bundle) o; Bundle imageMapThumbnailBundle = imageMapBundle.getBundle("thumbnail"); Bundle imageMapDisplayBundle = imageMapBundle.getBundle("display"); if (imageMapThumbnailBundle != null && imageMapDisplayBundle != null) { Set<String> keys = imageMapThumbnailBundle.keySet(); Iterator<String> itKeys = keys.iterator(); if (keys.size() > 0) { value = new HashMap<String, Map<String, String>>(keys.size()); while (itKeys.hasNext()) { String keyMap = itKeys.next(); Map<String, String> imagePaths = new HashMap<String, String>(2); imagePaths.put("thumbnail", (String) imageMapThumbnailBundle.get(keyMap)); imagePaths.put("display", (String) imageMapDisplayBundle.get(keyMap)); value.put(keyMap, imagePaths); } } } } addedView = FormUtilities.addPictureView(this, requestCode, mainView, label, value, constraintDescription); } /*else if (type.equals(TYPE_SKETCH)) { addedView = FormUtilities.addSketchView(noteId, this, requestCode, mainView, label, value, constraintDescription); } */ else { Toast.makeText(getActivity().getApplicationContext(), "Type non implemented yet: " + type, Toast.LENGTH_LONG).show(); } /* } else if (type.equals(TYPE_MAP)) { if (value.length() <= 0) { // need to read image File tempDir = ResourcesManager.getInstance(activity).getTempDir(); File tmpImage = new File(tempDir, LibraryConstants.TMPPNGIMAGENAME); if (tmpImage.exists()) { byte[][] imageAndThumbnailFromPath = ImageUtilities.getImageAndThumbnailFromPath(tmpImage.getAbsolutePath(), 1); Date date = new Date(); String mapImageName = ImageUtilities.getMapImageName(date); IImagesDbHelper imageHelper = DefaultHelperClasses.getDefaulfImageHelper(); long imageId = imageHelper.addImage(longitude, latitude, -1.0, -1.0, date.getTime(), mapImageName, imageAndThumbnailFromPath[0], imageAndThumbnailFromPath[1], noteId); value = "" + imageId; } } addedView = FormUtilities.addMapView(activity, mainView, label, value, constraintDescription); } else if (type.equals(TYPE_NFCUID)) { addedView = new GNfcUidView(this, null, requestCode, mainView, label, value, constraintDescription); } else { GPLog.addLogEntry(this, null, null, "Type non implemented yet: " + type); }*/ key2WidgetMap.put(key, addedView); keyList.add(key); requestCodes2WidgetMap.put(requestCode, addedView); requestCode++; } // end of the form items loop } else { String size = "20"; //$NON-NLS-1$ String url = null; String value = getResources().getString(R.string.error_while_loading_form_configuration); GView addedView = FormUtilities.addTextView(activity, mainView, value, size, true, url); String key = "-"; //$NON-NLS-1$ key2WidgetMap.put(key, addedView); keyList.add(key); requestCodes2WidgetMap.put(requestCode, addedView); } LinearLayout btnLinear = (LinearLayout) mainView.findViewById(R.id.btn_linear); if (keyList.size() == 1) { Button btnSave = (Button) btnLinear.findViewById(R.id.saveButton); btnSave.setEnabled(false); } mainView.removeView(btnLinear); mainView.addView(btnLinear); } } catch (ParseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } return view; }
From source file:org.apache.openaz.xacml.std.json.JSONResponse.java
/** * When reading a JSON string to create a Result object, parse the PolicyIdReference and * PolicySetIdReference texts./*from w ww .j a v a 2s . c o m*/ * * @param policyIdReferenceObject * @param stdMutableResult * @param isSet */ private static void parseIdReferences(Object policyIdReferenceObject, StdMutableResult stdMutableResult, boolean isSet) throws JSONStructureException { String idTypeName = isSet ? "PolicySetIdReference" : "PolicyIdReference"; if (!(policyIdReferenceObject instanceof List)) { throw new JSONStructureException(idTypeName + " must be array"); } List<?> policyIdReferenceList = (List<?>) policyIdReferenceObject; for (Object idReferenceObject : policyIdReferenceList) { if (idReferenceObject == null || !(idReferenceObject instanceof Map)) { throw new JSONStructureException(idTypeName + " array item must be non-null object"); } Map<?, ?> idReferenceMap = (Map<?, ?>) idReferenceObject; // mandatory Id Object idReferenceIdObject = idReferenceMap.remove("Id"); if (idReferenceIdObject == null) { throw new JSONStructureException(idTypeName + " array item must contain Id"); } Identifier idReferenceId = new IdentifierImpl(idReferenceIdObject.toString()); // optional Version StdVersion version = null; Object idReferenceVersionObject = idReferenceMap.remove("Version"); if (idReferenceVersionObject != null) { try { version = StdVersion.newInstance(idReferenceVersionObject.toString()); } catch (ParseException e) { throw new JSONStructureException(idTypeName + " array item Version: " + e.getMessage()); } } checkUnknown("IdReference in " + idTypeName, idReferenceMap); StdIdReference policyIdentifier = new StdIdReference(idReferenceId, version); // add to the appropriate list in the Result if (isSet) { stdMutableResult.addPolicySetIdentifier(policyIdentifier); } else { stdMutableResult.addPolicyIdentifier(policyIdentifier); } } }
From source file:com.neusoft.mid.clwapi.service.statistics.StatisticsServiceImpl.java
/** * ??./*www . j a v a 2 s .co m*/ * * @param token * ?. * @param month * ,?yyyymm * @return ??. */ @Override public Response getEntiReport(String token, String month) { month = StringUtils.strip(month); String epid = context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID); logger.info("?-?ID:" + epid + "," + month); Date reportMonth; try { reportMonth = TimeUtil.parseStringToDate(month, HttpConstant.MONTH_FORMAT); } catch (ParseException e) { logger.error("?-yyyyMM?" + e.getMessage()); throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST); } if (reportMonth.after(TimeUtil.getLastMonthD())) { logger.info("?-??" + month + "?"); throw new ApplicationException(ErrorConstant.ERROR10004, Response.Status.BAD_REQUEST); } if (CheckRequestParam.isEmpty(epid)) { logger.info("?--?ID"); throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR); } List<EpMonthData> infos = stMapper.getEpMonthData(month, epid); if (CheckRequestParam.isEmpty(infos)) { logger.info("?-?ID:" + epid + "???"); return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store") .header("Pragma", "no-cache").build(); } EpStatReport resp = convertEpResp(infos, reportMonth); if (CheckRequestParam.isEmpty(resp)) { logger.info("?-?ID:" + epid + "???"); return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store") .header("Pragma", "no-cache").build(); } return Response.ok(JacksonUtils.toJsonRuntimeException(resp)).header(HttpHeaders.CACHE_CONTROL, "no-store") .header("Pragma", "no-cache").build(); }
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) { PrintWriter out = null;//w ww . j ava 2 s . com try { out = resp.getWriter(); } catch (IOException e1) { log.log(Level.SEVERE, "Cannot get an output PrintWriter!"); } try { boolean isDevInstance = isDevInstance(req); ServletFileUpload fileUploadTool = new ServletFileUpload(); fileUploadTool.setSizeMax(50000); resp.setContentType("text/html;charset=UTF-8"); FileItemIterator iterator = fileUploadTool.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = null; try { in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); String fileContents = null; fileContents = IOUtils.toString(in); out.println("length: " + fileContents.length()); out.println(fileContents); saveCSV(fileContents, isDevInstance); } } catch (ParseException e) { log.info("Parse Exception: " + e.getMessage()); out.println("Could not parse your csv upload: " + e.getMessage()); } finally { in.close(); } } } catch (SizeLimitExceededException e) { log.info("SizeLimitExceededException: " + e.getMessage()); out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); return; } catch (IOException e) { log.severe("IOException: " + e.getMessage()); out.println("Error in receiving file."); } catch (FileUploadException e) { log.severe("FileUploadException: " + e.getMessage()); out.println("Error in receiving file."); } }
From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java
/** * load saved timestamp file (if available) * @param oldestDate /*from w w w . java 2 s. c o m*/ * @throws IOException */ private Map<String, Date> loadTimestamp(File f, Date defaultDate) { Map<String, Date> result = new HashMap<String, Date>(); if (f.exists() && f.canRead()) { @SuppressWarnings("resource") BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); String line = null; SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT); while ((line = br.readLine()) != null) { String[] ss = line.split("="); if (ss.length != 2) { LOG.warn("Don't understand line [" + line + "]"); continue; } try { result.put(ss[0], df.parse(ss[1])); } catch (ParseException e) { LOG.warn("Unable to parse date [" + ss[1] + "]"); continue; } } } catch (IOException e) { LOG.error("Error loading user timestamps from " + f.getAbsolutePath() + ": " + e.getMessage(), e); } finally { close(br); } } // fill with defaults for (String user : this.users) { if (!result.containsKey(user)) { result.put(user, defaultDate); } } // log for (Map.Entry<String, Date> me : result.entrySet()) { LOG.info(me.getKey() + "=" + me.getValue()); } return result; }
From source file:com.neusoft.mid.clwapi.service.statistics.StatisticsServiceImpl.java
/** * ??.// w w w . j av a2 s . c o m * * @param token * ?. * @param month * ,?yyyymm * @param rsType * ?,01- ;02- ?;03- * * @return ??. */ @Override public Response getEntiReportDetail(String token, String month, String rsType) { month = StringUtils.strip(month); rsType = StringUtils.strip(rsType); String epid = context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID); String orgID = context.getHttpHeaders().getHeaderString(UserInfoKey.ORGANIZATION_ID); logger.info("?-?ID:" + epid + ",ID" + orgID + "," + month + "," + rsType); Date reportMonth; try { reportMonth = TimeUtil.parseStringToDate(month, HttpConstant.MONTH_FORMAT); } catch (ParseException e) { logger.error("?-yyyyMM?" + e.getMessage()); throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST); } if (reportMonth.after(TimeUtil.getLastMonthD())) { logger.info("?-??" + month + "?"); throw new ApplicationException(ErrorConstant.ERROR10004, Response.Status.BAD_REQUEST); } if (!HttpConstant.REPORT_QY_D_SPEED.equals(rsType) && !HttpConstant.REPORT_QY_D_BAD.equals(rsType) && !HttpConstant.REPORT_QY_D_OIL.equals(rsType)) { logger.info("?-?" + rsType + "?[01,02,03]"); throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST); } if (CheckRequestParam.isEmpty(epid) || CheckRequestParam.isEmpty(orgID)) { logger.info("?--?IDID"); throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR); } List<EpCarDtl> infos = stMapper.getCarMonthDtl(month, epid, rsType, orgID); if (CheckRequestParam.isEmpty(infos)) { logger.info("?-?ID:" + epid + "ID:" + orgID + "" + month + "" + rsType + "?"); return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store") .header("Pragma", "no-cache").build(); } EpDtlResp result = new EpDtlResp(); result.setDetailInfo(infos); return Response.ok(JacksonUtils.toJsonRuntimeException(result)) .header(HttpHeaders.CACHE_CONTROL, "no-store").header("Pragma", "no-cache").build(); }
From source file:net.sourceforge.fenixedu.presentationTier.backBeans.coordinator.evaluation.CoordinatorEvaluationsBackingBean.java
public String editWrittenTest() throws FenixServiceException { final ExecutionCourse executionCourse = getExecutionCourse(); final List<String> executionCourseIDs = new ArrayList<String>(1); executionCourseIDs.add(this.getExecutionCourseID().toString()); final List<String> degreeModuleScopeIDs = getDegreeModuleScopeIDs(executionCourse); try {/*from w ww. ja va 2s .c o m*/ EditWrittenEvaluation.runEditWrittenEvaluation(executionCourse.getExternalId(), DateFormatUtil.parse("dd/MM/yyyy", getDate()), DateFormatUtil.parse("HH:mm", getBeginTime()), DateFormatUtil.parse("HH:mm", getEndTime()), executionCourseIDs, degreeModuleScopeIDs, null, getEvaluationID(), null, getDescription(), null); } catch (ParseException ex) { setErrorMessage("error.invalid.date"); return "viewEditPage"; } catch (NotAuthorizedException ex) { setErrorMessage(ex.getMessage()); return "viewEditPage"; } return "viewCalendar"; }
From source file:org.apache.nutch.tools.CommonCrawlDataDumper.java
/** * Dumps the reverse engineered CBOR content from the provided segment * directories if a parent directory contains more than one segment, * otherwise a single segment can be passed as an argument. If the boolean * argument is provided then the CBOR is also zipped. * * @param outputDir the directory you wish to dump the raw content to. This * directory will be created. * @param segmentRootDir a directory containing one or more segments. * @param linkdb Path to linkdb. * @param gzip a boolean flag indicating whether the CBOR content should also * be gzipped.//from w ww .ja va 2s. c om * @param epochFilename if {@code true}, output files will be names using the epoch time (in milliseconds). * @param extension a file extension to use with output documents. * @throws Exception if any exception occurs. */ public void dump(File outputDir, File segmentRootDir, File linkdb, boolean gzip, String[] mimeTypes, boolean epochFilename, String extension, boolean warc) throws Exception { if (gzip) { LOG.info("Gzipping CBOR data has been skipped"); } // total file counts Map<String, Integer> typeCounts = new HashMap<>(); // filtered file counters Map<String, Integer> filteredCounts = new HashMap<>(); Configuration nutchConfig = NutchConfiguration.create(); Path segmentRootPath = new Path(segmentRootDir.toString()); FileSystem fs = segmentRootPath.getFileSystem(nutchConfig); //get all paths List<Path> parts = new ArrayList<>(); RemoteIterator<LocatedFileStatus> files = fs.listFiles(segmentRootPath, true); String partPattern = ".*" + File.separator + Content.DIR_NAME + File.separator + "part-[0-9]{5}" + File.separator + "data"; while (files.hasNext()) { LocatedFileStatus next = files.next(); if (next.isFile()) { Path path = next.getPath(); if (path.toString().matches(partPattern)) { parts.add(path); } } } LinkDbReader linkDbReader = null; if (linkdb != null) { linkDbReader = new LinkDbReader(nutchConfig, new Path(linkdb.toString())); } if (parts == null || parts.size() == 0) { LOG.error("No segment directories found in {} ", segmentRootDir.getAbsolutePath()); System.exit(1); } LOG.info("Found {} segment parts", parts.size()); if (gzip && !warc) { fileList = new ArrayList<>(); constructNewStream(outputDir); } for (Path segmentPart : parts) { LOG.info("Processing segment Part : [ {} ]", segmentPart); try { SequenceFile.Reader reader = new SequenceFile.Reader(nutchConfig, SequenceFile.Reader.file(segmentPart)); Writable key = (Writable) reader.getKeyClass().newInstance(); Content content = null; while (reader.next(key)) { content = new Content(); reader.getCurrentValue(content); Metadata metadata = content.getMetadata(); String url = key.toString(); String baseName = FilenameUtils.getBaseName(url); String extensionName = FilenameUtils.getExtension(url); if (!extension.isEmpty()) { extensionName = extension; } else if ((extensionName == null) || extensionName.isEmpty()) { extensionName = "html"; } String outputFullPath = null; String outputRelativePath = null; String filename = null; String timestamp = null; String reverseKey = null; if (epochFilename || config.getReverseKey()) { try { long epoch = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z") .parse(getDate(metadata.get("Date"))).getTime(); timestamp = String.valueOf(epoch); } catch (ParseException pe) { LOG.warn(pe.getMessage()); } reverseKey = reverseUrl(url); config.setReverseKeyValue( reverseKey.replace("/", "_") + "_" + DigestUtils.sha1Hex(url) + "_" + timestamp); } if (!warc) { if (epochFilename) { outputFullPath = DumpFileUtil.createFileNameFromUrl(outputDir.getAbsolutePath(), reverseKey, url, timestamp, extensionName, !gzip); outputRelativePath = outputFullPath.substring(0, outputFullPath.lastIndexOf(File.separator) - 1); filename = content.getMetadata().get(Metadata.DATE) + "." + extensionName; } else { String md5Ofurl = DumpFileUtil.getUrlMD5(url); String fullDir = DumpFileUtil.createTwoLevelsDirectory(outputDir.getAbsolutePath(), md5Ofurl, !gzip); filename = DumpFileUtil.createFileName(md5Ofurl, baseName, extensionName); outputFullPath = String.format("%s/%s", fullDir, filename); String[] fullPathLevels = fullDir.split(Pattern.quote(File.separator)); String firstLevelDirName = fullPathLevels[fullPathLevels.length - 2]; String secondLevelDirName = fullPathLevels[fullPathLevels.length - 1]; outputRelativePath = firstLevelDirName + secondLevelDirName; } } // Encode all filetypes if no mimetypes have been given Boolean filter = (mimeTypes == null); String jsonData = ""; try { String mimeType = new Tika().detect(content.getContent()); // Maps file to JSON-based structure Set<String> inUrls = null; //there may be duplicates, so using set if (linkDbReader != null) { Inlinks inlinks = linkDbReader.getInlinks((Text) key); if (inlinks != null) { Iterator<Inlink> iterator = inlinks.iterator(); inUrls = new LinkedHashSet<>(); while (inUrls.size() <= MAX_INLINKS && iterator.hasNext()) { inUrls.add(iterator.next().getFromUrl()); } } } //TODO: Make this Jackson Format implementation reusable try (CommonCrawlFormat format = CommonCrawlFormatFactory .getCommonCrawlFormat(warc ? "WARC" : "JACKSON", nutchConfig, config)) { if (inUrls != null) { format.setInLinks(new ArrayList<>(inUrls)); } jsonData = format.getJsonData(url, content, metadata); } collectStats(typeCounts, mimeType); // collects statistics for the given mimetypes if ((mimeType != null) && (mimeTypes != null) && Arrays.asList(mimeTypes).contains(mimeType)) { collectStats(filteredCounts, mimeType); filter = true; } } catch (IOException ioe) { LOG.error("Fatal error in creating JSON data: " + ioe.getMessage()); return; } if (!warc) { if (filter) { byte[] byteData = serializeCBORData(jsonData); if (!gzip) { File outputFile = new File(outputFullPath); if (outputFile.exists()) { LOG.info("Skipping writing: [" + outputFullPath + "]: file already exists"); } else { LOG.info("Writing: [" + outputFullPath + "]"); IOUtils.copy(new ByteArrayInputStream(byteData), new FileOutputStream(outputFile)); } } else { if (fileList.contains(outputFullPath)) { LOG.info("Skipping compressing: [" + outputFullPath + "]: file already exists"); } else { fileList.add(outputFullPath); LOG.info("Compressing: [" + outputFullPath + "]"); //TarArchiveEntry tarEntry = new TarArchiveEntry(firstLevelDirName + File.separator + secondLevelDirName + File.separator + filename); TarArchiveEntry tarEntry = new TarArchiveEntry( outputRelativePath + File.separator + filename); tarEntry.setSize(byteData.length); tarOutput.putArchiveEntry(tarEntry); tarOutput.write(byteData); tarOutput.closeArchiveEntry(); } } } } } reader.close(); } catch (Exception e) { LOG.warn("SKIPPED: {} Because : {}", segmentPart, e.getMessage()); } finally { fs.close(); } } if (gzip && !warc) { closeStream(); } if (!typeCounts.isEmpty()) { LOG.info("CommonsCrawlDataDumper File Stats: " + DumpFileUtil.displayFileTypes(typeCounts, filteredCounts)); } }