List of usage examples for java.lang NullPointerException getMessage
public String getMessage()
From source file:org.opencb.opencga.storage.core.search.solr.SolrQueryParser.java
/** * Create a SolrQuery object from Query and QueryOptions. * * @param query Query/* w w w . j a v a2 s . com*/ * @param queryOptions Query Options * @return SolrQuery */ public SolrQuery parse(Query query, QueryOptions queryOptions) { List<String> filterList = new ArrayList<>(); SolrQuery solrQuery = new SolrQuery(); //------------------------------------- // QueryOptions processing //------------------------------------- if (queryOptions.containsKey(QueryOptions.INCLUDE)) { solrQuery.setFields(queryOptions.getAsStringList(QueryOptions.INCLUDE).toString()); } if (queryOptions.containsKey(QueryOptions.LIMIT)) { solrQuery.setRows(queryOptions.getInt(QueryOptions.LIMIT)); } if (queryOptions.containsKey(QueryOptions.SKIP)) { solrQuery.setStart(queryOptions.getInt(QueryOptions.SKIP)); } if (queryOptions.containsKey(QueryOptions.SORT)) { solrQuery.addSort(queryOptions.getString(QueryOptions.SORT), getSortOrder(queryOptions)); } //------------------------------------- // Query processing //------------------------------------- // OR conditions // create a list for xrefs (without genes), genes, regions and cts // the function classifyIds function differentiates xrefs from genes List<String> xrefs = new ArrayList<>(); List<String> genes = new ArrayList<>(); List<Region> regions = new ArrayList<>(); List<String> consequenceTypes = new ArrayList<>(); // xref classifyIds(VariantQueryParams.ANNOT_XREF.key(), query, xrefs, genes); classifyIds(VariantQueryParams.ID.key(), query, xrefs, genes); classifyIds(VariantQueryParams.GENE.key(), query, xrefs, genes); classifyIds(VariantQueryParams.ANNOT_CLINVAR.key(), query, xrefs, genes); classifyIds(VariantQueryParams.ANNOT_COSMIC.key(), query, xrefs, genes); // classifyIds(VariantQueryParams.ANNOT_HPO.key(), query, xrefs, genes); // Convert region string to region objects if (query.containsKey(VariantQueryParams.REGION.key())) { regions = Region.parseRegions(query.getString(VariantQueryParams.REGION.key())); } // consequence types (cts) if (query.containsKey(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key()) && StringUtils.isNotEmpty(query.getString(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key()))) { consequenceTypes = Arrays .asList(query.getString(VariantQueryParams.ANNOT_CONSEQUENCE_TYPE.key()).split("[,;]")); } // goal: [((xrefs OR regions) AND cts) OR (genes AND cts)] AND ... AND ... if (consequenceTypes.size() > 0) { if (genes.size() > 0) { // consequence types and genes String or = buildXrefOrRegionAndConsequenceType(xrefs, regions, consequenceTypes); if (xrefs.size() == 0 && regions.size() == 0) { // no xrefs or regions: genes AND cts filterList.add(buildGeneAndCt(genes, consequenceTypes)); } else { // otherwise: [((xrefs OR regions) AND cts) OR (genes AND cts)] filterList.add("(" + or + ") OR (" + buildGeneAndCt(genes, consequenceTypes) + ")"); } } else { // consequence types but no genes: (xrefs OR regions) AND cts // in this case, the resulting string will never be null, because there are some consequence types!! filterList.add(buildXrefOrRegionAndConsequenceType(xrefs, regions, consequenceTypes)); } } else { // no consequence types: (xrefs OR regions) but we must add "OR genes", i.e.: xrefs OR regions OR genes // no consequence types: (xrefs OR regions) but we must add "OR genMINes", i.e.: xrefs OR regions OR genes // we must make an OR with xrefs, genes and regions and add it to the "AND" filter list String orXrefs = buildXrefOrGeneOrRegion(xrefs, genes, regions); if (!orXrefs.isEmpty()) { filterList.add(orXrefs); } } // now we continue with the other AND conditions... // type (t) String key = VariantQueryParams.STUDIES.key(); if (isValidParam(query, VariantQueryParams.STUDIES)) { try { String value = query.getString(key); VariantDBAdaptorUtils.QueryOperation op = checkOperator(value); Set<Integer> studyIds = new HashSet<>( variantDBAdaptorUtils.getStudyIds(splitValue(value, op), queryOptions)); List<String> studyNames = new ArrayList<>(studyIds.size()); Map<String, Integer> map = variantDBAdaptorUtils.getStudyConfigurationManager().getStudies(null); if (map != null && map.size() > 1) { map.forEach((name, id) -> { if (studyIds.contains(id)) { String[] s = name.split(":"); studyNames.add(s[s.length - 1]); } }); if (op == null || op == VariantDBAdaptorUtils.QueryOperation.OR) { filterList.add(parseCategoryTermValue("studies", StringUtils.join(studyNames, ","))); } else { filterList.add(parseCategoryTermValue("studies", StringUtils.join(studyNames, ";"))); } } } catch (NullPointerException e) { logger.error(e.getMessage()); e.printStackTrace(); } } // type (t) key = VariantQueryParams.TYPE.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseCategoryTermValue("type", query.getString(key))); } // Gene biotype key = VariantQueryParams.ANNOT_BIOTYPE.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseCategoryTermValue("biotypes", query.getString(key))); } // protein-substitution key = VariantQueryParams.ANNOT_PROTEIN_SUBSTITUTION.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseScoreValue(query.getString(key))); } // conservation key = VariantQueryParams.ANNOT_CONSERVATION.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseScoreValue(query.getString(key))); } // cadd, functional score key = VariantQueryParams.ANNOT_FUNCTIONAL_SCORE.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseScoreValue(query.getString(key))); } // maf population frequency // in the model: "popFreq__1kG_phase3__CLM":0.005319148767739534 key = VariantQueryParams.ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parsePopValue("popFreq", query.getString(key))); } // stats maf // in the model: "stats__1kg_phase3__ALL"=0.02 key = VariantQueryParams.STATS_MAF.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parsePopValue("stats", query.getString(key))); } // GO key = VariantQueryParams.ANNOT_GO.key(); if (StringUtils.isNotEmpty(query.getString(key))) { List<String> gos = Arrays.asList(query.getString(key).split(",")); Set genesByGo = variantDBAdaptorUtils.getGenesByGo(gos); if (genesByGo != null && genesByGo.size() > 0) { filterList.add(parseCategoryTermValue("xrefs", StringUtils.join(genesByGo, ","))); } } // hpo key = VariantQueryParams.ANNOT_HPO.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseCategoryTermValue("traits", query.getString(key))); } // clinvar key = VariantQueryParams.ANNOT_CLINVAR.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseCategoryTermValue("traits", query.getString(key))); } // traits key = VariantQueryParams.ANNOT_TRAITS.key(); if (StringUtils.isNotEmpty(query.getString(key))) { filterList.add(parseCategoryTermValue("traits", query.getString(key))); } //------------------------------------- // Facet processing //------------------------------------- if (query.containsKey("facet.field")) { solrQuery.addFacetField((query.get("facet.field").toString())); } if (query.containsKey("facet.fields")) { solrQuery.addFacetField((query.get("facet.fields").toString().split(","))); } if (query.containsKey("facet.query")) { solrQuery.addFacetQuery(query.get("facet.query").toString()); } if (query.containsKey("facet.prefix")) { solrQuery.setFacetPrefix(query.get("facet.prefix").toString()); } if (query.containsKey("facet.range")) { Map<String, Map<String, Number>> rangeFields = (Map<String, Map<String, Number>>) query .get("facet.range"); for (String k : rangeFields.keySet()) { Number rangeStart = rangeFields.get(k).get("facet.range.start"); Number rangeEnd = rangeFields.get(k).get("facet.range.end"); Number rangeGap = rangeFields.get(k).get("facet.range.gap"); solrQuery.addNumericRangeFacet(k, rangeStart, rangeEnd, rangeGap); } } logger.debug("query = {}\n", query.toJson()); solrQuery.setQuery("*:*"); filterList.forEach(filter -> { solrQuery.addFilterQuery(filter); logger.debug("Solr fq: {}\n", filter); }); return solrQuery; }
From source file:com.omertron.slackbot.listeners.BoardGameListener.java
/** * Search for a game/*from w ww . j a v a2s. c o m*/ * * @param session * @param msgChannel * @param msgSender * @param query */ private void commandSearch(SlackSession session, SlackChannel msgChannel, String query) { StringBuilder response; SearchWrapper results; LOG.info("Search request for '{}'", query); session.sendTyping(msgChannel); try { results = BGG.searchBoardGame(query, false, false); LOG.info("Got {} results for '{}'", results.getTotal(), query); } catch (NullPointerException ex) { LOG.warn("Error getting BGG information: {}", ex.getMessage(), ex); session.sendMessage(msgChannel, "Could not find information from BGG for " + query + ".\n Error: " + ex.getMessage()); return; } catch (BggException ex) { LOG.warn("Error getting BGG information: {}", ex.getMessage(), ex); session.sendMessage(msgChannel, "Could not get information from BGG for " + query + ".\n Error: " + ex.getMessage()); return; } if (results.getItems() == null || results.getItems().isEmpty()) { session.sendMessage(msgChannel, "Could not find information from BGG for " + query); return; } response = new StringBuilder("Found "); response.append(results.getTotal()).append(" matches for *").append(query).append("*"); List<SlackAttachment> attachments = new ArrayList<>(); for (Thing item : results.getItems()) { attachments.add(makeSimpleAttachment(item)); } SlackPreparedMessage spm = new SlackPreparedMessage.Builder().withMessage(response.toString()) .withAttachments(attachments).withUnfurl(false).build(); session.sendMessage(msgChannel, spm); }
From source file:org.jenkinsci.plugins.os_ci.repohandlers.OpenStackClient.java
public StackDetails getStackDetails(final String stackName) throws Exception { // GET http://10.56.165.71:8004/v1/<jenkins-tenant_id>/stacks/<stack_name> try {/* w w w. j a va 2 s.c o m*/ StackDetails stackDetails = new StackDetails(); URI uri = new URIBuilder().setPath(this.entryPoints.getServiceCatalog().get("heat") + "stacks").build(); HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("X-Auth-Token", this.entryPoints.getToken()); httpGet.addHeader("X-Auth-User", openstackUser); httpGet.addHeader("X-Auth-Key", openstackPassword); CloseableHttpResponse response = httpClient.execute(httpGet); try { int status = response.getStatusLine().getStatusCode(); if (status == 401 && !renewed) { renewed = true; renewToken(); httpGet.removeHeaders("X-Auth-Token"); httpGet.addHeader("X-Auth-Token", entryPoints.getToken()); response = httpClient.execute(httpGet); status = response.getStatusLine().getStatusCode(); } if (status != 200) { throw new OsCiPluginException("Invalid OpenStack server response " + status); } JsonNode stackJson = JsonParser.parseGetStackDetails(response, stackName); stackDetails.setStackHref(stackJson.get("links").elements().next().get("href").textValue()); stackDetails.setStackId(stackJson.get("id").textValue()); stackDetails.setStackStatus(StackStatus.valueOf(stackJson.get("stack_status").textValue())); // fill parameters and outputs to stackDetails. uri = new URIBuilder().setPath(stackDetails.getStackHref()).build(); httpGet = new HttpGet(uri); httpGet.addHeader("X-Auth-Token", this.entryPoints.getToken()); response = httpClient.execute(httpGet); status = response.getStatusLine().getStatusCode(); if (status != 200 && status != 400) { throw new OsCiPluginException("Invalid OpenStack server response " + status); } if (status == 200) { // fill parameters stackJson = JsonParser.parseGetFullStackDetails(response); Map<String, String> parameters = new HashMap<String, String>(); Iterator<Map.Entry<String, JsonNode>> parameters_elements = stackJson.get("parameters") .fields(); while (parameters_elements.hasNext()) { Map.Entry<String, JsonNode> parameter_element = parameters_elements.next(); String key = parameter_element.getKey(); String value = parameter_element.getValue().textValue(); if (value == null) value = parameter_element.getValue().toString(); parameters.put(key, value); } stackDetails.setParameters(parameters); // fill outputs Map<String, String> outputs = new HashMap<String, String>(); if (stackDetails.getStackStatus() == StackStatus.CREATE_COMPLETE) { Iterator<JsonNode> outputs_elements = stackJson.get("outputs").elements(); while (outputs_elements.hasNext()) { JsonNode output_element = outputs_elements.next(); String key = output_element.get("output_key").textValue(); String value = output_element.get("output_value").textValue(); LogUtils.log(listener, "Stack " + stackName + " Output info: " + key + " with value - " + value); if (value == null) value = output_element.get("output_value").toString(); outputs.put(key, value); } } stackDetails.setOutputs(parameters); } else if (status == 400) { LogUtils.log(listener, "Stack " + stackName + " exists, but filed to get its details. Please check your stack outputs: " + JsonParser.parseGetStackError(response)); } return stackDetails; } finally { response.close(); } } catch (NullPointerException e) { return new StackDetails(); } catch (IOException e) { throw new OsCiPluginException("IOException in getStackDetails " + e.getMessage()); } catch (URISyntaxException e) { throw new OsCiPluginException("URISyntaxException in getStackDetails " + e.getMessage()); } }
From source file:eu.eidas.auth.engine.AbstractSAMLEngine.java
private XMLObject performUnmarshall(final UnmarshallerFactory unmarshallerFact, final Element root) throws SAMLEngineException { final Unmarshaller unmarshaller = unmarshallerFact.getUnmarshaller(root); try {/*from w w w .j a va2s . c o m*/ return unmarshaller.unmarshall(root); } catch (NullPointerException e) { LOG.info("ERROR : element tag incomplet or null."); throw new SAMLEngineException("NullPointerException", e); } catch (UnmarshallingException e) { LOG.info("ERROR : TransformerException.", e.getMessage()); LOG.debug("ERROR : TransformerException.", e); throw new SAMLEngineException(e); } }
From source file:com.wso2telco.authenticationstephandler.MIFEAuthenticationStepHandler.java
@SuppressWarnings("unchecked") @Override/*from ww w . j a v a 2 s . co m*/ protected void doAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatorConfig authenticatorConfig) throws FrameworkException { SequenceConfig sequenceConfig = context.getSequenceConfig(); int currentStep = context.getCurrentStep(); StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep); // Set false for all steps ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator(); try { context.setAuthenticatorProperties(FrameworkUtils .getAuthenticatorPropertyMapFromIdP(context.getExternalIdP(), authenticator.getName())); AuthenticatorFlowStatus status = authenticator.process(request, response, context); request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status); if (log.isDebugEnabled()) { log.debug(authenticator.getName() + " returned: " + status.toString()); } if (status == AuthenticatorFlowStatus.INCOMPLETE) { if (log.isDebugEnabled()) { log.debug(authenticator.getName() + " is redirecting"); } return; } // This is only a routing authenticator if (authenticator instanceof LOACompositeAuthenticator) { removeFailedStep(context, currentStep); } else { try { if (Boolean.parseBoolean(authenticatorConfig.getParameterMap().get("isLastAuthenticator"))) { removeAllFollowingSteps(context, currentStep); } // set authenticator name in the context // This gets used in ID token later Object amrValue = context.getProperty("amr"); List<String> amr; if (null != amrValue && amrValue instanceof ArrayList<?>) { amr = (ArrayList<String>) amrValue; amr.add(authenticator.getName()); context.setProperty("amr", amr); } else { amr = new ArrayList<String>(); amr.add(authenticator.getName()); context.setProperty("amr", amr); } } catch (NullPointerException e) { // Possible exception during dashboard login // Should continue even if NPE is thrown } setAuthenticationAttributes(context, stepConfig, authenticatorConfig); } } catch (AuthenticationFailedException e) { if (e instanceof InvalidCredentialsException) { log.warn("A login attempt was failed due to invalid credentials"); } else { log.error(e.getMessage(), e); } // add failed authenticators Object amrValue = context.getProperty("failedamr"); List<String> amr; if (null != amrValue && amrValue instanceof ArrayList<?>) { amr = (ArrayList<String>) amrValue; amr.add(authenticator.getName()); context.setProperty("failedamr", amr); } else { amr = new ArrayList<String>(); amr.add(authenticator.getName()); context.setProperty("failedamr", amr); } // Remove failed step from step map removeFailedStep(context, currentStep); try { String onFailProperty = authenticatorConfig.getParameterMap().get("onFail"); if (!"".equals(onFailProperty) && !onFailProperty.equals("continue")) { // Should fail the whole LOA and continue to next if defined String fallBacklevel = authenticatorConfig.getParameterMap().get("fallBack"); if (onFailProperty.equals("fallback") && StringUtils.isNotBlank(fallBacklevel)) { removeFollowingStepsOfCurrentLOA(context, authenticatorConfig.getParameterMap().get("currentLOA"), currentStep); } else { context.setRequestAuthenticated(false); context.getSequenceConfig().setCompleted(true); } } } catch (NullPointerException e1) { // Possible exception during dashboard login removeAllFollowingSteps(context, currentStep); context.setRequestAuthenticated(false); context.getSequenceConfig().setCompleted(true); } } catch (LogoutFailedException e) { throw new FrameworkException(e.getMessage(), e); } stepConfig.setCompleted(true); }
From source file:org.openadaptor.auxil.connector.mail.MailReadConnector.java
/** * Retrieves any "new" (ie. any eligible to be processed) messages from the InBox. We * only process the first message in the folder. The rest will be picked up on * subsequent polls. If required we also try to set the message status as READ/SEEN. * <p />// w w w. j a v a 2 s. c o m * * If the message is deleted while we are processing it then we just log the problem * and return null. * * @return the first mail message to precess or null if none present. * * @throws MessagingException if the inbox can not be opened, if there was a comms * error or if we failed to retrieve the message details. */ private Message getNextMessage() throws MessagingException { if (inbox == null || !inbox.isOpen()) openInbox(); Message[] messages = inbox.getMessages(); log.debug(messages.length + " msssage(s) found"); if (messages.length == 0) return null; int index = 0; try { while (index < messages.length) { // we only process the first unread message in the folder. The rest will be // picked up on subsequent polls Message msg = messages[index++]; if (isToBeProcessed(msg)) { log.info("Processing message [" + msg.getSubject() + "] from " + msg.getFrom()[0]); return msg; } } } catch (NullPointerException e) { // ok, so this is a little dodgy as different version of the JavaMail API might // exhibit different behaviour but works for 1.3 and 1.4 log.warn("Message [" + index + "] deleted by external party. " + "Will skip this iteration and continue on the next poll."); } catch (Exception e) { log.warn("Failed to retrieve message [" + index + "]: " + e.getMessage() + ". " + "Will skip this iteration and continue on the next poll."); } return null; }
From source file:org.restcomm.connect.http.GeolocationEndpoint.java
public Response putGeolocation(final String accountSid, final MultivaluedMap<String, String> data, GeolocationType geolocationType, final MediaType responseType) { Account account;/* w w w . ja v a 2 s .c o m*/ try { account = accountsDao.getAccount(accountSid); secure(account, "RestComm:Create:Geolocation", SecuredType.SECURED_APP); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } try { validate(data, geolocationType); } catch (final NullPointerException nullPointerException) { // API compliance check regarding missing mandatory parameters return status(BAD_REQUEST).entity(nullPointerException.getMessage()).build(); } catch (final IllegalArgumentException illegalArgumentException) { // API compliance check regarding malformed parameters cause = illegalArgumentException.getMessage(); rStatus = responseStatus.Failed.toString(); } catch (final UnsupportedOperationException unsupportedOperationException) { // API compliance check regarding parameters not allowed for Immediate type of Geolocation return status(BAD_REQUEST).entity(unsupportedOperationException.getMessage()).build(); } /*********************************************/ /*** Query GMLC for Location Data, stage 1 ***/ /*********************************************/ try { String targetMSISDN = data.getFirst("DeviceIdentifier"); Configuration gmlcConf = configuration.subset("gmlc"); String gmlcURI = gmlcConf.getString("gmlc-uri"); // Authorization for further stage of the project String gmlcUser = gmlcConf.getString("gmlc-user"); String gmlcPassword = gmlcConf.getString("gmlc-password"); // Credentials credentials = new UsernamePasswordCredentials(gmlcUser, gmlcPassword); URL url = new URL(gmlcURI + targetMSISDN); HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(String.valueOf(url)); // Authorization for further stage of the project request.addHeader("User-Agent", gmlcUser); request.addHeader("User-Password", gmlcPassword); HttpResponse response = client.execute(request); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); try { BufferedReader br = new BufferedReader(new InputStreamReader(stream)); String gmlcResponse = null; while (null != (gmlcResponse = br.readLine())) { List<String> items = Arrays.asList(gmlcResponse.split("\\s*,\\s*")); if (logger.isInfoEnabled()) { logger.info("Data retrieved from GMLC: " + items.toString()); } for (String item : items) { for (int i = 0; i < items.size(); i++) { if (item.contains("mcc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileCountryCode", token); } if (item.contains("mnc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileNetworkCode", token); } if (item.contains("lac")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAreaCode", token); } if (item.contains("cellid")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("CellId", token); } if (item.contains("aol")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAge", token); } if (item.contains("vlrNumber")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("NetworkEntityAddress", token); } if (item.contains("latitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLatitude", token); } if (item.contains("longitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLongitude", token); } if (item.contains("civicAddress")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("FormattedAddress", token); } } } if (gmlcURI != null && gmlcResponse != null) { // For debugging/logging purposes only if (logger.isDebugEnabled()) { logger.debug("Geolocation data of " + targetMSISDN + " retrieved from GMCL at: " + gmlcURI); logger.debug( "MCC (Mobile Country Code) = " + getInteger("MobileCountryCode", data)); logger.debug("MNC (Mobile Network Code) = " + data.getFirst("MobileNetworkCode")); logger.debug("LAC (Location Area Code) = " + data.getFirst("LocationAreaCode")); logger.debug("CI (Cell ID) = " + data.getFirst("CellId")); logger.debug("AOL (Age of Location) = " + getInteger("LocationAge", data)); logger.debug("NNN (Network Node Number/Address) = " + +getLong("NetworkEntityAddress", data)); logger.debug("Devide Latitude = " + data.getFirst("DeviceLatitude")); logger.debug("Devide Longitude = " + data.getFirst("DeviceLongitude")); logger.debug("Civic Address = " + data.getFirst("FormattedAddress")); } } } } finally { stream.close(); } } } catch (Exception ex) { if (logger.isInfoEnabled()) { logger.info("Problem while trying to retrieve data from GMLC"); } return status(INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } Geolocation geolocation = createFrom(new Sid(accountSid), data, geolocationType); if (geolocation.getResponseStatus() != null && geolocation.getResponseStatus().equals(responseStatus.Rejected.toString())) { if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } else { dao.addGeolocation(geolocation); if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } }
From source file:com.swordlord.jalapeno.datacontainer.DataContainer.java
/** * Persist object context./*from ww w . ja va 2 s .co m*/ * * @param oc the oc * * @return true, if successful */ private boolean persistObjectContext(ObjectContext oc) { try { // disabling the context validation should only be used when you know what you do! if (getDisableValidation()) { DataContext context = (DataContext) oc; context.setValidatingObjectsOnCommit(false); } oc.commitChanges(); } catch (ValidationException vex) { String strMessage = ""; ValidationResult vr = vex.getValidationResult(); if (vr.hasFailures()) { List<ValidationFailure> failures = vr.getFailures(); if (failures.size() > 0) { Iterator<ValidationFailure> it = failures.iterator(); while (it.hasNext()) { ValidationFailure failure = it.next(); if (failure != null) { addError(failure.getSource().toString(), failure.getDescription()); LOG.info(failure.getSource() + " - " + failure.getDescription()); } if (failure instanceof BeanValidationFailure) { BeanValidationFailure bvf = (BeanValidationFailure) failure; strMessage += bvf.getSource() + " - " + bvf.getProperty() + " - " + bvf.getDescription() + ".\n\r"; LOG.error(bvf.getSource() + " - " + bvf.getProperty() + " - " + bvf.getDescription()); } } } } String strError = "Persist crashed: " + vex.getMessage() + ": " + vex.getCause() + "\n\r" + strMessage; LOG.info(strError); strMessage = vex.getLocalizedMessage() + " - " + strMessage; Throwable cause = vex.getCause(); if (cause != null) { strMessage += " - " + cause.getMessage(); } addError("", strMessage); //ErrorDialog.reportError("validation: " + strMessage); return false; } catch (DeleteDenyException dde) { String strError = "Persist crashed: " + dde.getLocalizedMessage() + ": " + dde.getCause(); LOG.error(strError); String strMessage = dde.getLocalizedMessage(); addError("", strMessage); return false; } catch (FaultFailureException ffe) { String strError = "Persist crashed: " + ffe.getLocalizedMessage() + ": " + ffe.getCause(); LOG.error(strError); String strMessage = ffe.getLocalizedMessage(); addError("", strMessage); return false; } catch (CayenneRuntimeException cex) { String strError = "Persist crashed: " + cex.getMessage() + ": " + cex.getCause(); LOG.error(strError); String strMessage = cex.getLocalizedMessage(); addError("", strMessage); return false; } catch (NullPointerException e) { String strError = "Persist crashed: NullPointerException"; LOG.error(strError); addError("", strError); LOG.debug(e.getMessage()); return false; } catch (Exception e) { String strError = "Persist crashed: " + e.getLocalizedMessage() + ": " + e.getCause(); LOG.error(strError); String strMessage = e.getLocalizedMessage(); addError("", strMessage); return false; } return true; }
From source file:org.wildfly.security.tool.FileSystemRealmCommand.java
/** * Handles creating the Elytron filesystem-realm from the input arrays * * @throws Exception Exception to be handled by Elytron Tool *//*from w w w . ja va2 s. c om*/ private void createFileSystemRealm() throws Exception { Security.addProvider(new WildFlyElytronProvider()); for (int i = 0; i < descriptors.size(); i++) { Descriptor descriptor = descriptors.get(i); if (descriptor.getUsersFile() == null || descriptor.getRolesFile() == null || descriptor.getOutputLocation() == null) { continue; } List<String> usersList = parseInputFile(descriptor, USERS_FILE_PARAM, i + 1); List<String> rolesList = parseInputFile(descriptor, ROLES_FILE_PARAM, i + 1); if (usersList.isEmpty() || rolesList.isEmpty()) { descriptor.reset(); continue; } FileSystemSecurityRealm newFileSystemRealm = new FileSystemSecurityRealm( Paths.get(descriptor.getOutputLocation())); Map<String, ArrayList<String>> usersMap = new HashMap<>(); for (String userMapping : usersList) { String[] userStringSplit = userMapping.split("="); String user = userStringSplit[0].trim(); String password; if (userStringSplit.length == 1) { String message = String.format("No password was found for user %s", user); warningHandler(message); password = null; } else { password = userStringSplit[1].trim(); } ArrayList<String> userAttributes = new ArrayList<>(); userAttributes.add(password); usersMap.put(user, userAttributes); } for (String rolesMapping : rolesList) { String[] rolesStringSplit = rolesMapping.split("="); String user = rolesStringSplit[0].trim(); String[] roles = new String[] {}; if (rolesStringSplit.length < 2) { String message = String.format("No roles were found for user %s", user); warningHandler(message); } else { roles = rolesStringSplit[1].trim().split(","); } ArrayList<String> userAttributes = usersMap.get(user); if (userAttributes == null) { String message = String.format("Roles were found for user %1$s, but user %1$s was not defined.", user); warningHandler(message); ArrayList<String> attributesWithEmptyPassword = new ArrayList<>(); attributesWithEmptyPassword.add(null); attributesWithEmptyPassword.addAll(new ArrayList<>(Arrays.asList(roles))); userAttributes = attributesWithEmptyPassword; usersMap.put(user, userAttributes); } else { userAttributes.addAll(Arrays.asList(roles)); usersMap.replace(user, userAttributes); } if (summaryMode) { summaryString.append( String.format("Added roles: %s for user %s.", ArrayUtils.toString(roles), user)); summaryString.append(System.getProperty("line.separator")); } } usersMap.forEach((key, value) -> { ModifiableRealmIdentity identity = newFileSystemRealm .getRealmIdentityForUpdate(new NamePrincipal(key)); try { identity.create(); MapAttributes attributes = new MapAttributes(); attributes.addAll("roles", value.subList(1, value.size())); identity.setAttributes(attributes); String password = value.get(0); if (password != null) { byte[] hashed = ByteIterator.ofBytes(password.getBytes(StandardCharsets.UTF_8)) .asUtf8String().hexDecode().drain(); PasswordSpec passwordSpec = new DigestPasswordSpec(key, descriptor.getRealmName(), hashed); PasswordFactory factory = PasswordFactory.getInstance(DigestPassword.ALGORITHM_DIGEST_MD5); DigestPassword digestPassword = (DigestPassword) factory.generatePassword(passwordSpec); identity.setCredentials(Collections.singleton(new PasswordCredential(digestPassword))); } identity.dispose(); } catch (NullPointerException e) { warningHandler(String.format("Could not read realm name from the users file")); } catch (Exception e) { warningHandler(String.format("Could not create realm for user %s due to error: ", key) + e.getMessage()); } }); } }
From source file:com.undatech.opaque.RemoteCanvasActivity.java
@Override public boolean onCreateOptionsMenu(Menu menu) { Log.e(TAG, "onCreateOptionsMenu called"); try {/*from w ww . j av a2 s . c om*/ getMenuInflater().inflate(R.menu.connectedmenu, menu); // Check the proper input method item. Menu inputMenu = menu.findItem(R.id.menuInputMethod).getSubMenu(); inputMenu.findItem(inputHandlerIdToXmlId(connection.getInputMethod())).setChecked(true); // Set the text of the Extra Keys menu item appropriately. if (connection.getExtraKeysToggleType() == Constants.EXTRA_KEYS_ON) menu.findItem(R.id.menuExtraKeys).setTitle(R.string.extra_keys_disable); else menu.findItem(R.id.menuExtraKeys).setTitle(R.string.extra_keys_enable); } catch (NullPointerException e) { Log.e(TAG, "There was an error: " + e.getMessage()); } return true; }