List of usage examples for java.lang NumberFormatException getMessage
public String getMessage()
From source file:org.eclipse.ebr.maven.EclipseIpLogUtil.java
private String createCq(final CloseableHttpClient httpclient, final Artifact artifact, final Model artifactPom, final Map<String, Xpp3Dom> existingLicenses) throws URISyntaxException, MojoExecutionException, IOException { final URIBuilder postUri = new URIBuilder(DISPATCH_PHP); postUri.addParameter("id", "portal/contribution_questionnaire.contribution_questionnaire_reuse." + projectId + "!reuse"); postUri.addParameter("action", "submit"); final HttpPost httpPost = new HttpPost(postUri.build()); httpPost.addHeader("Referer", PORTAL_PHP); final List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("name", getCqName(artifact, artifactPom))); nvps.add(new BasicNameValuePair("version", artifact.getVersion())); nvps.add(new BasicNameValuePair("description", getCqDescription(artifact, artifactPom))); nvps.add(new BasicNameValuePair("cryptography", Strings.nullToEmpty(getCqCryptography(artifact, artifactPom)))); nvps.add(new BasicNameValuePair("projecturl", Strings.nullToEmpty(getCqProjectUrl(artifact, artifactPom)))); nvps.add(new BasicNameValuePair("sourceurl", Strings.nullToEmpty(getCqSourceUrl(artifact, artifactPom)))); nvps.add(new BasicNameValuePair("license", getCqLicense(artifact, artifactPom, existingLicenses))); nvps.add(new BasicNameValuePair("otherlicense", "")); nvps.add(new BasicNameValuePair("sourcebinary", "sourceandbinary")); nvps.add(new BasicNameValuePair("modifiedcode", "unmodified")); nvps.add(new BasicNameValuePair("apachehosted", getCqApacheHosted(artifact, artifactPom))); nvps.add(new BasicNameValuePair("codeagreement", getCqCodeAgreement(artifact, artifactPom))); nvps.add(new BasicNameValuePair("stateid", "not_existing")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); if (getLog().isDebugEnabled()) { for (final NameValuePair pair : nvps) { getLog().debug(" " + pair.getName() + "=" + pair.getValue()); }/*from ww w .j av a 2 s .c om*/ } final String responseHtml = executeRequest(httpclient, httpPost, StringUtils.removeEnd(artifact.getFile().getName(), ".jar") + "-ipzilla-response.html"); final String cqUrl = "https://dev.eclipse.org/ipzilla/show_bug.cgi?id="; final int cqUrlIndex = responseHtml.indexOf(cqUrl); final StrBuilder cqId = new StrBuilder(); for (int i = cqUrlIndex + cqUrl.length(); i < responseHtml.length(); i++) { final char c = responseHtml.charAt(i); if (Character.isDigit(c)) { cqId.append(c); } else { break; } } try { final int cqNumber = Integer.parseInt(cqId.toString()); if (cqNumber > 0) return String.valueOf(cqNumber); } catch (final NumberFormatException e) { getLog().error(format("Error parsing extracted CQ number '%s'. %s", cqId, e.getMessage()), e); } // we can only fail at this point throw new MojoExecutionException( "Unable to extract CQ number from response. Please check response and IPzilla!"); }
From source file:gsn.http.restapi.RequestHandler.java
public RestResponse getMeasurementsForSensor(User user, String sensor, String from, String to, String size, String filter, String selectedFields) { RestResponse restResponse = userHasAccessToVirtualSensor(user, sensor); if (restResponse != null) { //error occured return restResponse; }/* w w w.j a v a2 s.co m*/ restResponse = new RestResponse(); String filename = String.format(stringConstantsProperties.getProperty("FILENAME_SENSOR_FIELDS"), sensor, datetime); setRestResponseParams(restResponse, filename); long fromAsLong = 0; long toAsLong = 0; int window = -1; try { fromAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT")) .parse(from).getTime(); toAsLong = new java.text.SimpleDateFormat(stringConstantsProperties.getProperty("ISO_FORMAT")).parse(to) .getTime(); if (size != null) window = Integer.parseInt(size); } catch (NumberFormatException e) { logger.error(e.getMessage(), e); restResponse = errorResponse(ErrorType.MALFORMED_SIZE, user, sensor); return restResponse; } catch (Exception e) { logger.error(e.getMessage(), e); restResponse = errorResponse(ErrorType.MALFORMED_DATE_FROM_TO, user, sensor); return restResponse; } String[] conditionList = null; if (filter != null) { String[] filters = filter.split(","); Try<String[]> conditions = XprConditions.serializeConditions(filters); if (conditions.isFailure()) { logger.error(conditions.failed().toString(), conditions.failed().get()); return errorResponse(ErrorType.MALFORMED_FILTER, user, sensor); } else { conditionList = conditions.get(); } } VSensorConfig sensorConfig = Mappings.getConfig(sensor); VirtualSensor sensorObj = new VirtualSensor(); sensorObj.setMetadata(createHeaderMap(sensorConfig)); sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIME"), "Time")); sensorObj.appendField(new DataField(stringConstantsProperties.getProperty("TIMESTAMP"), "BigInt")); Vector<Long> timestamps = new Vector<Long>(); ArrayList<Vector<Double>> elements = new ArrayList<Vector<Double>>(); ArrayList<String> fields = new ArrayList<String>(); ArrayList<String> allfields = new ArrayList<String>(); for (DataField df : sensorConfig.getOutputStructure()) { allfields.add(df.getName().toLowerCase()); if (selectedFields == null) { sensorObj.appendField(df); fields.add(df.getName().toLowerCase()); } } String[] fieldNames = null; if (selectedFields != null) { fieldNames = selectedFields.toLowerCase().split(","); for (String f : fieldNames) { if (!allfields.contains(f)) { logger.error("Invalid field name in selection: " + f); return errorResponse(ErrorType.MALFORMED_FIELD_SELECT, user, sensor); } fields.add(f); } } for (DataField df : sensorConfig.getOutputStructure()) { String fieldName = df.getName().toLowerCase(); if (selectedFields != null && fields.contains(fieldName)) { sensorObj.appendField(df); } } boolean errorFlag = !getData(sensor, fields, fromAsLong, toAsLong, window, elements, timestamps, conditionList); if (errorFlag) { return errorResponse(ErrorType.ERROR_IN_REQUEST, user, sensor); } sensorObj.setValues(elements, timestamps); List<VirtualSensor> listSens = new LinkedList<VirtualSensor>(); listSens.add(sensorObj); restResponse.setResponse(VirtualSensor.generateFileContent(listSens, format)); return restResponse; }
From source file:com.sfs.whichdoctor.search.sql.CreditSqlHandler.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 *///from w ww.j av a2 s. c om public final Map<String[], Collection<Object>> construct(final Object objCriteria, final Object objConstraints) throws IllegalArgumentException { CreditBean searchCriteria = null; CreditBean searchConstraints = null; if (objCriteria instanceof CreditBean) { searchCriteria = (CreditBean) objCriteria; } if (objConstraints instanceof CreditBean) { searchConstraints = (CreditBean) objConstraints; } if (searchCriteria == null) { throw new IllegalArgumentException("The search criteria must " + "be a valid CreditBean"); } if (searchConstraints == null) { throw new IllegalArgumentException("The search constraints must " + "be a valid CreditBean"); } 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 (tagWHERE.compareTo("") != 0) { /* A WHERE condition is defined */ sqlWHERE.append( " " + this.getSQL().getValue("credit/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()); } } if (searchCriteria.getBasicSearch() != null) { if (searchCriteria.getBasicSearch().compareTo("") != 0) { String searchString = searchCriteria.getBasicSearch().trim(); int basicSearch = 0; try { basicSearch = Integer.parseInt(searchString); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing basic search parameter: " + nfe.getMessage()); } if (basicSearch == 0) { // If the search string has : in the first ten // characters the financial abbreviation is probably // included - strip it out for search purposes if (searchString.indexOf(": ") > 3 && searchString.indexOf(": ") < 10) { searchString = searchString.substring(3, searchString.length()); } String field = "%" + searchString + "%"; sqlWHERE.append(" AND (concat(credit.CreditNo, ': '," + " credit.Description) LIKE ?)"); description.append(" and a credit description like '" + searchString + "'"); parameters.add(field); } else { sqlWHERE.append(" AND (credit.CreditNo LIKE ?)"); description.append(" and a credit number of '" + searchString + "'"); parameters.add("%" + searchString); } } } if (searchCriteria.getNumber() != null) { boolean blSearchConstraints = false; if (searchCriteria.getNumber().compareTo("") != 0) { if (searchConstraints.getNumber() != null) { if (searchConstraints.getNumber().compareTo("") != 0) { blSearchConstraints = true; } } if (blSearchConstraints) { if (searchConstraints.getNumber().compareTo("-") == 0) { // Less than Credit specified String field = searchCriteria.getNumber(); sqlWHERE.append(" AND credit.CreditNo <= ?"); description.append(" and a credit number less than '" + field + "'"); parameters.add(field); } else if (searchConstraints.getNumber().compareTo("+") == 0) { // Greater then Credit specified String field = searchCriteria.getNumber(); sqlWHERE.append(" AND credit.CreditNo >= ?"); description.append(" and a credit number greater than '" + field + "'"); parameters.add(field); } else { // Range between a and b - find whether greater than or // less than int intA = 0; int intB = 0; try { intA = Integer.parseInt(searchCriteria.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing CreditNo: " + nfe.getMessage()); } try { intB = Integer.parseInt(searchConstraints.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing CreditNo: " + nfe.getMessage()); } if (intA == intB) { // criteria A and B are the same sqlWHERE.append(" AND credit.CreditNo LIKE ?"); description.append(" and a credit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } if (intA < intB) { // criteria A is less than B sqlWHERE.append(" AND credit.CreditNo BETWEEN ? AND ?"); description.append(" and a credit number between '" + searchCriteria.getNumber() + "' and '" + searchConstraints.getNumber() + "'"); parameters.add(searchCriteria.getNumber()); parameters.add(searchConstraints.getNumber()); } if (intA > intB) { // Criteria A is greater than B sqlWHERE.append(" AND credit.CreditNo BETWEEN ? AND ?"); description.append(" and a credit number between '" + searchConstraints.getNumber() + "' and '" + searchCriteria.getNumber() + "'"); parameters.add(searchConstraints.getNumber()); parameters.add(searchCriteria.getNumber()); } } } else { sqlWHERE.append(" AND credit.CreditNo LIKE ?"); description.append(" and a credit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } } } if (searchCriteria.getGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR credit.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 credit.CreditNo LIKE ?"); 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 has a credit number in the supplied list"); } } if (searchCriteria.getPersonId() > 0) { sqlWHERE.append(" AND credit.PersonId = ?"); description.append(" and a person GUID equal to '" + searchCriteria.getPersonId() + "'"); parameters.add(searchCriteria.getPersonId()); } if (searchCriteria.getOrganisationId() > 0) { sqlWHERE.append(" AND credit.OrganisationId = ?"); description.append(" and a organisation GUID equal to '" + searchCriteria.getOrganisationId() + "'"); parameters.add(searchCriteria.getOrganisationId()); } if (searchCriteria.getCancelled()) { if (searchConstraints.getCancelled()) { // Only cancelled sqlWHERE.append(" AND credit.Cancelled = true"); description.append(" and the credit is cancelled"); } } else { if (!searchConstraints.getCancelled()) { // Only active sqlWHERE.append(" AND credit.Cancelled = false"); description.append(" and the credit is not cancelled"); } } if (searchCriteria.getTypeName() != null) { if (searchCriteria.getTypeName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Name LIKE ?"); description.append(" and a credit type like '" + searchCriteria.getTypeName() + "'"); parameters.add("%" + searchCriteria.getTypeName() + "%"); } } if (searchCriteria.getClassName() != null) { if (searchCriteria.getClassName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Class LIKE ?"); description.append(" and a credit class like '" + searchCriteria.getClassName() + "'"); parameters.add("%" + searchCriteria.getClassName() + "%"); } } if (searchCriteria.getGSTRate() >= 0) { sqlWHERE.append(" AND credit.GSTRate = ?"); description.append(" and GST is " + Formatter.toPercent(searchCriteria.getGSTRate() / 100, 1, "%") + " in the credit"); parameters.add(searchCriteria.getGSTRate()); } if (StringUtils.isNotBlank(searchCriteria.getDescription())) { if (searchCriteria.getDescription().indexOf("\"") > -1) { // Description contains "" so treat as a specific search sqlWHERE.append(" AND credit.Description LIKE ?"); description.append(" and has a credit description like '" + searchCriteria.getDescription() + "'"); parameters.add(StringUtils.replace(searchCriteria.getDescription(), "\"", "")); } else { sqlWHERE.append(" AND credit.Description LIKE ?"); description.append(" and has a credit description like '" + searchCriteria.getDescription() + "'"); parameters.add("%" + searchCriteria.getDescription() + "%"); } } if (searchCriteria.getSecurity() != null) { if (searchCriteria.getSecurity().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Security = ?"); description.append(" and has a security setting of '" + searchCriteria.getSecurity() + "'"); parameters.add(searchCriteria.getSecurity()); } } if (searchCriteria.getIssued() != null) { if (searchConstraints.getIssued() != null) { int larger = searchCriteria.getIssued().compareTo(searchConstraints.getIssued()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND credit.Issued BETWEEN ? AND ?"); description.append(" and was issued between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND credit.Issued BETWEEN ? AND ?"); description.append(" and was issued between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND credit.Issued = ?"); description.append(" and was issued on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND credit.Issued = ?"); description.append(" and was issued on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getDebit() != null && searchCriteria.getDebit().getGUID() > 0) { sqlWHERE.append(" AND credit.InvoiceId = ?"); description.append(" and a debit GUID of '" + searchCriteria.getDebit().getGUID() + "'"); parameters.add(searchCriteria.getDebit().getGUID()); } 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 credit.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:com.eyekabob.jaxrs.Event.java
protected String getResponseBySearchTerm(String search, String limit) { JSONObject response = new JSONObject(); int intLimit; try {/*from w ww. j a v a 2s. co m*/ intLimit = Integer.parseInt(limit); } catch (NumberFormatException e) { intLimit = DEFAULT_SEARCH_LIMIT; } Connection conn = null; String error = null; try { response.put("search", search); String query = "SELECT id,name FROM event WHERE name LIKE ? LIMIT ?"; String wildcardSearch = "%" + search + "%"; List<Map<String, Object>> eventResult = DBUtils.query(query, wildcardSearch, intLimit); JSONArray events = new JSONArray(); for (Map<String, Object> row : eventResult) { JSONObject event = new JSONObject(); event.put("id", row.get("id")); event.put("name", row.get("name")); events.put(event); } response.put("events", events); } catch (SQLException e) { error = getJSONError(SQLException.class.getSimpleName(), e.getMessage()); } catch (JSONException e) { error = getJSONError(JSONException.class.getSimpleName(), e.getMessage()); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { error = getJSONError(SQLException.class.getSimpleName(), e.getMessage()); } } } if (error != null) { return error; } return response.toString(); }
From source file:de.micromata.genome.gwiki.controls.GWikiRegisterUserActionBean.java
protected boolean doRegister() { if (StringUtils.isBlank(catchaInput) == true) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.nocatcha", "catchaInput"); return false; }/*from www .ja v a 2s. com*/ if (checkCatcha() == false) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.wrongcatcha", "catchaInput"); return false; } user = StringUtils.trim(user); if (StringUtils.isBlank(user) == true) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userempty", "user"); return false; } email = StringUtils.trim(email); if (StringUtils.isBlank(email) == true) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailempty", "email"); return false; } if (checkEmail(email) == false) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.emailnotvalid", "email"); return false; } if (doubleOptIn == false) { if (StringUtils.isBlank(pass) == true) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passempty", "pass"); pass2 = ""; return false; } if (pass.equals(pass2) == false) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.passnotequal", "pass"); return false; } } else { pass = GWikiLoginActionBean.genPassword(); } GWikiAuthorizationExt authExt = (GWikiAuthorizationExt) wikiContext.getWikiWeb().getAuthorization(); if (authExt.hasUser(wikiContext, user) == true) { wikiContext.addValidationFieldError("gwiki.page.admin.RegisterUser.message.userexists", "user"); return false; } if (GWikiSimpleUserAuthorization.rankPasswort(pass) < 1000) { wikiContext.addValidationFieldError("gwiki.profile.message.password_too_simple", "pass"); return false; } String cp = GWikiSimpleUserAuthorization.encrypt(pass); GWikiProps props = new GWikiProps(); GWikiElement registeredUser = wikiContext.getWikiWeb().findElement("admin/user/registereduser"); if (registeredUser != null) { props = new GWikiProps(((GWikiPropsArtefakt) registeredUser.getMainPart()).getCompiledObject()); } props.setStringValue(GWikiAuthorizationExt.USER_PROP_EMAIL, email); if (props.getStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, null) == null) { props.setStringValue(GWikiAuthorizationExt.USER_PROP_RIGHTSRULE, "GWIKI_VIEWPAGES"); } props.setStringValue(GWikiAuthorizationExt.USER_PROP_PASSWORD, cp); Locale loc = wikiContext.getRequest().getLocale(); GWikiGlobalConfig gc = wikiContext.getWikiWeb().getWikiConfig(); if (loc != null) { String lang = loc.getLanguage(); if (gc.getAvailableLanguages(wikiContext).contains(lang) == true) { props.setStringValue(GWikiAuthorizationExt.USER_LANG, lang); } } if (StringUtils.isEmpty(clientTzOffset) == false) { try { int offsetMin = Integer.parseInt(clientTzOffset); int daysaving = TimeZone.getDefault().getDSTSavings(); int offsetMs = (offsetMin * 1000 * 60 * -1) - daysaving; int offsetHour = ((offsetMin / 60) * -1) - (daysaving / ((int) TimeInMillis.HOUR)); String tzs = "Etc/GMT"; if (offsetHour != 0) { if (offsetHour > 0) { tzs += "+"; } tzs += offsetHour; } List<String> tcs = gc.getAvailableTimeZones(wikiContext); if (tcs.contains(tzs) == true) { props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzs); } else { // String[] offsets = TimeZone.getAvailableIDs(offsetMs); for (String tzss : tcs) { TimeZone tz = TimeZone.getTimeZone(tzss); int rawo = tz.getOffset(System.currentTimeMillis()); if (rawo == offsetMs) { props.setStringValue(GWikiAuthorizationExt.USER_TZ, tzss); break; } } } } catch (NumberFormatException ex) { // ignore } } if (authExt.createUser(wikiContext, user, props) == false) { wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.internalerrorstore"); return false; } if (doubleOptIn == true) { try { GWikiLoginActionBean.sendPasswordToUser(wikiContext, user, email, pass); wikiContext.addValidationError("gwiki.page.admin.Login.message.resetpassw.emailsent"); } catch (Exception ex) { GWikiLog.error("Cannot send register email: " + ex.getMessage(), ex); wikiContext.addValidationError("gwiki.page.admin.RegisterUser.message.unabletosend"); } showForm = false; } else { boolean success = wikiContext.getWikiWeb().getAuthorization().login(wikiContext, StringUtils.trim(user), StringUtils.trim(pass)); if (success == false) { return false; } } return true; }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointAuthority.java
protected void getSharePointSession() throws ManifoldCFException { if (proxy == null) { // Set up server URL try {//www. j ava 2s. c o m if (serverPortString == null || serverPortString.length() == 0) { if (serverProtocol.equals("https")) this.serverPort = 443; else this.serverPort = 80; } else this.serverPort = Integer.parseInt(serverPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } int proxyPort = 8080; if (proxyPortString != null && proxyPortString.length() > 0) { try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } } serverUrl = serverProtocol + "://" + serverName; if (serverProtocol.equals("https")) { if (serverPort != 443) serverUrl += ":" + Integer.toString(serverPort); } else { if (serverPort != 80) serverUrl += ":" + Integer.toString(serverPort); } fileBaseUrl = serverUrl + encodedServerLocation; int connectionTimeout = 60000; int socketTimeout = 900000; // Set up ssl if indicated connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); SSLConnectionSocketFactory myFactory = null; if (keystoreData != null) { keystoreManager = KeystoreManagerFactory.make("", keystoreData); myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), new BrowserCompatHostnameVerifier()); } if (strippedUserName != null) { credentialsProvider.setCredentials(new AuthScope(serverName, serverPort), new NTCredentials(strippedUserName, password, currentHost, ntlmDomain)); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider); if (myFactory != null) builder.setSSLSocketFactory(myFactory); builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); httpClient = builder.build(); proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, serverUserName, password, org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd", httpClient, isClaimSpace); } sharepointSessionTimeout = System.currentTimeMillis() + SharePointExpirationInterval; }
From source file:eu.gloriaproject.tools.userreservations.UserReservationController.java
/** * To go to the Experiment Panel (Private Page) *///from w w w. j a v a 2s.c o m @ResourceMapping(value = "goExperiment") public void goExperiment(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { ResourceBundle rb = ResourceBundle.getBundle("Language", request.getLocale()); String reservationId = request.getParameter("reservationId"); // Get email and password of the current user ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String emailUser = themeDisplay.getUser().getEmailAddress(); String passwordUser = themeDisplay.getUser().getPassword(); try { reservationsService.getExperimentInformation(emailUser, passwordUser, Integer.parseInt(reservationId)); // TODO Set the experiment selected String friendlyURL = renderExperiment(request, response, reservationId, "SOLAR"); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", true); jsonObject.put("message", rb.getString("msg-experiment-created")); jsonObject.put("url", friendlyURL); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NumberFormatException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (OnlineExperimentException e) { log.error("No reservation for " + reservationId + ":" + e.getMessage()); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-not-reservations")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentNotInstantiatedException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-not-instantiated")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); log.error("No reservation for " + reservationId + ":" + e.getMessage()); } catch (NoSuchReservationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-current-reservation")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ConnectionException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NoSuchOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentParameterException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NoSuchExperimentException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } }
From source file:com.collabnet.ccf.pi.sfee.v44.SFEETrackerHandler.java
/** * Updates the artifact if conflict resolution priority allows it * /*from ww w.j a v a 2 s . co m*/ * @param ga * generic artifact passed to the update method * @param sessionId * @param trackerId * @param description * @param category * @param group * @param status * @param statusClass * @param customer * @param priority * @param estimatedHours * @param actualHours * @param closeDate * @param assignedTo * @param reportedReleaseId * @param resolvedReleaseId * @param flexFieldNames * @param flexFieldValues * @param flexFieldTypes * @param flexFieldPreserve * @param title * @param Id * @param comments * @param conflictResolutionPriority * @return updated artifact or null if conflict resolution has decided not * to update the artifact * @throws RemoteException */ public ArtifactSoapDO updateArtifact(GenericArtifact ga, String sessionId, GenericArtifactField trackerId, GenericArtifactField description, GenericArtifactField category, GenericArtifactField group, GenericArtifactField status, GenericArtifactField statusClass, GenericArtifactField customer, GenericArtifactField priority, GenericArtifactField estimatedHours, GenericArtifactField actualHours, GenericArtifactField closeDate, GenericArtifactField assignedTo, GenericArtifactField reportedReleaseId, GenericArtifactField resolvedReleaseId, List<String> flexFieldNames, List<Object> flexFieldValues, List<String> flexFieldTypes, Set<String> overriddenFlexFields, GenericArtifactField title, String Id, String[] comments, boolean translateTechnicalReleaseIds) throws RemoteException { boolean mainArtifactNotUpdated = true; ArtifactSoapDO artifactData = null; while (mainArtifactNotUpdated) { try { mainArtifactNotUpdated = false; artifactData = mTrackerApp.getArtifactData(sessionId, Id); // do conflict resolution if (!AbstractWriter.handleConflicts(artifactData.getVersion(), ga)) { return null; } // here we store the values which will be really sent ArrayList<String> finalFlexFieldNames = new ArrayList<String>(); ArrayList<String> finalFlexFieldTypes = new ArrayList<String>(); ArrayList<Object> finalFlexFieldValues = new ArrayList<Object>(); SoapFieldValues currentFlexFields = artifactData.getFlexFields(); String[] currentFlexFieldNames = currentFlexFields.getNames(); Object[] currentFlexFieldValues = currentFlexFields.getValues(); String[] currentFlexFieldTypes = currentFlexFields.getTypes(); // first we filter out all current flex fields that should be // overridden for (int i = 0; i < currentFlexFieldNames.length; ++i) { if (!overriddenFlexFields.contains(currentFlexFieldNames[i])) { finalFlexFieldNames.add(currentFlexFieldNames[i]); finalFlexFieldTypes.add(currentFlexFieldTypes[i]); finalFlexFieldValues.add(currentFlexFieldValues[i]); } } // now we have to add all anticipated flex fields finalFlexFieldNames.addAll(flexFieldNames); finalFlexFieldValues.addAll(flexFieldValues); finalFlexFieldTypes.addAll(flexFieldTypes); SoapFieldValues flexFields = new SoapFieldValues(); flexFields.setNames(finalFlexFieldNames.toArray(new String[0])); flexFields.setValues(finalFlexFieldValues.toArray()); flexFields.setTypes(finalFlexFieldTypes.toArray(new String[0])); String folderIdString = artifactData.getFolderId(); if (trackerId != null && trackerId.getFieldValueHasChanged()) { folderIdString = (String) trackerId.getFieldValue(); artifactData.setFolderId(folderIdString); } if (title != null && title.getFieldValueHasChanged()) { artifactData.setTitle((String) title.getFieldValue()); } if (description != null && description.getFieldValueHasChanged()) { artifactData.setDescription((String) description.getFieldValue()); } if (group != null && group.getFieldValueHasChanged()) { artifactData.setGroup((String) group.getFieldValue()); } if (category != null && category.getFieldValueHasChanged()) { artifactData.setCategory((String) category.getFieldValue()); } if (status != null && status.getFieldValueHasChanged()) { artifactData.setStatus((String) status.getFieldValue()); } if (customer != null && customer.getFieldValueHasChanged()) { artifactData.setCustomer((String) customer.getFieldValue()); } if (priority != null && priority.getFieldValueHasChanged()) { Object fieldValueObj = priority.getFieldValue(); int fieldValue = 0; if (fieldValueObj instanceof String) { String fieldValueString = (String) fieldValueObj; try { fieldValue = Integer.parseInt(fieldValueString); } catch (NumberFormatException e) { throw new CCFRuntimeException( "Could not parse value of mandatory field priority: " + e.getMessage(), e); } } else if (fieldValueObj instanceof Integer) { fieldValue = ((Integer) fieldValueObj).intValue(); } artifactData.setPriority(fieldValue); } if (estimatedHours != null && estimatedHours.getFieldValueHasChanged()) { Object fieldValueObj = estimatedHours.getFieldValue(); int fieldValue = 0; if (fieldValueObj instanceof String) { String fieldValueString = (String) fieldValueObj; try { fieldValue = Integer.parseInt(fieldValueString); } catch (NumberFormatException e) { throw new CCFRuntimeException( "Could not parse value of mandatory field estimatedHours: " + e.getMessage(), e); } } else if (fieldValueObj instanceof Integer) { fieldValue = ((Integer) fieldValueObj).intValue(); } artifactData.setEstimatedHours(fieldValue); } if (actualHours != null && actualHours.getFieldValueHasChanged()) { Object fieldValueObj = actualHours.getFieldValue(); int fieldValue = 0; if (fieldValueObj instanceof String) { String fieldValueString = (String) fieldValueObj; try { fieldValue = Integer.parseInt(fieldValueString); } catch (NumberFormatException e) { throw new CCFRuntimeException( "Could not parse value of mandatory field actualHours: " + e.getMessage(), e); } } else if (fieldValueObj instanceof Integer) { fieldValue = ((Integer) fieldValueObj).intValue(); } artifactData.setActualHours(fieldValue); } if (assignedTo != null && assignedTo.getFieldValueHasChanged()) { artifactData.setAssignedTo((String) assignedTo.getFieldValue()); } if (statusClass != null && statusClass.getFieldValueHasChanged()) { artifactData.setStatusClass((String) statusClass.getFieldValue()); } if (closeDate != null && closeDate.getFieldValueHasChanged()) { Object fieldValueObj = closeDate.getFieldValue(); Date fieldValue = null; if (fieldValueObj instanceof String) { String fieldValueString = (String) fieldValueObj; fieldValue = DateUtil.parse(fieldValueString); } else if (fieldValueObj instanceof Date) { fieldValue = (Date) fieldValueObj; } artifactData.setCloseDate(fieldValue); } if (reportedReleaseId != null && reportedReleaseId.getFieldValueHasChanged()) { String reportedReleaseIdString = (String) reportedReleaseId.getFieldValue(); if (translateTechnicalReleaseIds) { reportedReleaseIdString = convertReleaseId(sessionId, reportedReleaseIdString, folderIdString); } artifactData.setReportedReleaseId(reportedReleaseIdString); } if (resolvedReleaseId != null && resolvedReleaseId.getFieldValueHasChanged()) { String resolvedReleaseIdString = (String) resolvedReleaseId.getFieldValue(); if (translateTechnicalReleaseIds) { resolvedReleaseIdString = convertReleaseId(sessionId, resolvedReleaseIdString, folderIdString); } artifactData.setResolvedReleaseId(resolvedReleaseIdString); } artifactData.setFlexFields(flexFields); mTrackerApp.setArtifactData(sessionId, artifactData, null, null, null, null); } catch (AxisFault e) { javax.xml.namespace.QName faultCode = e.getFaultCode(); if (!faultCode.getLocalPart().equals("VersionMismatchFault")) { throw e; } logConflictResolutor.warn("Stale update for TF tracker item " + Id + " in tracker " + trackerId + ". Trying again ...", e); mainArtifactNotUpdated = true; } } // increase version number for comment updates if (comments.length != 0) { artifactData.setVersion(artifactData.getVersion() + 1); } for (String comment : comments) { boolean commentNotUpdated = true; while (commentNotUpdated) { try { commentNotUpdated = false; if (StringUtils.isEmpty(comment)) { continue; } mTrackerApp.setArtifactData(sessionId, artifactData, comment, null, null, null); artifactData.setVersion(artifactData.getVersion() + 1); } catch (AxisFault e) { javax.xml.namespace.QName faultCode = e.getFaultCode(); if (!faultCode.getLocalPart().equals("VersionMismatchFault")) { throw e; } logConflictResolutor.warn("Stale comment update, trying again ...:", e); artifactData = mTrackerApp.getArtifactData(sessionId, Id); commentNotUpdated = true; } } } // since TF 5.3, we cannot be sure that the version number has increased automatically if (comments.length == 0) { // artifactData.setVersion(artifactData.getVersion() + 1); artifactData = mTrackerApp.getArtifactData(sessionId, Id); } log.info("Artifact updated id: " + artifactData.getId() + " in tracker " + artifactData.getFolderId()); return artifactData; }
From source file:com.sfs.whichdoctor.search.sql.DebitSqlHandler.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 ww .jav a 2s . c o m public final Map<String[], Collection<Object>> construct(final Object objCriteria, final Object objConstraints) throws IllegalArgumentException { DebitBean searchCriteria = null; DebitBean searchConstraints = null; if (objCriteria instanceof DebitBean) { searchCriteria = (DebitBean) objCriteria; } if (objConstraints instanceof DebitBean) { searchConstraints = (DebitBean) objConstraints; } if (searchCriteria == null) { throw new IllegalArgumentException("The search criteria must be " + "a valid DebitBean"); } if (searchConstraints == null) { throw new IllegalArgumentException("The search constraints must be " + "a valid DebitBean"); } 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 (tagWHERE.compareTo("") != 0) { /* * A WHERE condition is defined, add to the SQL * WHERE clause */ sqlWHERE.append( " " + this.getSQL().getValue("debit/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()); } } if (searchCriteria.getBasicSearch() != null) { if (searchCriteria.getBasicSearch().compareTo("") != 0) { String searchString = searchCriteria.getBasicSearch().trim(); int basicSearch = 0; try { basicSearch = Integer.parseInt(searchCriteria.getBasicSearch()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing BasicSearch parameter: " + nfe.getMessage()); } if (basicSearch == 0) { // If the search string has : in the first ten characters // the financial // abbreviation is probably included - strip it out for // search purposes if (searchString.indexOf(": ") > 3 && searchString.indexOf(": ") < 10) { searchString = searchString.substring(3, searchString.length()); } String field = "%" + searchString + "%"; sqlWHERE.append(" AND (concat(invoice.InvoiceNo, ': ', " + "invoice.Description) LIKE ?)"); description.append(" and a debit description like '" + searchCriteria.getBasicSearch() + "'"); parameters.add(field); } else { String field = searchCriteria.getBasicSearch(); sqlWHERE.append(" AND (invoice.InvoiceNo LIKE ?)"); description.append(" and a debit number of '" + searchCriteria.getBasicSearch() + "'"); parameters.add("%" + field); } } } if (searchCriteria.getNumber() != null) { boolean blSearchConstraints = false; if (searchCriteria.getNumber().compareTo("") != 0) { if (searchConstraints.getNumber() != null) { if (searchConstraints.getNumber().compareTo("") != 0) { blSearchConstraints = true; } } if (blSearchConstraints) { if (searchConstraints.getNumber().compareTo("-") == 0) { // Less than DebitNo specified sqlWHERE.append(" AND invoice.InvoiceNo <= ?"); description.append(" and a debit number less than '" + searchCriteria.getNumber() + "'"); parameters.add(searchCriteria.getNumber()); } else if (searchConstraints.getNumber().compareTo("+") == 0) { // Greater then DebitNo specified sqlWHERE.append(" AND invoice.InvoiceNo >= ?"); description.append(" and a debit number greater than '" + searchCriteria.getNumber() + "'"); parameters.add(searchCriteria.getNumber()); } else { // Range between a and b - find whether greater than or // less than int debitA = 0; int debitB = 0; try { debitA = Integer.parseInt(searchCriteria.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing DebitNo parameter: " + nfe.getMessage()); } try { debitB = Integer.parseInt(searchConstraints.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing DebitNo parameter: " + nfe.getMessage()); } if (debitA == debitB) { // criteria A and B are the same sqlWHERE.append(" AND invoice.InvoiceNo LIKE ?"); description.append(" and a debit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } if (debitA < debitB) { // criteria A is less than B sqlWHERE.append(" AND invoice.InvoiceNo BETWEEN ? AND ?"); description.append(" and a debit number between '" + searchCriteria.getNumber() + "' and '" + searchConstraints.getNumber() + "'"); parameters.add(searchCriteria.getNumber()); parameters.add(searchConstraints.getNumber()); } if (debitA > debitB) { // Criteria A is greater than B sqlWHERE.append(" AND invoice.InvoiceNo BETWEEN ? AND ?"); description.append(" and a debit number between '" + searchConstraints.getNumber() + "' and '" + searchCriteria.getNumber() + "'"); parameters.add(searchConstraints.getNumber()); parameters.add(searchCriteria.getNumber()); } } } else { sqlWHERE.append(" AND invoice.InvoiceNo LIKE ?"); description.append(" and a debit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } } } if (searchCriteria.getGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR invoice.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 invoice.InvoiceNo LIKE ?"); 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 has a debit number in the supplied list"); } } if (searchConstraints.getOutstandingValue() != 0) { final double outstandingA = searchCriteria.getOutstandingValue(); final double outstandingB = searchConstraints.getOutstandingValue(); if (outstandingA < outstandingB) { // criteria A is less than B sqlWHERE.append(" AND invoice.OutstandingValue BETWEEN ? AND ?"); description.append(" and an outstanding value between '" + Formatter.toCurrency(outstandingA, "$") + "' and '" + Formatter.toCurrency(outstandingB, "$") + "'"); parameters.add(outstandingA); parameters.add(outstandingB); } if (outstandingA > outstandingB) { // Criteria A is greater than B sqlWHERE.append(" AND invoice.OutstandingValue BETWEEN ? AND ?"); description.append(" and an outstanding value between '" + Formatter.toCurrency(outstandingB, "$") + "' and '" + Formatter.toCurrency(outstandingA, "$") + "'"); parameters.add(outstandingB); parameters.add(outstandingA); } if (outstandingA == outstandingB) { sqlWHERE.append(" AND invoice.OutstandingValue = ?"); description.append( " and an outstanding value equal to '" + Formatter.toCurrency(outstandingA, "$") + "'"); parameters.add(outstandingA); } } else { if (searchCriteria.getOutstandingValue() != 0) { sqlWHERE.append(" AND invoice.OutstandingValue = ?"); description.append(" and an outstanding value equal to '" + Formatter.toCurrency(searchCriteria.getOutstandingValue(), "$") + "'"); parameters.add(searchCriteria.getOutstandingValue()); } } if (searchCriteria.getPersonId() > 0) { sqlWHERE.append(" AND invoice.PersonId = ?"); description.append(" and a person GUID equal to '" + searchCriteria.getPersonId() + "'"); parameters.add(searchCriteria.getPersonId()); } if (searchCriteria.getOrganisationId() > 0) { sqlWHERE.append(" AND invoice.OrganisationId = ?"); description.append(" and an organisation GUID equal to '" + searchCriteria.getOrganisationId() + "'"); parameters.add(searchCriteria.getOrganisationId()); } if (searchCriteria.getDescription() != null) { if (searchCriteria.getDescription().compareTo("") != 0) { if (searchCriteria.getDescription().indexOf("\"") > -1) { // Description contains "" so treat as a specific search sqlWHERE.append(" AND invoice.Description LIKE ?"); description.append(" and a debit description like '" + searchCriteria.getDescription() + "'"); parameters.add(StringUtils.replace(searchCriteria.getDescription(), "\"", "")); } else { sqlWHERE.append(" AND invoice.Description LIKE ?"); description.append(" and a debit description like '" + searchCriteria.getDescription() + "'"); parameters.add("%" + searchCriteria.getDescription() + "%"); } } } if (searchCriteria.getCancelled()) { if (searchConstraints.getCancelled()) { // Only cancelled invoices sqlWHERE.append(" AND invoice.Cancelled = true"); description.append(" and the debit is cancelled"); } } else { if (!searchConstraints.getCancelled()) { // Only non-cancelled debits sqlWHERE.append(" AND invoice.Cancelled = false"); description.append(" and the debit is not cancelled"); } } if (searchCriteria.getGSTRate() >= 0) { sqlWHERE.append(" AND invoice.GSTRate = ?"); description.append(" and GST is " + Formatter.toPercent(searchCriteria.getGSTRate() / 100, 1, "%") + " in the debit"); parameters.add(searchCriteria.getGSTRate()); } if (StringUtils.isNotBlank(searchCriteria.getSecurity())) { sqlWHERE.append(" AND financialtype.Security = ?"); description.append(" and has a security setting of '" + searchCriteria.getSecurity() + "'"); parameters.add(searchCriteria.getSecurity()); } // Other searches: cancelled, date issued if (searchCriteria.getIssued() != null) { if (searchConstraints.getIssued() != null) { int larger = searchCriteria.getIssued().compareTo(searchConstraints.getIssued()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND invoice.Issued BETWEEN ? AND ?"); description.append(" and issued between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND invoice.Issued BETWEEN ? AND ?"); description.append(" and issued between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND invoice.Issued = ?"); description.append(" and issued on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND invoice.Issued = ?"); description.append(" and issued on '" + field + "'"); parameters.add(field); } } 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 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 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 created on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and created between '" + 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 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 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 modified on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and modified on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getTypeName() != null) { if (searchCriteria.getTypeName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Name LIKE ?"); description.append(" and a debit type like '" + searchCriteria.getTypeName() + "'"); parameters.add(searchCriteria.getTypeName()); } } if (searchCriteria.getClassName() != null) { if (searchCriteria.getClassName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Class LIKE ?"); description.append(" and a debit class like '" + searchCriteria.getClassName() + "'"); parameters.add(searchCriteria.getClassName()); } } if (searchCriteria.getIncludeGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getIncludeGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR invoice.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:com.lrodriguez.SVNBrowser.java
private void doGetFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logDebug("dispatching getFile"); HttpSession session = request.getSession(); if (session != null && (request.getParameter(GET_FILE) == null || "".equals(request.getParameter(GET_FILE))) && request.getParameter(REVISION) != null) { response.getWriter().println("an error ocurred, check the query parameters"); }//from ww w .ja v a 2 s . com if (session.getAttribute(SVNBrowser.SVNSESSION) != null) { SVNHttpSession svnsession = (SVNHttpSession) session.getAttribute(SVNBrowser.SVNSESSION); if (svnsession != null) { SVNRepository repo = svnsession.getRepository(); logDebug("im here!"); response.setHeader("Content-disposition", "attachment; filename=\"" + request.getParameter(GET_FILE) .substring(request.getParameter(GET_FILE).lastIndexOf("/") + 1)); try { repo.getFile(request.getParameter(GET_FILE), Long.parseLong(request.getParameter("revision")), null, response.getOutputStream()); } catch (NumberFormatException e) { request.setAttribute(ERROR, e.getMessage()); request.getRequestDispatcher(INDEX_JSP).forward(request, response); } catch (SVNException e) { request.setAttribute(ERROR, e.getMessage()); request.getRequestDispatcher(INDEX_JSP).forward(request, response); } } else { request.setAttribute(ERROR, "svnsession is null, try refreshing the session by setting the Repository URL"); request.getRequestDispatcher(INDEX_JSP).forward(request, response); } } }