List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:gov.va.vinci.v3nlp.negex.GenNegEx.java
public String negCheck(String sentenceString, String phraseString, List<String> ruleStrings, boolean negatePossible) throws Exception { Sorter s = new Sorter(); String sToReturn = ""; String sScope = ""; List<String> sortedRules = new ArrayList<String>(); String filler = "_"; boolean negPoss = negatePossible; // Sort the rules by length in descending order. // Rules need to be sorted so the longest rule is always tried to match // first./*w w w .j ava 2 s . c o m*/ // Some of the rules overlap so without sorting first shorter rules (some of them POSSIBLE or PSEUDO) // would match before longer legitimate negation rules. // // There is efficiency issue here. It is better if rules are sorted by the // calling program once and used without sorting in GennegEx. sortedRules = s.sortRules(ruleStrings); // Process the sentence and tag each matched negation // rule with correct negation rule tag. // // At the same time check for the phrase that we want to decide // the negation status for and // tag the phrase with [PHRASE] ... [PHRASE] // In both the negation rules and in the phrase replace white space // with "filler" string. (This could cause problems if the sentences // we study has "filler" on their own.) // Sentence needs one character in the beginning and end to match. // We remove the extra characters after processing. String sentence = "." + sentenceString + "."; // Tag the phrases we want to detect for negation. // Should happen before rule detection. String phrase = phraseString; Pattern pph = null; try { pph = Pattern.compile(phrase.trim(), Pattern.CASE_INSENSITIVE); } catch (Exception e) { // IF There was an exception, escape the phrase for special regex characters. It is more // efficient to only escape if an error, as most phrases will work fine. logger.info("In Special processing... (" + phrase.trim() + ")"); pph = Pattern.compile(escapeRegexCharacters(phrase.trim()), Pattern.CASE_INSENSITIVE); } Matcher mph = pph.matcher(sentence); while (mph.find() == true) { sentence = mph.replaceAll(" [PHRASE]" + mph.group().trim().replaceAll(" ", filler) + "[PHRASE]"); } Iterator<String> iRule = sortedRules.iterator(); while (iRule.hasNext()) { String rule = iRule.next(); Pattern p = Pattern.compile("[\\t]+"); // Working. String[] ruleTokens = p.split(rule.trim()); // Add the regular expression characters to tokens and asemble the rule again. String[] ruleMembers = ruleTokens[0].trim().split(" "); String rule2 = ""; for (int i = 0; i <= ruleMembers.length - 1; i++) { if (!ruleMembers[i].equals("")) { if (ruleMembers.length == 1) { rule2 = ruleMembers[i]; } else { rule2 = rule2 + ruleMembers[i].trim() + "\\s+"; } } } // Remove the last s+ if (rule2.endsWith("\\s+")) { rule2 = rule2.substring(0, rule2.lastIndexOf("\\s+")); } rule2 = "(?m)(?i)[[\\p{Punct}&&[^\\]\\[]]|\\s+](" + rule2 + ")[[\\p{Punct}&&[^_]]|\\s+]"; Pattern p2 = Pattern.compile(ruleTokens[0].trim()); Matcher m = p2.matcher(sentence); while (m.find()) { String rpWith = ruleTokens[2].substring(2).trim(); sentence = m.replaceAll(" " + rpWith + m.group().trim().replaceAll(" ", filler) + rpWith + " "); } } // Exchange the [PHRASE] ... [PHRASE] tags for [NEGATED] ... [NEGATED] // based of PREN, POST rules and if flag is set to true // then based on PREP and POSP, as well. // Because PRENEGATION [PREN} is checked first it takes precedent over // POSTNEGATION [POST]. // Similarly POSTNEGATION [POST] takes precedent over POSSIBLE PRENEGATION [PREP] // and [PREP] takes precedent over POSSIBLE POSTNEGATION [POSP]. Pattern pSpace = Pattern.compile("[\\s+]"); String[] sentenceTokens = pSpace.split(sentence); StringBuilder sb = new StringBuilder(); // Check for [PREN] for (int i = 0; i < sentenceTokens.length; i++) { sb.append(" " + sentenceTokens[i].trim()); if (sentenceTokens[i].trim().startsWith("[PREN]") || sentenceTokens[i].trim().startsWith("[PRE_NEG]")) { for (int j = i + 1; j < sentenceTokens.length; j++) { if (sentenceTokens[j].trim().startsWith("[CONJ]") || sentenceTokens[j].trim().startsWith("[PSEU]") || sentenceTokens[j].trim().startsWith("[POST]") || sentenceTokens[j].trim().startsWith("[PREP]") || sentenceTokens[j].trim().startsWith("[POSP]")) { break; } if (sentenceTokens[j].trim().startsWith("[PHRASE]")) { sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]"); } } } } sentence = sb.toString(); pSpace = Pattern.compile("[\\s+]"); sentenceTokens = pSpace.split(sentence); StringBuilder sb2 = new StringBuilder(); // Check for [POST] for (int i = sentenceTokens.length - 1; i > 0; i--) { sb2.insert(0, sentenceTokens[i] + " "); if (sentenceTokens[i].trim().startsWith("[POST]")) { for (int j = i - 1; j > 0; j--) { if (sentenceTokens[j].trim().startsWith("[CONJ]") || sentenceTokens[j].trim().startsWith("[PSEU]") || sentenceTokens[j].trim().startsWith("[PRE_NEG]") || sentenceTokens[j].trim().startsWith("[PREN]") || sentenceTokens[j].trim().startsWith("[PREP]") || sentenceTokens[j].trim().startsWith("[POSP]")) { break; } if (sentenceTokens[j].trim().startsWith("[PHRASE]")) { sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[NEGATED]"); } } } } sentence = sb2.toString(); // If POSSIBLE negation is detected as negation. // negatePossible being set to "true" then check for [PREP] and [POSP]. if (negPoss == true) { pSpace = Pattern.compile("[\\s+]"); sentenceTokens = pSpace.split(sentence); StringBuilder sb3 = new StringBuilder(); // Check for [PREP] for (int i = 0; i < sentenceTokens.length; i++) { sb3.append(" " + sentenceTokens[i].trim()); if (sentenceTokens[i].trim().startsWith("[PREP]")) { for (int j = i + 1; j < sentenceTokens.length; j++) { if (sentenceTokens[j].trim().startsWith("[CONJ]") || sentenceTokens[j].trim().startsWith("[PSEU]") || sentenceTokens[j].trim().startsWith("[POST]") || sentenceTokens[j].trim().startsWith("[PRE_NEG]") || sentenceTokens[j].trim().startsWith("[PREN]") || sentenceTokens[j].trim().startsWith("[POSP]")) { break; } if (sentenceTokens[j].trim().startsWith("[PHRASE]")) { sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]"); } } } } sentence = sb3.toString(); pSpace = Pattern.compile("[\\s+]"); sentenceTokens = pSpace.split(sentence); StringBuilder sb4 = new StringBuilder(); // Check for [POSP] for (int i = sentenceTokens.length - 1; i > 0; i--) { sb4.insert(0, sentenceTokens[i] + " "); if (sentenceTokens[i].trim().startsWith("[POSP]")) { for (int j = i - 1; j > 0; j--) { if (sentenceTokens[j].trim().startsWith("[CONJ]") || sentenceTokens[j].trim().startsWith("[PSEU]") || sentenceTokens[j].trim().startsWith("[PREN]") || sentenceTokens[j].trim().startsWith("[PRE_NEG]") || sentenceTokens[j].trim().startsWith("[PREP]") || sentenceTokens[j].trim().startsWith("[POST]")) { break; } if (sentenceTokens[j].trim().startsWith("[PHRASE]")) { sentenceTokens[j] = sentenceTokens[j].trim().replaceAll("\\[PHRASE\\]", "[POSSIBLE]"); } } } } sentence = sb4.toString(); } // Remove the filler character we used. sentence = sentence.replaceAll(filler, " "); // Remove the extra periods at the beginning // and end of the sentence. sentence = sentence.substring(0, sentence.trim().lastIndexOf('.')); sentence = sentence.replaceFirst(".", ""); // Get the scope of the negation for PREN and PREP if (sentence.contains("[PRE_NEG]") || sentence.contains("[PREN]") || sentence.contains("[PREP]")) { int startOffset = sentence.indexOf("[PREN]"); if (startOffset == -1) { startOffset = sentence.indexOf("[PRE_NEG]"); } if (startOffset == -1) { startOffset = sentence.indexOf("[PREP]"); } int endOffset = sentence.indexOf("[CONJ]"); if (endOffset == -1) { endOffset = sentence.indexOf("[PSEU]"); } if (endOffset == -1) { endOffset = sentence.indexOf("[POST]"); } if (endOffset == -1) { endOffset = sentence.indexOf("[POSP]"); } if (endOffset == -1 || endOffset < startOffset) { endOffset = sentence.length() - 1; } sScope = sentence.substring(startOffset, endOffset + 1); } // Get the scope of the negation for POST and POSP if (sentence.contains("[POST]") || sentence.contains("[POSP]")) { int endOffset = sentence.lastIndexOf("[POST]"); if (endOffset == -1) { endOffset = sentence.lastIndexOf("[POSP]"); } int startOffset = sentence.lastIndexOf("[CONJ]"); if (startOffset == -1) { startOffset = sentence.lastIndexOf("[PSEU]"); } if (startOffset == -1) { startOffset = sentence.lastIndexOf("[PREN]"); } if (startOffset == -1) { startOffset = sentence.lastIndexOf("[PRE_NEG]"); } if (startOffset == -1) { startOffset = sentence.lastIndexOf("[PREP]"); } if (startOffset == -1) { startOffset = 0; } sScope = sentence.substring(startOffset, endOffset); } // Classify to: negated/possible/affirmed if (sentence.contains("[NEGATED]")) { sentence = sentence + "\t" + "negated" + "\t" + sScope; } else if (sentence.contains("[POSSIBLE]")) { sentence = sentence + "\t" + "possible" + "\t" + sScope; } else { sentence = sentence + "\t" + "affirmed" + "\t" + sScope; } sToReturn = sentence; return sToReturn; }
From source file:org.janusgraph.diskstorage.es.rest.RestElasticSearchClient.java
@Override public void bulkRequest(List<ElasticSearchMutation> requests, String ingestPipeline) throws IOException { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (final ElasticSearchMutation request : requests) { final Map actionData = ImmutableMap.of(request.getRequestType().name().toLowerCase(), ImmutableMap .of("_index", request.getIndex(), "_type", request.getType(), "_id", request.getId())); outputStream.write(mapWriter.writeValueAsBytes(actionData)); outputStream.write("\n".getBytes(UTF8_CHARSET)); if (request.getSource() != null) { outputStream.write(mapWriter.writeValueAsBytes(request.getSource())); outputStream.write("\n".getBytes(UTF8_CHARSET)); }//from ww w .j av a 2s . c o m } final StringBuilder builder = new StringBuilder(); if (ingestPipeline != null) { APPEND_OP.apply(builder).append("pipeline=").append(ingestPipeline); } if (bulkRefresh != null && !bulkRefresh.toLowerCase().equals("false")) { APPEND_OP.apply(builder).append("refresh=").append(bulkRefresh); } builder.insert(0, REQUEST_SEPARATOR + "_bulk"); final Response response = performRequest(REQUEST_TYPE_POST, builder.toString(), outputStream.toByteArray()); try (final InputStream inputStream = response.getEntity().getContent()) { final RestBulkResponse bulkResponse = mapper.readValue(inputStream, RestBulkResponse.class); final List<Object> errors = bulkResponse.getItems().stream().flatMap(item -> item.values().stream()) .filter(item -> item.getError() != null && item.getStatus() != 404) .map(RestBulkItemResponse::getError).collect(Collectors.toList()); if (!errors.isEmpty()) { errors.forEach(error -> log.error("Failed to execute ES query: {}", error)); throw new IOException("Failure(s) in Elasticsearch bulk request: " + errors); } } }
From source file:hudson.tasks.test.TestObject.java
@Override public final String getId() { if (id == null) { StringBuilder buf = new StringBuilder(); buf.append(getSafeName());/*from w ww . j a v a 2 s .c o m*/ TestObject parent = getParent(); if (parent != null) { String parentId = parent.getId(); if ((parentId != null) && (parentId.length() > 0)) { buf.insert(0, '/'); buf.insert(0, parent.getId()); } } id = buf.toString(); } return id; }
From source file:com.dabay6.android.apps.carlog.ui.vehicle.fragments.VehicleEditFragment.java
/** * */// w w w .ja v a2 s.com @Override protected ContentValues buildContentValues() { final ContentResolver resolver = getActivity().getContentResolver(); final StringBuilder vehicleName = new StringBuilder(); vehicleName.append(ViewUtils.getText(name)); if (vehicle == null) { vehicle = new VehicleDTO(); } if (TextUtils.isEmpty(vehicleName)) { if (!ViewUtils.isEmpty(year)) { vehicleName.insert(0, " "); vehicleName.insert(0, ViewUtils.getText(year)); } vehicleName.append(ViewUtils.getText(make)).append(" ").append(ViewUtils.getText(model)); } vehicle.setIsActive(true); vehicle.setLicensePlate(ViewUtils.getText(licensePlate)); vehicle.setName(vehicleName.toString()); vehicle.setVin(ViewUtils.getText(vin)); if (modelAdapter.getMakeId() == null) { final MakeDTO makeDTO = new MakeDTO(); makeDTO.setMakeName(ViewUtils.getText(make)); modelAdapter.setMakeId( ContentUris.parseId(resolver.insert(Make.CONTENT_URI, MakeDTO.buildContentValues(makeDTO)))); } vehicle.setMakeId(modelAdapter.getMakeId()); if (modelId == null) { final ModelDTO modelDTO = new ModelDTO(); modelDTO.setMakeId(modelAdapter.getMakeId()); modelDTO.setModelName(ViewUtils.getText(model)); modelId = ContentUris .parseId(resolver.insert(Model.CONTENT_URI, ModelDTO.buildContentValues(modelDTO))); } vehicle.setModelId(modelId); if (!ViewUtils.isEmpty(year)) { vehicle.setYear(Integer.valueOf(ViewUtils.getText(year))); } return VehicleDTO.buildContentValues(vehicle); }
From source file:org.sakuli.aop.RhinoAspect.java
/** * Method to do all Logs for the action classes annotated with {@link org.sakuli.actions.logging.LogToResult}. A log * entry will created at the sakuli log files and at the sahi HTML {@link net.sf.sahi.report.Report}. * * @param joinPoint {@link JoinPoint} object of the calling aspect * @param logToResult {@link LogToResult} Annotation *//* w ww . ja v a 2 s.c o m*/ protected void addActionLog(JoinPoint joinPoint, LogToResult logToResult) { Logger logger = getLogger(joinPoint); if (logToResult != null) { StringBuilder message = createLoggingString(joinPoint, logToResult); //log the action to log file and print switch (logToResult.level()) { case ERROR: logger.error(message.toString()); break; case INFO: logger.info(message.toString()); break; case DEBUG: logger.debug(message.toString()); break; case WARNING: logger.warn(message.toString()); message.insert(0, "WARNING: "); break; } if (logToResult.level().getResultType() != null) { Report sahiReport = BeanLoader.loadBaseActionLoader().getSahiReport(); if (sahiReport != null) { sahiReport.addResult(message.toString(), logToResult.level().getResultType(), joinPoint.getSignature().getDeclaringTypeName(), ""); } } } }
From source file:org.syncope.core.persistence.dao.impl.UserSearchDAOImpl.java
private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page, final int itemsPerPage) { List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>()); // 1. get the query string from the search condition final StringBuilder queryString = getQuery(nodeCond, parameters); // 2. take into account administrative roles if (queryString.charAt(0) == '(') { queryString.insert(0, "SELECT u.user_id FROM "); queryString.append(" u WHERE user_id NOT IN ("); } else {//w w w .j a va 2 s . c om queryString.insert(0, "SELECT u.user_id FROM ("); queryString.append(") u WHERE user_id NOT IN ("); } queryString.append(getAdminRolesFilter(adminRoles)).append(")"); // 3. prepare the search query final Query query = entityManager.createNativeQuery(queryString.toString()); // page starts from 1, while setFirtResult() starts from 0 query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1)); if (itemsPerPage >= 0) { query.setMaxResults(itemsPerPage); } // 4. populate the search query with parameter values fillWithParameters(query, parameters); LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters); // 5. Prepare the result (avoiding duplicates - set) final Set<Number> userIds = new HashSet<Number>(); final List resultList = query.getResultList(); //fix for HHH-5902 - bug hibernate if (resultList != null) { for (Object userId : resultList) { if (userId instanceof Object[]) { userIds.add((Number) ((Object[]) userId)[0]); } else { userIds.add((Number) userId); } } } final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size()); SyncopeUser user; for (Object userId : userIds) { user = userDAO.find(((Number) userId).longValue()); if (user == null) { LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId); } else { result.add(user); } } return result; }
From source file:com.scaleunlimited.cascading.FlowMonitor.java
private void replace(StringBuilder template, String key, String value) { int offset = template.indexOf(key); if (offset == -1) { throw new RuntimeException("Key doesn't exist in template: " + key); }//from w w w . ja v a2s . c o m template.delete(offset, offset + key.length()); template.insert(offset, value); }
From source file:mergedoc.core.JavaBuffer.java
/** * Javadoc ??????// w ww . jav a 2s . c om * <p> * Javadoc ???? Java nextComment ? * ??????????? * ??? classBlock ????? * <p> * ????? Javadoc ??????? * ??? Javadoc ???????Javadoc * ???? Javadoc API ??? * <pre> * JDK1.4 javax.swing.JEditorPane ? ?? * JEditorPaneAccessibleHypertextSupport.HTMLLink ?? * </pre> * <p> * JDK1.4 java.beans.beancontext.BeanContextServicesSupport#BCSSChild ? * /* ????????Javadoc ????? * Javadoc API ??????????????? * ?????? * * @param src Java * @return ?? */ private String setupDummyComment(String src) { // ? Javadoc ??????? // ?????????????? // ????????? // ? //Matcher mat = Pattern.compile("\\{[^@]").matcher(src); //int pos = 0; //if (mat.find()) pos = mat.start(); //String head = src.substring(0, pos); //String body = src.substring(pos); //body = body.replaceAll( // "([^/\\s]( *?\n)+)((\\s*)[\\w\\s]*\\s(class|interface)\\s)", // "$1$4/\\*\\*" + DUMMY_COMMENT + "\\*/\n$3"); //return head + body; //---------------------------------------------------------------------- // ????? Profiler ????? // ??????????? 1 ???? // ??? 6 ?? // ???????????? // ? Javadoc ?????? // ?? // // ????? // JDK1.4 java.net.Authenticator ?? // ????? // JDK1.4 javax.swing.plaf.basic.BasicTableUI ?? //---------------------------------------------------------------------- char[] c = src.toCharArray(); int last = c.length - 1; List<Integer> dummyInsertPositions = new ArrayList<Integer>(); int declareMaxLength = 12; for (int i = declareMaxLength; i <= last; i++) { if (c[i - 1] == '/' && c[i] == '*') { // ??? for (i++; i <= last; i++) { if (c[i - 1] == '*' && c[i] == '/') { break; } } } else if (c[i - 1] == '/' && c[i] == '/') { // ??? for (i++; i <= last; i++) { if (c[i] == '\n') { i++; break; } } } else if (c[i - 1] != '\'' && c[i] == '"') { // ?????? for (i++; i <= last; i++) { if (c[i] == '"') { if (c[i - 1] != '\\' || (c[i - 1] == '\\' && c[i - 2] == '\\')) { break; } } } } else if (c[i - 1] != '"' && c[i] == '\'') { // ?????? for (i++; i <= last; i++) { if (c[i] == '\'') { if (c[i - 1] != '\\' || (c[i - 1] == '\\' && c[i - 2] == '\\')) { break; } } } } if (i >= last) { break; } // ??? // class|interface|@interface|enum int declaPos = -1; if (c[i] == ' ' || c[i] == '\n' || c[i] == '<') { if (c[i - 5] == 'c' && c[i - 4] == 'l' && c[i - 3] == 'a' && c[i - 2] == 's' && c[i - 1] == 's') { // class ?? if (c[i - 6] == ' ' || c[i - 6] == '\n') { declaPos = i - 7; } } else if (c[i - 9] == 'i' && c[i - 8] == 'n' && c[i - 7] == 't' && c[i - 6] == 'e' && c[i - 5] == 'r' && c[i - 4] == 'f' && c[i - 3] == 'a' && c[i - 2] == 'c' && c[i - 1] == 'e') { // interface ?? if (c[i - 10] == ' ' || c[i - 10] == '\n') { declaPos = i - 11; } else if (c[i - 10] == '@') { // @interface ?? if (c[i - 11] == ' ' || c[i - 11] == '\n') { declaPos = i - 12; } } } else if (c[i - 4] == 'e' && c[i - 3] == 'n' && c[i - 2] == 'u' && c[i - 1] == 'm') { // enum ?? if (c[i - 5] == ' ' || c[i - 5] == '\n') { declaPos = i - 6; } } } // ? Javadoc ?????? for (int j = declaPos; j > 0; j--) { if (c[j - 1] == '*' && c[j] == '/') { break; } if (c[j] == ';' || c[j] == '}' || c[j] == '{') { for (int k = j - 1; k > 0; k--) { if (c[k - 1] == '/' && c[k] == '/') { break; } if (c[k] == '\n') { for (int l = j + 1; l < i; l++) { if (c[l] == '\n') { dummyInsertPositions.add(l + 1); k = -1; j = -1; break; } } } } } } } // ??? Javadoc ? StringBuilder sb = new StringBuilder(src); for (int i = dummyInsertPositions.size() - 1; i >= 0; i--) { int pos = dummyInsertPositions.get(i); sb.insert(pos, DUMMY_COMMENT); } return sb.toString(); }
From source file:Main.java
/** * Builds an XPointer that refers to the given node. If a shorthand pointer * (using a schema-determined identifier) cannot be constructed, then a * scheme-based pointer is derived that indicates the absolute location path * of a node in a DOM document. The location is specified as a scheme-based * XPointer having two parts:// w w w. ja v a 2 s .c o m * <ul> * <li>an xmlns() part that declares a namespace binding context;</li> * <li>an xpointer() part that includes an XPath expression using the * abbreviated '//' syntax for selecting a descendant node.</li> * </ul> * * @param node * A node in a DOM document. * @return A String containing either a shorthand or a scheme-based pointer * that refers to the node. * * @see <a href="http://www.w3.org/TR/xptr-framework/"target="_blank"> * XPointer Framework</a> * @see <a href="http://www.w3.org/TR/xptr-xmlns/" target="_blank">XPointer * xmlns() Scheme</a> * @see <a href="http://www.w3.org/TR/xptr-xpointer/" * target="_blank">XPointer xpointer() Scheme</a> */ public static String buildXPointer(Node node) { if (null == node) { return ""; } StringBuilder xpointer = new StringBuilder(); if (null != node.getAttributes() && null != node.getAttributes().getNamedItem("id")) { String id = node.getAttributes().getNamedItem("id").getNodeValue(); xpointer.append(node.getLocalName()).append("[@id='").append(id).append("']"); return xpointer.toString(); } String nsURI = node.getNamespaceURI(); String nsPrefix = node.getPrefix(); if (null == nsPrefix) nsPrefix = "tns"; // WARNING: Escaping rules are currently ignored. xpointer.append("xmlns(").append(nsPrefix).append("=").append(nsURI).append(")"); xpointer.append("xpointer(("); switch (node.getNodeType()) { case Node.ELEMENT_NODE: // Find the element in the list of all similarly named descendants // of the document root. NodeList elementsByName = node.getOwnerDocument().getElementsByTagNameNS(nsURI, node.getLocalName()); for (int i = 0; i < elementsByName.getLength(); i++) { if (elementsByName.item(i).isSameNode(node)) { xpointer.append("//"); xpointer.append(nsPrefix).append(':').append(node.getLocalName()).append(")[").append(i + 1) .append("])"); break; } } break; case Node.DOCUMENT_NODE: xpointer.append("/"); break; case Node.ATTRIBUTE_NODE: Attr attrNode = (Attr) node; xpointer = new StringBuilder(buildXPointer(attrNode.getOwnerElement())); xpointer.insert(xpointer.lastIndexOf(")"), "/@" + attrNode.getName()); break; default: xpointer.setLength(0); break; } return xpointer.toString(); }
From source file:com.evolveum.polygon.scim.ServiceAccessManager.java
/** * Used for login to the service. The data needed for this operation is * provided by the configuration./* w ww . j a v a 2 s. co m*/ * * @param configuration * The instance of "ScimConnectorConfiguration" which holds all * the provided configuration data. * * @return a Map object carrying meta information about the login session. */ public void logIntoService(ScimConnectorConfiguration configuration) { HttpPost loginInstance = new HttpPost(); Header authHeader = null; String loginAccessToken = null; String loginInstanceUrl = null; JSONObject jsonObject = null; String proxyUrl = configuration.getProxyUrl(); LOGGER.ok("proxyUrl: {0}", proxyUrl); // LOGGER.ok("Configuration: {0}", configuration); if (!"token".equalsIgnoreCase(configuration.getAuthentication())) { HttpClient httpClient; if (proxyUrl != null && !proxyUrl.isEmpty()) { HttpHost proxy = new HttpHost(proxyUrl, configuration.getProxyPortNumber()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).build(); LOGGER.ok("Proxy enabled: {0}:{1}", proxyUrl, configuration.getProxyPortNumber()); } else { httpClient = HttpClientBuilder.create().build(); } String loginURL = new StringBuilder(configuration.getLoginURL()).append(configuration.getService()) .toString(); GuardedString guardedPassword = configuration.getPassword(); GuardedStringAccessor accessor = new GuardedStringAccessor(); guardedPassword.access(accessor); String contentUri = new StringBuilder("&client_id=").append(configuration.getClientID()) .append("&client_secret=").append(configuration.getClientSecret()).append("&username=") .append(configuration.getUserName()).append("&password=").append(accessor.getClearString()) .toString(); loginInstance = new HttpPost(loginURL); CloseableHttpResponse response = null; StringEntity bodyContent; String getResult = null; Integer statusCode = null; try { bodyContent = new StringEntity(contentUri); bodyContent.setContentType("application/x-www-form-urlencoded"); loginInstance.setEntity(bodyContent); response = (CloseableHttpResponse) httpClient.execute(loginInstance); getResult = EntityUtils.toString(response.getEntity()); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { LOGGER.info("Login Successful"); } else { String[] loginUrlParts; String providerName = ""; if (configuration.getLoginURL() != null && !configuration.getLoginURL().isEmpty()) { loginUrlParts = configuration.getLoginURL().split("\\."); // e.g. // https://login.salesforce.com } else { loginUrlParts = configuration.getBaseUrl().split("\\."); // e.g. } // https://login.salesforce.com if (loginUrlParts.length >= 2) { providerName = loginUrlParts[1]; } if (!providerName.isEmpty()) { StrategyFetcher fetcher = new StrategyFetcher(); HandlingStrategy strategy = fetcher.fetchStrategy(providerName); strategy.handleInvalidStatus(" while loging into service", getResult, "loging into service", statusCode); } } jsonObject = (JSONObject) new JSONTokener(getResult).nextValue(); loginAccessToken = jsonObject.getString("access_token"); loginInstanceUrl = jsonObject.getString("instance_url"); } catch (UnsupportedEncodingException e) { LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of login into the service", e.getLocalizedMessage()); LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of login into the service", e); throw new ConnectorException( "Unsupported encoding. Occurrence in the process of login into the service", e); } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}", e); throw new ConnectionFailedException( "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification", e); } catch (IOException ioException) { StringBuilder errorBuilder = new StringBuilder( "An error occurred while processing the query http response to the login request. "); if ((ioException instanceof SocketTimeoutException || ioException instanceof NoRouteToHostException)) { errorBuilder.insert(0, "The connection timed out. "); throw new OperationTimeoutException(errorBuilder.toString(), ioException); } else { LOGGER.error( "An error occurred while processing the query http response to the login request : {0}", ioException.getLocalizedMessage()); LOGGER.info( "An error occurred while processing the query http response to the login request : {0}", ioException); throw new ConnectorIOException(errorBuilder.toString(), ioException); } } catch (JSONException jsonException) { LOGGER.error( "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}", jsonException.getLocalizedMessage()); LOGGER.info( "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}", jsonException); throw new ConnectorException("An exception has occurred while setting the \"jsonObject\".", jsonException); } finally { try { response.close(); } catch (IOException e) { if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { throw new OperationTimeoutException( "The connection timed out while closing the http connection. Occurrence in the process of logging into the service", e); } else { LOGGER.error( "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service: {0}", e.getLocalizedMessage()); throw new ConnectorIOException( "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service", e); } } } authHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken); } else { loginInstanceUrl = configuration.getBaseUrl(); GuardedString guardedToken = configuration.getToken(); GuardedStringAccessor accessor = new GuardedStringAccessor(); guardedToken.access(accessor); loginAccessToken = accessor.getClearString(); authHeader = new BasicHeader("Authorization", "Bearer " + loginAccessToken); } String scimBaseUri = new StringBuilder(loginInstanceUrl).append(configuration.getEndpoint()) .append(configuration.getVersion()).toString(); this.baseUri = scimBaseUri; this.aHeader = authHeader; if (jsonObject != null) { this.loginJson = jsonObject; } }