List of usage examples for org.apache.commons.lang StringUtils right
public static String right(String str, int len)
Gets the rightmost len
characters of a String.
From source file:net.refractions.udig.ui.FeatureTableLabelProvider.java
/** * * Returns the value of the column / feature attribute. * //www . j ava2 s . c o m * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) * @param element the array of feature attributes. * @param columnIndex the column index / feature attribute. * @return the string representation of the feature attribute, except * for attributes of type Geometry in which a string representing the * type of Geometry is returned. */ public String getColumnText(Object element, int columnIndex) { if (element instanceof FeatureCollection) { FeatureCollection<SimpleFeatureType, SimpleFeature> fc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) element; if (columnIndex == 0) { return fc.getSchema().getName().getLocalPart(); } return ""; //$NON-NLS-1$ } else if (element instanceof SimpleFeature) { SimpleFeature f = (SimpleFeature) element; if (columnIndex == 0) { // _p3: FIXME displaying FID is useless for most users return "..." + StringUtils.right(f.getID(), 3); } if (owningFeatureTableControl.features == null) return ""; //$NON-NLS-1$ String attName = owningFeatureTableControl.getViewer().getTable().getColumn(columnIndex).getText(); AttributeDescriptor at = f.getFeatureType().getDescriptor(attName); if (at != null && at.getType() != null && at.getType().getBinding() != null && Geometry.class.isAssignableFrom(at.getType().getBinding())) { //was at.isGeometry() Object att = f.getAttribute(attName); if (att == null) return ""; //$NON-NLS-1$ String s = att.getClass().getName(); return s.substring(s.lastIndexOf('.') + 1); } Object attribute = f.getAttribute(attName); return attribute == null ? "" : attribute.toString(); //$NON-NLS-1$ } else if (element instanceof Throwable) { if (columnIndex == 0) { return ((Throwable) element).getLocalizedMessage(); } return null; } else if (element instanceof String) { return (String) element; } else return Messages.get("FeatureTableControl_loadingMessage"); }
From source file:net.sf.sail.webapp.dao.user.impl.HibernateUserDao.java
/** * Capitalizes the first letter of a given String * //from ww w. j av a2s .c o m * @param string * @return String */ private String capitalizeFirst(String string) { return StringUtils.upperCase(StringUtils.left(string, 1)) + StringUtils.right(string, string.length() - 1); }
From source file:jenkins.branch.WorkspaceLocatorImpl.java
static String minimize(String name) { String mnemonic = name.replaceAll("(%[0-9A-F]{2}|[^a-zA-Z0-9-_.])+", "_"); int maxSuffix = 53; /* ceil(256 / lg(32)) + length("-") */ int maxMnemonic = Math.max(PATH_MAX - maxSuffix, 1); if (maxSuffix + maxMnemonic > PATH_MAX) { // The whole suffix cannot be included in the path. Trim the suffix // and the mnemonic to fit inside PATH_MAX. The mnemonic always gets // at least one character. The suffix always gets 10 characters plus // the "-". The rest of PATH_MAX is split evenly between the two. LOGGER.log(Level.WARNING, "WorkspaceLocatorImpl.PATH_MAX is small enough that workspace path collisions are more likely to occur"); final int minSuffix = 10 + /* length("-") */ 1; maxMnemonic = Math.max((int) ((PATH_MAX - minSuffix) / 2), 1); maxSuffix = Math.max(PATH_MAX - maxMnemonic, minSuffix); }//from w w w .ja v a2 s .c o m maxSuffix = maxSuffix - 1; // Remove the "-" String result = StringUtils.right(mnemonic, maxMnemonic) + "-" + uniqueSuffix(name).substring(0, maxSuffix); return result; }
From source file:com.cloudbees.jenkins.plugins.amazonecs.ECSService.java
AmazonECSClient getAmazonECSClient() { final AmazonECSClient client; ProxyConfiguration proxy = Jenkins.getInstance().proxy; ClientConfiguration clientConfiguration = new ClientConfiguration(); if (proxy != null) { clientConfiguration.setProxyHost(proxy.name); clientConfiguration.setProxyPort(proxy.port); clientConfiguration.setProxyUsername(proxy.getUserName()); clientConfiguration.setProxyPassword(proxy.getPassword()); }/* w w w . jav a 2 s . c o m*/ AmazonWebServicesCredentials credentials = getCredentials(credentialsId); if (credentials == null) { // no credentials provided, rely on com.amazonaws.auth.DefaultAWSCredentialsProviderChain // to use IAM Role define at the EC2 instance level ... client = new AmazonECSClient(clientConfiguration); } else { if (LOGGER.isLoggable(Level.FINE)) { String awsAccessKeyId = credentials.getCredentials().getAWSAccessKeyId(); String obfuscatedAccessKeyId = StringUtils.left(awsAccessKeyId, 4) + StringUtils.repeat("*", awsAccessKeyId.length() - (2 * 4)) + StringUtils.right(awsAccessKeyId, 4); LOGGER.log(Level.FINE, "Connect to Amazon ECS with IAM Access Key {1}", new Object[] { obfuscatedAccessKeyId }); } client = new AmazonECSClient(credentials, clientConfiguration); } client.setRegion(getRegion(regionName)); LOGGER.log(Level.FINE, "Selected Region: {0}", regionName); return client; }
From source file:com.cisco.oss.foundation.tools.simulator.rest.resources.SimulatorConfigurationResource.java
@PUT @Consumes({ MediaType.APPLICATION_JSON }) public Response updateSimulator(@PathParam("port") final int port, final String simulatorResponseStr) { if (!simulatorService.simulatorExists(port)) { String msg = "can not update simulator. simulator on port " + port + " doesn't exist"; logger.error(msg);/*from w ww .j a v a 2s . c o m*/ return Response.status(Status.BAD_REQUEST).entity(msg).build(); } SimulatorResponse simulatorResponse; boolean added = false; ; if (StringUtils.isEmpty(simulatorResponseStr)) { String msg = "When adding a response to an existing simulator you need to specify the response json in the body." + " if you want to load the simulator from a file just write 'file' in the body and we'll take it from the default location which is at: " + " src/main/resources/responses/defaultResponses.json - sababa ?"; logger.error(msg); return Response.status(Status.BAD_REQUEST).entity(msg).build(); } if (simulatorResponseStr.trim().equalsIgnoreCase("file")) { added = addResponsesFromDefaultFile(port); } else if (simulatorResponseStr.trim().startsWith("file:") && simulatorResponseStr.trim().endsWith(".json")) { String fileName = StringUtils.right(simulatorResponseStr, simulatorResponseStr.length() - 5); added = addResponsesFromSpecificFile(port, fileName); } else { try { simulatorResponse = objectMapper.readValue(simulatorResponseStr, SimulatorResponse.class); logger.debug("Request added to simulator:\n" + simulatorResponseStr); } catch (Exception e) { logger.error("failed parsing json request", e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } added = simulatorService.addResponseToSimulator(port, simulatorResponse); } ResponseBuilder rb; if (added) { rb = Response.ok(); } else { rb = Response.status(Status.INTERNAL_SERVER_ERROR); } return rb.build(); }
From source file:gov.nih.nci.firebird.test.ValueGenerator.java
private static String getIntegerString(int length) { String value = StringUtils.leftPad(String.valueOf(getUniqueInt()), length, '0'); return StringUtils.right(value, length); }
From source file:jenkins.branch.NameMangler.java
public static String apply(String name) { if (name.length() <= MAX_SAFE_LENGTH) { boolean unsafe = false; boolean first = true; for (char c : name.toCharArray()) { if (first) { if (c == '-') { // no leading dash unsafe = true;// w ww . ja v a2 s .c o m break; } first = false; } if (!isSafe(c)) { unsafe = true; break; } } // See https://msdn.microsoft.com/en-us/library/aa365247 we need to consistently reserve names across all OS if (!unsafe) { // we know it is only US-ASCII if we got to here switch (name.toLowerCase(Locale.ENGLISH)) { case ".": case "..": case "con": case "prn": case "aux": case "nul": case "com1": case "com2": case "com3": case "com4": case "com5": case "com6": case "com7": case "com8": case "com9": case "lpt1": case "lpt2": case "lpt3": case "lpt4": case "lpt5": case "lpt6": case "lpt7": case "lpt8": case "lpt9": unsafe = true; break; default: if (name.endsWith(".")) { unsafe = true; } break; } } if (!unsafe) { return name; } } StringBuilder buf = new StringBuilder(name.length() + 16); for (char c : name.toCharArray()) { if (isSafe(c)) { buf.append(c); } else if (c == '/' || c == '\\' || c == ' ' || c == '.' || c == '_') { if (buf.length() == 0) { buf.append("0-"); } else { buf.append('-'); } } else if (c <= 0xff) { if (buf.length() == 0) { buf.append("0_"); } else { buf.append('_'); } buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0')); } else { if (buf.length() == 0) { buf.append("0_"); } else { buf.append('_'); } buf.append(StringUtils.leftPad(Integer.toHexString(((c & 0xffff) >> 8) & 0xff), 2, '0')); buf.append('_'); buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0')); } } // use the digest of the original name String digest; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] bytes = sha.digest(name.getBytes(StandardCharsets.UTF_8)); int bits = 0; int data = 0; StringBuffer dd = new StringBuffer(32); for (byte b : bytes) { while (bits >= 5) { dd.append(toDigit(data & 0x1f)); bits -= 5; data = data >> 5; } data = data | ((b & 0xff) << bits); bits += 8; } digest = dd.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA-1 not installed", e); // impossible } if (buf.length() <= MAX_SAFE_LENGTH - MIN_HASH_LENGTH - 1) { // we have room to add the min hash buf.append('.'); buf.append(StringUtils.right(digest, MIN_HASH_LENGTH)); return buf.toString(); } // buf now holds the mangled string, we will now try and rip the middle out to put in some of the digest int overage = buf.length() - MAX_SAFE_LENGTH; String hash; if (overage <= MIN_HASH_LENGTH) { hash = "." + StringUtils.right(digest, MIN_HASH_LENGTH) + "."; } else if (overage > MAX_HASH_LENGTH) { hash = "." + StringUtils.right(digest, MAX_HASH_LENGTH) + "."; } else { hash = "." + StringUtils.right(digest, overage) + "."; } int start = (MAX_SAFE_LENGTH - hash.length()) / 2; buf.delete(start, start + hash.length() + overage); buf.insert(start, hash); return buf.toString(); }
From source file:fc.extensions.itext.Writer.java
@Override public void onCloseDocument(PdfWriter writer, Document document) { if (pageObject == null) { return;/*from ww w . ja v a2s. co m*/ } pageHeadTemplate.beginText(); pageHeadTemplate.setFontAndSize(baseFont, pageObject.getHeader().getFontSize()); pageHeadTemplate.showTextAligned(PdfContentByte.ALIGN_RIGHT, StringUtils.right(CONTENT_OF_PAGE_COUNT + (writer.getCurrentPageNumber() - 1), 6), pageHeadTemplate.getWidth(), 0F, 0); pageHeadTemplate.endText(); }
From source file:com.openbravo.pos.admin.RolesViewTree.java
private void createTree() { //Create the jtree root = new DefaultMutableTreeNode(); uTree = new CheckboxTree(root); root.setUserObject("All Permissions"); uTree.getCheckingModel().setCheckingMode(TreeCheckingModel.CheckingMode.PROPAGATE_PRESERVING_CHECK); uTree.clearSelection();/*from ww w. java 2 s . c o m*/ DefaultCheckboxTreeCellRenderer renderer = (DefaultCheckboxTreeCellRenderer) uTree.getCellRenderer(); renderer.setLeafIcon(null); renderer.setClosedIcon(null); renderer.setOpenIcon(null); // set up listeners MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = uTree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = uTree.getPathForLocation(e.getX(), e.getY()); if (selPath != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent(); // If using Right to left Language change the way the check tree works if (!uTree.getComponentOrientation().isLeftToRight()) { if (uTree.isPathChecked(new TreePath(node.getPath()))) { uTree.removeCheckingPath(new TreePath(node.getPath())); } else { uTree.addCheckingPath(new TreePath(node.getPath())); } } jPermissionDesc.setText(descriptionMap.get(node)); } } }; uTree.addMouseListener(ml); // when this listener is fired changes state to dirty uTree.addTreeCheckingListener(new TreeCheckingListener() { public void valueChanged(TreeCheckingEvent e) { passedDirty.setDirty(true); } }); try { // Get list of all the permisions in the database // and the list of sections dbPermissions = (List) m_dlAdmin.getAlldbPermissions(); branches = m_dlAdmin.getSectionsList(); } catch (BasicException ex) { Logger.getLogger(RolesViewTree.class.getName()).log(Level.SEVERE, null, ex); } // Create the main branches in the tree for (Object branch : branches) { section = ((StringUtils.substring(branch.toString(), 0, 2)).equals("##")) ? AppLocal.getIntString(StringUtils.right(branch.toString(), branch.toString().length() - 2)) : branch.toString(); root.add(new DefaultMutableTreeNode(section)); } classMap = new HashMap(); descriptionMap = new HashMap(); nodePaths = new HashMap(); // Replace displayname, Section and Description // from the database with the correct details from the permissions locale for (DBPermissionsInfo Perm : dbPermissions) { Perm.setDisplayName(((StringUtils.substring(Perm.getDisplayName(), 0, 2)).equals("##")) ? AppLocal.getIntString( StringUtils.right(Perm.getDisplayName(), Perm.getDisplayName().length() - 2)) : Perm.getDisplayName()); Perm.setSection(((StringUtils.substring(Perm.getSection(), 0, 2)).equals("##")) ? AppLocal.getIntString(StringUtils.right(Perm.getSection(), Perm.getSection().length() - 2)) : Perm.getSection()); Perm.setDescription(((StringUtils.substring(Perm.getDescription(), 0, 2)).equals("##")) ? AppLocal.getIntString( StringUtils.right(Perm.getDescription(), Perm.getDescription().length() - 2)) : Perm.getDescription()); } //put the list into order by display name sort(); // Create the leaf nodes & fill in hashmap's for (DBPermissionsInfo Perm : dbPermissions) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(Perm.getDisplayName(), false); if (searchNode(Perm.getSection(), root) != null) { searchNode(Perm.getSection(), root).add(newNode); classMap.put("[All Permissions, " + Perm.getSection() + ", " + newNode + "]", Perm.getClassName()); descriptionMap.put(newNode, Perm.getDescription()); nodePaths.put(Perm.getClassName(), newNode); } } root = sortTree(root); jScrollPane1.setViewportView(uTree); uTree.expandAll(); }
From source file:fc.extensions.itext.Writer.java
@Override public void onEndPage(PdfWriter writer, Document document) { if (pageObject == null) { return;// www .ja va 2 s.c om } float llx = pageObject.getHeader().getPosition().getLeft(); float lly = pageObject.getHeader().getPosition().getBottom(); float urx = pageObject.getHeader().getPosition().getRight(); float ury = pageObject.getHeader().getPosition().getTop(); float alingY = pageObject.getHeader().getPosition().getTop(); int fontSize = (int) pageObject.getHeader().getFontSize(); String[] headerBody = pageObject.getHeader().getBody(); try { pdfWriterCB.saveState(); pdfWriterCB.beginText(); pdfWriterCB.setFontAndSize(baseFont, fontSize); pdfWriterCB.setTextMatrix(llx, ury); pdfWriterCB.setLeading(fontSize); for (int i = 0; i < headerBody.length; i++) { alingY = alingY - getLetterHeight(fontSize); if (i == headerBody.length - 1) { pdfWriterCB.showTextAligned(PdfContentByte.ALIGN_RIGHT, headerBody[i] + StringUtils.right(CONTENT_OF_PAGE_COUNT + writer.getCurrentPageNumber(), 6) + "/ ", urx, alingY, 0); } else { pdfWriterCB.showTextAligned(PdfContentByte.ALIGN_RIGHT, headerBody[i], urx, alingY, 0); } } pdfWriterCB.endText(); pdfWriterCB.addTemplate(pageHeadTemplate, urx - baseFont.getWidthPoint(CONTENT_OF_PAGE_COUNT, fontSize), alingY); } finally { pdfWriterCB.restoreState(); } }