List of usage examples for org.apache.commons.lang3 StringUtils substringBetween
public static String substringBetween(final String str, final String open, final String close)
Gets the String that is nested in between two Strings.
From source file:org.xlrnet.tibaija.tools.fontgen.FontgenApplication.java
@NotNull private Font importFont(String source, String fontIdentifier) throws IOException { Path sourcePath = Paths.get(source); Pattern filePattern = Pattern.compile("[0-9A-F]{2}h_" + fontIdentifier + "[a-zA-Z0-9]*.gif"); List<Path> fileList = Files.list(sourcePath) .filter(p -> filePattern.matcher(p.getFileName().toString()).matches()) .collect(Collectors.toList()); Font font = new Font(); List<Symbol> symbols = new ArrayList<>(); for (Path path : fileList) { try {/* w ww . j av a 2 s. c o m*/ Symbol symbol = importFile(path, font, fontIdentifier); if (symbol == null) continue; String filename = path.getFileName().toString(); String hexValue = StringUtils.substring(filename, 0, 2); String internalIdentifier = StringUtils.substringBetween(filename, "_" + fontIdentifier, ".gif"); symbol.setHexValue(hexValue); symbol.setInternalIdentifier(internalIdentifier); symbols.add(symbol); } catch (ImageReadException e) { LOGGER.error("Reading image {} failed", path.toAbsolutePath(), e); } } Collections.sort(symbols); font.setSymbols(symbols); return font; }
From source file:qic.util.DurianUtils.java
public static Verify verify(String thread, String dataHash) { // http://verify.xyz.is/1504841/d571ac1d216e9e84dd1f44172c73abcb?callback=__callback_1450079321791_659&_=735.8083963058672 // function query(thread, hash, callback) { // callback_name = "__callback_" + (new Date()).getTime() + "_" + Math.floor((Math.random() * 1000)); // window[callback_name] = callback; // a = document.createElement('script'); // var domain = "http://verify.xyz.is/"; // a.src = domain + thread + "/" + hash + "?callback=" + callback_name + "&_=" + Math.random() * 1000; // a.type = "text/javascript"; // document.getElementsByTagName("head")[0].appendChild(a); // }//from www. j av a 2s . c o m String url = String.format("http://verify.xyz.is/%s/%s", thread, dataHash); String callback_name = "__callback_" + (new Date()).getTime() + "_" + Math.floor((Math.random() * 1000)); String underscoreValue = String.valueOf(Math.random() * 1000); Map<String, Object> parameters = new HashMap<>(); parameters.put("callback", callback_name); parameters.put("_", underscoreValue); String verifyRaw = null; try { verifyRaw = getVerifyAndRetry(url, parameters, verifyRaw); } catch (UnirestException e) { return ERROR; // default to verified if call to verify failed } // __callback_1450079321791_659(true); String result = StringUtils.substringBetween(verifyRaw, callback_name + "(", ");"); boolean verified = Boolean.parseBoolean(result); return verified ? VERIFIED : SOLD; }
From source file:sonicScream.models.Script.java
/** * Takes the currently active simple tree, and uses its values to update the main * rootNode tree, then returns the newly-updated tree. * @return The newly-updated tree.//from w ww . jav a2s. c o m */ public TreeItem<String> updateRootNodeWithSimpleTree() { if (_simpleRootNode == null) { return getRootNode(); } for (TreeItem<String> entry : _simpleRootNode.getChildren()) { List<TreeItem<String>> sounds = entry.getChildren(); for (int i = 0; i < sounds.size(); i++) { TreeItem<String> currentEntryInRoot = TreeUtils.findKey(_rootNode, entry.getValue()); List<TreeItem<String>> rootSounds = TreeUtils.getWaveStrings(currentEntryInRoot).orElseThrow(null); if (rootSounds != null && rootSounds.size() > i) { if (rootSounds.get(i).getValue().contains(sounds.get(i).getValue())) { continue; } String rootSoundString = rootSounds.get(i).getValue(); String soundPrefix = StringUtils.substringBetween(rootSoundString, "\"", "\""); soundPrefix = soundPrefix.substring(0, soundPrefix.length() - 1); //Remove the number from the prefix String value = "\"" + soundPrefix + i + "\" \"" + sounds.get(i).getValue() + "\""; rootSounds.get(i).setValue(value); } } } return _rootNode; }
From source file:sonicScream.models.ScriptTest.java
/** * Tested last using the class annotation, because it causes side effects * on the loaded scripts.//from w ww. j a va 2s.co m */ @Test public void z_testUpdateRootNodeWithSimpleTree() { allTestScripts.stream().forEach(s -> { try { TreeItem<String> simple = s.getSimpleTree(); TreeItem<String> simpleNode = simple.getChildren().get(0).getChildren().get(0); String simpleSoundString = "some_test_sound.mp3"; String value = "some_test_sound.mp3"; simpleNode.setValue(value); s.updateRootNodeWithSimpleTree(); String rootSoundString = TreeUtils.getWaveStrings(s.getRootNode()).get().get(0).getValue(); String soundPrefix = StringUtils.substringBetween(rootSoundString, "\"", "\""); soundPrefix = soundPrefix.substring(0, soundPrefix.length() - 1); //Remove the number from the prefix String expected = "\"" + soundPrefix + "0\" \"" + simpleSoundString + "\""; String actual = TreeUtils.getWaveStrings(s.getRootNode()).get().get(0).getValue(); assertEquals(expected, actual); } catch (Exception ex) { System.err.println("testUpdateRootNodeWithSimpleTree failed on script " + s.toString() + ": " + ex.getMessage()); } }); }
From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java
/** * Transforms the given <code>xml</code> that is in KFS3 format to KFS6 * format./*from w ww .j a v a2 s . com*/ * * @param xml * {@link String} of the XML to transform * @return {@link String} of the transformed XML * @throws Exception * Any {@link Exception}s encountered will be rethrown */ public String transformMaintainableXML(String xml, String docid) throws Exception { /* * a handful of documents have unfriendly Unicode characters which the * XML processor (and the rest of KFS) can't handle. Pre-process to * replace with a friendly base ASCII characters. */ xml = xml.replace("\u0001", "-"); xml = xml.replace("\u001e", " "); xml = xml.replace("\u001d", " "); String beginning = StringUtils.substringBefore(xml, "<" + OLD_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">"); String oldMaintainableObjectXML = StringUtils.substringBetween(xml, "<" + OLD_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">", "</" + OLD_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">"); String newMaintainableObjectXML = StringUtils.substringBetween(xml, "<" + NEW_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">", "</" + NEW_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">"); String ending = StringUtils.substringAfter(xml, "</" + NEW_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">"); // quick hack to catch top-level class replacements for (String className : classNameRuleMap.keySet()) { if (beginning.contains("maintainableImplClass=\"" + className + "\"")) { LOGGER.trace("Replacing top-level maintainableImplClass attribute: " + className + " with: " + classNameRuleMap.get(className)); beginning = beginning.replace("maintainableImplClass=\"" + className + "\"", "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\""); } } String convertedOldMaintainableObjectXML = transformSection(oldMaintainableObjectXML, docid); String convertedNewMaintainableObjectXML = transformSection(newMaintainableObjectXML, docid); String convertedXML = beginning + "<" + OLD_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">" + convertedOldMaintainableObjectXML + "</" + OLD_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">" + "<" + NEW_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">" + convertedNewMaintainableObjectXML + "</" + NEW_MAINTAINABLE_OBJECT_ELEMENT_NAME + ">" + ending; return convertedXML; }
From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java
/** * Transforms the given <code>xml</code> section from KFS3 format to KFS6 * format.// ww w. j a v a 2s. c om * * @param xml * {@link String} of the XML to transform * @return {@link String} of the transformed XML * @throws Exception * Any {@link Exception}s encountered will be rethrown. */ private String transformSection(String xml, String docid) throws Exception { String rawXml = xml; String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">", "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = upgradeBONotes(xml, docid); if (classNameRuleMap == null) { setRuleMaps(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document; try { document = db.parse(new InputSource(new StringReader(xml))); } catch (SAXParseException ex) { String eol = System.getProperty("line.separator"); String exMsg = "Failed in db.parse(new InputSource(new StringReader(xml))) where xml=" + xml + eol + "of maintenanceAction = " + maintenanceAction + eol + "contained in rawXml = " + rawXml; throw new SAXParseException(exMsg, null, ex); } for (Node childNode = document.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); transformClassNode(document, childNode); // Also Transform first level Children which have class attribute NodeList children = childNode.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if ((child != null) && (child.getNodeType() == Node.ELEMENT_NODE) && (child.hasAttributes())) { NamedNodeMap childAttributes = child.getAttributes(); if (childAttributes.item(0).getNodeName() == "class") { String childClassName = childAttributes.item(0).getNodeValue(); if (classPropertyRuleMap.containsKey(childClassName)) { Map<String, String> propertyMappings = classPropertyRuleMap.get(childClassName); NodeList nestedChildren = child.getChildNodes(); for (int i = 0; i < nestedChildren.getLength() - 1; i++) { Node property = nestedChildren.item(i); String propertyName = property.getNodeName(); if ((property.getNodeType() == Node.ELEMENT_NODE) && (propertyMappings != null) && (propertyMappings.containsKey(propertyName))) { String newPropertyName = propertyMappings.get(propertyName); if (StringUtils.isNotBlank(newPropertyName)) { document.renameNode(property, null, newPropertyName); propertyName = newPropertyName; } else { // If there is no replacement name then the element needs to be removed child.removeChild(property); } } } } } } } childNode = nextChild; } /* * the default logic that traverses over the document tree doesn't * handle classes that are in an @class attribute, so we deal with those * individually. */ migratePersonObjects(document); migrateKualiCodeBaseObjects(document); migrateAccountExtensionObjects(document); migrateClassAsAttribute(document); removeAutoIncrementSetElements(document); removeReconcilerGroup(document); catchMissedTypedArrayListElements(document); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); trans.transform(source, result); /* * (?m) puts the regex into multiline mode: * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern. * html#MULTILINE So the effect of this statement is * "remove any empty lines" */ xml = writer.toString().replaceAll("(?m)^\\s+\\n", ""); xml = xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"; // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("active defined-in=\"" + className + "\"")) { LOGGER.info("Replacing active defined-in= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("active defined-in=\"" + className + "\"", "active defined-in=\"" + classNameRuleMap.get(className) + "\""); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("<" + className + ">")) { LOGGER.info("Replacing open tag: <" + className + "> with: <" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("<" + className + ">", "<" + classNameRuleMap.get(className) + ">"); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("</" + className + ">")) { LOGGER.info("Replacing close tag: </" + className + "> with: </" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("</" + className + ">", "</" + classNameRuleMap.get(className) + ">"); } } // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("maintainableImplClass=\"" + className + "\"")) { LOGGER.info("Replacing maintainableImplClass= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("maintainableImplClass=\"" + className + "\"", "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\""); } } // investigative logging, still useful as a smoke test for (String oldClassName : classNameRuleMap.keySet()) { if (xml.contains(oldClassName)) { LOGGER.warn("Document has classname in contents that should have been mapped: " + oldClassName); LOGGER.warn("at docid= " + docid + " for xml= " + xml); } } checkForElementsWithClassAttribute(document); return xml; }
From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java
/** * Upgrades the old Bo notes tag that was part of the maintainable to the * new notes tag.//w w w.jav a 2 s. c o m * * @param oldXML * - the xml to upgrade * @throws Exception */ private String upgradeBONotes(String oldXML, String docId) throws Exception { // Get the old bo note xml String notesXml = StringUtils.substringBetween(oldXML, "<boNotes>", "</boNotes>"); if (notesXml != null) { LOGGER.trace("BO Notes present, upgrading -> " + docId); notesXml = notesXml.replace("org.kuali.rice.kns.bo.Note", "org.kuali.rice.krad.bo.Note"); notesXml = "<org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl>\n" + notesXml + "\n</org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl>"; int pos1 = oldXML.indexOf("<boNotes>"); int pos2 = oldXML.indexOf("</boNotes>", pos1); if ((pos1 > -1) && (pos2 > pos1)) { oldXML = (oldXML.substring(0, pos1) + "\n<boNotes>\n" + notesXml + "\n</boNotes>" + oldXML.substring(pos2 + "</boNotes>".length())); } } //replace empty boNotes if present oldXML = oldXML.replace("<boNotes/>", ""); return oldXML; }
From source file:uk.org.funcube.fcdw.server.processor.DataProcessor.java
@Transactional(readOnly = false) @RequestMapping(value = "/{siteId}/", method = RequestMethod.POST) public ResponseEntity<String> uploadData(@PathVariable String siteId, @RequestParam(value = "digest") String digest, @RequestBody String body) { // get the user from the repository List<UserEntity> users = userDao.findBySiteId(siteId); if (users.size() != 0) { String hexString = StringUtils.substringBetween(body, "=", "&"); hexString = hexString.replace("+", " "); String authKey = userAuthKeys.get(siteId); final UserEntity user = users.get(0); try {//from w w w .j a v a 2s. c om if (authKey == null) { if (user != null) { authKey = user.getAuthKey(); userAuthKeys.put(siteId, authKey); } else { LOG.error(USER_WITH_SITE_ID + siteId + NOT_FOUND); return new ResponseEntity<String>("UNAUTHORIZED", HttpStatus.UNAUTHORIZED); } } final String calculatedDigest = calculateDigest(hexString, authKey, null); final String calculatedDigestUTF8 = calculateDigest(hexString, authKey, new Integer(8)); final String calculatedDigestUTF16 = calculateDigest(hexString, authKey, new Integer(16)); if (null != digest && (digest.equals(calculatedDigest) || digest.equals(calculatedDigestUTF8)) || digest.equals(calculatedDigestUTF16)) { hexString = StringUtils.deleteWhitespace(hexString); final int frameId = Integer.parseInt(hexString.substring(0, 2), 16); final int frameType = frameId & 63; final int satelliteId = (frameId & (128 + 64)) >> 6; final int sensorId = frameId % 2; final String binaryString = convertHexBytePairToBinary( hexString.substring(2, hexString.length())); final Date now = clock.currentDate(); final RealTime realTime = new RealTime(satelliteId, frameType, sensorId, now, binaryString); final long sequenceNumber = realTime.getSequenceNumber(); if (sequenceNumber != -1) { final List<HexFrameEntity> frames = hexFrameDao .findBySatelliteIdAndSequenceNumberAndFrameType(satelliteId, sequenceNumber, frameType); HexFrameEntity hexFrame = null; if (frames != null && frames.size() == 0) { hexFrame = new HexFrameEntity((long) satelliteId, (long) frameType, sequenceNumber, hexString, now, true); hexFrame.getUsers().add(user); hexFrameDao.save(hexFrame); RealTimeEntity realTimeEntity = new RealTimeEntity(realTime); realTimeDao.save(realTimeEntity); } else { hexFrame = frames.get(0); hexFrame.getUsers().add(user); hexFrameDao.save(hexFrame); } } return new ResponseEntity<String>("OK", HttpStatus.OK); } else { LOG.error(USER_WITH_SITE_ID + siteId + HAD_INCORRECT_DIGEST + ", received: " + digest + ", calculated: " + calculatedDigest); return new ResponseEntity<String>("UNAUTHORIZED", HttpStatus.UNAUTHORIZED); } } catch (final Exception e) { LOG.error(e.getMessage()); return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST); } } else { LOG.error("Site id: " + siteId + " not found in database"); return new ResponseEntity<String>("UNAUTHORIZED", HttpStatus.UNAUTHORIZED); } }
From source file:utils.UtilsMainframe.java
public static MEMBER readMember(String dsn) { System.out.println("dsn " + dsn); Matcher m = Pattern.compile("\\(\\w+\\)").matcher(dsn); if (m.find()) { String pds = StringUtils.substringBefore(dsn, "("); String mmbr = StringUtils.substringBetween(m.group(), "(", ")"); System.out.println("pdsd sd " + pds + " mmbr " + mmbr); MEMBER member = readMember(pds, mmbr); return member; }//from w w w . jav a2 s.co m return new MEMBER(); }
From source file:v7db.files.CatCommand.java
static byte[] decodeSHAPrefix(String shaPrefix) throws DecoderException, IOException { byte[] id;// ww w . j a v a 2s . co m if (shaPrefix.startsWith("BinData(")) { id = Base64.decodeBase64(StringUtils.substringBetween(shaPrefix, ",", ")")); } else { id = Hex.decodeHex(shaPrefix.toCharArray()); } if (id.length > 20) throw new DecoderException("too long"); return id; }