List of usage examples for java.text Normalizer normalize
public static String normalize(CharSequence src, Form form)
From source file:org.olat.core.util.vfs.restapi.VFSWebservice.java
public static String normalize(String segment) { segment = segment.replace(" ", "_"); segment = Normalizer.normalize(segment, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""); return segment; }
From source file:org.disit.servicemap.api.ServiceMapApi.java
public void queryService(JspWriter out, RepositoryConnection con, String idService) throws Exception { Configuration conf = Configuration.getInstance(); String sparqlType = conf.get("sparqlType", "virtuoso"); String km4cVersion = conf.get("km4cVersion", "new"); int i = 0;/*from w ww . ja v a 2 s .c o m*/ String queryService = "PREFIX km4c:<http://www.disit.org/km4city/schema#> " + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>" + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#> " + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#> " + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX schema:<http://schema.org/>" //+ "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#> " //+ "PREFIX foaf:<http://xmlns.com/foaf/0.1/> " + "PREFIX skos:<http://www.w3.org/2004/02/skos/core#>" //+ "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX dcterms:<http://purl.org/dc/terms/>" + "SELECT ?serAddress ?serNumber ?elat ?elong ?sName ?sType ?type ?sCategory ?sTypeIta ?email ?note ?multimedia ?descriptionEng ?descriptionIta ?phone ?fax ?website ?prov ?city ?cap WHERE{" + " {" + " <" + idService + "> km4c:hasAccess ?entry ." + " ?entry geo:lat ?elat . " //+ " FILTER (?elat>40) " + " ?entry geo:long ?elong . " //+ " FILTER (?elong>10) ." + " }UNION{" + " <" + idService + "> km4c:isInRoad ?road." + " <" + idService + "> geo:lat ?elat." //+ " FILTER (?elat>40) " + " <" + idService + "> geo:long ?elong." //+ " FILTER (?elong>10) ." + " }UNION{" + " <" + idService + "> geo:lat ?elat." //+ " FILTER (?elat>40) " + " <" + idService + "> geo:long ?elong." //+ " FILTER (?elong>10) ." + " }" + " OPTIONAL {<" + idService + "> schema:name ?sName.}" + " OPTIONAL { <" + idService + "> schema:streetAddress ?serAddress.}" + (km4cVersion.equals("old") ? " <" + idService + "> km4c:hasServiceCategory ?cat ." + " ?cat rdfs:label ?nome . " + " BIND (?nome AS ?sType) ." + " BIND (?nome AS ?sTypeIta) ." + " FILTER(LANG(?nome) = \"it\") ." + " OPTIONAL {<" + idService + "> <http://purl.org/dc/elements/1.1/description> ?description ." + " FILTER(LANG(?description) = \"it\")} ." : " <" + idService + "> a ?type . FILTER(?type!=km4c:RegularService && ?type!=km4c:Service)" + " ?type rdfs:label ?nome . " + " ?type rdfs:subClassOf ?sCategory. " + " BIND (?nome AS ?sType) ." + " BIND (?nome AS ?sTypeIta) ." + " FILTER(LANG(?nome) = \"it\") .") + " OPTIONAL {<" + idService + "> km4c:houseNumber ?serNumber} ." + " OPTIONAL {<" + idService + "> dcterms:description ?descriptionIta" //+ " FILTER(LANG(?descriptionEng) = \"en\")" + "}" + " OPTIONAL {<" + idService + "> dcterms:description ?descriptionEng FILTER(?descriptionEng!=?descriptionIta)" //+ " FILTER(LANG(?descriptionIta) = \"it\")" + "}" + " OPTIONAL {<" + idService + "> km4c:multimediaResource ?multimedia} ." + " OPTIONAL {<" + idService + "> skos:note ?note} . " + " OPTIONAL {<" + idService + "> schema:email ?email } . " // AGGIUNTA CAMPI DA VISUALIZZARE NELLA SCHEDA + " OPTIONAL {<" + idService + "> schema:faxNumber ?fax }" + " OPTIONAL {<" + idService + "> schema:telephone ?phone }" + " OPTIONAL {<" + idService + "> schema:addressRegion ?prov }" + " OPTIONAL {<" + idService + "> schema:addressLocality ?city }" + " OPTIONAL {<" + idService + "> schema:postalCode ?cap }" + " OPTIONAL {<" + idService + "> schema:url ?website }" // ---- FINE CAMPI AGGIUNTI --- + "}LIMIT 1"; // out.println("count = "+count); String queryDBpedia = "PREFIX km4c:<http://www.disit.org/km4city/schema#>\n" + "PREFIX cito:<http://purl.org/spar/cito/>\n" + "SELECT ?linkDBpedia WHERE{\n" + " OPTIONAL {<" + idService + "> km4c:isInRoad ?road.\n" + "?road cito:cites ?linkDBpedia.}\n" + "}"; out.println("{ \"Service\":" + "{\"type\": \"FeatureCollection\", " + "\"features\": [ "); TupleQuery tupleQueryService = con.prepareTupleQuery(QueryLanguage.SPARQL, queryService); TupleQueryResult resultService = tupleQueryService.evaluate(); String TOS = ""; String NOS = ""; TupleQuery tupleQueryDBpedia = con.prepareTupleQuery(QueryLanguage.SPARQL, queryDBpedia); TupleQueryResult resultDBpedia = tupleQueryDBpedia.evaluate(); String valueOfDBpedia = "["; while (resultService.hasNext()) { BindingSet bindingSetService = resultService.next(); while (resultDBpedia.hasNext()) { BindingSet bindingSetDBpedia = resultDBpedia.next(); if (bindingSetDBpedia.getValue("linkDBpedia") != null) { if (!("[".equals(valueOfDBpedia))) { valueOfDBpedia = valueOfDBpedia + ", \"" + bindingSetDBpedia.getValue("linkDBpedia").stringValue() + "\""; } else { valueOfDBpedia = valueOfDBpedia + "\"" + bindingSetDBpedia.getValue("linkDBpedia").stringValue() + "\""; } } } valueOfDBpedia = valueOfDBpedia + "]"; String valueOfSerAddress = ""; if (bindingSetService.getValue("serAddress") != null) { valueOfSerAddress = bindingSetService.getValue("serAddress").stringValue(); } String valueOfSerNumber = ""; if (bindingSetService.getValue("serNumber") != null) { valueOfSerNumber = bindingSetService.getValue("serNumber").stringValue(); } String valueOfSType = bindingSetService.getValue("sType").stringValue(); String valueOfSTypeIta = ""; if (bindingSetService.getValue("sTypeIta") != null) { valueOfSTypeIta = bindingSetService.getValue("sTypeIta").stringValue(); } // DICHIARAZIONE VARIABILI serviceType e serviceCategory per ICONA String subCategory = ""; if (bindingSetService.getValue("type") != null) { subCategory = bindingSetService.getValue("type").stringValue(); subCategory = subCategory.replace("http://www.disit.org/km4city/schema#", ""); //subCategory = Character.toLowerCase(subCategory.charAt(0)) + subCategory.substring(1); //subCategory = subCategory.replace(" ", "_"); } String category = ""; if (bindingSetService.getValue("sCategory") != null) { category = bindingSetService.getValue("sCategory").stringValue(); category = category.replace("http://www.disit.org/km4city/schema#", ""); //category = Character.toLowerCase(category.charAt(0)) + category.substring(1); //category = category.replace(" ", "_"); } String serviceType = category + "_" + subCategory; // controllo del Nome per i Geolocated Object String valueOfSName = ""; if (bindingSetService.getValue("sName") != null) { valueOfSName = bindingSetService.getValue("sName").stringValue(); } else { valueOfSName = subCategory.replace("_", " ").toUpperCase(); } String valueOfELat = bindingSetService.getValue("elat").stringValue(); String valueOfELong = bindingSetService.getValue("elong").stringValue(); String valueOfNote = ""; if (bindingSetService.getValue("note") != null) { valueOfNote = bindingSetService.getValue("note").stringValue(); } String valueOfEmail = ""; if (bindingSetService.getValue("email") != null) { valueOfEmail = bindingSetService.getValue("email").stringValue(); } String valueOfMultimediaResource = ""; if (bindingSetService.getValue("multimedia") != null) { valueOfMultimediaResource = bindingSetService.getValue("multimedia").stringValue(); } String valueOfDescriptionIta = ""; if (bindingSetService.getValue("descriptionIta") != null) { valueOfDescriptionIta = bindingSetService.getValue("descriptionIta").stringValue(); } String valueOfDescriptionEng = ""; if (bindingSetService.getValue("descriptionEng") != null) { valueOfDescriptionEng = bindingSetService.getValue("descriptionEng").stringValue(); } //AGGIUNTA CAMPI DA VISUALIZZARE SU SCHEDA String valueOfFax = ""; if (bindingSetService.getValue("fax") != null) { valueOfFax = bindingSetService.getValue("fax").stringValue(); } String valueOfPhone = ""; if (bindingSetService.getValue("phone") != null) { valueOfPhone = bindingSetService.getValue("phone").stringValue(); } String valueOfProv = ""; if (bindingSetService.getValue("prov") != null) { valueOfProv = bindingSetService.getValue("prov").stringValue(); } String valueOfCity = ""; if (bindingSetService.getValue("city") != null) { valueOfCity = bindingSetService.getValue("city").stringValue(); } String valueOfUrl = ""; if (bindingSetService.getValue("website") != null) { valueOfUrl = bindingSetService.getValue("website").stringValue(); } String valueOfCap = ""; if (bindingSetService.getValue("cap") != null) { valueOfCap = bindingSetService.getValue("cap").stringValue(); } // ---- FINE AGGIUNTA --- NOS = valueOfSName; //valueOfSTypeIta = Character.toLowerCase(valueOfSTypeIta.charAt(0)) + valueOfSTypeIta.substring(1); valueOfSTypeIta = valueOfSTypeIta.replace(" ", "_"); valueOfSTypeIta = valueOfSTypeIta.replace("@it", ""); TOS = valueOfSTypeIta; Normalizer.normalize(valueOfNote, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""); valueOfNote = valueOfNote.replaceAll("[^A-Za-z0-9 ]+", ""); if (i != 0) { out.println(", "); } out.println("{ " + " \"geometry\": { " + " \"type\": \"Point\", " + " \"coordinates\": [ " + " " + valueOfELong + ", " + " " + valueOfELat + " " + " ] " + "}, " + "\"type\": \"Feature\", " + "\"properties\": { " + " \"nome\": \"" + escapeJSON(valueOfSName) + "\", " + " \"tipo\": \"" + TOS + "\", " // *** INSERIMENTO serviceType + " \"serviceType\": \"" + escapeJSON(mapServiceType(serviceType)) + "\", " + " \"phone\": \"" + valueOfPhone + "\", " + " \"fax\": \"" + valueOfFax + "\", " + " \"website\": \"" + valueOfUrl + "\", " + " \"province\": \"" + valueOfProv + "\", " + " \"city\": \"" + valueOfCity + "\", " + " \"cap\": \"" + valueOfCap + "\", " // ********************************************** + " \"email\": \"" + escapeJSON(valueOfEmail) + "\", " + " \"linkDBpedia\": " + valueOfDBpedia + ", " + " \"note\": \"" + escapeJSON(valueOfNote) + "\", " + " \"description\": \"" + escapeJSON(valueOfDescriptionIta) + "\", " + " \"description2\": \"" + escapeJSON(valueOfDescriptionEng) + "\", " + " \"multimedia\": \"" + valueOfMultimediaResource + "\", " + " \"serviceUri\": \"" + idService + "\", " + " \"indirizzo\": \"" + valueOfSerAddress + "\", \"numero\": \"" + valueOfSerNumber + "\" " + "}, " + "\"id\": " + Integer.toString(i + 1) + " " + "}"); i++; } out.println("] }"); if ("Parcheggio_auto".equals(TOS)) { String queryStringParkingStatus = " PREFIX km4c:<http://www.disit.org/km4city/schema#>" + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>" + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX schema:<http://schema.org/#>" + "PREFIX time:<http://www.w3.org/2006/time#>" + "SELECT distinct ?situationRecord ?instantDateTime ?occupancy ?free ?occupied ?capacity ?cpStatus WHERE { " + " ?cps km4c:observeCarPark <" + idService + ">." + " ?cps km4c:capacity ?capacity." + " ?situationRecord km4c:relatedToSensor ?cps." + " ?situationRecord km4c:observationTime ?time." + " ?time <http://purl.org/dc/terms/identifier> ?instantDateTime." + " ?situationRecord km4c:parkOccupancy ?occupancy." + " ?situationRecord km4c:free ?free." + " ?situationRecord km4c:carParkStatus ?cpStatus." + " ?situationRecord km4c:occupied ?occupied." + "} ORDER BY DESC (?instantDateTime) LIMIT 1"; TupleQuery tupleQueryParking = con.prepareTupleQuery(QueryLanguage.SPARQL, queryStringParkingStatus); TupleQueryResult resultParkingStatus = tupleQueryParking.evaluate(); out.println(",\"realtime\": "); if (resultParkingStatus.hasNext()) { out.println("{ \"head\": {" + "\"parcheggio\":[ " + "\"" + NOS + "\"" + "]," + "\"vars\":[ " + "\"Capacit\", " + "\"PostiLiberi\"," + "\"PostiOccupati\"," + "\"Occupazione\"," + "\"Aggiornamento\"" + "]" + "},"); out.println("\"results\": {"); out.println("\"bindings\": ["); int p = 0; while (resultParkingStatus.hasNext()) { BindingSet bindingSetParking = resultParkingStatus.next(); String valueOfInstantDateTime = ""; if (bindingSetParking.getValue("instantDateTime") != null) { valueOfInstantDateTime = bindingSetParking.getValue("instantDateTime").stringValue(); } String valueOfOccupancy = ""; if (bindingSetParking.getValue("occupancy") != null) { valueOfOccupancy = bindingSetParking.getValue("occupancy").stringValue(); } String valueOfFree = ""; if (bindingSetParking.getValue("free") != null) { valueOfFree = bindingSetParking.getValue("free").stringValue(); } String valueOfOccupied = ""; if (bindingSetParking.getValue("occupied") != null) { valueOfOccupied = bindingSetParking.getValue("occupied").stringValue(); } String valueOfCapacity = ""; if (bindingSetParking.getValue("capacity") != null) { valueOfCapacity = bindingSetParking.getValue("capacity").stringValue(); } String valueOfcpStatus = ""; if (bindingSetParking.getValue("cpStatus") != null) { valueOfcpStatus = bindingSetParking.getValue("cpStatus").stringValue(); } if (p != 0) { out.println(", "); } out.println("{" + "\"Capacit\": {" + "\"value\": \"" + valueOfCapacity + "\" " + " }," + "\"PostiLiberi\": { " + "\"value\": \"" + valueOfFree + "\" " + " }," + "\"PostiOccupati\": {" + "\"value\": \"" + valueOfOccupied + "\" " + " }," + "\"Occupazione\": {" + "\"value\": \"" + valueOfOccupancy + "\" " + " }," + "\"Stato\": {" + "\"value\": \"" + valueOfcpStatus + "\" " + " }," + "\"Aggiornamento\": {" + "\"value\": \"" + valueOfInstantDateTime + "\" " + " }"); out.println("}"); p++; } out.println("]}}}"); } else { out.println("{}}"); } } else { out.println("}"); } }
From source file:org.rythmengine.utils.S.java
/** * Replace accent character (usually found in European languages) of the String representation of a * give object to non-accent char./*from w w w . java2 s. c om*/ * * @param o * @return the string result */ @Transformer public static String noAccents(Object o) { if (null == o) return ""; String string = o.toString(); return Normalizer.normalize(string, Normalizer.Form.NFKC).replaceAll("[?]", "a") .replaceAll("[?]", "c").replaceAll("[?]", "d").replaceAll("[]", "e") .replaceAll("[]", "f").replaceAll("[?]", "g").replaceAll("[]", "h") .replaceAll("[]", "i").replaceAll("[]", "j").replaceAll("[]", "k") .replaceAll("[]", "l").replaceAll("[]", "n") .replaceAll("[??]", "o").replaceAll("[]", "p").replaceAll("[]", "r") .replaceAll("[?]", "s").replaceAll("[]", "t") .replaceAll("[]", "u").replaceAll("[]", "w").replaceAll("[]", "y") .replaceAll("[]", "z").replaceAll("[]", "ae").replaceAll("[?]", "A") .replaceAll("[]", "C").replaceAll("[??]", "D").replaceAll("[]", "E") .replaceAll("[]", "G").replaceAll("[]", "H").replaceAll("[??]", "I") .replaceAll("[]", "J").replaceAll("[]", "K").replaceAll("[?]", "L") .replaceAll("[]", "N").replaceAll("[?]", "O").replaceAll("[]", "R") .replaceAll("[]", "S").replaceAll("[]", "U").replaceAll("[]", "W") .replaceAll("[?]", "Y").replaceAll("[]", "Z").replaceAll("[]", "ss"); }
From source file:org.lockss.servlet.AddContentTab.java
/** * Sanitises a string so that it can be used as a div id * * @param name/* w w w . j a v a 2s .co m*/ * @return Returns sanitised string */ public static String cleanName(String name) { return Normalizer.normalize(HtmlUtil.encode(name.replace(" ", "_").replace("&", "").replace("(", "") .replace(")", "").replace(",", "").replace("+", "_"), HtmlUtil.ENCODE_TEXT), Normalizer.Form.NFC); }
From source file:org.georchestra.console.ws.backoffice.users.UsersController.java
/** * Deaccentuate a string and remove non-word characters * * references: http://stackoverflow.com/a/8523728 and * http://stackoverflow.com/a/2397830/*from ww w .j av a2 s. co m*/ * * @param string an accentuated string, eg. "Jo+o" * @return return the deaccentuated string, eg. "Joao" */ public static String normalizeString(String string) { return Normalizer.normalize(string, Normalizer.Form.NFD).replaceAll("\\W", ""); }
From source file:org.medici.bia.service.peoplebase.PeopleBaseServiceImpl.java
/** * {@inheritDoc}//ww w .ja v a 2 s. c o m */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public People addNewPerson(People person) throws ApplicationThrowable { Date now = new Date(); try { User user = getCurrentUser(); person.setPersonId(null); //Setting fields that are defined as nullable = false person.setResearcher( ((BiaUserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal()) .getInitials()); person.setCreatedBy(user); person.setDateCreated(now); person.setLastUpdate(now); person.setLastUpdateBy(user); person.setMapNameLf(PersonUtils.generateMapNameLf(person)); if (person.getGender().equals(Gender.NULL)) { person.setGender(null); } if (person.getBornApprox() == null) { person.setBornApprox(Boolean.FALSE); } if (person.getBornDateBc() == null) { person.setBornDateBc(Boolean.FALSE); } if (person.getBornPlaceUnsure() == null) { person.setBornPlaceUnsure(Boolean.FALSE); } if (person.getDeathApprox() == null) { person.setDeathApprox(Boolean.FALSE); } if (person.getDeathDateBc() == null) { person.setDeathDateBc(Boolean.FALSE); } if (person.getDeathPlaceUnsure() == null) { person.setDeathPlaceUnsure(Boolean.FALSE); } if (person.getPortrait() == null) { person.setPortrait(false); } if (person.getBornMonth() != null) { Month month = getMonthDAO().find(person.getBornMonth().getMonthNum()); person.setBornMonth(month); } else { person.setBornMonth(null); } person.setBornDate( DateUtils.getLuceneDate(person.getBornYear(), person.getBornMonth(), person.getBornDay())); if (person.getDeathMonth() != null) { Month month = getMonthDAO().find(person.getDeathMonth().getMonthNum()); person.setDeathMonth(month); } else { person.setDeathMonth(null); } person.setDeathDate( DateUtils.getLuceneDate(person.getDeathYear(), person.getDeathMonth(), person.getDeathDay())); if (!ObjectUtils.toString(person.getBornPlace()).equals("")) { person.setBornPlace(getPlaceDAO().find(person.getBornPlace().getPlaceAllId())); if (person.getBornPlace().getPrefFlag().equals("V")) { person.setBornPlace(getPlaceDAO().findPrinicipalPlace(person.getBornPlace().getGeogKey())); } } else { person.setBornPlace(null); } if (!ObjectUtils.toString(person.getDeathPlace()).equals("")) { person.setDeathPlace(getPlaceDAO().find(person.getDeathPlace().getPlaceAllId())); if (person.getDeathPlace().getPrefFlag().equals("V")) { person.setDeathPlace(getPlaceDAO().findPrinicipalPlace(person.getDeathPlace().getGeogKey())); } } else { person.setDeathPlace(null); } if (ObjectUtils.toString(person.getActiveStart()).equals("")) { person.setActiveStart(null); } else { person.setActiveStart(person.getActiveStart()); } if (ObjectUtils.toString(person.getActiveEnd()).equals("")) { person.setActiveEnd(null); } else { person.setActiveEnd(person.getActiveEnd()); } person.setLogicalDelete(Boolean.FALSE); //Code for create altNames AltName given = new AltName(); given.setAltName(person.getFirst()); given.setNameType(NameType.Given.toString()); AltName family = new AltName(); family.setAltName(person.getLast()); family.setNameType(NameType.Family.toString()); AltName searchName = new AltName(); searchName.setAltName(Normalizer.normalize(person.getMapNameLf(), Normalizer.Form.NFD)); searchName.setAltName(searchName.getAltName().replaceAll("\\p{InCombiningDiacriticalMarks}+", "")); searchName.setAltName(searchName.getAltName().replace(",", "")); searchName.setAltName(searchName.getAltName().replace("(", "")); searchName.setAltName(searchName.getAltName().replace(")", "")); searchName.setAltName(searchName.getAltName().toUpperCase()); searchName.setNameType(NameType.SearchName.toString()); getPeopleDAO().persist(person); person = getPeopleDAO().findLastEntryPerson(); given.setPerson(person); getAltNameDAO().persist(given); family.setPerson(person); getAltNameDAO().persist(family); searchName.setPerson(person); getAltNameDAO().persist(searchName); getUserHistoryDAO() .persist(new UserHistory(user, "Add person", Action.CREATE, Category.PEOPLE, person)); getVettingHistoryDAO().persist( new VettingHistory(user, "Add person", org.medici.bia.domain.VettingHistory.Action.CREATE, org.medici.bia.domain.VettingHistory.Category.PEOPLE, person)); return person; } catch (Throwable th) { throw new ApplicationThrowable(th); } }
From source file:org.lockss.util.StringUtil.java
/** * Normalize string by removing diacritical marks. * @param s the string//from w w w.jav a 2 s .c o m * @return the string with diacritical marks removed */ static public String toUnaccented(String s) { return COMBINING_DIACRIT_PAT.matcher(Normalizer.normalize(s, Form.NFD)).replaceAll(""); }
From source file:org.apache.nifi.processors.standard.EncryptContent.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { FlowFile flowFile = session.get();//from ww w .j a va 2s . c o m if (flowFile == null) { return; } final ComponentLog logger = getLogger(); final String method = context.getProperty(ENCRYPTION_ALGORITHM).getValue(); final EncryptionMethod encryptionMethod = EncryptionMethod.valueOf(method); final String providerName = encryptionMethod.getProvider(); final String algorithm = encryptionMethod.getAlgorithm(); final String password = context.getProperty(PASSWORD).getValue(); final KeyDerivationFunction kdf = KeyDerivationFunction .valueOf(context.getProperty(KEY_DERIVATION_FUNCTION).getValue()); final boolean encrypt = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCRYPT_MODE); Encryptor encryptor; StreamCallback callback; try { if (isPGPAlgorithm(algorithm)) { final String filename = flowFile.getAttribute(CoreAttributes.FILENAME.key()); final String publicKeyring = context.getProperty(PUBLIC_KEYRING).getValue(); final String privateKeyring = context.getProperty(PRIVATE_KEYRING).getValue(); if (encrypt && publicKeyring != null) { final String publicUserId = context.getProperty(PUBLIC_KEY_USERID).getValue(); encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, publicKeyring, publicUserId, null, filename); } else if (!encrypt && privateKeyring != null) { final char[] keyringPassphrase = context.getProperty(PRIVATE_KEYRING_PASSPHRASE).getValue() .toCharArray(); encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, privateKeyring, null, keyringPassphrase, filename); } else { final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray(); encryptor = new OpenPGPPasswordBasedEncryptor(algorithm, providerName, passphrase, filename); } } else if (kdf.equals(KeyDerivationFunction.NONE)) { // Raw key final String keyHex = context.getProperty(RAW_KEY_HEX).getValue(); encryptor = new KeyedEncryptor(encryptionMethod, Hex.decodeHex(keyHex.toCharArray())); } else { // PBE final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray(); encryptor = new PasswordBasedEncryptor(encryptionMethod, passphrase, kdf); } if (encrypt) { callback = encryptor.getEncryptionCallback(); } else { callback = encryptor.getDecryptionCallback(); } } catch (final Exception e) { logger.error("Failed to initialize {}cryption algorithm because - ", new Object[] { encrypt ? "en" : "de", e }); session.rollback(); context.yield(); return; } try { final StopWatch stopWatch = new StopWatch(true); flowFile = session.write(flowFile, callback); logger.info("successfully {}crypted {}", new Object[] { encrypt ? "en" : "de", flowFile }); session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(flowFile, REL_SUCCESS); } catch (final ProcessException e) { logger.error("Cannot {}crypt {} - ", new Object[] { encrypt ? "en" : "de", flowFile, e }); session.transfer(flowFile, REL_FAILURE); } }
From source file:org.opensextant.util.TextUtils.java
/** * Supports Phoneticizer utility from OpenSextant v1.x Remove diacritics * from a phrase/* w ww . j a v a 2 s .c o m*/ * * @param word * text * @return scrubbed text */ public static String removeDiacritics(String word) { // first, fully decomposed all chars String tmpWord = Normalizer.normalize(word, Normalizer.Form.NFD); StringBuilder newWord = new StringBuilder(); char[] chars = tmpWord.toCharArray(); // now, discard any characters from one of the "Mark" categories. for (char c : chars) { if (Character.getType(c) != Character.NON_SPACING_MARK && Character.getType(c) != Character.COMBINING_SPACING_MARK && Character.getType(c) != Character.ENCLOSING_MARK) { newWord.append(c); } } return newWord.toString(); }
From source file:net.pms.dlna.RootFolder.java
/** * Returns iTunes folder. Used by manageRoot, so it is usually used as a * folder at the root folder. Only works on Mac OS X or Windows. * * The iTunes XML is parsed fully when this method is called, so it can * take some time for larger (+1000 albums) databases. * * This method does not support genius playlists and does not provide a * media library./*from www .j a v a 2s. c om*/ * * @see RootFolder#getiTunesFile() */ private DLNAResource getiTunesFolder() { DLNAResource res = null; logger.info("Start building iTunes folder..."); if (Platform.isMac() || Platform.isWindows()) { Map<String, Object> iTunesLib; List<?> Playlists; Map<?, ?> Playlist; Map<?, ?> Tracks; Map<?, ?> track; List<?> PlaylistTracks; try { String iTunesFile = getiTunesFile(); if (iTunesFile != null && (new File(iTunesFile)).exists()) { iTunesLib = Plist.load(URLDecoder.decode(iTunesFile, System.getProperty("file.encoding"))); // loads the (nested) properties. Tracks = (Map<?, ?>) iTunesLib.get("Tracks"); // the list of tracks Playlists = (List<?>) iTunesLib.get("Playlists"); // the list of Playlists res = new VirtualFolder("iTunes Library", null); VirtualFolder playlistsFolder = null; for (Object item : Playlists) { Playlist = (Map<?, ?>) item; if (Playlist.containsKey("Visible") && Playlist.get("Visible").equals(Boolean.FALSE)) continue; if (Playlist.containsKey("Music") && Playlist.get("Music").equals(Boolean.TRUE)) { // Create virtual folders for artists, albums and genres VirtualFolder musicFolder = new VirtualFolder(Playlist.get("Name").toString(), null); res.addChild(musicFolder); VirtualFolder virtualFolderArtists = new VirtualFolder(Messages.getString("PMS.13"), null); VirtualFolder virtualFolderAlbums = new VirtualFolder(Messages.getString("PMS.16"), null); VirtualFolder virtualFolderGenres = new VirtualFolder(Messages.getString("PMS.19"), null); VirtualFolder virtualFolderAllTracks = new VirtualFolder(Messages.getString("PMS.11"), null); PlaylistTracks = (List<?>) Playlist.get("Playlist Items"); // list of tracks in a playlist String artistName; String albumName; String genreName; if (PlaylistTracks != null) { for (Object t : PlaylistTracks) { Map<?, ?> td = (Map<?, ?>) t; track = (Map<?, ?>) Tracks.get(td.get("Track ID").toString()); if (track != null && track.get("Location") != null && track.get("Location").toString().startsWith("file://")) { String name = Normalizer.normalize((String) track.get("Name"), Normalizer.Form.NFC); // remove dots from name to prevent media renderer from trimming name = name.replace('.', '-'); if (track.containsKey("Protected") && track.get("Protected").equals(Boolean.TRUE)) name = String.format(Messages.getString("RootFolder.1"), name); boolean isCompilation = (track.containsKey("Compilation") && track.get("Compilation").equals(Boolean.TRUE)); artistName = (String) (isCompilation ? "Compilation" : track.containsKey("Album Artist") ? track.get("Album Artist") : track.get("Artist")); albumName = (String) track.get("Album"); genreName = (String) track.get("Genre"); if (artistName == null) { artistName = "Unknown Artist"; } else { artistName = Normalizer.normalize(artistName, Normalizer.Form.NFC); } if (albumName == null) { albumName = "Unknown Album"; } else { albumName = Normalizer.normalize(albumName, Normalizer.Form.NFC); } if (genreName == null) { genreName = "Unknown Genre"; } else if ("".equals(genreName.replaceAll("[^a-zA-Z]", ""))) { // This prevents us from adding blank or numerical genres genreName = "Unknown Genre"; } else { genreName = Normalizer.normalize(genreName, Normalizer.Form.NFC); } // Replace   with space and then trim artistName = artistName.replace('\u0160', ' ').trim(); albumName = albumName.replace('\u0160', ' ').trim(); genreName = genreName.replace('\u0160', ' ').trim(); URI tURI2 = new URI(track.get("Location").toString()); File refFile = new File( URLDecoder.decode(tURI2.toURL().getFile(), "UTF-8")); RealFile file = new RealFile(refFile, name); // ARTISTS FOLDER - Put the track into the artist's album folder and the artist's "All tracks" folder { VirtualFolder individualArtistFolder = null; VirtualFolder individualArtistAllTracksFolder = null; VirtualFolder individualArtistAlbumFolder = null; for (DLNAResource artist : virtualFolderArtists.getChildren()) { if (areNamesEqual(artist.getName(), artistName)) { individualArtistFolder = (VirtualFolder) artist; for (DLNAResource album : individualArtistFolder .getChildren()) { if (areNamesEqual(album.getName(), albumName)) { individualArtistAlbumFolder = (VirtualFolder) album; } } break; } } if (individualArtistFolder == null) { individualArtistFolder = new VirtualFolder(artistName, null); virtualFolderArtists.addChild(individualArtistFolder); individualArtistAllTracksFolder = new VirtualFolder( Messages.getString("PMS.11"), null); individualArtistFolder.addChild(individualArtistAllTracksFolder); } else { individualArtistAllTracksFolder = (VirtualFolder) individualArtistFolder .getChildren().get(0); } if (individualArtistAlbumFolder == null) { individualArtistAlbumFolder = new VirtualFolder(albumName, null); individualArtistFolder.addChild(individualArtistAlbumFolder); } individualArtistAlbumFolder.addChild(file.clone()); individualArtistAllTracksFolder.addChild(file); } // ALBUMS FOLDER - Put the track into its album folder { if (!isCompilation) albumName += " " + artistName; VirtualFolder individualAlbumFolder = null; for (DLNAResource album : virtualFolderAlbums.getChildren()) { if (areNamesEqual(album.getName(), albumName)) { individualAlbumFolder = (VirtualFolder) album; break; } } if (individualAlbumFolder == null) { individualAlbumFolder = new VirtualFolder(albumName, null); virtualFolderAlbums.addChild(individualAlbumFolder); } individualAlbumFolder.addChild(file.clone()); } // GENRES FOLDER - Put the track into its genre folder { VirtualFolder individualGenreFolder = null; for (DLNAResource genre : virtualFolderGenres.getChildren()) { if (areNamesEqual(genre.getName(), genreName)) { individualGenreFolder = (VirtualFolder) genre; break; } } if (individualGenreFolder == null) { individualGenreFolder = new VirtualFolder(genreName, null); virtualFolderGenres.addChild(individualGenreFolder); } individualGenreFolder.addChild(file.clone()); } // ALL TRACKS - Put the track into the global "All tracks" folder virtualFolderAllTracks.addChild(file.clone()); } } } musicFolder.addChild(virtualFolderArtists); musicFolder.addChild(virtualFolderAlbums); musicFolder.addChild(virtualFolderGenres); musicFolder.addChild(virtualFolderAllTracks); // Sort the virtual folders alphabetically Collections.sort(virtualFolderArtists.getChildren(), new Comparator<DLNAResource>() { @Override public int compare(DLNAResource o1, DLNAResource o2) { VirtualFolder a = (VirtualFolder) o1; VirtualFolder b = (VirtualFolder) o2; return a.getName().compareToIgnoreCase(b.getName()); } }); Collections.sort(virtualFolderAlbums.getChildren(), new Comparator<DLNAResource>() { @Override public int compare(DLNAResource o1, DLNAResource o2) { VirtualFolder a = (VirtualFolder) o1; VirtualFolder b = (VirtualFolder) o2; return a.getName().compareToIgnoreCase(b.getName()); } }); Collections.sort(virtualFolderGenres.getChildren(), new Comparator<DLNAResource>() { @Override public int compare(DLNAResource o1, DLNAResource o2) { VirtualFolder a = (VirtualFolder) o1; VirtualFolder b = (VirtualFolder) o2; return a.getName().compareToIgnoreCase(b.getName()); } }); } else { // Add all playlists VirtualFolder pf = new VirtualFolder(Playlist.get("Name").toString(), null); PlaylistTracks = (List<?>) Playlist.get("Playlist Items"); // list of tracks in a playlist if (PlaylistTracks != null) { for (Object t : PlaylistTracks) { Map<?, ?> td = (Map<?, ?>) t; track = (Map<?, ?>) Tracks.get(td.get("Track ID").toString()); if (track != null && track.get("Location") != null && track.get("Location").toString().startsWith("file://")) { String name = Normalizer.normalize(track.get("Name").toString(), Normalizer.Form.NFC); // remove dots from name to prevent media renderer from trimming name = name.replace('.', '-'); if (track.containsKey("Protected") && track.get("Protected").equals(Boolean.TRUE)) name = String.format(Messages.getString("RootFolder.1"), name); URI tURI2 = new URI(track.get("Location").toString()); RealFile file = new RealFile( new File(URLDecoder.decode(tURI2.toURL().getFile(), "UTF-8")), name); pf.addChild(file); } } } int kind = Playlist.containsKey("Distinguished Kind") ? ((Number) Playlist.get("Distinguished Kind")).intValue() : -1; if (kind >= 0 && kind != 17 && kind != 19 && kind != 20) { // System folder, but not voice memos (17) and purchased items (19 & 20) res.addChild(pf); } else { // User playlist or playlist folder if (playlistsFolder == null) { playlistsFolder = new VirtualFolder("Playlists", null); res.addChild(playlistsFolder); } playlistsFolder.addChild(pf); } } } } else { logger.info("Could not find the iTunes file"); } } catch (Exception e) { logger.error("Something went wrong with the iTunes Library scan: ", e); } } logger.info("Done building iTunes folder."); return res; }