List of usage examples for org.springframework.util StringUtils capitalize
public static String capitalize(String str)
From source file:com.phoenixnap.oss.ramlapisync.naming.SchemaHelper.java
/** * Maps a JSON Schema to a JCodeModel using JSONSchema2Pojo and encapsulates it along with some metadata into an {@link ApiBodyMetadata} object. * /*from ww w . j av a 2 s . co m*/ * @param document The Raml document being parsed * @param schema The Schema (full schema or schema name to be resolved) * @param basePackage The base package for the classes we are generating * @param name The suggested name of the class based on the api call and whether it's a request/response. This will only be used if no suitable alternative is found in the schema * @return Object representing this Body */ public static ApiBodyMetadata mapSchemaToPojo(Raml document, String schema, String basePackage, String name) { String resolvedName = null; String schemaName = schema; String resolvedSchema = SchemaHelper.resolveSchema(schema, document); if (resolvedSchema == null) { resolvedSchema = schema; schemaName = null; } if (resolvedSchema.contains("\"id\"")) { //check if id can give us exact name int idIdx = resolvedSchema.indexOf("\"id\""); //find the 1st and second " after the idx int startIdx = resolvedSchema.indexOf("\"", idIdx + 4); int endIdx = resolvedSchema.indexOf("\"", startIdx + 1); String id = resolvedSchema.substring(startIdx + 1, endIdx); if (id.startsWith("urn:") && ((id.lastIndexOf(":") + 1) < id.length())) { id = id.substring(id.lastIndexOf(":") + 1); } else if (id.startsWith(JSON_SCHEMA_IDENT)) { if (id.length() > (JSON_SCHEMA_IDENT.length() + 3)) { id = id.substring(JSON_SCHEMA_IDENT.length()); } } else { resolvedName = StringUtils.capitalize(id); } } if (!NamingHelper.isValidJavaClassName(resolvedName)) { if (NamingHelper.isValidJavaClassName(schemaName)) { resolvedName = Inflector.capitalize(schemaName); //try schema name } else { resolvedName = name; //fallback to generated } } JCodeModel codeModel = new JCodeModel(); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { // set config option by overriding method return true; } @Override public boolean isIncludeAdditionalProperties() { return false; } @Override public boolean isIncludeDynamicAccessors() { return false; } }; SchemaStore schemaStore = new SchemaStore(); SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), schemaStore), new SchemaGenerator()); try { mapper.generate(codeModel, resolvedName, basePackage, resolvedSchema); return new ApiBodyMetadata(resolvedName, resolvedSchema, codeModel); } catch (Exception e) { logger.error("Error generating pojo from schema " + name, e); return null; } }
From source file:net.nan21.dnet.core.presenter.service.ds.AbstractEntityDsWriteService.java
protected void doImportAsUpdate_(File file, String ukFieldName, int batchSize, Object config) throws Exception { if (this.isReadOnly()) { throw new ActionNotSupportedException("Import not allowed."); }// w ww . j ava 2s . co m Assert.notNull(ukFieldName, "For import as update you must specify the unique-key " + "field which is used to lookup the existing record."); // TODO: check type-> csv, json, etc DsCsvLoader l = new DsCsvLoader(); if (config != null && config instanceof ConfigCsvImport) { l.setConfig((ConfigCsvImport) config); } DsCsvLoaderResult<M> result = l.run2(file, this.getModelClass(), null); List<M> list = result.getResult(); String[] columns = result.getHeader(); F filter = this.getFilterClass().newInstance(); // TODO: optimize me to do the work in batches Method filterUkFieldSetter = this.getFilterClass().getMethod("set" + StringUtils.capitalize(ukFieldName), String.class); Method modelUkFieldGetter = this.getModelClass().getMethod("get" + StringUtils.capitalize(ukFieldName)); Map<String, Method> modelSetters = new HashMap<String, Method>(); Map<String, Method> modelGetters = new HashMap<String, Method>(); int len = columns.length; for (int i = 0; i < len; i++) { String fieldName = columns[i]; Class<?> clz = this.getModelClass(); Field f = null; while (f == null && clz != null) { try { f = clz.getDeclaredField(fieldName); } catch (Exception e) { } clz = clz.getSuperclass(); } if (f != null) { Method modelSetter = this.getModelClass().getMethod("set" + StringUtils.capitalize(fieldName), f.getType()); modelSetters.put(fieldName, modelSetter); Method modelGetter = this.getModelClass().getMethod("get" + StringUtils.capitalize(fieldName)); modelGetters.put(fieldName, modelGetter); } else { } } List<M> targets = new ArrayList<M>(); for (M newDs : list) { filterUkFieldSetter.invoke(filter, modelUkFieldGetter.invoke(newDs)); List<M> res = this.find(filter); // TODO: add an extra flag for what to do if the target is not // found: // ignore or raise an error if (res.size() > 0) { M oldDs = this.find(filter).get(0); for (Map.Entry<String, Method> entry : modelSetters.entrySet()) { entry.getValue().invoke(oldDs, modelGetters.get(entry.getKey()).invoke(newDs)); } targets.add(oldDs); // this.update(oldDs, null); } } this.update(targets, null); try { this.getEntityService().getEntityManager().flush(); } catch (Exception e) { } }
From source file:com.erudika.para.rest.ParaClientIT.java
@Test public void testMisc() { String kittenType = "kitten"; Map<String, String> cred = pc.setup(); assertFalse(cred.containsKey("accessKey")); Map<String, String> types = pc.types(); assertFalse(types.isEmpty());/*from w ww. ja v a 2 s.c om*/ assertTrue(types.containsKey(new User().getPlural())); Map<String, ?> constraints = pc.validationConstraints(); assertFalse(constraints.isEmpty()); assertTrue(constraints.containsKey("App")); assertTrue(constraints.containsKey("User")); Map<String, Map<String, Map<String, ?>>> constraint = pc.validationConstraints("app"); assertFalse(constraint.isEmpty()); assertTrue(constraint.containsKey("App")); assertEquals(1, constraint.size()); pc.addValidationConstraint(kittenType, "paws", required()); constraint = pc.validationConstraints(kittenType); assertTrue(constraint.get(StringUtils.capitalize(kittenType)).containsKey("paws")); Sysprop ct = new Sysprop("felix"); ct.setType(kittenType); Sysprop ct2 = null; try { // validation fails ct = pc.create(ct); } catch (Exception e) { } assertNull(ct2); ct.addProperty("paws", "4"); assertNotNull(pc.create(ct)); pc.removeValidationConstraint(kittenType, "paws", "required"); constraint = pc.validationConstraints(kittenType); assertFalse(constraint.get(StringUtils.capitalize(kittenType)).isEmpty()); }
From source file:jenkins.plugins.openstack.compute.SlaveOptionsDescriptor.java
/** * Add dependencies on credentials// www.j a va 2 s . c om */ @Override public void calcFillSettings(String field, Map<String, Object> attributes) { super.calcFillSettings(field, attributes); List<String> deps = new ArrayList<>(); String fillDependsOn = (String) attributes.get("fillDependsOn"); if (fillDependsOn != null) { deps.addAll(Arrays.asList(fillDependsOn.split(" "))); } String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); // Replace direct reference to references to possible relative paths if (method.getAnnotation(InjectOsAuth.class) != null) { for (String attr : Arrays.asList("endPointUrl", "identity", "credential", "zone")) { deps.remove(attr); deps.add("../" + attr); deps.add("../../" + attr); } } attributes.put("fillDependsOn", Joiner.on(' ').join(deps)); }
From source file:org.iff.infra.util.spring.script.ScriptFactoryPostProcessor.java
/** * Create a config interface for the given bean definition, defining setter * methods for the defined property values as well as an init method and * a destroy method (if defined).// w w w.ja v a2 s . c om * <p>This implementation creates the interface via CGLIB's InterfaceMaker, * determining the property types from the given interfaces (as far as possible). * @param bd the bean definition (property values etc) to create a * config interface for * @param interfaces the interfaces to check against (might define * getters corresponding to the setters we're supposed to generate) * @return the config interface * @see org.springframework.cglib.proxy.InterfaceMaker * @see org.springframework.beans.BeanUtils#findPropertyType */ protected Class<?> createConfigInterface(BeanDefinition bd, Class<?>[] interfaces) { InterfaceMaker maker = new InterfaceMaker(); PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues(); for (PropertyValue pv : pvs) { String propertyName = pv.getName(); Class<?> propertyType = BeanUtils.findPropertyType(propertyName, interfaces); String setterName = "set" + StringUtils.capitalize(propertyName); Signature signature = new Signature(setterName, Type.VOID_TYPE, new Type[] { Type.getType(propertyType) }); maker.add(signature, new Type[0]); } if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.getInitMethodName() != null) { Signature signature = new Signature(abd.getInitMethodName(), Type.VOID_TYPE, new Type[0]); maker.add(signature, new Type[0]); } if (abd.getDestroyMethodName() != null) { Signature signature = new Signature(abd.getDestroyMethodName(), Type.VOID_TYPE, new Type[0]); maker.add(signature, new Type[0]); } } return maker.create(); }
From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java
/** * Creates a tab pane for the given GridJob. * /* w w w . ja v a2 s .c o m*/ * @param jobId JobId */ protected void createJobTab(final String jobId) { // Request Job Profile final InternalClusterJobService jobService = ClusterManager.getInstance().getJobService(); final GridJobProfile profile = jobService.getProfile(jobId); // Job Start Time final long startTime = System.currentTimeMillis(); final JPanel jobPanel = new JPanel(); jobPanel.setLayout(new BorderLayout(10, 10)); // Progess Panel JPanel progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(10, 10)); progressPanel.setBorder(BorderFactory.createTitledBorder("Progress")); jobPanel.add(progressPanel, BorderLayout.NORTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setStringPainted(true); progressPanel.add(progressBar, BorderLayout.CENTER); addUIElement("jobs." + jobId + ".progress", progressBar); // Add to components map // Buttons Panel JPanel buttonsPanel = new JPanel(); jobPanel.add(buttonsPanel, BorderLayout.SOUTH); buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); // Terminate Button JButton terminateButton = new JButton("Terminate"); terminateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread(new Runnable() { public void run() { // Job Name = Class Name String name = profile.getJob().getClass().getSimpleName(); // Request user confirmation int option = JOptionPane.showConfirmDialog(ClusterMainUI.this, "Are you sure to terminate GridJob " + name + "?", "Nebula - Terminate GridJob", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; // Attempt Cancel boolean result = profile.getFuture().cancel(); // Notify results if (result) { JOptionPane.showMessageDialog(ClusterMainUI.this, "Grid Job '" + name + "terminated successfully.", "Nebula - Job Terminated", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(ClusterMainUI.this, "Failed to terminate Grid Job '" + name, "Nebula - Job Termination Failed", JOptionPane.WARNING_MESSAGE); } } }).start(); } }); buttonsPanel.add(terminateButton); addUIElement("jobs." + jobId + ".terminate", terminateButton); // Add to components map // Close Tab Button JButton closeButton = new JButton("Close Tab"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { removeJobTab(jobId); } }); } }); closeButton.setEnabled(false); buttonsPanel.add(closeButton); addUIElement("jobs." + jobId + ".closetab", closeButton); // Add to components map JPanel centerPanel = new JPanel(); centerPanel.setLayout(new GridBagLayout()); jobPanel.add(centerPanel, BorderLayout.CENTER); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weightx = 1.0; /* -- Job Information -- */ JPanel jobInfoPanel = new JPanel(); jobInfoPanel.setBorder(BorderFactory.createTitledBorder("Job Information")); jobInfoPanel.setLayout(new GridBagLayout()); c.gridy = 0; c.ipady = 30; centerPanel.add(jobInfoPanel, c); GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.weightx = 1; c1.weighty = 1; // Name jobInfoPanel.add(new JLabel("Name :"), c1); JLabel jobNameLabel = new JLabel(); jobInfoPanel.add(jobNameLabel, c1); jobNameLabel.setText(profile.getJob().getClass().getSimpleName()); addUIElement("jobs." + jobId + ".job.name", jobNameLabel); // Add to components map // Gap jobInfoPanel.add(new JLabel(), c1); // Type jobInfoPanel.add(new JLabel("Type :"), c1); JLabel jobType = new JLabel(); jobType.setText(getJobType(profile.getJob())); jobInfoPanel.add(jobType, c1); addUIElement("jobs." + jobId + ".job.type", jobType); // Add to components map // Job Class Name c1.gridy = 1; c1.gridwidth = 1; jobInfoPanel.add(new JLabel("GridJob Class :"), c1); c1.gridwidth = GridBagConstraints.REMAINDER; JLabel jobClassLabel = new JLabel(); jobClassLabel.setText(profile.getJob().getClass().getName()); jobInfoPanel.add(jobClassLabel, c1); addUIElement("jobs." + jobId + ".job.class", jobClassLabel); // Add to components map /* -- Execution Information -- */ JPanel executionInfoPanel = new JPanel(); executionInfoPanel.setBorder(BorderFactory.createTitledBorder("Execution Statistics")); executionInfoPanel.setLayout(new GridBagLayout()); c.gridy = 1; c.ipady = 30; centerPanel.add(executionInfoPanel, c); GridBagConstraints c3 = new GridBagConstraints(); c3.weightx = 1; c3.weighty = 1; c3.fill = GridBagConstraints.BOTH; // Start Time executionInfoPanel.add(new JLabel("Job Status :"), c3); final JLabel statusLabel = new JLabel("Initializing"); executionInfoPanel.add(statusLabel, c3); addUIElement("jobs." + jobId + ".execution.status", statusLabel); // Add to components map // Status Update Listener profile.getFuture().addGridJobStateListener(new GridJobStateListener() { public void stateChanged(final GridJobState newState) { SwingUtilities.invokeLater(new Runnable() { public void run() { statusLabel.setText(StringUtils.capitalize(newState.toString().toLowerCase())); } }); } }); executionInfoPanel.add(new JLabel(), c3); // Space Holder // Percent Complete executionInfoPanel.add(new JLabel("Completed % :"), c3); final JLabel percentLabel = new JLabel("-N/A-"); executionInfoPanel.add(percentLabel, c3); addUIElement("jobs." + jobId + ".execution.percentage", percentLabel); // Add to components map c3.gridy = 1; // Start Time executionInfoPanel.add(new JLabel("Start Time :"), c3); JLabel startTimeLabel = new JLabel(DateFormat.getInstance().format(new Date(startTime))); executionInfoPanel.add(startTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.starttime", startTimeLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Elapsed Time executionInfoPanel.add(new JLabel("Elapsed Time :"), c3); JLabel elapsedTimeLabel = new JLabel("-N/A-"); executionInfoPanel.add(elapsedTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.elapsedtime", elapsedTimeLabel); // Add to components map c3.gridy = 2; // Tasks Deployed (Count) executionInfoPanel.add(new JLabel("Tasks Deployed :"), c3); JLabel tasksDeployedLabel = new JLabel("-N/A-"); executionInfoPanel.add(tasksDeployedLabel, c3); addUIElement("jobs." + jobId + ".execution.tasks", tasksDeployedLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Results Collected (Count) executionInfoPanel.add(new JLabel("Results Collected :"), c3); JLabel resultsCollectedLabel = new JLabel("-N/A-"); executionInfoPanel.add(resultsCollectedLabel, c3); addUIElement("jobs." + jobId + ".execution.results", resultsCollectedLabel); // Add to components map c3.gridy = 3; // Remaining Tasks (Count) executionInfoPanel.add(new JLabel("Remaining Tasks :"), c3); JLabel remainingTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(remainingTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.remaining", remainingTasksLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Failed Tasks (Count) executionInfoPanel.add(new JLabel("Failed Tasks :"), c3); JLabel failedTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(failedTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.failed", failedTasksLabel); // Add to components map /* -- Submitter Information -- */ UUID ownerId = profile.getOwner(); GridNodeDelegate owner = ClusterManager.getInstance().getClusterRegistrationService() .getGridNodeDelegate(ownerId); JPanel ownerInfoPanel = new JPanel(); ownerInfoPanel.setBorder(BorderFactory.createTitledBorder("Owner Information")); ownerInfoPanel.setLayout(new GridBagLayout()); c.gridy = 2; c.ipady = 10; centerPanel.add(ownerInfoPanel, c); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.BOTH; c2.weightx = 1; c2.weighty = 1; // Host Name ownerInfoPanel.add(new JLabel("Host Name :"), c2); JLabel hostNameLabel = new JLabel(owner.getProfile().getName()); ownerInfoPanel.add(hostNameLabel, c2); addUIElement("jobs." + jobId + ".owner.hostname", hostNameLabel); // Add to components map // Gap ownerInfoPanel.add(new JLabel(), c2); // Host IP Address ownerInfoPanel.add(new JLabel("Host IP :"), c2); JLabel hostIPLabel = new JLabel(owner.getProfile().getIpAddress()); ownerInfoPanel.add(hostIPLabel, c2); addUIElement("jobs." + jobId + ".owner.hostip", hostIPLabel); // Add to components map // Owner UUID c2.gridy = 1; c2.gridx = 0; ownerInfoPanel.add(new JLabel("Owner ID :"), c2); JLabel ownerIdLabel = new JLabel(profile.getOwner().toString()); c2.gridx = 1; c2.gridwidth = 4; ownerInfoPanel.add(ownerIdLabel, c2); addUIElement("jobs." + jobId + ".owner.id", ownerIdLabel); // Add to components map SwingUtilities.invokeLater(new Runnable() { public void run() { // Create Tab addUIElement("jobs." + jobId, jobPanel); JTabbedPane tabs = getUIElement("tabs"); tabs.addTab(profile.getJob().getClass().getSimpleName(), jobPanel); tabs.revalidate(); } }); // Execution Information Updater Thread new Thread(new Runnable() { boolean initialized = false; boolean unbounded = false; public void run() { // Unbounded, No Progress Supported if ((!initialized) && profile.getJob() instanceof UnboundedGridJob<?>) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Infinity Symbol percentLabel.setText(String.valueOf('\u221e')); } }); initialized = true; unbounded = true; } // Update Job Info while (true) { try { // 500ms Interval Thread.sleep(500); } catch (InterruptedException e) { log.warn("Interrupted Progress Updater Thread", e); } final int totalCount = profile.getTotalTasks(); final int tasksRem = profile.getTaskCount(); final int resCount = profile.getResultCount(); final int failCount = profile.getFailedCount(); showBusyIcon(); // Task Information JLabel totalTaskLabel = getUIElement("jobs." + jobId + ".execution.tasks"); totalTaskLabel.setText(String.valueOf(totalCount)); // Result Count JLabel resCountLabel = getUIElement("jobs." + jobId + ".execution.results"); resCountLabel.setText(String.valueOf(resCount)); // Remaining Task Count JLabel remLabel = getUIElement("jobs." + jobId + ".execution.remaining"); remLabel.setText(String.valueOf(tasksRem)); // Failed Task Count JLabel failedLabel = getUIElement("jobs." + jobId + ".execution.failed"); failedLabel.setText(String.valueOf(failCount)); // Elapsed Time JLabel elapsedLabel = getUIElement("jobs." + jobId + ".execution.elapsedtime"); elapsedLabel.setText(TimeUtils.timeDifference(startTime)); // Job State final JLabel statusLabel = getUIElement("jobs." + jobId + ".execution.status"); // If not in Executing Mode if ((!profile.getFuture().isJobFinished()) && profile.getFuture().getState() != GridJobState.EXECUTING) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Progress Bar progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Status Text String state = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(state.toLowerCase())); // Percentage Label percentLabel.setText(String.valueOf('\u221e')); } }); } else { // Executing Mode : Progress Information // Job Finished, Stop if (profile.getFuture().isJobFinished()) { showIdleIcon(); return; } // Double check for status label if (!statusLabel.getText().equalsIgnoreCase("executing")) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String newstate = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(newstate.toLowerCase())); } }); } if (!unbounded) { final int percentage = (int) (profile.percentage() * 100); //final int failCount = profile.get SwingUtilities.invokeLater(new Runnable() { public void run() { // If finished at this point, do not update if (progressBar.getValue() == 100) { return; } // If ProgressBar is in indeterminate if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); progressBar.setStringPainted(true); } // Update Progress Bar / Percent Label progressBar.setValue(percentage); percentLabel.setText(percentage + " %"); } }); } } } } }).start(); // Job End Hook to Execute Job End Actions ServiceEventsSupport.addServiceHook(new ServiceHookCallback() { public void onServiceEvent(final ServiceMessage event) { SwingUtilities.invokeLater(new Runnable() { public void run() { JButton close = getUIElement("jobs." + jobId + ".closetab"); JButton terminate = getUIElement("jobs." + jobId + ".terminate"); terminate.setEnabled(false); close.setEnabled(true); JProgressBar progress = getUIElement("jobs." + jobId + ".progress"); JLabel percentage = getUIElement("jobs." + jobId + ".execution.percentage"); progress.setEnabled(false); // If Successfully Finished if (event.getType() == ServiceMessageType.JOB_END) { if (profile.getFuture().getState() != GridJobState.FAILED) { // If Not Job Failed progress.setValue(100); percentage.setText("100 %"); } else { // If Failed percentage.setText("N/A"); } // Stop (if) Indeterminate Progress Bar if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(true); } } else if (event.getType() == ServiceMessageType.JOB_CANCEL) { if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(false); percentage.setText("N/A"); } } showIdleIcon(); } }); } }, jobId, ServiceMessageType.JOB_CANCEL, ServiceMessageType.JOB_END); }
From source file:com.ethercamp.harmony.jsonrpc.EthJsonRpcImpl.java
@Override public List<Map<String, ?>> admin_peers() { return channelManager.getActivePeers().stream() .map(c -> ImmutableMap.of("id", toJsonHex(c.getNodeId()), "name", toJsonHex(c.getNodeStatistics().getClientId()), "caps", c.getNodeStatistics().capabilities.stream().filter(cap -> c != null) .map(cap -> StringUtils.capitalize(cap.getName()) + "/" + cap.getVersion()) .collect(Collectors.toList()), "network", ImmutableMap.of( // TODO put local port which initiated connection "localAddress", config.bindIp() + ":" + c.getInetSocketAddress().getPort(), "remoteAddress", c.getNode().getHost() + ":" + c.getNode().getPort(), "hostname", c.getInetSocketAddress().getHostName(), "protocols", Optional.ofNullable(c.getEthHandler()).map(ethHandler -> ImmutableMap.of("eth", ImmutableMap.of("version", c.getEthVersion().getCode(), "difficulty", toJsonHex(ethHandler.getTotalDifficulty()), "head", Optional.ofNullable(ethHandler.getBestKnownBlock()) .map(block -> toJsonHex( ethHandler.getBestKnownBlock().getHash())) .orElse(null)))) .orElse(null)))) .collect(Collectors.toList()); }
From source file:com.phoenixnap.oss.ramlapisync.naming.NamingHelper.java
/** * Converts an http contentType into a qualifier that can be used within a Java method * /* w w w .j a v a 2 s . c om*/ * @param contentType The content type to convert application/json * @return qualifier, example V1Html */ public static String convertContentTypeToQualifier(String contentType) { //lets start off simple since qualifers are better if they are simple :) //if we have simple standard types lets add some heuristics if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) { return "AsJson"; } if (contentType.equals(MediaType.APPLICATION_OCTET_STREAM_VALUE)) { return "AsBinary"; } if (contentType.equals(MediaType.TEXT_PLAIN_VALUE) || contentType.equals(MediaType.TEXT_HTML_VALUE)) { return "AsText"; } //we have a non standard type. lets see if we have a version Matcher versionMatcher = CONTENT_TYPE_VERSION.matcher(contentType); if (versionMatcher.find()) { String version = versionMatcher.group(1); if (version != null) { return StringUtils.capitalize(version).replace(".", "_"); } } //if we got here we have some sort of funky content type. deal with it int seperatorIndex = contentType.indexOf("/"); if (seperatorIndex != -1 && seperatorIndex < contentType.length()) { String candidate = contentType.substring(seperatorIndex + 1).toLowerCase(); String out = ""; if (candidate.contains("json")) { candidate = candidate.replace("json", ""); out += "AsJson"; } candidate = StringUtils.deleteAny(candidate, " ,.+=-'\"\\|~`#$%^&\n\t"); if (StringUtils.hasText(candidate)) { out = StringUtils.capitalize(candidate) + out; } return "_" + out; } return ""; }
From source file:com.phoenixnap.oss.ramlapisync.naming.NamingHelper.java
/** * Attempts to infer the name of a resource from a resources's relative URL * /*from w w w .j a v a 2 s . c o m*/ * @param resource The Url representation of this object * @param singularize indicates if the resource name should be singularized or not * @return A name representing this resource or null if one cannot be inferred */ public static String getResourceName(String resource, boolean singularize) { if (StringUtils.hasText(resource)) { String resourceName = StringUtils.capitalize(resource); if (singularize) { resourceName = Inflector.singularize(resourceName); } resourceName = cleanNameForJava(resourceName); return resourceName; } return null; }