List of usage examples for java.util Objects toString
public static String toString(Object o, String nullDefault)
From source file:com.navercorp.pinpoint.web.service.TransactionInfoServiceImpl.java
private String getDisplayArgument(Event event) { AnnotationBo displayArgument = getDisplayArgument0(event); if (displayArgument == null) { return ""; }//from w w w . j a v a2s.c o m return Objects.toString(displayArgument.getValue(), ""); }
From source file:org.apache.metron.enrichment.integration.EnrichmentIntegrationTest.java
public static void baseValidation(Map<String, Object> jsonDoc) { assertEnrichmentsExists("threatintels.", setOf("hbaseThreatIntel"), jsonDoc.keySet()); assertEnrichmentsExists("enrichments.", setOf("geo", "host", "hbaseEnrichment"), jsonDoc.keySet()); //ensure no values are empty for (Map.Entry<String, Object> kv : jsonDoc.entrySet()) { String actual = Objects.toString(kv.getValue(), ""); Assert.assertTrue(String.format("Value of '%s' is empty: '%s'", kv.getKey(), actual), StringUtils.isNotEmpty(actual)); }//from w w w . j av a 2 s . co m //ensure we always have a source ip and destination ip Assert.assertNotNull(jsonDoc.get(SRC_IP)); Assert.assertNotNull(jsonDoc.get(DST_IP)); Assert.assertNotNull(jsonDoc.get("ALL_CAPS")); Assert.assertNotNull(jsonDoc.get("foo")); Assert.assertEquals("TEST", jsonDoc.get("ALL_CAPS")); Assert.assertNotNull(jsonDoc.get("bar")); Assert.assertEquals("TEST", jsonDoc.get("bar")); }
From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s .c o m*/ */ @NonNull @Override public String getRepositoryUri(@NonNull BitbucketRepositoryType type, @NonNull BitbucketRepositoryProtocol protocol, @CheckForNull String cloneLink, @NonNull String owner, @NonNull String repository) { switch (type) { case GIT: URI baseUri; try { baseUri = new URI(baseURL); } catch (URISyntaxException e) { throw new IllegalStateException("Server URL is not a valid URI", e); } UriTemplate template = UriTemplate .fromTemplate("{scheme}://{+authority}{+path}{/owner,repository}.git"); template.set("owner", owner); template.set("repository", repository); switch (protocol) { case HTTP: template.set("scheme", baseUri.getScheme()); template.set("authority", baseUri.getRawAuthority()); template.set("path", Objects.toString(baseUri.getRawPath(), "") + "/scm"); break; case SSH: template.set("scheme", BitbucketRepositoryProtocol.SSH.getType()); template.set("authority", "git@" + baseUri.getHost()); if (cloneLink != null) { try { URI cloneLinkUri = new URI(cloneLink); if (cloneLinkUri.getScheme() != null) { template.set("scheme", cloneLinkUri.getScheme()); } if (cloneLinkUri.getRawAuthority() != null) { template.set("authority", cloneLinkUri.getRawAuthority()); } } catch (@SuppressWarnings("unused") URISyntaxException ignored) { // fall through } } break; default: throw new IllegalArgumentException("Unsupported repository protocol: " + protocol); } return template.expand(); default: throw new IllegalArgumentException("Unsupported repository type: " + type); } }
From source file:com.github.anba.es6draft.test262.Test262Info.java
private void readTagged(String descriptor, boolean lenient) throws MalformedDataException { assert descriptor != null && !descriptor.isEmpty(); for (LineIterator lines = new LineIterator(new StringReader(descriptor)); lines.hasNext();) { String line = lines.next(); Matcher m = tags.matcher(line); if (m.matches()) { String type = m.group(1); String val = m.group(2); switch (type) { case "description": this.description = requireNonNull(val, "description must not be null"); break; case "noStrict": requireNull(val); this.noStrict = true; break; case "onlyStrict": requireNull(val); this.onlyStrict = true; break; case "negative": this.negative = true; this.errorType = Objects.toString(val, this.errorType); break; case "hostObject": case "reviewers": case "generator": case "verbatim": case "noHelpers": case "bestPractice": case "implDependent": case "author": // ignore for now break; // legacy case "strict_mode_negative": this.negative = true; this.onlyStrict = true; this.errorType = Objects.toString(val, this.errorType); break; case "strict_only": requireNull(val); this.onlyStrict = true; break; case "errortype": this.errorType = requireNonNull(val, "error-type must not be null"); break; case "assertion": case "section": case "path": case "comment": case "name": // ignore for now break; default: // error if (lenient) { break; }// w w w.j av a 2s .c o m throw new MalformedDataException(String.format("unhandled type '%s' (%s)\n", type, this)); } } } }
From source file:at.itbh.bev.rest.client.BevRestClient.java
/** * Query the ReST endpoint using the command line arguments * /* w ww . java2s . c o m*/ * @param args * the command line arguments */ public void query(String[] args) { BevQueryExecutor executor = null; ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); int threadPoolSize = 1; if (line.hasOption("t")) { threadPoolSize = Integer.parseInt(line.getOptionValue("t")); } String postalCode = null; String place = null; String addressLine = null; String houseId = null; String radius = null; String longitude = null; String latitude = null; String separator = ";"; boolean enforceUnique = false; if (line.hasOption("z")) { postalCode = line.getOptionValue("z"); } if (line.hasOption("p")) { place = line.getOptionValue("p"); } if (line.hasOption("a")) { addressLine = line.getOptionValue("a"); } if (line.hasOption("i")) { houseId = line.getOptionValue("i"); } if (line.hasOption("radius")) { radius = line.getOptionValue("radius"); } if (line.hasOption("longitude")) { longitude = line.getOptionValue("longitude"); } if (line.hasOption("latitude")) { latitude = line.getOptionValue("latitude"); } if (line.hasOption("s")) { separator = line.getOptionValue("s"); } if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(0); } if (line.hasOption("u")) { enforceUnique = true; } if (line.hasOption("disable-certificate-validation")) { clientBuilder.disableTrustManager(); } if (!line.hasOption("proxy-port") && line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-host is only allowed in combination with the option --proxy-port."); } if (line.hasOption("proxy-port") && !line.hasOption("proxy-host")) { throw new ParseException( "The option --proxy-port is only allowed in combination with the option --proxy-host."); } if (line.hasOption("proxy-host") && line.hasOption("proxy-port")) { clientBuilder.defaultProxy(line.getOptionValue("proxy-host"), Integer.parseInt(line.getOptionValue("proxy-port"))); } OutputStreamWriter output; if (line.hasOption("o")) { output = new OutputStreamWriter(new FileOutputStream(line.getOptionValue("o"))); } else { output = new OutputStreamWriter(System.out); } // avoid concurrent access exceptions in the Apache http client clientBuilder.connectionPoolSize(threadPoolSize); executor = new BevQueryExecutor(clientBuilder.build(), line.getOptionValue("r"), threadPoolSize); CsvPreference csvPreference = new CsvPreference.Builder('"', Objects.toString(line.getOptionValue("s"), ";").toCharArray()[0], System.getProperty("line.separator")).build(); csvWriter = new CsvMapWriter(output, csvPreference, true); if (line.hasOption("b")) { ICsvMapReader mapReader = null; try { FileReader fileReader = new FileReader(line.getOptionValue("b")); mapReader = new CsvMapReader(fileReader, csvPreference); // calculate the output header (field names) final String[] header = mapReader.getHeader(true); ArrayList<String> tempFields = new ArrayList<>(Arrays.asList(defaultFieldNames)); for (int i = 0; i < header.length; i++) { if (!tempFields.contains(header[i])) { tempFields.add(header[i]); } } fieldNames = tempFields.toArray(new String[] {}); Map<String, String> inputData; List<Future<List<BevQueryResult>>> queryResults = new ArrayList<>(); while ((inputData = mapReader.read(header)) != null) { queryResults .add(executor.query(inputData.get(INPUT_POSTAL_CODE), inputData.get(INPUT_PLACE), inputData.get(INPUT_ADDRESS_LINE), inputData.get(INPUT_HOUSE_ID), inputData.get(INPUT_LONGITUDE), inputData.get(INPUT_LATITUDE), inputData.get(INPUT_RADIUS), inputData.get(INPUT_ENFORCE_UNIQUE) == null ? false : Boolean.parseBoolean(inputData.get(INPUT_ENFORCE_UNIQUE)), inputData)); } csvWriter.writeHeader(fieldNames); for (Future<List<BevQueryResult>> queryResult : queryResults) { List<BevQueryResult> results = queryResult.get(); outputResults(separator, results); } } finally { if (mapReader != null) { mapReader.close(); } } } else { fieldNames = defaultFieldNames; Map<String, String> inputData = new HashMap<String, String>(); Future<List<BevQueryResult>> queryResult = executor.query(postalCode, place, addressLine, houseId, longitude, latitude, radius, enforceUnique, inputData); try { List<BevQueryResult> results = queryResult.get(); if (enforceUnique && results.size() == 1) { if (!results.get(0).getFoundMatch()) throw new Exception("No unique result found."); } outputResults(separator, results); } catch (ExecutionException e) { throw e.getCause(); } } } catch (ParseException exp) { System.out.println(exp.getMessage()); System.out.println(); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar BevRestClient.jar", options, true); System.exit(-2); } catch (BevRestException e) { System.err.println(e.toString()); System.exit(e.getErrorCode()); } catch (JsonProcessingException e) { System.err.println(e.toString()); System.exit(-3); } catch (IOException e) { System.err.println(e.toString()); System.exit(-4); } catch (Throwable t) { System.err.println(t.toString()); t.printStackTrace(); System.exit(-1); } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } if (executor != null) { executor.dispose(); } } }
From source file:com.github.fengtan.sophie.tables.DocumentsTable.java
/** * Create the Table./*from w w w.j a v a 2 s.com*/ */ private void createTable() { // Instantiate the table. int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.VIRTUAL; table = new Table(composite, style); // Set layout. GridData gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessVerticalSpace = true; table.setLayoutData(gridData); // Set styles. table.setLinesVisible(true); table.setHeaderVisible(true); // Add KeyListener to delete documents. table.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent event) { if (event.keyCode == SWT.DEL) { deleteSelectedDocument(); } } }); // Initialize item count to 1 so we can populate the first row with // filters. table.setItemCount(1); // Populate subsequent rows with remote documents (virtual table). table.addListener(SWT.SetData, new Listener() { @Override public void handleEvent(Event event) { TableItem item = (TableItem) event.item; int rowIndex = table.indexOf(item); // The first line is populated by filters. if (rowIndex == 0) { return; } SolrDocument document; // The last lines are populated by local additions. if (rowIndex >= table.getItemCount() - documentsAdded.size()) { document = documentsAdded.get(documentsAdded.size() - table.getItemCount() + rowIndex); item.setBackground(GREEN); } else { try { // rowIndex - 1 since the first line is used for // filters. document = getRemoteDocument(rowIndex - 1); } catch (SophieException e) { ExceptionDialog.open(composite.getShell(), new SophieException("Unable to populate table", e)); return; } } // First column is used to show the row ID. item.setText(0, Integer.toString(rowIndex)); // Subsequent columns are used to show field values. for (int index = 1; index < table.getColumnCount(); index++) { TableColumn column = table.getColumn(index); String fieldName = (String) column.getData("fieldName"); FieldInfo field = (FieldInfo) column.getData("field"); // If field is not stored, display message. if (!SolrUtils.getFlags(field).contains(FieldFlag.STORED)) { item.setText(index, LABEL_NOT_STORED); } else { Object value = document.getFieldValue(fieldName); item.setText(index, value == null ? StringUtils.EMPTY : value.toString()); } } // Store document in item. item.setData("document", document); } }); // Add doubleclick listener to edit values. table.addListener(SWT.MouseDoubleClick, new Listener() { public void handleEvent(Event event) { Point point = new Point(event.x, event.y); TableItem item = table.getItem(point); if (item == null) { return; } // The first row is used for filters. if (table.indexOf(item) == 0) { return; } // We add 1 since the first column is used for row ID's. for (int i = 1; i < table.getColumnCount(); i++) { Rectangle rect = item.getBounds(i); if (rect.contains(point)) { SolrDocument document = (SolrDocument) item.getData("document"); String fieldName = (String) table.getColumn(i).getData("fieldName"); FieldInfo field = (FieldInfo) table.getColumn(i).getData("field"); Object defaultValue = document.getFieldValue(fieldName); // Add editor dialog: // - list widget if we are dealing with a multi-valued // field. // - datepicker if we field type contains "date". // - text if we are dealing with any other field type. EditValueDialog dialog; if (SolrUtils.getFlags(field).contains(FieldFlag.MULTI_VALUED)) { dialog = new EditListValueDialog(composite.getShell(), (AbstractList<?>) defaultValue); } else if (StringUtils.containsIgnoreCase(field.getType(), "date")) { dialog = new EditDateValueDialog(composite.getShell(), (Date) defaultValue); } else { String oldValueString = Objects.toString(defaultValue, StringUtils.EMPTY); dialog = new EditTextValueDialog(composite.getShell(), oldValueString); } dialog.open(); if (dialog.getReturnCode() != IDialogConstants.OK_ID) { return; } Object value = dialog.getValue(); if (!Objects.equals(defaultValue, value)) { updateDocument(item, i, value); } } } } }); }
From source file:org.openhab.binding.plclogo.internal.PLCLogoBinding.java
@Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { Boolean configured = false;//from ww w . j a v a 2 s . com if (config != null) { String refreshIntervalString = Objects.toString(config.get("refresh"), null); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } if (controllers == null) { controllers = new HashMap<String, PLCLogoConfig>(); } Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { continue; } matcher.reset(); matcher.find(); String controllerName = matcher.group(1); PLCLogoConfig deviceConfig = controllers.get(controllerName); if (deviceConfig == null) { deviceConfig = new PLCLogoConfig(); controllers.put(controllerName, deviceConfig); logger.info("Create new config for {}", controllerName); } if (matcher.group(2).equals("host")) { String ip = config.get(key).toString(); deviceConfig.setIP(ip); logger.info("Set host of {}: {}", controllerName, ip); configured = true; } if (matcher.group(2).equals("remoteTSAP")) { String tsap = config.get(key).toString(); deviceConfig.setRemoteTSAP(Integer.decode(tsap)); logger.info("Set remote TSAP for {}: {}", controllerName, tsap); } if (matcher.group(2).equals("localTSAP")) { String tsap = config.get(key).toString(); deviceConfig.setLocalTSAP(Integer.decode(tsap)); logger.info("Set local TSAP for {}: {}", controllerName, tsap); } if (matcher.group(2).equals("model")) { PLCLogoModel model = null; String modelName = config.get(key).toString(); if (modelName.equalsIgnoreCase("0BA7")) { model = PLCLogoModel.LOGO_MODEL_0BA7; } else if (modelName.equalsIgnoreCase("0BA8")) { model = PLCLogoModel.LOGO_MODEL_0BA8; } else { logger.info("Found unknown model for {}: {}", controllerName, modelName); } if (model != null) { deviceConfig.setModel(model); logger.info("Set model for {}: {}", controllerName, modelName); } } } // while Iterator<Entry<String, PLCLogoConfig>> entries = controllers.entrySet().iterator(); while (entries.hasNext()) { Entry<String, PLCLogoConfig> thisEntry = entries.next(); String controllerName = thisEntry.getKey(); PLCLogoConfig deviceConfig = thisEntry.getValue(); S7Client LogoS7Client = deviceConfig.getS7Client(); if (LogoS7Client == null) { LogoS7Client = new Moka7.S7Client(); } else { LogoS7Client.Disconnect(); } LogoS7Client.SetConnectionParams(deviceConfig.getlogoIP(), deviceConfig.getlocalTSAP(), deviceConfig.getremoteTSAP()); logger.info("About to connect to {}", controllerName); if ((LogoS7Client.Connect() == 0) && LogoS7Client.Connected) { logger.info("Connected to PLC LOGO! device {}", controllerName); } else { logger.error("Could not connect to PLC LOGO! device {} : {}", controllerName, S7Client.ErrorText(LogoS7Client.LastError)); throw new ConfigurationException("Could not connect to PLC LOGO! device ", controllerName + " " + deviceConfig.getlogoIP()); } deviceConfig.setS7Client(LogoS7Client); } setProperlyConfigured(configured); } else { logger.info("No configuration for PLCLogoBinding"); } }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private static void checkAccountLocked(HttpResponse response) { Header header = response.getLastHeader("X-Authentication-Denied-Reason"); if (header != null) { String info = Objects.toString(header.getValue(), "").trim(); throw new AccessControlException( "Your account seems to be locked" + (info.isEmpty() ? "" : ": " + info)); }/*from w w w . j a va 2 s .com*/ }
From source file:org.everit.jira.hr.admin.SchemeUsersComponent.java
public String render(final HttpServletRequest request, final Locale locale, final String fragment) { String userFilter = request.getParameter("schemeUsersUserFilter"); boolean currentOnly = Boolean.parseBoolean(request.getParameter("schemeUsersCurrentFilter")); String schemeIdParam = request.getParameter("schemeId"); Long schemeId = (schemeIdParam != null) ? Long.parseLong(schemeIdParam) : null; int pageIndex = Integer.parseInt(Objects.toString(request.getParameter("pageIndex"), "1")); QueryResultWithCount<SchemeUserDTO> schemeUsers; if (schemeId != null) { schemeUsers = querySchemeUsers(pageIndex, schemeId, userFilter, currentOnly); } else {//from w w w . ja va2s . c o m schemeUsers = new QueryResultWithCount<>(Collections.emptyList(), 0); } Map<String, Object> vars = new HashMap<String, Object>(); vars.put("request", request); vars.put("schemeUsers", schemeUsers); vars.put("userFilter", userFilter); vars.put("currentTimeRangesFilter", currentOnly); vars.put("pageIndex", pageIndex); StringWriter sw = new StringWriter(); TEMPLATE.render(sw, vars, locale, fragment); return sw.toString(); }
From source file:org.dcache.srm.client.HttpClientSender.java
/** * Extracts the SOAP response from an HttpResponse. *///from w ww . java 2 s .c om protected Message extractResponse(MessageContext msgContext, HttpResponse response) throws IOException { int returnCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null && returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (entity != null && msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if (entity != null && returnCode > 499 && returnCode < 600 && Objects.equals(getMimeType(entity), "text/xml")) { // SOAP Fault should be in here - so fall through } else { String statusMessage = response.getStatusLine().getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString("Return code: " + String.valueOf(returnCode) + (entity == null ? "" : "\n" + EntityUtils.toString(entity))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, String.valueOf(returnCode)); throw fault; } Header contentLocation = response.getFirstHeader(HttpHeaders.CONTENT_LOCATION); Message outMsg = new Message(entity.getContent(), false, Objects.toString(ContentType.get(entity), null), (contentLocation == null) ? null : contentLocation.getValue()); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (Header responseHeader : response.getAllHeaders()) { responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); return outMsg; }