List of usage examples for org.apache.commons.lang StringUtils removeStart
public static String removeStart(String str, String remove)
Removes a substring only if it is at the begining of a source string, otherwise returns the source string.
From source file:com.amalto.core.objects.DroppedItemPOJO.java
/** * find all pks of dropped items/*from ww w. ja v a 2 s. c o m*/ */ public static List<DroppedItemPOJOPK> findAllPKs(String regex) throws XtentisException { // get XmlServerSLWrapperLocal XmlServer server = Util.getXmlServerCtrlLocal(); if ("".equals(regex) || "*".equals(regex) || ".*".equals(regex)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ regex = null; } try { //retrieve the item String[] ids = server.getAllDocumentsUniqueID(MDM_ITEMS_TRASH); if (ids == null) { return Collections.emptyList(); } //build PKs collection List<DroppedItemPOJOPK> list = new ArrayList<DroppedItemPOJOPK>(); Map<String, ComplexTypeMetadata> conceptMap = new HashMap<String, ComplexTypeMetadata>(); for (String uid : ids) { String[] uidValues = uid.split("\\."); //$NON-NLS-1$ ItemPOJOPK refItemPOJOPK; if (uidValues.length < 3) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not read id '" + uid + "'. Skipping it."); } continue; } // check xsd key's length String uidPrefix = uidValues[0] + "." + uidValues[1] + "."; //$NON-NLS-1$//$NON-NLS-2$ String[] idArray = Arrays.copyOfRange(uidValues, 2, uidValues.length); if (!conceptMap.containsKey(uidPrefix)) { MetadataRepository repository = ServerContext.INSTANCE.get().getMetadataRepositoryAdmin() .get(uidValues[0]); conceptMap.put(uidPrefix, repository.getComplexType(uidValues[1])); } if (conceptMap.get(uidPrefix) != null && conceptMap.get(uidPrefix).getKeyFields().size() == 1) { idArray = new String[] { StringUtils.removeStart(uid, uidPrefix) }; } refItemPOJOPK = new ItemPOJOPK(new DataClusterPOJOPK(uidValues[0]), uidValues[1], idArray); // set revision id as "" DroppedItemPOJOPK droppedItemPOJOPK = new DroppedItemPOJOPK(refItemPOJOPK, "/"); //$NON-NLS-1$ //$NON-NLS-2$ if (regex != null) { if (uid.matches(regex)) { list.add(droppedItemPOJOPK); } } else { list.add(droppedItemPOJOPK); } } return list; } catch (Exception e) { String err = "Unable to find all the identifiers for dropped items " + ": " + e.getClass().getName() + ": " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:jenkins.plugins.git.AbstractGitSCMSource.java
@NonNull @Override//from ww w . ja v a 2 s. c o m protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener) throws IOException, InterruptedException { String cacheEntry = getCacheEntry(); Lock cacheLock = getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitClient client = git.getClient(); client.addDefaultCredentials(getCredentials()); if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = getRemoteName(); listener.getLogger().println("Setting " + remoteName + " to " + getRemote()); client.setRemoteUrl(remoteName, getRemote()); listener.getLogger().println("Fetching " + remoteName + "..."); List<RefSpec> refSpecs = getRefSpecs(); client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()])); listener.getLogger().println("Pruning stale remotes..."); final Repository repository = client.getRepository(); try { client.prune(new RemoteConfig(repository.getConfig(), remoteName)); } catch (UnsupportedOperationException e) { e.printStackTrace(listener.error("Could not prune stale remotes")); } catch (URISyntaxException e) { e.printStackTrace(listener.error("Could not prune stale remotes")); } listener.getLogger().println("Getting remote branches..."); SCMSourceCriteria branchCriteria = getCriteria(); RevWalk walk = new RevWalk(repository); try { walk.setRetainBody(false); for (Branch b : client.getRemoteBranches()) { if (!b.getName().startsWith(remoteName + "/")) { continue; } final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); listener.getLogger().println("Checking branch " + branchName); if (isExcluded(branchName)) { continue; } if (branchCriteria != null) { RevCommit commit = walk.parseCommit(b.getSHA1()); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); final RevTree tree = commit.getTree(); SCMSourceCriteria.Probe probe = new SCMSourceCriteria.Probe() { @Override public String name() { return branchName; } @Override public long lastModified() { return lastModified; } @Override public boolean exists(@NonNull String path) throws IOException { TreeWalk tw = TreeWalk.forPath(repository, path, tree); try { return tw != null; } finally { if (tw != null) { tw.release(); } } } }; if (branchCriteria.isHead(probe, listener)) { listener.getLogger().println("Met criteria"); } else { listener.getLogger().println("Does not meet criteria"); continue; } } SCMHead head = new SCMHead(branchName); SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String()); observer.observe(head, hash); if (!observer.isObserving()) { return; } } } finally { walk.dispose(); } listener.getLogger().println("Done."); } finally { cacheLock.unlock(); } }
From source file:hudson.plugins.clearcase.ucm.UcmCommon.java
private static List<Baseline> getBaselinesDesc(ClearTool clearTool, String stream, String format) throws IOException, InterruptedException { BufferedReader rd = new BufferedReader(clearTool.describe(format, "stream:" + stream)); List<String> baselines = new ArrayList<String>(); try {/*from ww w . ja v a 2s. c om*/ for (String line = rd.readLine(); line != null; line = rd.readLine()) { if (!line.startsWith("cleartool: Error:")) { String[] bl = line.split(" "); for (String b : bl) { if (StringUtils.isNotBlank(b)) { baselines.add(b); } } } } } finally { rd.close(); } if (baselines.isEmpty()) { throw new IOException("Unexpected output for command \"cleartool describe -fmt " + format + " stream:" + stream + "\" or no available baseline found"); } List<Baseline> foundationBaselines = new ArrayList<Baseline>(); BufferedReader br = new BufferedReader(clearTool.describe("%[component]Xp\\n", (String[]) baselines.toArray(new String[baselines.size()]))); Iterator<String> blIterator = baselines.iterator(); for (String line = br.readLine(); line != null; line = br.readLine()) { if (StringUtils.isNotBlank(line)) { String simpleBaseline = StringUtils.removeStart(blIterator.next(), "baseline:"); String simpleComponent = StringUtils.removeStart(line, "component:"); foundationBaselines.add(new Baseline(simpleBaseline, simpleComponent)); } } return foundationBaselines; }
From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractController.java
protected boolean isPartialRedirect(HttpServletRequest request, String urlTemplatePath) { String adjustedTemplate = StringUtils.removeEnd(urlTemplatePath, ALL_WILDCARD); String contextPath = this.getUrlPathHelper().getContextPath(request); String requestUri = StringUtils.removeStart(request.getRequestURI(), contextPath); return !(StringUtils.removeStart(StringUtils.removeEnd(requestUri, "/"), "/") .equals(StringUtils.removeStart(StringUtils.removeEnd(adjustedTemplate, "/"), "/"))); }
From source file:hydrograph.ui.graph.action.subjob.SubJobOpenAction.java
private boolean isJobAlreadyOpen(IPath jobFilePath) { String jobPathRelative = StringUtils.removeStart(jobFilePath.toString(), ".."); jobPathRelative = StringUtils.removeStart(jobPathRelative, "/"); String jobPathAbsolute = StringUtils.replace(jobPathRelative, "/", "\\"); for (IEditorReference editorRefrence : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getEditorReferences()) {// ww w. j av a2s .c o m if (StringUtils.equals(editorRefrence.getTitleToolTip(), jobPathRelative)) { return true; } else if (StringUtils.equals(editorRefrence.getTitleToolTip(), jobPathAbsolute)) { return true; } } return false; }
From source file:com.egt.core.util.EA.java
private static void clipConfigurationProperties() { Bitacora.trace(EA.class, "clipConfigurationProperties"); String key;//from ww w .j a v a2 s .co m String sep = System.getProperties().getProperty("file.separator"); String osname1 = System.getProperties().getProperty("os.name"); String osname2 = StringUtils.containsIgnoreCase(osname1, "windows") ? "windows" : "linux"; String glassRoot = System.getProperties().getProperty("com.sun.aas.instanceRoot"); String jbossHome = System.getProperties().getProperty("jboss.home.dir"); String jbossBase = System.getProperties().getProperty("jboss.server.base.dir"); String somedir; boolean glassfish = StringUtils.isNotBlank(glassRoot); boolean jboss = StringUtils.isNotBlank(jbossHome); if (StringUtils.isBlank(content_root_dir)) { key = StringUtils.removeStart(SEV.ENT_APP_CONTENT_ROOT_DIR, SEV.ENT_APP_VAR_PREFFIX); somedir = coalesceToUserDir(glassRoot, jbossHome); if (glassfish) { content_root_dir = somedir + sep + "docroot"; } else if (jboss) { content_root_dir = somedir + sep + "welcome-content"; } else { content_root_dir = somedir + sep + "ROOT"; } show(key, content_root_dir); isDirectory(content_root_dir); } if (StringUtils.isBlank(home_dir)) { key = StringUtils.removeStart(SEV.ENT_APP_HOME_DIR, SEV.ENT_APP_VAR_PREFFIX); somedir = coalesceToUserDir(glassRoot, jbossBase); home_dir = somedir + sep + lower_case_code; show(key, home_dir); isDirectory(home_dir); } if (StringUtils.isBlank(configuration_properties_file)) { key = StringUtils.removeStart(SEV.ENT_APP_CONFIGURATION_PROPERTIES_FILE, SEV.ENT_APP_VAR_PREFFIX); configuration_properties_file = home_dir + sep + "resources" + sep + "config" + sep + osname2 + sep + lower_case_code + ".properties"; show(key, configuration_properties_file); isFile(configuration_properties_file); } if (StringUtils.isBlank(jdbc_driver)) { key = StringUtils.removeStart(SEV.ENT_APP_JDBC_DRIVER, SEV.ENT_APP_VAR_PREFFIX); jdbc_driver = "org.postgresql.Driver"; show(key, jdbc_driver); } if (StringUtils.isBlank(jdbc_url)) { key = StringUtils.removeStart(SEV.ENT_APP_JDBC_URL, SEV.ENT_APP_VAR_PREFFIX); jdbc_url = "jdbc:postgresql://localhost:5432/" + upper_case_code; show(key, jdbc_url); } if (StringUtils.isBlank(jdbc_user)) { key = StringUtils.removeStart(SEV.ENT_APP_JDBC_USER, SEV.ENT_APP_VAR_PREFFIX); jdbc_user = lower_case_code; show(key, jdbc_user); } if (StringUtils.isBlank(jdbc_password)) { key = StringUtils.removeStart(SEV.ENT_APP_JDBC_PASSWORD, SEV.ENT_APP_VAR_PREFFIX); jdbc_password = lower_case_code; show(key, jdbc_password); } if (StringUtils.isBlank(jndi_ejb_persistence_pattern)) { key = StringUtils.removeStart(SEV.ENT_APP_JNDI_EJB_PERSISTENCE_PATTERN, SEV.ENT_APP_VAR_PREFFIX); jndi_ejb_persistence_pattern = "java:global" + "/" + lower_case_code + "/" + lower_case_code + "-ejb-persistence/{0}"; show(key, jndi_ejb_persistence_pattern); } if (StringUtils.isBlank(velocity_properties_file)) { key = StringUtils.removeStart(SEV.ENT_APP_VELOCITY_PROPERTIES_FILE, SEV.ENT_APP_VAR_PREFFIX); velocity_properties_file = home_dir + sep + "resources" + sep + "velocity" + sep + "velocity.properties"; show(key, velocity_properties_file); isFile(velocity_properties_file); } if (StringUtils.isBlank(velocity_file_resource_loader_path)) { key = StringUtils.removeStart(SEV.ENT_APP_VELOCITY_FILE_RESOURCE_LOADER_PATH, SEV.ENT_APP_VAR_PREFFIX); velocity_file_resource_loader_path = home_dir + sep + "resources" + sep + "velocity" + sep + "templates"; show(key, velocity_file_resource_loader_path); isDirectory(velocity_file_resource_loader_path); } }
From source file:com.cloud.hypervisor.kvm.resource.LibvirtDomainXMLParser.java
public boolean parseDomainXML(String domXML) { DocumentBuilder builder;//from w w w .j a v a2s. c om try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(domXML)); Document doc = builder.parse(is); Element rootElement = doc.getDocumentElement(); desc = getTagValue("description", rootElement); Element devices = (Element) rootElement.getElementsByTagName("devices").item(0); NodeList disks = devices.getElementsByTagName("disk"); for (int i = 0; i < disks.getLength(); i++) { Element disk = (Element) disks.item(i); String type = disk.getAttribute("type"); DiskDef def = new DiskDef(); if (type.equalsIgnoreCase("network")) { String diskFmtType = getAttrValue("driver", "type", disk); String diskCacheMode = getAttrValue("driver", "cache", disk); String diskPath = getAttrValue("source", "name", disk); String protocol = getAttrValue("source", "protocol", disk); String authUserName = getAttrValue("auth", "username", disk); String poolUuid = getAttrValue("secret", "uuid", disk); String host = getAttrValue("host", "name", disk); int port = Integer.parseInt(getAttrValue("host", "port", disk)); String diskLabel = getAttrValue("target", "dev", disk); String bus = getAttrValue("target", "bus", disk); DiskDef.DiskFmtType fmt = null; if (diskFmtType != null) { fmt = DiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase()); } def.defNetworkBasedDisk(diskPath, host, port, authUserName, poolUuid, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase()), DiskDef.DiskProtocol.valueOf(protocol.toUpperCase()), fmt); def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase())); } else { String diskFmtType = getAttrValue("driver", "type", disk); String diskCacheMode = getAttrValue("driver", "cache", disk); String diskFile = getAttrValue("source", "file", disk); String diskDev = getAttrValue("source", "dev", disk); String diskLabel = getAttrValue("target", "dev", disk); String bus = getAttrValue("target", "bus", disk); String device = disk.getAttribute("device"); if (type.equalsIgnoreCase("file")) { if (device.equalsIgnoreCase("disk")) { DiskDef.DiskFmtType fmt = null; if (diskFmtType != null) { fmt = DiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase()); } def.defFileBasedDisk(diskFile, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase()), fmt); } else if (device.equalsIgnoreCase("cdrom")) { def.defISODisk(diskFile); } } else if (type.equalsIgnoreCase("block")) { def.defBlockBasedDisk(diskDev, diskLabel, DiskDef.DiskBus.valueOf(bus.toUpperCase())); } if (diskCacheMode != null) { def.setCacheMode(DiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase())); } } NodeList iotune = disk.getElementsByTagName("iotune"); if ((iotune != null) && (iotune.getLength() != 0)) { String bytesReadRateStr = getTagValue("read_bytes_sec", (Element) iotune.item(0)); if (bytesReadRateStr != null) { Long bytesReadRate = Long.parseLong(bytesReadRateStr); def.setBytesReadRate(bytesReadRate); } String bytesWriteRateStr = getTagValue("write_bytes_sec", (Element) iotune.item(0)); if (bytesWriteRateStr != null) { Long bytesWriteRate = Long.parseLong(bytesWriteRateStr); def.setBytesWriteRate(bytesWriteRate); } String iopsReadRateStr = getTagValue("read_iops_sec", (Element) iotune.item(0)); if (iopsReadRateStr != null) { Long iopsReadRate = Long.parseLong(iopsReadRateStr); def.setIopsReadRate(iopsReadRate); } String iopsWriteRateStr = getTagValue("write_iops_sec", (Element) iotune.item(0)); if (iopsWriteRateStr != null) { Long iopsWriteRate = Long.parseLong(iopsWriteRateStr); def.setIopsWriteRate(iopsWriteRate); } } diskDefs.add(def); } NodeList nics = devices.getElementsByTagName("interface"); for (int i = 0; i < nics.getLength(); i++) { Element nic = (Element) nics.item(i); String type = nic.getAttribute("type"); String mac = getAttrValue("mac", "address", nic); String dev = getAttrValue("target", "dev", nic); String model = getAttrValue("model", "type", nic); String slot = StringUtils.removeStart(getAttrValue("address", "slot", nic), "0x"); InterfaceDef def = new InterfaceDef(); NodeList bandwidth = nic.getElementsByTagName("bandwidth"); Integer networkRateKBps = 0; if ((bandwidth != null) && (bandwidth.getLength() != 0)) { Integer inbound = Integer .valueOf(getAttrValue("inbound", "average", (Element) bandwidth.item(0))); Integer outbound = Integer .valueOf(getAttrValue("outbound", "average", (Element) bandwidth.item(0))); if (inbound.equals(outbound)) { networkRateKBps = inbound; } } if (type.equalsIgnoreCase("network")) { String network = getAttrValue("source", "network", nic); def.defPrivateNet(network, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps); } else if (type.equalsIgnoreCase("bridge")) { String bridge = getAttrValue("source", "bridge", nic); def.defBridgeNet(bridge, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps); } else if (type.equalsIgnoreCase("ethernet")) { String scriptPath = getAttrValue("script", "path", nic); def.defEthernet(dev, mac, NicModel.valueOf(model.toUpperCase()), scriptPath, networkRateKBps); } if (StringUtils.isNotBlank(slot)) { def.setSlot(Integer.parseInt(slot, 16)); } interfaces.add(def); } NodeList ports = devices.getElementsByTagName("channel"); for (int i = 0; i < ports.getLength(); i++) { Element channel = (Element) ports.item(i); String type = channel.getAttribute("type"); String path = getAttrValue("source", "path", channel); String name = getAttrValue("target", "name", channel); String state = getAttrValue("target", "state", channel); ChannelDef def = null; if (!StringUtils.isNotBlank(state)) { def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()), new File(path)); } else { def = new ChannelDef(name, ChannelDef.ChannelType.valueOf(type.toUpperCase()), ChannelDef.ChannelState.valueOf(state.toUpperCase()), new File(path)); } channels.add(def); } Element graphic = (Element) devices.getElementsByTagName("graphics").item(0); if (graphic != null) { String port = graphic.getAttribute("port"); if (port != null) { try { vncPort = Integer.parseInt(port); if (vncPort != -1) { vncPort = vncPort - 5900; } else { vncPort = null; } } catch (NumberFormatException nfe) { vncPort = null; } } } NodeList rngs = devices.getElementsByTagName("rng"); for (int i = 0; i < rngs.getLength(); i++) { RngDef def = null; Element rng = (Element) rngs.item(i); String backendModel = getAttrValue("backend", "model", rng); String path = getTagValue("backend", rng); String bytes = getAttrValue("rate", "bytes", rng); String period = getAttrValue("rate", "period", rng); if (Strings.isNullOrEmpty(backendModel)) { def = new RngDef(path, Integer.parseInt(bytes), Integer.parseInt(period)); } else { def = new RngDef(path, RngBackendModel.valueOf(backendModel.toUpperCase()), Integer.parseInt(bytes), Integer.parseInt(period)); } rngDefs.add(def); } NodeList watchDogs = devices.getElementsByTagName("watchdog"); for (int i = 0; i < watchDogs.getLength(); i++) { WatchDogDef def = null; Element watchDog = (Element) watchDogs.item(i); String action = watchDog.getAttribute("action"); String model = watchDog.getAttribute("model"); if (Strings.isNullOrEmpty(model)) { continue; } if (Strings.isNullOrEmpty(action)) { def = new WatchDogDef(WatchDogModel.valueOf(model.toUpperCase())); } else { def = new WatchDogDef(WatchDogAction.valueOf(action.toUpperCase()), WatchDogModel.valueOf(model.toUpperCase())); } watchDogDefs.add(def); } return true; } catch (ParserConfigurationException e) { s_logger.debug(e.toString()); } catch (SAXException e) { s_logger.debug(e.toString()); } catch (IOException e) { s_logger.debug(e.toString()); } return false; }
From source file:gda.device.detector.addetector.filewriter.FileWriterBase.java
/** * @return the file path relative to the data directory if it starts with the datadir, * otherwise returns absolute path.//from w w w. jav a2s . c o m * @throws Exception */ protected String getRelativeFilePath() throws Exception { String fullFileName = getFullFileName(); String datadir = PathConstructor.createFromDefaultProperty(); if (StringUtils.startsWith(fullFileName, datadir)) { String relativeFilename = StringUtils.removeStart(fullFileName, datadir); relativeFilename = StringUtils.removeStart(relativeFilename, "/"); return relativeFilename; } return fullFileName; }
From source file:it.geosolutions.opensdi2.configurations.controller.OSDIModuleController.java
protected String getPathFragment(HttpServletRequest req, int index) { String path = req.getPathInfo(); if (path == null) { throw new IllegalArgumentException( "The path found in the request is null... this should never happen..."); }/* w ww. ja v a 2s . c o m*/ LOGGER.debug("Extracting part of the following path '" + path + "' in order to get the module name..."); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String[] parts = path.split("/"); if (parts == null || parts.length <= index || parts[index] == null) { throw new IllegalArgumentException("no fragment is found... this should never happen..."); } if (StringUtils.isNotEmpty(parts[index])) { return parts[index]; } for (int i = index; i < parts.length; i++) { if (StringUtils.isNotEmpty(parts[i])) { return parts[i]; } } return null; }
From source file:ips1ap101.lib.core.util.Utils.java
public static String getServerRelativePath(String absolutePath) { String root = sep(EA.getContentRootDir()); String pathname = sep(absolutePath); return StringUtils.removeStart(pathname, root); }