List of usage examples for java.text ParseException ParseException
public ParseException(String s, int errorOffset)
From source file:org.sakaiproject.tool.app.scheduler.SchedulerTool.java
public void validateTriggerExpression(FacesContext context, UIComponent component, Object value) { if (value != null) { try {//from w w w .j a va 2 s . c o m String expression = (String) value; CronTrigger trigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule(expression)).build(); // additional checks // quartz does not check for more than 7 tokens in expression String[] arr = expression.split("\\s"); if (arr.length > 7) { throw new RuntimeException(new ParseException("Expression has more than 7 tokens", 7)); } //(check that last 2 entries are not both * or ? String trimmed_expression = expression.replaceAll("\\s", ""); // remove whitespace if (trimmed_expression.endsWith(CRON_CHECK_ASTERISK) || trimmed_expression.endsWith(CRON_CHECK_QUESTION_MARK)) { throw new RuntimeException(new ParseException("Cannot End in * * or ? ?", 1)); } } catch (RuntimeException e) { // not giving a detailed message to prevent line wraps FacesMessage message = new FacesMessage(rb.getString("parse_exception")); message.setSeverity(FacesMessage.SEVERITY_WARN); throw new ValidatorException(message); } } }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * // w w w . ja v a 2 s . com * @param value * @return * @throws ParseException */ public Date asDate(String value) throws ParseException { SimpleDateFormat format = null; for (String pattern : SUPPORTED_DATE_FORMATS) { format = new SimpleDateFormat(pattern); try { return format.parse(value); } catch (ParseException pe) { } } throw new ParseException("Unknown date format!", -1); }
From source file:gov.usda.DataCatalogClient.Dataset.java
/** * bureau code must be in the following format 000:00 or NNN:NN. This validates. * This method is used from CKAN string. * @param bureauCode//from w w w .j ava 2s. c o m */ public void setBureauCodeList(String bureauCode) throws ParseException { if (!bureauCodeList.contains(bureauCode)) { if (Pattern.matches("\\d{3}:\\d{2}", bureauCode)) { bureauCodeList.add(bureauCode); } else { throw new ParseException("Bureau Code must be \\d{3}:\\d{2}: " + bureauCode, 2); } } }
From source file:edu.hawaii.soest.kilonalu.ctd.CTDParser.java
public void parse() throws ParseException { logger.debug("CTDParser.parse() called."); if (!this.metadataAndDataString.equals("")) { // create the two sections String[] sections = this.metadataAndDataString.split(this.metadataDelimiter); String[] nameValueArray = { "", "" }; //used later for splitting name/value pairs if (sections.length > 1) { this.metadataString = sections[0]; this.observationsString = sections[1]; // tokenize the legacy DS/Dcal metadata into lines StringTokenizer lineTokenizer = new StringTokenizer(this.metadataString, this.recordDelimiter); while (lineTokenizer.hasMoreTokens()) { String line = lineTokenizer.nextToken(); StringTokenizer fieldTokenizer = new StringTokenizer(line, this.METADATA_FIELD_DELIMITER); // tokenize the lines into field pairs while (fieldTokenizer.hasMoreTokens()) { // remove leading "*" characters and trim whitespace String nameValuePair = fieldTokenizer.nextToken().replaceAll("^\\**", "").trim(); // check for pairs delimited by a colon if (nameValuePair.indexOf(this.PRIMARY_PAIR_DELIMITER) > 0) { nameValueArray = nameValuePair.split(this.PRIMARY_PAIR_DELIMITER, 2); // add the pair to the metadata map if (nameValueArray.length > 1) { this.metadataValuesMap.put(nameValueArray[0].trim(), nameValueArray[1].trim()); // otherwise add an empty pair to the metadata map } else { this.metadataValuesMap.put(nameValueArray[0].trim(), ""); }/* ww w.j a v a 2 s.c o m*/ // check for pairs delimited by an equals sign } else if (nameValuePair.indexOf(this.SECONDARY_PAIR_DELIMITER) > 0) { nameValueArray = nameValuePair.split(this.SECONDARY_PAIR_DELIMITER, 2); // add the pair to the metadata map if (nameValueArray.length > 1) { this.metadataValuesMap.put(nameValueArray[0].trim(), nameValueArray[1].trim()); // otherwise add an empty pair to the metadata map } else { this.metadataValuesMap.put(nameValueArray[0].trim(), ""); } // otherwise add an empty pair to the metadata map } else { this.metadataValuesMap.put(nameValuePair.trim(), ""); } //if } //while } //while StringTokenizer dataTokenizer = new StringTokenizer(this.observationsString, this.recordDelimiter); // tokenize the lines into observations strings, place them in sequential // order into the dataValuesMap while (dataTokenizer.hasMoreTokens()) { String dataLine = dataTokenizer.nextToken(); //logger.debug("|" + dataLine + "|"); this.dataValuesMap.put(dataValuesMap.size() + 1, dataLine); } } else { throw new ParseException("Parsing of the CTD data input failed. The header " + "and data sections do not appear to be delimited " + "correctly. Please be sure that the output of the" + "'DS' and 'DCAL' commands are followed by " + "'*END*\\r\\n' and then the data observation lines.", 0); } //end if (sections.length) } else { // just parse the observations data lines since the metadata came in // XML form StringTokenizer dataTokenizer = new StringTokenizer(this.observationsString, this.recordDelimiter); // tokenize the lines into observations strings, place them in sequential // order into the dataValuesMap while (dataTokenizer.hasMoreTokens()) { String dataLine = dataTokenizer.nextToken(); //logger.debug("|" + dataLine + "|"); this.dataValuesMap.put(dataValuesMap.size() + 1, dataLine); } } }
From source file:gov.usda.DataCatalogClient.Dataset.java
/** * This is called from CKAN import//from ww w . ja v a 2 s. co m * @param programCode * @throws DatasetException */ public void setProgramCodeList(String programCode) throws ParseException { if (!programCodeList.contains(programCode)) { if (Pattern.matches("\\d{3}:\\d{3}", programCode)) { programCodeList.add(programCode); } else { //dsEx.addError("Program Code must be \\d{3}:\\d{3}: " + programCode); throw new ParseException("Program Code must be \\d{3}:\\d{3}: " + programCode, 3); } } }
From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryFieldPanel.java
/** * @return/*from www .ja v a2 s . c om*/ */ @SuppressWarnings("unchecked") public String getCriteriaFormula(final TableAbbreviator ta, final List<Pair<String, Object>> paramList) throws ParseException { if (operatorCBX.getSelectedItem().equals(SpQueryField.OperatorType.EMPTY)) { boolean isNot = isNotCheckbox.isSelected(); String nullCond = fieldQRI.getNullCondition(ta, schemaItem != null, isNot, getFormatName()); if (fieldQRI.getDataClass().equals(String.class)) { String fieldSpec = fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()); return "(" + nullCond + (isNot ? " and " : " or ") + fieldSpec + (isNot ? " <> " : " = ") + "'')"; } return nullCond; } if (hasCriteria()) { boolean addNullConjunction = false; boolean nullPick = criteria instanceof PickListCriteriaCombo && ((PickListCriteriaCombo) criteria).nullItemIsPicked(); Object[] criteriaStrs = parseCriteria(getCriteriaText(true).trim()); String criteriaFormula = ""; //String operStr = operatorCBX.getSelectedItem().toString(); String operStr = getOperatorQLText(); if (!(criteriaStrs[0] instanceof String) && !(criteriaStrs[0] instanceof Pair)) { //XXX - If the field has a formatter and it returned non-String data // then assume all parsing and conversion has been accomplished?? //(hopefully this will never occur) log.info(fieldQRI.getFieldInfo() + ": formatter returned non-string data."); criteriaFormula = concatCriteria(criteriaStrs, operStr, false, ta); } else { if (fieldQRI.getDataClass().equals(Boolean.class)) { if (operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.TRUE.getOrdinal())) || operStr.equals(SpQueryField.OperatorType .getOp(SpQueryField.OperatorType.TRUEORNULL.getOrdinal()))) { criteriaFormula = "true"; } else { criteriaFormula = "false"; } addNullConjunction = operStr.equals( SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.FALSEORNULL.getOrdinal())) || operStr.equals(SpQueryField.OperatorType .getOp(SpQueryField.OperatorType.TRUEORNULL.getOrdinal())); operStr = "="; } else if (fieldQRI.getDataClass().equals(String.class) && !isNumericCatalogNumber()) { criteriaFormula = concatCriteria(criteriaStrs, operStr, !(pickList instanceof PickListTableAdapter), ta); } else if (fieldQRI.getDataClass().equals(Calendar.class) || fieldQRI.getDataClass().equals(java.sql.Timestamp.class)) { for (int p = 0; p < criteriaStrs.length; p++) { String paramName = "spparam" + paramList.size(); try { if (fieldQRI instanceof DateAccessorQRI) { new Integer((String) criteriaStrs[p]); } else { Object arg = dateConverter.convert((String) criteriaStrs[p]); if (fieldQRI.getDataClass().equals(java.sql.Timestamp.class)) { arg = new java.sql.Timestamp(((Calendar) arg).getTimeInMillis()); } paramList.add(new Pair<String, Object>(paramName, arg)); } } catch (ParseException ex) { throw new ParseException(getLabel() + " - " + String.format( UIRegistry.getResourceString("QB_PARSE_ERROR"), ex.getLocalizedMessage()), -1); } if (p > 0) { if (operatorCBX.getSelectedItem() == SpQueryField.OperatorType.BETWEEN) { criteriaFormula += " and "; } else { criteriaFormula += ", "; } } if (fieldQRI instanceof DateAccessorQRI) { criteriaFormula += (String) criteriaStrs[p]; } else { criteriaFormula += ":" + paramName; } } if (SpQueryField.OperatorType.getOrdForOp(operStr) == SpQueryField.OperatorType.IN .getOrdinal()) { criteriaFormula = "(" + criteriaFormula + ")"; } } else if (Number.class.isAssignableFrom(fieldQRI.getDataClass()) || isNumericCatalogNumber()) { Constructor<?> tester; try { tester = isNumericCatalogNumber() ? BigInteger.class.getConstructor(String.class) : fieldQRI.getDataClass().getConstructor(String.class); for (int s = 0; s < criteriaStrs.length; s++) { Object critter = criteriaStrs[s]; List<String> strs = new ArrayList<String>(2); if (critter instanceof String) { strs.add(critter.toString()); } else { //seriesPresent = true; if (!operStr.equals(SpQueryField.OperatorType .getOp(SpQueryField.OperatorType.IN.getOrdinal()))) { throw new ParseException(getLabel() + " - " + UIRegistry.getResourceString("QB_INVALID_CRITERIA"), -1); } strs.add(((Pair<String, String>) critter).getFirst()); strs.add(((Pair<String, String>) critter).getSecond()); } List<String> newStrs = new ArrayList<String>(2); for (String str : strs) { tester.newInstance(str); //remove leading zeroes String newString = str; boolean isZeroes = false; while (newString.startsWith("0")) { newString = newString.substring(1); isZeroes = true; } if (isZeroes && StringUtils.isBlank(newString)) { newString = "0"; } newStrs.add(newString); } if (newStrs.size() == 2) { ((Pair<String, String>) criteriaStrs[s]).setFirst(newStrs.get(0)); ((Pair<String, String>) criteriaStrs[s]).setSecond(newStrs.get(1)); } else { criteriaStrs[s] = newStrs.get(0); } } } catch (NoSuchMethodException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex); // this will never happen. trust me. throw new RuntimeException(ex); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof NumberFormatException) { String msg = ex.getTargetException().getLocalizedMessage(); if (StringUtils.isBlank(msg)) { msg = ex.getTargetException().getClass().getSimpleName(); } throw new ParseException( getLabel() + " - " + String.format(UIRegistry.getResourceString("QB_PARSE_ERROR"), msg), -1); } throw new RuntimeException(ex); } catch (IllegalAccessException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex); throw new RuntimeException(ex); } catch (InstantiationException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryFieldPanel.class, ex); throw new RuntimeException(ex); } catch (NumberFormatException ex) { String msg = ex.getLocalizedMessage(); if (StringUtils.isBlank(msg)) { msg = ex.getClass().getSimpleName(); } throw new ParseException(getLabel() + " - " + String.format(UIRegistry.getResourceString("QB_PARSE_ERROR"), msg), -1); } criteriaFormula = concatCriteria(criteriaStrs, operStr, false, ta); } } if (operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.CONTAINS.getOrdinal()))) { operStr = "Like"; } if (criteriaFormula.length() > 0 || nullPick || fieldQRI instanceof TreeLevelQRI) { if (fieldQRI instanceof TreeLevelQRI) { try { return ((TreeLevelQRI) fieldQRI).getNodeNumberCriteria(criteriaFormula, ta, operStr, isNotCheckbox.isSelected()); } catch (ParseException pe) { throw new ParseException(getLabel() + " - " + String .format(UIRegistry.getResourceString("QB_PARSE_ERROR"), pe.getLocalizedMessage()), -1); } } StringBuilder str = new StringBuilder(); str.append(isNotCheckbox.isSelected() ? "(NOT " : ""); if (!operStr.equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.IN.getOrdinal()))) { str.append(fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()) + " "); } if (nullPick && "=".equals(operStr)) { str.append(" is null "); } else if (!operStr .equals(SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.IN.getOrdinal()))) { str.append(operStr); } str.append(" "); if (!(nullPick && "=".equals(operStr))) { str.append(criteriaFormula); } if (isNotCheckbox.isSelected()) { if (!operStr.equals( SpQueryField.OperatorType.getOp(SpQueryField.OperatorType.EMPTY.getOrdinal()))) { str.append(" or " + fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()) + " is null"); } str.append(")"); } String result = str.toString(); if (addNullConjunction || (StringUtils.isNotBlank(result) && isEnforcedCkbx != null && isEnforcedCkbx.isSelected() && schemaMapping != null) || (nullPick && !"=".equals(operStr))) { //Currently, when the null value is picked with the IN condition, a '' entry is included in the IN list //This is not technically correct, but probably will never matter, and possibly produce more desirable //results then the technically correct criteria result = "(" + result + " or " + fieldQRI.getSQLFldSpec(ta, true, schemaItem != null, getFormatName()) + " is null)"; } return result; } } return null; }
From source file:org.sakaiproject.tool.podcasts.podHomeBean.java
/** * Gathers information and calls PodcastService to make changes to existing * podcast.//from w ww. j a va 2 s .co m */ public String processRevisePodcast() { // set error messages to false so can be // turned on during processing displayNoTitleErrMsg = false; displayInvalidDateErrMsg = false; String whereToGo = "cancel"; boolean filenameChange = false; byte[] fileContents = null; // if they blank out the title, stay here since // a title is a requirement if ("".equals(selectedPodcast.title.trim())) { displayNoTitleErrMsg = true; if ("".equals(selectedPodcast.displayDateRevise)) { displayInvalidDateErrMsg = true; } else { displayInvalidDateErrMsg = false; } return "revise"; } // If file has changed, change it in the resource if (filename != null) { if (!filename.equals("")) { selectedPodcast.filename = filename; filenameChange = true; if (fileAsStream != null) { fileContents = new byte[(int) fileSize]; } else { fileContents = new byte[(int) selectedPodcast.fileSize]; } try { if (fileAsStream != null) { fileAsStream.read(fileContents); } } catch (IOException e) { LOG.error( "IOException while attempting to get file contents when revising podcast for " + filename + " in site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(IO_ALERT); return "podcastRevise"; } finally { try { if (fileAsStream != null) fileAsStream.close(); } catch (IOException ioe) { LOG.warn("IOException error while closing the stream:" + ioe); } } } } Date displayDate = null; Date displayDateRevise = null; try { try { // SAK-13493: SimpleDateFormat.parse() did not enforce format specified, so // had to call custom method to check if String was valid if (DateUtil.isValidDate(selectedPodcast.displayDateRevise, getErrorMessageString(DATE_BY_HAND_FORMAT), rb.getLocale())) { displayDateRevise = convertDateString(selectedPodcast.displayDateRevise, getErrorMessageString(DATE_BY_HAND_FORMAT)); } else { throw new ParseException("Invalid displayDate stored in selectedPodcast", 0); } } catch (ParseException e) { // must have used date picker, so try again if (isValidDate(selectedPodcast.displayDateRevise)) { displayDateRevise = convertDateString(selectedPodcast.displayDateRevise, FIXED_DATE_PICKER_FORMAT); } else { throw new ParseException( "Invalid displayDate entered while revising podcast " + selectedPodcast.filename, 0); } } if (filenameChange) { // filename has changed, so create an entirely new entry - is // needed since filename part of resource URL podcastService.addPodcast(selectedPodcast.title, displayDateRevise, selectedPodcast.description, fileContents, filename, fileContentType); podcastService.removePodcast(selectedPodcast.getResourceId()); } else { // only title, description, or date has changed, so can revise podcastService.revisePodcast(selectedPodcast.resourceId, selectedPodcast.title, displayDateRevise, selectedPodcast.description, fileContents, selectedPodcast.filename); } /* FUTURE: Enable notification if (email.equalsIgnoreCase("high")) { EmailService.send("josrodri@iupui.edu","josrodri@iupui.edu", "A podcast has been added to feed.", "A podcast has been added to the list of podcasts. " + "It's publish date will determine when it will be available in the feed", null, null, null); } else if (email.equalsIgnoreCase("low")) { // FUTURE: email only those who have opted in } */ } catch (ParseException e1) { LOG.error("ParseException attempting to convert date for " + selectedPodcast.title + " for site " + podcastService.getSiteId() + ". " + e1.getMessage(), e1); date = ""; displayInvalidDateErrMsg = true; return "podcastRevise"; } catch (PermissionException e) { LOG.error("PermissionException while revising podcast " + selectedPodcast.title + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(PERMISSION_ALERT); } catch (InUseException e) { LOG.warn("InUseException while revising podcast " + selectedPodcast.title + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(INTERNAL_ERROR_ALERT); } catch (OverQuotaException e) { LOG.warn("OverQuotaException while revising podcast " + selectedPodcast.title + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(QUOTA_ALERT); } catch (ServerOverloadException e) { LOG.warn("ServerOverloadException while revising podcast " + selectedPodcast.title + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(INTERNAL_ERROR_ALERT); } catch (IdLengthException e) { LOG.warn("IdLengthException while revising podcast with filename changed from " + selectedPodcast.filename + " to " + filename + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(LENGTH_ALERT); return "podcastRevise"; } catch (Exception e) { // catches IdUnusedException TypeException // IdInvalidException InconsistentException // IdUniquenessException LOG.error(e.getMessage() + " while revising podcast with filename changed from " + selectedPodcast.filename + " to " + filename + " for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); setErrorMessage(INTERNAL_ERROR_ALERT); } // Reset values to continue processing date = null; title = ""; description = ""; try { fileAsStream = null; } catch (Exception e) { LOG.warn("Exception error while setting the stream to null: " + e); } finally { try { if (fileAsStream != null) fileAsStream.close(); } catch (IOException ioe) { LOG.warn("IOException error while closing the stream:" + ioe); } } filename = ""; displayNoTitleErrMsg = false; return whereToGo; }
From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java
@Test(dataProvider = "provideDataForUserAuthz", groups = "testWithConnection") public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserApproved, boolean skipConsent, boolean idTokenHintValid, String loggedInUser, String idTokenHintSubject, String errorCode) throws Exception { AuthenticationResult result = setAuthenticationResult(true, null, null, null, null); result.getSubject().setAuthenticatedSubjectIdentifier(loggedInUser); Map<String, String[]> requestParams = new HashMap<>(); Map<String, Object> requestAttributes = new HashMap<>(); requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE }); requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" }); requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID }); requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE); requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE); requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result); mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST); OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, null, APP_REDIRECT_URL);// ww w . ja v a 2 s.c o m oAuth2Params.setClientId(CLIENT_ID_VALUE); oAuth2Params.setPrompt(prompt); oAuth2Params.setIDTokenHint(idTokenHint); mockStatic(SessionDataCache.class); when(SessionDataCache.getInstance()).thenReturn(sessionDataCache); SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE); when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry); when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject()); when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params); mockEndpointUtil(); mockOAuthServerConfiguration(); mockStatic(IdentityDatabaseUtil.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); mockStatic(OpenIDConnectUserRPStore.class); when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore); when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())) .thenReturn(hasUserApproved); spy(OAuth2Util.class); doReturn(idTokenHintValid).when(OAuth2Util.class, "validateIdToken", anyString()); mockStatic(SignedJWT.class); if ("invalid".equals(idTokenHint)) { when(SignedJWT.parse(anyString())).thenThrow(new ParseException("error", 1)); } else { when(SignedJWT.parse(anyString())).thenReturn(signedJWT); } JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder(); jwtClaimsSetBuilder.subject(idTokenHintSubject); JWTClaimsSet jwtClaimsSet = jwtClaimsSetBuilder.build(); when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet); when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE"); mockApplicationManagementService(); Response response; try { response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse); } catch (InvalidRequestParentException ire) { InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper(); response = invalidRequestExceptionMapper.toResponse(ire); } assertNotNull(response, "Authorization response is null"); assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status"); if (errorCode != null) { MultivaluedMap<String, Object> responseMetadata = response.getMetadata(); assertNotNull(responseMetadata, "Response metadata is null"); assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response"); String location = (String) responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0); assertTrue(location.contains(errorCode), "Expected error code not found in URL"); } }
From source file:fr.aliacom.obm.common.calendar.CalendarBindingImpl.java
@Override @Transactional/* w w w .j a v a 2 s .c o m*/ public boolean changeParticipationState(AccessToken token, String calendar, EventExtId extId, RecurrenceId recurrenceId, Participation participation, int sequence, boolean notification) throws ServerFault, EventNotFoundException, ParseException, NotAllowedException { assertUserCanWriteOnCalendar(token, calendar); String userEmail = userService.getUserFromAccessToken(token).getEmailAtDomain(); try { boolean wasDone = changeParticipationForRecursiveEvent(token, calendar, extId, recurrenceId, participation, sequence, notification); if (!wasDone) { logger.warn("Change of participation state failed to " + participation + " (got sequence number " + sequence + ", probably stale) on calendar " + calendar + " on event " + extId + " by user " + userEmail); } return wasDone; } catch (FindException e) { throw new ServerFault("no user found with calendar " + calendar); } catch (SQLException e) { throw new ServerFault(e); } catch (ParseException e) { throw new ParseException(e.getMessage(), 0); } }
From source file:edu.hawaii.soest.kilonalu.ctd.CTDParser.java
public void setData(String dataString) throws ParseException { logger.debug("CTDParser.setData() called."); // make the observations available to the class this.observationsString = dataString; // build the list of data variable names and offsets // handle profile mode if (this.samplingMode.equals("profile")) { // handle the raw frquencies and voltages in Hex OUTPUTFORMAT (0) if (this.outputFormat.equals("raw HEX")) { this.dataVariableNames = new ArrayList<String>(); this.dataVariableNames.add(this.RAW_TEMPERATURE_FIELD_NAME); this.dataVariableNames.add(this.RAW_CONDUCTIVITY_FIELD_NAME); this.dataVariableUnits = new ArrayList<String>(); this.dataVariableUnits.add("counts"); this.dataVariableUnits.add("Hz"); this.currentOffset = 6; this.dataVariableOffsets = new ArrayList<Integer>(); this.dataVariableOffsets.add(currentOffset); this.currentOffset = currentOffset + 6; this.dataVariableOffsets.add(currentOffset); // Is pressure present? if (this.hasPressure) { this.dataVariableNames.add(this.RAW_PRESSURE_FIELD_NAME); this.dataVariableUnits.add("counts"); this.currentOffset = this.currentOffset + 6; this.dataVariableOffsets.add(this.currentOffset); // And is it a strain gauge sensor? if (this.hasStrainGaugePressure) { dataVariableNames.add(this.RAW_PRESSURE_TEMP_COMP_FIELD_NAME); dataVariableUnits.add("counts"); currentOffset = currentOffset + 4; dataVariableOffsets.add(currentOffset); }/*w w w . jav a2s. c om*/ } else { logger.info("There is no pressure sensor."); } // Is there a channel zero voltage present? if (this.hasVoltageChannelZero) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ZERO_FIELD_NAME); this.dataVariableUnits.add("V"); this.currentOffset = this.currentOffset + 4; this.dataVariableOffsets.add(this.currentOffset); } // Is there a channel one voltage present? if (this.hasVoltageChannelOne) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ONE_FIELD_NAME); this.dataVariableUnits.add("V"); this.currentOffset = this.currentOffset + 4; this.dataVariableOffsets.add(this.currentOffset); } // Is there a channel two voltage present? if (this.hasVoltageChannelTwo) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_TWO_FIELD_NAME); this.dataVariableUnits.add("V"); this.currentOffset = this.currentOffset + 4; this.dataVariableOffsets.add(this.currentOffset); } // Is there a channel three voltage present? if (this.hasVoltageChannelThree) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_THREE_FIELD_NAME); this.dataVariableUnits.add("V"); this.currentOffset = this.currentOffset + 4; this.dataVariableOffsets.add(this.currentOffset); } /* * @todo - handle SBE38, SBE50, and/or gasTensionDevice data */ // We now know the data variable names, units, and corresponding // character offsets for each Hex data string found in the // dataValuesMap. Build a raw matrix from the dataValuesMap by only // applying output factors. Conversion to useful variable units // will happen in the calling source driver since voltage channel // semantics are unknown to the parser int beginIndex = 0; int endIndex = 0; int offsetIndex = 0; String hexSubstring = ""; String hexDataString = ""; Hex decoder = new Hex(); double value = 0d; this.convertedDataValuesMatrix = new Array2DRowRealMatrix(this.dataValuesMap.size() - 1, this.dataVariableOffsets.size()); for (int rowIndex = 1; rowIndex < this.dataValuesMap.size(); rowIndex++) { hexDataString = this.dataValuesMap.get(rowIndex); logger.debug(rowIndex + ") hexDataString is: " + hexDataString); for (offsetIndex = 0; offsetIndex < this.dataVariableOffsets.size(); offsetIndex++) { endIndex = this.dataVariableOffsets.get(offsetIndex); hexSubstring = hexDataString.substring(beginIndex, endIndex); try { // convert the hex characters to bytes byte[] hexAsBytes = decoder.decodeHex(hexSubstring.toCharArray()); BigInteger bigInteger = new BigInteger(hexAsBytes); int intValue = bigInteger.intValue(); // the hex values are either 2 or 3 bytes long (AABBCC or AABB) // BigInteger fills in missing bits with 0xFF. Remove them. This // is only a problem with large bytes that cause the value to // become negative. if (hexAsBytes.length < 3) { intValue = (intValue & 0x0000FFFF); } else { intValue = (intValue & 0x00FFFFFF); } value = new Integer(intValue).doubleValue(); // convert the value based on the CTD User manual conversion using // the corresponding data variable name to determine which conversion double convertedValue = convert(value, this.dataVariableNames.get(offsetIndex)); convertedDataValuesMatrix.setEntry(rowIndex - 1, offsetIndex, convertedValue); logger.debug("\t" + this.dataVariableNames.get(offsetIndex) + " is:\t" + value + "\tConverted: " + convertedValue); // set the beginIndex to start at the endIndex beginIndex = endIndex; } catch (DecoderException de) { logger.debug("Could not decode the Hex string: " + hexSubstring); } } // for // reset the offsetIndex for the next hexDataString offsetIndex = 0; beginIndex = 0; } // for // handle the engineering units in Hex OUTPUTFORMAT (1) } else if (this.outputFormat.equals("converted Hex")) { /* * @todo - handle OUTPUTFORMAT (1) */ // handle the raw frquencies and voltages in decimal OUTPUTFORMAT (2) } else if (this.outputFormat.equals("raw decimal")) { /* * @todo - handle OUTPUTFORMAT (2) */ // handle the engineering units in decimal OUTPUTFORMAT (3) } else if (this.outputFormat.equals("converted decimal")) { /* * @todo - handle OUTPUTFORMAT (3) */ } // handle moored mode } else if (this.samplingMode.equals("moored")) { // handle the raw frequencies and voltages in Hex OUTPUTFORMAT (0) if (this.outputFormat.equals("raw HEX")) { // handle the engineering units in Hex OUTPUTFORMAT (1) } else if (this.outputFormat.equals("converted Hex")) { /* * @todo - handle OUTPUTFORMAT (1) */ // handle the raw frequencies and voltages in decimal OUTPUTFORMAT (2) } else if (this.outputFormat.equals("raw decimal")) { /* * @todo - handle OUTPUTFORMAT (2) */ // handle the engineering units in decimal OUTPUTFORMAT (3) } else if (this.outputFormat.equals("converted decimal")) { this.dataVariableNames = new ArrayList<String>(); this.dataVariableNames.add(this.TEMPERATURE_FIELD_NAME); this.dataVariableNames.add(this.CONDUCTIVITY_FIELD_NAME); this.dataVariableUnits = new ArrayList<String>(); this.dataVariableUnits.add("degrees C"); this.dataVariableUnits.add("S/m"); // Is pressure present? if (this.hasPressure) { this.dataVariableNames.add(this.PRESSURE_FIELD_NAME); this.dataVariableUnits.add("decibars"); } else { logger.info("There is no pressure sensor."); } // Is there a channel zero voltage present? if (this.hasVoltageChannelZero) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ZERO_FIELD_NAME); this.dataVariableUnits.add("V"); } // Is there a channel one voltage present? if (this.hasVoltageChannelOne) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_ONE_FIELD_NAME); this.dataVariableUnits.add("V"); } // Is there a channel two voltage present? if (this.hasVoltageChannelTwo) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_TWO_FIELD_NAME); this.dataVariableUnits.add("V"); } // Is there a channel three voltage present? if (this.hasVoltageChannelThree) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_THREE_FIELD_NAME); this.dataVariableUnits.add("V"); } // Is there a channel four voltage present? if (this.hasVoltageChannelFour) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_FOUR_FIELD_NAME); this.dataVariableUnits.add("V"); } // Is there a channel five voltage present? if (this.hasVoltageChannelFive) { this.dataVariableNames.add(this.RAW_VOLTAGE_CHANNEL_FIVE_FIELD_NAME); this.dataVariableUnits.add("V"); } /* * @todo - handle SBE38, SBE50, and/or gasTensionDevice data */ // Will salinity be output? if (this.willOutputSalinity) { this.dataVariableNames.add(this.SALINITY_FIELD_NAME); this.dataVariableUnits.add("psu"); } // Will sound velocity be output? if (this.willOutputSalinity) { this.dataVariableNames.add(this.SOUND_VELOCITY_FIELD_NAME); this.dataVariableUnits.add("m/s"); } // Add the date and time fields this.dataVariableNames.add(this.DATE_FIELD_NAME); this.dataVariableUnits.add("dd MMM yyyy"); this.dataVariableNames.add(this.TIME_FIELD_NAME); this.dataVariableUnits.add("hh:mm:ss"); } this.convertedDataValuesMatrix = new Array2DRowRealMatrix(this.dataValuesMap.size() - 1, this.dataVariableOffsets.size()); // CSJ fix this } else { throw new ParseException( "There was an error parsing the data string. " + "The sampling mode is not recognized.", 0); } }