List of usage examples for java.lang NumberFormatException getMessage
public String getMessage()
From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java
/** * Creates a new instance of this class. *//*from w ww. j a v a 2 s.com*/ public RetrievalServiceImpl() { super(); PORTAL_SINGLE_RECORD_URL = PropertyReader.getProperty(UimConfigurationProperty.PORTAL_URI); PORTAL_PREVIEW_URL = PropertyReader.getProperty(UimConfigurationProperty.TESTPORTAL_URI); try { IBindingFactory bfact = BindingDirectory.getFactory(RDF.class); uctx = bfact.createUnmarshallingContext(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); BlockingInitializer initializer = new BlockingInitializer() { @Override protected void initializeInternal() { solrServer = new HttpSolrServer( PropertyReader.getProperty(UimConfigurationProperty.SOLR_HOSTURL) + PropertyReader.getProperty(UimConfigurationProperty.SOLR_CORE)); } }; initializer.initialize(HttpSolrServer.class.getClassLoader()); BlockingInitializer mongoInitializer = new BlockingInitializer() { @Override protected void initializeInternal() { try { mongoServer = new EdmMongoServerImpl( new Mongo(PropertyReader.getProperty(UimConfigurationProperty.MONGO_HOSTURL), Integer.parseInt(PropertyReader .getProperty(UimConfigurationProperty.MONGO_HOSTPORT))), PropertyReader.getProperty(UimConfigurationProperty.MONGO_DB_EUROPEANA), "", ""); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MongoDBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MongoException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; mongoInitializer.initialize(EdmMongoServerImpl.class.getClassLoader()); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); } }
From source file:no.kantega.kwashc.server.test.SSLProtocolTest.java
@Override protected TestResult testSite(Site site, TestResult testResult) throws Throwable { long startTime = System.nanoTime(); int httpsPort; try {//from w w w . j a v a2s . c om httpsPort = new Integer(site.getSecureport()); } catch (NumberFormatException e) { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage("No HTTPS port specified, test not run!"); setDuration(testResult, startTime); return testResult; } HttpClient httpclient = HttpClientUtil.getHttpClient(); try { HttpClient httpClient = HttpClientUtil.getHttpClient(); HttpResponse response = checkClient(site, httpsPort, httpClient, new String[] { "SSLv3" }, null); if (response.getStatusLine().getStatusCode() == 200) { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage("Your application accepts an insecure SSL protocol!"); } else { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage("Actual testing failed, check that the connection is working!"); } } catch (KeyManagementException e) { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage( "Certificate configuration does not seem to be correct, check certificate on remote environment!"); return testResult; } catch (IOException e) { if (e.getMessage().contains("peer not authenticated")) { HttpClient httpClient = HttpClientUtil.getHttpClient(); HttpResponse response = checkClient(site, httpsPort, httpClient, new String[] { "TLSv1.2" }, null); if (response.getStatusLine().getStatusCode() == 200) { testResult.setResultEnum(ResultEnum.passed); testResult .setMessage("That`s better, you application supports secure SSL/TLS protocol TLSv1.2!"); } else { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage("Your application does not support secure SSL/TLS Protocols!"); } return testResult; } else { testResult.setResultEnum(ResultEnum.failed); testResult.setMessage("Actual testing failed, check that the connection is working!"); } } finally { httpclient.getConnectionManager().shutdown(); setDuration(testResult, startTime); } return testResult; }
From source file:info.magnolia.jcr.util.PropertyUtil.java
/** * Transforms a string to a jcr value object. *///from w w w . java2 s.c om public static Value createValue(String valueStr, int type, ValueFactory valueFactory) { Value value = null; if (type == PropertyType.STRING) { value = valueFactory.createValue(valueStr); } else if (type == PropertyType.BOOLEAN) { value = valueFactory.createValue(BooleanUtils.toBoolean(valueStr)); } else if (type == PropertyType.DOUBLE) { try { value = valueFactory.createValue(Double.parseDouble(valueStr)); } catch (NumberFormatException e) { value = valueFactory.createValue(0d); } } else if (type == PropertyType.LONG) { try { value = valueFactory.createValue(Long.parseLong(valueStr)); } catch (NumberFormatException e) { value = valueFactory.createValue(0L); } } else if (type == PropertyType.DATE) { try { Calendar date = new GregorianCalendar(); try { String newDateAndTime = valueStr; String[] dateAndTimeTokens = newDateAndTime.split("T"); String newDate = dateAndTimeTokens[0]; String[] dateTokens = newDate.split("-"); int hour = 0; int minute = 0; int second = 0; int year = Integer.parseInt(dateTokens[0]); int month = Integer.parseInt(dateTokens[1]) - 1; int day = Integer.parseInt(dateTokens[2]); if (dateAndTimeTokens.length > 1) { String newTime = dateAndTimeTokens[1]; String[] timeTokens = newTime.split(":"); hour = Integer.parseInt(timeTokens[0]); minute = Integer.parseInt(timeTokens[1]); second = Integer.parseInt(timeTokens[2]); } date.set(year, month, day, hour, minute, second); // this is used in the searching date.set(Calendar.MILLISECOND, 0); date.setTimeZone(TimeZone.getTimeZone("GMT")); } // todo time zone?? catch (Exception e) { // ignore, it sets the current date / time } value = valueFactory.createValue(date); } catch (Exception e) { log.debug("Exception caught: " + e.getMessage(), e); } } return value; }
From source file:gda.gui.mca.McaGUI.java
private boolean getEnergyPolyConverter() { boolean foundOffset = false, foundSlope = false, foundQuadratic = false; String fileName = LocalProperties.get("mca.calibration.dir", "."); File file = new File(fileName + File.separator + mcaName); if (file.exists()) { try {//from ww w . java 2 s . co m BufferedReader reader = new BufferedReader(new FileReader(file)); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("offset")) { this.offset = Double.parseDouble(line.substring(line.indexOf("=") + 1)); foundOffset = true; } if (line.startsWith("slope")) { this.slope = Double.parseDouble(line.substring(line.indexOf("=") + 1)); foundSlope = true; } if (line.startsWith("quadratic")) { this.quadratic = Double.parseDouble(line.substring(line.indexOf("=") + 1)); foundQuadratic = true; } } reader.close(); } catch (NumberFormatException e) { logger.error("Exception: " + e.getMessage()); } catch (FileNotFoundException e) { logger.error("Exception: " + e.getMessage()); } catch (IOException e) { logger.error("Exception: " + e.getMessage()); } } return foundOffset && foundSlope && foundQuadratic; }
From source file:com.diversityarrays.dal.db.TestDalDatabase.java
private void checkJsonResult(String where, DalResponseBuilder responseBuilder, String... keysExpected) { String response = responseBuilder.asString(); assertNotEquals(where + ": No record returned", "{}", response); try {// ww w . j a v a 2 s. c o m JsonParser parser = new JsonParser(response); if (!parser.isMapResult()) { fail(where + ": result is not a JsonMap"); } JsonMap jsonMap = parser.getMapResult(); List<String> responseKeys = jsonMap.getKeysInOrder(); if (responseKeys.size() != (keysExpected.length + 1)) { fail(where + " : expected key count mismatch: " + responseKeys.size() + "<>" + (keysExpected.length + 1) + "\n\tactual= " + StringUtil.join(",", responseKeys) + " \n\texpected= " + DALClient.TAG_RECORD_META + "," + StringUtil.join(",", (Object[]) keysExpected)); } Set<String> keySet; keySet = new HashSet<String>(Arrays.asList(keysExpected)); keySet.add(DALClient.TAG_RECORD_META); // must ALWAYS expect 'RecordMeta' boolean checkPagination = keySet.contains(DALClient.TAG_PAGINATION); keySet.removeAll(responseKeys); if (!keySet.isEmpty()) { fail(where + ": missing keys in response: " + StringUtil.join(",", keySet)); } keySet = new HashSet<String>(responseKeys); keySet.removeAll(Arrays.asList(keysExpected)); keySet.remove("RecordMeta"); if (!keySet.isEmpty()) { fail(where + ": unexpected keys in response: " + StringUtil.join(",", keySet)); } if (checkPagination) { Object paginationObject = jsonMap.get(DALClient.TAG_PAGINATION); assertNotNull("Missing tag '" + DALClient.TAG_PAGINATION + "'", paginationObject); if (!(paginationObject instanceof List)) { fail(DALClient.TAG_PAGINATION + " is not a List: " + paginationObject.getClass().getName()); } @SuppressWarnings("rawtypes") List list = (List) paginationObject; assertEquals(DALClient.TAG_PAGINATION + " is not a List of size 1", 1, list.size()); Object mapObject = list.get(0); assertEquals(DALClient.TAG_PAGINATION + "[0] is not a JsonMap", JsonMap.class, mapObject.getClass()); JsonMap pagination = (JsonMap) mapObject; Set<String> paginationKeys = new HashSet<String>(pagination.getKeysInOrder()); for (String attrName : PAGINATION_ATTRIBUTES) { Object attrObject = pagination.get(attrName); assertNotNull("Missing attribute " + DALClient.TAG_PAGINATION + "." + attrName, attrObject); assertEquals(DALClient.TAG_PAGINATION + "." + attrName + " is not a String", String.class, attrObject.getClass()); try { Integer.parseInt((String) attrObject); } catch (NumberFormatException e) { fail(DALClient.TAG_PAGINATION + "." + attrName + " is not a valid Integer"); } paginationKeys.remove(attrName); } if (!paginationKeys.isEmpty()) { fail("Unexpected keys in " + DALClient.TAG_PAGINATION + ": " + StringUtil.join(",", paginationKeys)); } } } catch (ParseException e) { fail(where + ": invalid JSON : " + e.getMessage()); } }
From source file:com.flexive.core.search.PropertyEntry.java
private Pair<String, String> escapeScalarValue(DBStorage storage, String column, String constantValue) { String value = null;/*from w w w. ja v a2 s. c o m*/ switch (getProperty().getDataType()) { case String1024: case Text: case HTML: value = constantValue; if (value == null) { value = "NULL"; } else { // First remove surrounding "'" characters value = FxFormatUtils.unquote(value); // single quotes ("'") should be quoted already, otherwise the // parser would have failed // Convert back to an SQL string value = "'" + value + "'"; } break; case LargeNumber: if ("STEP".equals(column)) { // filter by workflow step definition, not internal step ID column = "(SELECT sd.stepdef FROM " + DatabaseConst.TBL_WORKFLOW_STEP + " sd " + " WHERE sd.id=" + column + ")"; } if ("TDEF".equals(column) && FxSharedUtils.isQuoted(constantValue, '\'')) { // optionally allow to select by type name (FX-613) value = "" + getEnvironment().getType(FxSharedUtils.stripQuotes(constantValue, '\'')).getId(); } else { try { value = String.valueOf(Long.parseLong(FxFormatUtils.unquote(constantValue))); } catch (NumberFormatException e) { throw new FxConversionException("ex.conversion.value.error", FxLargeNumber.class.getCanonicalName(), constantValue, e.getMessage()) .asRuntimeException(); } } break; case Number: try { value = String.valueOf(Integer.parseInt(FxFormatUtils.unquote(constantValue))); } catch (NumberFormatException e) { throw new FxConversionException("ex.conversion.value.error", FxLargeNumber.class.getCanonicalName(), constantValue, e.getMessage()).asRuntimeException(); } break; case Double: value = "" + FxFormatUtils.toDouble(constantValue); break; case Float: value = "" + FxFormatUtils.toFloat(constantValue); break; case SelectOne: case SelectMany: value = mapSelectConstant(getProperty(), constantValue); break; case Boolean: value = FxFormatUtils.toBoolean(constantValue) ? "1" : "0"; break; case Date: case DateRange: if (constantValue == null) { value = "NULL"; } else { value = storage.formatDateCondition(FxFormatUtils.toDate(constantValue)); } break; case DateTime: case DateTimeRange: // CREATED_AT and MODIFIED_AT store the date in a "long" column with millisecond precision if (constantValue == null) { value = "NULL"; } else { final Date date; try { date = FxFormatUtils.getDateTimeFormat().parse(FxFormatUtils.unquote(constantValue)); } catch (ParseException e) { throw new FxApplicationException(e).asRuntimeException(); } if (isDateMillisColumn(getFilterColumn())) { value = String.valueOf(date.getTime()); } else { value = storage.formatDateCondition(date); } } break; case Reference: if (constantValue == null) { value = "NULL"; } else { value = String.valueOf(FxPK.fromString(constantValue).getId()); } break; case Binary: break; case InlineReference: break; } return value == null ? null : new Pair<String, String>(column, value); }
From source file:gda.gui.mca.McaGUI.java
protected void setNumberChannels() { long numberChannels = 0; try {//from w w w. ja va2 s .co m numberChannels = analyser.getNumberOfChannels(); analyser.setNumberOfChannels(Long.parseLong(numberChannelsField.getText())); } catch (DeviceException e) { logger.error("Unable to set Number of channels to use" + e.getMessage()); } catch (NumberFormatException nme) { JOptionPane.showMessageDialog(this, "Invalid channel number : " + nme.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); numberChannelsField.setText(String.valueOf(numberChannels)); } }
From source file:gda.gui.mca.McaGUI.java
private void setAdcValues() { try {//from ww w .j a v a 2 s. c o m adc.setAttribute(EpicsADC.GAIN, Double.parseDouble(gainField.getText())); adc.setAttribute(EpicsADC.OFFSET, Double.parseDouble(offsetField.getText())); adc.setAttribute(EpicsADC.LLD, Double.parseDouble(lldField.getText())); } catch (DeviceException e) { logger.error("Unable to set adc values"); } catch (NumberFormatException nme) { JOptionPane.showMessageDialog(this, "Invalid Adc parameters : " + nme.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }
From source file:com.sfs.whichdoctor.search.sql.RotationSqlHandler.java
/** * Construct the SQL string, description and parameters. * * @param objCriteria Object containing search criteria values * @param objConstraints Object containing search constraint values * * @return Map containing a String[] { sql, description } => * Collection< Object > parameters * * @throws IllegalArgumentException the illegal argument exception *///w w w. j a va 2s .c om public final Map<String[], Collection<Object>> construct(final Object objCriteria, final Object objConstraints) throws IllegalArgumentException { RotationBean searchCriteria = null; RotationBean searchConstraints = null; if (objCriteria instanceof RotationBean) { searchCriteria = (RotationBean) objCriteria; } if (objConstraints instanceof RotationBean) { searchConstraints = (RotationBean) objConstraints; } if (searchCriteria == null) { throw new IllegalArgumentException("The search criteria must be a valid RotationBean"); } if (searchConstraints == null) { throw new IllegalArgumentException("The search constraints must be a valid RotationBean"); } StringBuffer sqlWHERE = new StringBuffer(); StringBuffer description = new StringBuffer(); Collection<Object> parameters = new ArrayList<Object>(); if (searchCriteria.getTags() != null) { try { for (TagBean tag : searchCriteria.getTags()) { Map<String[], Collection<Object>> results = this.tagSearchDAO.construct(tag, new TagBean()); for (String[] index : results.keySet()) { String tagWHERE = index[0]; String tagDescription = index[1]; Collection<Object> tagParameters = results.get(index); if (StringUtils.isNotBlank(tagWHERE)) { // A WHERE condition is defined, add to the SQL WHERE clause sqlWHERE.append(" " + this.getSQL().getValue("rotation/searchTags") + " WHERE " + tagWHERE + ")"); /* Add to the description and process the arrays */ description.append(tagDescription); if (tagParameters != null) { parameters.addAll(tagParameters); } } } } } catch (Exception e) { dataLogger.error("Error setting tag search options: " + e.getMessage()); } } /* * Used to locate a rotation based on a perons name or rotation * description */ if (StringUtils.isNotBlank(searchCriteria.getBasicSearch())) { String searchString = searchCriteria.getBasicSearch().trim(); int identifier = 0; try { identifier = Integer.parseInt(searchString); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing Basic Search: " + nfe.getMessage()); } // If the search string ends with ) then meta-data is probably included if (searchString.endsWith(")") && searchString.indexOf(" (") > 0) { // The search string has brackets - remove the brackets and their content. searchString = searchString.substring(0, searchString.lastIndexOf(" (")); } if (identifier == 0) { sqlWHERE.append(" AND (concat(title.Name, ' ', people.FirstName, ' ', "); sqlWHERE.append("people.LastName) LIKE ? OR concat(title.Name, ' ', "); sqlWHERE.append("people.PreferredName, ' ', people.LastName) LIKE ? "); sqlWHERE.append("OR concat(title.Name,' ', people.Lastname) LIKE ? "); sqlWHERE.append("OR concat(title.Name, ' ', people.FirstName, ' ', "); sqlWHERE.append("people.MaidenName) LIKE ? )"); description.append(" and a name like '" + searchString + "'"); for (int i = 0; i < 4; i++) { parameters.add("%" + searchString + "%"); } } else { sqlWHERE.append(" AND (people.PersonIdentifier = ?)"); description.append(" and a MIN equal to '" + identifier + "'"); parameters.add(identifier); } } if (searchCriteria.getGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR rotation.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } if (searchCriteria.getIdentifierList() != null) { final StringBuffer identifierWHERE = new StringBuffer(); for (String identifier : searchCriteria.getIdentifierList()) { if (StringUtils.isNotBlank(identifier)) { identifierWHERE.append(" OR people.PersonIdentifier = ?"); parameters.add(identifier); } } if (identifierWHERE.length() > 0) { // Append the identifierWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the identifierWHERE but strip the first OR statement sqlWHERE.append(identifierWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and is a rotation associated with a MIN number " + "in the supplied list"); } } // Build name field if (StringUtils.isNotBlank(searchCriteria.getDescription())) { sqlWHERE.append(" AND rotation.Description LIKE ?"); description.append(" and a rotation description like '" + searchCriteria.getDescription() + "'"); parameters.add("%" + searchCriteria.getDescription() + "%"); } if (StringUtils.isNotBlank(searchCriteria.getRotationType())) { String field = searchCriteria.getRotationType(); sqlWHERE.append(" AND rotationtype.Class LIKE ?"); description.append(" and a training level of '" + searchCriteria.getRotationType() + "'"); parameters.add(field); } if (StringUtils.isNotBlank(searchCriteria.getTrainingClass())) { String field = searchCriteria.getTrainingClass(); sqlWHERE.append(" AND trainingtype.Class LIKE ?"); description.append(" and a rotation training class of '" + searchCriteria.getTrainingClass() + "'"); parameters.add(field); } if (StringUtils.isNotBlank(searchCriteria.getTrainingType())) { String field = searchCriteria.getTrainingType(); sqlWHERE.append(" AND trainingtype.Name LIKE ?"); description.append(" and a rotation training type of '" + searchCriteria.getTrainingType() + "'"); parameters.add(field); } if (searchCriteria.getPersonId() > 0) { sqlWHERE.append(" AND rotation.PersonId = ?"); description.append(" and has a person GUID equal to '" + searchCriteria.getPersonId() + "'"); parameters.add(searchCriteria.getPersonId()); } if (searchCriteria.getYear() > 0) { if (searchConstraints.getYear() > 0) { int yearA = searchCriteria.getYear(); int yearB = searchConstraints.getYear(); if (yearB < yearA) { // Switch the two variables so that the criteria is smaller yearA = searchConstraints.getYear(); yearB = searchCriteria.getYear(); } sqlWHERE.append(" AND rotation.Year BETWEEN ? AND ?"); description.append(" and a rotation training year between " + yearA + " and " + yearB); parameters.add(yearA); parameters.add(yearB); } else { sqlWHERE.append(" AND rotation.Year = ?"); description.append(" and a rotation training year of " + searchCriteria.getYear()); parameters.add(searchCriteria.getYear()); } } if (searchCriteria.getOrganisation1() != null) { StringBuffer organisationSearch = new StringBuffer(); OrganisationBean organisation = searchCriteria.getOrganisation1(); if (StringUtils.isNotBlank(organisation.getName())) { description.append(" and a organisation named '" + organisation.getName() + "'"); organisationSearch.append(" AND (first_organisation.Name LIKE ? OR " + "first_organisation.Name LIKE ? OR rotation.Organisation1Name " + "LIKE ? OR rotation.Organisation2Name LIKE ?)"); for (int i = 0; i < 4; i++) { parameters.add("%" + organisation.getName() + "%"); } } if (organisation.getFirstAddress() != null) { AddressBean address = organisation.getFirstAddress(); if (StringUtils.isNotBlank(address.getCity())) { description.append(" and an organisation based in the city of '" + address.getCity() + "'"); organisationSearch .append(" AND (first_city.TextValue LIKE ? " + "OR second_city.TextValue LIKE ?)"); for (int i = 0; i < 2; i++) { parameters.add(address.getCity()); } } if (StringUtils.isNotBlank(address.getCountry())) { description.append(" and an organisation based in '" + address.getCountry() + "'"); organisationSearch.append( " AND (first_country.TextValue LIKE ? " + "OR second_country.TextValue LIKE ?)"); for (int i = 0; i < 2; i++) { parameters.add(address.getCountry()); } } } if (organisationSearch.length() > 0) { sqlWHERE.append(" " + getSQL().getValue("rotation/searchOrganisation") + organisationSearch.toString() + ")"); } } // Search for start or end date if (searchCriteria.getStartDate() != null) { if (searchConstraints.getStartDate() != null) { int larger = searchCriteria.getStartDate().compareTo(searchConstraints.getStartDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getStartDate()); String fieldB = this.getDf().format(searchConstraints.getStartDate()); sqlWHERE.append(" AND rotation.StartDate BETWEEN ? AND ?"); description.append(" and a start date between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getStartDate()); String fieldB = this.getDf().format(searchConstraints.getStartDate()); sqlWHERE.append(" AND rotation.StartDate BETWEEN ? AND ?"); description.append(" and a start date between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getStartDate()); sqlWHERE.append(" AND rotation.StartDate = ?"); description.append(" and a start date on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getStartDate()); sqlWHERE.append(" AND rotation.StartDate = ?"); description.append(" and a start date on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getEndDate() != null) { if (searchConstraints.getEndDate() != null) { int larger = searchCriteria.getEndDate().compareTo(searchConstraints.getEndDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getEndDate()); String fieldB = this.getDf().format(searchConstraints.getEndDate()); sqlWHERE.append(" AND rotation.EndDate BETWEEN ? AND ?"); description.append(" and a end date between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getEndDate()); String fieldB = this.getDf().format(searchConstraints.getEndDate()); sqlWHERE.append(" AND rotation.EndDate BETWEEN ? AND ?"); description.append(" and a end date between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getEndDate()); sqlWHERE.append(" AND rotation.EndDate = ?"); description.append(" and a end date on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getEndDate()); sqlWHERE.append(" AND rotation.EndDate = ?"); description.append(" and a end date on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getTrainingTime() > 0) { if (searchConstraints.getTrainingTime() > 0) { if (searchCriteria.getTrainingTime() > searchConstraints.getTrainingTime()) { // SearchCriteria training time larger than SearchConstraint String fieldA = Formatter.toPercent(searchConstraints.getTrainingTime(), 0, "%"); String fieldB = Formatter.toPercent(searchCriteria.getTrainingTime(), 0, "%"); sqlWHERE.append(" AND rotation.TrainingTime BETWEEN ? AND ?"); description.append(" and a training time between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(searchConstraints.getTrainingTime()); parameters.add(searchCriteria.getTrainingTime()); } if (searchCriteria.getTrainingTime() < searchConstraints.getTrainingTime()) { // SearchCriteria training time less than SearchConstraint String fieldA = Formatter.toPercent(searchCriteria.getTrainingTime(), 0, "%"); String fieldB = Formatter.toPercent(searchConstraints.getTrainingTime(), 0, "%"); sqlWHERE.append(" AND rotation.TrainingTime BETWEEN ? AND ?"); description.append(" and a training time between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(searchCriteria.getTrainingTime()); parameters.add(searchConstraints.getTrainingTime()); } if (searchCriteria.getTrainingTime() == searchConstraints.getTrainingTime()) { // SearchCritier and SearchConstraint are equal String field = Formatter.toPercent(searchCriteria.getTrainingTime(), 0, "%"); sqlWHERE.append(" AND rotation.TrainingTime = ?"); description.append(" and a training time of '" + field + "'"); parameters.add(searchCriteria.getTrainingTime()); } } else { String field = Formatter.toPercent(searchCriteria.getTrainingTime(), 0, "%"); sqlWHERE.append(" AND rotation.TrainingTime = ?"); description.append(" and a training time of '" + field + "'"); parameters.add(searchCriteria.getTrainingTime()); } } if (searchCriteria.getSupervisors() != null) { StringBuffer supervisorSearch = new StringBuffer(); for (SupervisorBean supervisor : searchCriteria.getSupervisors()) { if (supervisor.getPersonGUID() > 0) { if (supervisorSearch.length() > 0) { supervisorSearch.append(" OR "); } supervisorSearch.append("supervisors.PersonGUID = ?"); description.append(" and a supervisor with a GUID of '" + supervisor.getPersonGUID() + "'"); parameters.add(supervisor.getPersonGUID()); } } if (supervisorSearch.length() > 0) { sqlWHERE.append(" " + this.getSQL().getValue("rotation/searchSupervisor") + " AND (" + supervisorSearch + "))"); } } if (searchCriteria.getAccreditation() != null) { StringBuffer accreditationSearch = new StringBuffer(); for (AccreditationBean accreditation : searchCriteria.getAccreditation()) { if (StringUtils.isNotBlank(accreditation.getSpecialtyType())) { accreditationSearch.append(" AND accreditationtype.Name = ?"); description.append(" and an associated accreditation specialty of '" + accreditation.getSpecialtyType() + "'"); parameters.add(accreditation.getSpecialtyType()); } if (StringUtils.isNotBlank(accreditation.getAccreditationType())) { accreditationSearch.append(" AND accreditationtype.Name = ?"); description.append(" and an associated accreditation type of '" + accreditation.getAccreditationType() + "'"); parameters.add(accreditation.getAccreditationType()); } } if (accreditationSearch.length() > 0) { sqlWHERE.append( " " + getSQL().getValue("rotation/searchAccreditation") + accreditationSearch + ")"); } } // Do person name first and last search if (searchCriteria.getPersonSearch() != null) { PersonBean person = searchCriteria.getPersonSearch(); PersonBean personConstraints = searchConstraints.getPersonSearch(); if (personConstraints == null) { personConstraints = new PersonBean(); } if (StringUtils.isNotBlank(person.getFirstName())) { sqlWHERE.append(" AND people.FirstName LIKE ?"); description.append(" and a trainee's first name like '" + person.getFirstName() + "'"); parameters.add("%" + person.getFirstName() + "%"); } if (StringUtils.isNotBlank(person.getLastName())) { sqlWHERE.append(" AND people.LastName LIKE ?"); description.append(" and a trainee's last name like '" + person.getLastName() + "'"); parameters.add("%" + person.getLastName() + "%"); } if (person.getPersonIdentifier() > 0) { sqlWHERE.append(" AND people.PersonIdentifier = ?"); description.append(" and a trainee's with an identifier of '" + person.getPersonIdentifier() + "'"); parameters.add(person.getPersonIdentifier()); } /* Membership search */ if (person.getPrimaryMembership() != null) { MembershipBean mCriteria = person.getPrimaryMembership(); if (StringUtils.isNotBlank(mCriteria.getField("Division"))) { sqlWHERE.append(" AND " + mCriteria.getDataTableName("Division") + ".Class = ?"); description .append(" and a trainee with a division of '" + mCriteria.getField("Division") + "'"); parameters.add(mCriteria.getField("Division")); } if (mCriteria.getObjectTypeField("Training Type") != null) { ObjectTypeBean object = mCriteria.getObjectTypeField("Training Type"); sqlWHERE.append(" AND " + mCriteria.getDataTableName("Training Type") + ".Class = ?"); description.append(" and a trainee with training type of '" + object.getClassName() + "'"); parameters.add(object.getClassName()); } } // Perform a specialty search if (person.getSpecialtyList() != null) { StringBuffer specialtySearch = new StringBuffer(); for (SpecialtyBean specialty : person.getSpecialtyList()) { if (StringUtils.isNotBlank(specialty.getTrainingOrganisation())) { specialtySearch.append(" AND trainingprogram.Class = ?"); description.append(" and is associated with a person who is " + "in the '" + specialty.getTrainingOrganisation() + "' training organisation"); parameters.add(specialty.getTrainingOrganisation()); } if (StringUtils.isNotBlank(specialty.getTrainingProgram())) { specialtySearch.append(" AND trainingprogram.Name = ?"); description.append(" and is associated with a person who is " + "in the '" + specialty.getTrainingProgram() + "' training program"); parameters.add(specialty.getTrainingProgram()); } if (specialty.getTrainingProgramYear() > 0) { int trainingProgramYearA = specialty.getTrainingProgramYear(); int trainingProgramYearB = 0; for (SpecialtyBean spConstnt : personConstraints.getSpecialtyList()) { trainingProgramYearB = spConstnt.getTrainingProgramYear(); } if (trainingProgramYearB > 0) { if (trainingProgramYearB < trainingProgramYearA) { // Switch the two variables so that the criteria is smaller trainingProgramYearA = trainingProgramYearB; trainingProgramYearB = specialty.getTrainingProgramYear(); } specialtySearch.append(" AND specialty.TrainingProgramYear " + "BETWEEN ? AND ?"); description.append(" and a specialty with a curriculum year " + "between " + trainingProgramYearA + " and " + trainingProgramYearB); parameters.add(trainingProgramYearA); parameters.add(trainingProgramYearB); } else { specialtySearch.append(" AND specialty.TrainingProgramYear = ?"); description .append(" and a specialty with a curriculum year of " + trainingProgramYearA); parameters.add(trainingProgramYearA); } } if (StringUtils.isNotBlank(specialty.getStatus())) { specialtySearch.append(" AND specialtystatus.Class = ?"); description.append(" and is associated with a person whose " + "specialty status is '" + specialty.getStatus() + "'"); parameters.add(specialty.getStatus()); } } if (specialtySearch.length() > 0) { sqlWHERE.append( " " + getSQL().getValue("rotation/searchSpecialty") + specialtySearch.toString() + ")"); } } } if (searchCriteria.getAssessment() != null) { StringBuffer assessmentSearch = new StringBuffer(); for (AssessmentBean assessment : searchCriteria.getAssessment()) { if (StringUtils.isNotBlank(assessment.getTrainingOrganisation())) { assessmentSearch.append(" AND trainingprogram.Class = ?"); description.append(" and an assessment training organisation of '" + assessment.getTrainingOrganisation() + "'"); parameters.add(assessment.getTrainingOrganisation()); } if (StringUtils.isNotBlank(assessment.getTrainingProgram())) { assessmentSearch.append(" AND trainingprogram.Name = ?"); description.append( " and an assessment training program of '" + assessment.getTrainingProgram() + "'"); parameters.add(assessment.getTrainingProgram()); } if (StringUtils.isNotBlank(assessment.getCommitteeSpecialty())) { assessmentSearch.append(" AND assessment.SpecialtyType LIKE ?"); description .append(" and an assessment committee of '" + assessment.getCommitteeSpecialty() + "'"); parameters.add(assessment.getCommitteeSpecialty()); } if (StringUtils.isNotBlank(assessment.getApproved())) { assessmentSearch.append(" AND approval.Class = ?"); description.append(" and an approved status of '" + assessment.getApproved() + "'"); parameters.add(assessment.getApproved()); } if (StringUtils.isNotBlank(assessment.getApprovedCondition())) { assessmentSearch.append(" AND approval.Name = ?"); description.append(" and an approved condition of '" + assessment.getApprovedCondition() + "'"); parameters.add(assessment.getApprovedCondition()); } if (StringUtils.isNotBlank(assessment.getStatus())) { assessmentSearch.append(" AND rotationstatus.Class = ?"); description.append(" and a rotation status of '" + assessment.getStatus() + "'"); parameters.add(assessment.getStatus()); } if (StringUtils.isNotBlank(assessment.getStatusReason())) { assessmentSearch.append(" AND rotationstatus.Name = ?"); description.append(" and a rotation status reason of '" + assessment.getStatusReason() + "'"); parameters.add(assessment.getStatusReason()); } } if (assessmentSearch.length() > 0) { sqlWHERE.append( " " + getSQL().getValue("rotation/searchAssessment") + assessmentSearch.toString() + ")"); } } /* * Build SQL array based on People GUIDs - used in training summary * search */ if (searchCriteria.getPeopleGUIDs() != null) { StringBuffer peopleWHERE = new StringBuffer(); for (Integer guid : searchCriteria.getPeopleGUIDs()) { if (peopleWHERE.length() > 0) { peopleWHERE.append(" OR "); } peopleWHERE.append("rotation.PersonId = ?"); parameters.add(guid); } if (peopleWHERE.length() > 0) { sqlWHERE.append(" AND (" + peopleWHERE.toString() + ")"); } } /* Build SQL array based on list of types */ if (searchCriteria.getSummaryTypes() != null) { StringBuffer summaryWHERE = new StringBuffer(); for (String summaryType : searchCriteria.getSummaryTypes()) { if (StringUtils.isNotBlank(summaryType)) { if (summaryWHERE.length() > 0) { summaryWHERE.append(" OR "); } summaryWHERE.append(" rotationtype.Class LIKE ?"); parameters.add(summaryType); } } if (summaryWHERE.length() > 0) { sqlWHERE.append(" AND (" + summaryWHERE.toString() + ")"); } } if (searchCriteria.getCreatedDate() != null) { if (searchConstraints.getCreatedDate() != null) { int larger = searchCriteria.getCreatedDate().compareTo(searchConstraints.getCreatedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); description.append(" and was created between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); description.append(" and was created between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getModifiedDate() != null) { if (searchConstraints.getModifiedDate() != null) { int larger = searchCriteria.getModifiedDate().compareTo(searchConstraints.getModifiedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getIncludeGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getIncludeGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR rotation.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" OR ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } String[] index = new String[] { sqlWHERE.toString(), DataFilter.getHtml(description.toString()) }; Map<String[], Collection<Object>> results = new HashMap<String[], Collection<Object>>(); results.put(index, parameters); return results; }
From source file:net.yacy.peers.Protocol.java
public static long[] queryRWICount(final MultiProtocolURL targetBaseURL, final Seed target, int timeout) { // prepare request final String salt = crypt.randomSalt(); // send request try {/*from www.j ava 2 s . com*/ final Map<String, ContentBody> parts = basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt); parts.put("object", UTF8.StringBody("rwicount")); parts.put("env", UTF8.StringBody("")); //ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "posting request to " + targetBaseURL); final Post post = new Post(targetBaseURL, target.hash, "/yacy/query.html", parts, timeout); //ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "received CONTENT from requesting " + targetBaseURL + (post.result == null ? "NULL" : (": length = " + post.result.length))); final Map<String, String> result = FileUtils.table(post.result); if (result == null || result.isEmpty()) return new long[] { -1, -1 }; //ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "received RESULT from requesting " + targetBaseURL + " : result = " + result.toString()); final String resp = result.get("response"); //ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "received RESPONSE from requesting " + targetBaseURL + " : response = " + resp); if (resp == null) return new long[] { -1, -1 }; String magic = result.get("magic"); if (magic == null) magic = "0"; try { return new long[] { Long.parseLong(resp), Long.parseLong(magic) }; } catch (final NumberFormatException e) { return new long[] { -1, -1 }; } } catch (final Exception e) { //ConcurrentLog.info("**hello-DEBUG**queryRWICount**", "received EXCEPTION from requesting " + targetBaseURL + ": " + e.getMessage()); if (Network.log.isFine()) Network.log.fine("yacyClient.queryRWICount error:" + e.getMessage()); return new long[] { -1, -1 }; } }