List of usage examples for org.springframework.util MultiValueMap getFirst
@Nullable V getFirst(K key);
From source file:com.svds.resttest.services.GenericDataService.java
/** * Build and run a SELECT query// ww w . j av a 2s . c om * * @param databaseEngine Database engine to query (hive or impala) * @param tableName Table name to query * @param requestParams Parameters for WHERE clause * @return Output of select query */ public GenericResultsOutput runQueryResults(String databaseEngine, String tableName, MultiValueMap<String, String> requestParams) { GenericResultsOutput genericResultsOutput = new GenericResultsOutput(); genericResultsOutput.setName("GenericDataService.runQueryCount"); genericResultsOutput.setRequestParams(requestParams); genericResultsOutput.setDatabaseEngine(databaseEngine); genericResultsOutput.setTableName(tableName); Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; int limit = ROW_LIMIT; if (requestParams.containsKey("limit")) { limit = new Integer(requestParams.getFirst("limit")); } StringBuilder connectionURL = new StringBuilder(); connectionURL.append(DATABASES_BUNDLE.getString(databaseEngine)); LOG.info("connectionURL: " + connectionURL.toString()); StringBuilder sql = new StringBuilder(); sql.append("SELECT * FROM "); sql.append(TABLES_BUNDLE.getString(tableName)); try { LOG.info("RequestParams: " + requestParams.size()); if (requestParams.size() > 0) { sql.append(" WHERE "); sql.append(BuildWhereClause.buildWhereClause(requestParams)); } sql.append(" limit ").append(limit); LOG.info("sql: " + sql.toString()); genericResultsOutput.setSql(sql.toString()); Class.forName("org.apache.hive.jdbc.HiveDriver"); connection = DriverManager.getConnection(connectionURL.toString(), "hadoop", ""); pstmt = connection.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); int rowCount = 0; while (rs.next()) { if (genericResultsOutput.getMetaData().size() > 0) { //Got it!! } else { Map<String, Integer> metaDataSet = new HashMap<>(); this.getMetaData(rs, metaDataSet, genericResultsOutput); } List<Object> resultsArrayList = new ArrayList<>(); this.resultsWithoutMetaData(rs, genericResultsOutput, resultsArrayList); genericResultsOutput.getResults().add(resultsArrayList); rowCount++; } genericResultsOutput.setCount(rowCount); genericResultsOutput.setStatus("OK"); } catch (Exception e) { LOG.error("GenericDataService.runQueryResults(): " + e.getMessage(), e); genericResultsOutput.setMessage(e.getMessage()); genericResultsOutput.setStatus("ERROR"); } finally { try { rs.close(); } catch (Exception e) { LOG.error("GenericDataService.runQueryResults() Close result set: " + e.getMessage(), e); } try { pstmt.close(); } catch (Exception e) { LOG.error("GenericDataService.runQueryResults() Close prepared statement: " + e.getMessage(), e); } try { connection.close(); } catch (Exception e) { LOG.error("GenericDataService.runQueryResults() Close connection: " + e.getMessage(), e); } } return genericResultsOutput; }
From source file:com.gvmax.web.api.WebAppAPI.java
private void extractUserFromForm(User user, MultiValueMap<String, String> form) { if (form.containsKey("wc")) { ensureExists("sendGTalk", form); ensureExists("sendProwl", form); ensureExists("sendEmail", form); ensureExists("sendPost", form); ensureExists("sendTwitter", form); ensureExists("sendSMS", form); ensureExists("sendHowl", form); ensureExists("sendAutoResponse", form); }//from w ww . j ava 2 s . c o m // GTALK if (form.containsKey("sendGTalk")) { user.setSendGTalk(getBoolean("sendGTalk", form)); user.setgTalkEmail(form.getFirst("gTalkEmail")); String gTalkPassword = form.getFirst("gTalkPassword"); if (!HIDDEN_PASSWORD.equals(gTalkPassword)) { user.setgTalkPassword(gTalkPassword); } user.setgTalkGroup(form.getFirst("gTalkGroup")); } if (form.containsKey("sendProwl")) { user.setSendProwl(getBoolean("sendProwl", form)); user.setProwlApiKeys(form.getFirst("prowlApiKeys")); user.setProwlSMSPriority(getInt("prowlSMSPriority", form)); user.setProwlVMPriority(getInt("prowlVMPriority", form)); user.setProwlMCPriority(getInt("prowlMCPriority", form)); } if (form.containsKey("sendEmail")) { user.setSendEmail(getBoolean("sendEmail", form)); user.setEmailAddresses(form.getFirst("emailAddresses")); } if (form.containsKey("sendPost")) { user.setSendPost(getBoolean("sendPost", form)); user.setPostURLs(form.getFirst("postURLs")); } if (form.containsKey("sendTwitter")) { user.setSendTwitter(getBoolean("sendTwitter", form)); user.setTwitterScreenName(form.getFirst("twitterScreenName")); } if (form.containsKey("sendSMS")) { user.setSendSMS(getBoolean("sendSMS", form)); user.setSmsGroup(form.getFirst("smsGroup")); } if (form.containsKey("sendHowl")) { user.setSendHowl(getBoolean("sendHowl", form)); user.setHowlUsername(form.getFirst("howlUsername")); String howlPassword = form.getFirst("howlPassword"); if (!HIDDEN_PASSWORD.equals(howlPassword)) { user.setHowlPassword(howlPassword); } } if (form.containsKey("sendAutoResponse")) { user.setSendAutoResponse(getBoolean("sendAutoResponse", form)); user.setAutoResponse(form.getFirst("autoResponse")); } }
From source file:com.expedia.seiso.web.controller.delegate.RepoSearchDelegate.java
private Object getResult(Class<?> itemClass, Method searchMethod, Pageable pageable, MultiValueMap<String, String> params) { val searchMethodName = searchMethod.getName(); log.trace("Finding {} using method {}", itemClass.getSimpleName(), searchMethodName); val repo = repositories.getRepositoryFor(itemClass); val paramClasses = searchMethod.getParameterTypes(); val allAnns = searchMethod.getParameterAnnotations(); val paramVals = new Object[paramClasses.length]; for (int i = 0; i < paramClasses.length; i++) { log.trace("Processing param {}", i); if (paramClasses[i] == Pageable.class) { paramVals[i] = pageable;/*from w w w . ja va 2 s. c o m*/ } else { val currentAnns = allAnns[i]; for (val currentAnn : currentAnns) { if (Param.class.equals(currentAnn.annotationType())) { log.trace("Found @Param"); if (conversionService.canConvert(String.class, paramClasses[i])) { val paramAnn = (Param) currentAnn; val paramName = paramAnn.value(); val paramValAsStr = params.getFirst(paramName); log.trace("Setting param: {}={}", paramName, paramValAsStr); paramVals[i] = conversionService.convert(paramValAsStr, paramClasses[i]); } else { log.trace("BUG! Not setting the param value!"); } } } } } log.trace("Invoking {}.{} with {} params", repo.getClass().getName(), searchMethodName, paramVals.length); return ReflectionUtils.invokeMethod(searchMethod, repo, paramVals); }
From source file:de.blizzy.documentr.markdown.macro.impl.FlattrMacroTest.java
@Test public void getHtml() { String html = macro.getHtml(macroContext); @SuppressWarnings("nls") String re = "^<a href=\"([^\"]+)\">" + "<img src=\"https://api\\.flattr\\.com/button/flattr-badge-large\\.png\"/>" + "</a>$"; //$NON-NLS-2$ assertRE(re, html);/*from w w w.ja v a 2s . c o m*/ Matcher matcher = Pattern.compile(re, Pattern.DOTALL).matcher(html); matcher.find(); String url = StringEscapeUtils.unescapeHtml4(matcher.group(1)); UriComponents components = UriComponentsBuilder.fromHttpUrl(url).build(); assertEquals("https", components.getScheme()); //$NON-NLS-1$ assertEquals("flattr.com", components.getHost()); //$NON-NLS-1$ assertEquals(-1, components.getPort()); assertEquals("/submit/auto", components.getPath()); //$NON-NLS-1$ MultiValueMap<String, String> params = components.getQueryParams(); assertEquals(FLATTR_USER_ID, params.getFirst("user_id")); //$NON-NLS-1$ assertEquals(PAGE_URL, params.getFirst("url")); //$NON-NLS-1$ assertEquals(PAGE_TITLE, params.getFirst("title")); //$NON-NLS-1$ assertEquals("text", params.getFirst("category")); //$NON-NLS-1$ //$NON-NLS-2$ assertTrue(params.getFirst("tags").equals(TAG_1 + "," + TAG_2) || //$NON-NLS-1$ //$NON-NLS-2$ params.getFirst("tags").equals(TAG_2 + "," + TAG_1)); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:eionet.webq.web.controller.cdr.IntegrationWithCDRController.java
/** * Redirects to edit form./*w w w. ja v a2 s . co m*/ * * @param request parsed cdr request * @param xmlFiles xml files * @param webForms web forms * @return redirect string * @throws FileNotAvailableException if remote file not available */ private String redirectToEditWebForm(CdrRequest request, MultiValueMap<String, XmlFile> xmlFiles, Collection<ProjectFile> webForms) throws FileNotAvailableException { ProjectFile onlyOneAvailableForm = webForms.iterator().next(); XmlFile onlyOneAvailableFile = xmlFiles.getFirst(onlyOneAvailableForm.getXmlSchema()); String fileName = null; if (null != onlyOneAvailableFile.getFullName() && !onlyOneAvailableFile.getFullName().isEmpty()) { int index = onlyOneAvailableFile.getFullName().lastIndexOf('/'); fileName = onlyOneAvailableFile.getFullName().substring(index + 1); } return editFile(onlyOneAvailableForm, fileName, onlyOneAvailableFile.getFullName(), request); }
From source file:info.rmapproject.api.responsemgr.ResourceResponseManagerTestIT.java
/** * Test the RMap Resource RDF stmts./*w ww. j a va 2 s . c om*/ */ @Test public void getRMapResourceRdfStmtsWithLimit() { Response response = null; try { //create 1 disco RMapDiSCO rmapDisco = TestUtils.getRMapDiSCO(TestFile.DISCOA_XML); String discoURI = rmapDisco.getId().toString(); assertNotNull(discoURI); rmapService.createDiSCO(rmapDisco, requestEventDetails); MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>(); params.add(Constants.LIMIT_PARAM, "2"); response = resourceResponseManager.getRMapResourceTriples(discoURI, RdfMediaType.APPLICATION_RDFXML, params); assertNotNull(response); String body = response.getEntity().toString(); assertEquals(303, response.getStatus()); assertTrue(body.contains("page number")); URI location = response.getLocation(); MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(location).build() .getQueryParams(); String untildate = parameters.getFirst(Constants.UNTIL_PARAM); //check page 1 just has 2 statements params.add(Constants.PAGE_PARAM, "1"); params.add(Constants.UNTIL_PARAM, untildate); response = resourceResponseManager.getRMapResourceTriples(discoURI, RdfMediaType.APPLICATION_RDFXML, params); assertEquals(200, response.getStatus()); body = response.getEntity().toString(); int numMatches = StringUtils.countMatches(body, "xmlns="); assertEquals(2, numMatches); } catch (Exception e) { e.printStackTrace(); fail("Exception thrown " + e.getMessage()); } }
From source file:info.rmapproject.api.service.ResourceApiServiceTestIT.java
/** * Test the RMap Resource RDF stmts API call *//* ww w. ja va2 s. com*/ @Test public void getRMapResourceRdfStmts() throws Exception { Response response = null; //create 1 disco RMapDiSCO rmapDisco = TestUtils.getRMapDiSCO(TestFile.DISCOA_XML); String discoURI = rmapDisco.getId().toString(); assertNotNull(discoURI); rmapService.createDiSCO(rmapDisco, requestEventDetails); HttpHeaders httpheaders = mock(HttpHeaders.class); UriInfo uriInfo = mock(UriInfo.class); MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>(); params.add(Constants.LIMIT_PARAM, "2"); List<MediaType> mediatypes = new ArrayList<MediaType>(); mediatypes.add(MediaType.APPLICATION_XML_TYPE); when(uriInfo.getQueryParameters()).thenReturn(params); when(httpheaders.getAcceptableMediaTypes()).thenReturn(mediatypes); response = resourceApiService.apiGetRMapResourceTriples(httpheaders, discoURI, uriInfo); assertNotNull(response); String body = response.getEntity().toString(); assertEquals(303, response.getStatus()); assertTrue(body.contains("page number")); URI location = response.getLocation(); MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(location).build().getQueryParams(); String untildate = parameters.getFirst(Constants.UNTIL_PARAM); //check page 2 just has one statement params.add(Constants.PAGE_PARAM, "1"); params.add(Constants.UNTIL_PARAM, untildate); response = resourceApiService.apiGetRMapResourceTriples(httpheaders, discoURI, uriInfo); assertEquals(200, response.getStatus()); body = response.getEntity().toString(); int numMatches = StringUtils.countMatches(body, "xmlns="); assertEquals(2, numMatches); }
From source file:org.activiti.app.rest.editor.ModelResource.java
/** * POST /rest/models/{modelId}/editor/json -> save the JSON model *///from www.j a v a2s . c o m @RequestMapping(value = "/rest/models/{modelId}/editor/json", method = RequestMethod.POST) public ModelRepresentation saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) { // Validation: see if there was another update in the meantime long lastUpdated = -1L; String lastUpdatedString = values.getFirst("lastUpdated"); if (lastUpdatedString == null) { throw new BadRequestException("Missing lastUpdated date"); } try { Date readValue = objectMapper.getDeserializationConfig().getDateFormat().parse(lastUpdatedString); lastUpdated = readValue.getTime(); } catch (ParseException e) { throw new BadRequestException("Invalid lastUpdated date: '" + lastUpdatedString + "'"); } Model model = modelService.getModel(modelId); User currentUser = SecurityUtils.getCurrentUserObject(); boolean currentUserIsOwner = model.getLastUpdatedBy().equals(currentUser.getId()); String resolveAction = values.getFirst("conflictResolveAction"); // If timestamps differ, there is a conflict or a conflict has been resolved by the user if (model.getLastUpdated().getTime() != lastUpdated) { if (RESOLVE_ACTION_SAVE_AS.equals(resolveAction)) { String saveAs = values.getFirst("saveAs"); String json = values.getFirst("json_xml"); return createNewModel(saveAs, model.getDescription(), model.getModelType(), json); } else if (RESOLVE_ACTION_OVERWRITE.equals(resolveAction)) { return updateModel(model, values, false); } else if (RESOLVE_ACTION_NEW_VERSION.equals(resolveAction)) { return updateModel(model, values, true); } else { // Exception case: the user is the owner and selected to create a new version String isNewVersionString = values.getFirst("newversion"); if (currentUserIsOwner && "true".equals(isNewVersionString)) { return updateModel(model, values, true); } else { // Tried everything, this is really a conflict, return 409 ConflictingRequestException exception = new ConflictingRequestException( "Process model was updated in the meantime"); exception.addCustomData("userFullName", model.getLastUpdatedBy()); exception.addCustomData("newVersionAllowed", currentUserIsOwner); throw exception; } } } else { // Actual, regular, update return updateModel(model, values, false); } }
From source file:org.activiti.app.rest.editor.ModelResource.java
protected ModelRepresentation updateModel(Model model, MultiValueMap<String, String> values, boolean forceNewVersion) { String name = values.getFirst("name"); String key = values.getFirst("key"); String description = values.getFirst("description"); String isNewVersionString = values.getFirst("newversion"); String newVersionComment = null; ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(), key); if (modelKeyInfo.isKeyAlreadyExists()) { throw new BadRequestException("Model with provided key already exists " + key); }/*from w w w . j a va 2 s.c o m*/ boolean newVersion = false; if (forceNewVersion) { newVersion = true; newVersionComment = values.getFirst("comment"); } else { if (isNewVersionString != null) { newVersion = "true".equals(isNewVersionString); newVersionComment = values.getFirst("comment"); } } String json = values.getFirst("json_xml"); try { model = modelService.saveModel(model.getId(), name, key, description, json, newVersion, newVersionComment, SecurityUtils.getCurrentUserObject()); return new ModelRepresentation(model); } catch (Exception e) { log.error("Error saving model " + model.getId(), e); throw new BadRequestException("Process model could not be saved " + model.getId()); } }