List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.chiba.xml.xforms.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *///from w ww .j a va2 s . co m public boolean validateSchema(Model model, Node instance) throws XFormsException { boolean valid = true; String message; if (LOGGER.isDebugEnabled()) LOGGER.debug("SchemaValidator.validateSchema: validating instance"); //needed if we want to load schemas from Model + set it as "schemaLocation" attribute String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema"); if (schemas != null && !schemas.equals("")) { // valid=false; //add schemas to element //shouldn't it be done on a copy of the doc ? Element el = null; if (instance.getNodeType() == Node.ELEMENT_NODE) el = (Element) instance; else if (instance.getNodeType() == Node.DOCUMENT_NODE) el = ((Document) instance).getDocumentElement(); else { if (LOGGER.isDebugEnabled()) LOGGER.debug("instance node type is: " + instance.getNodeType()); } String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS); //test if with targetNamespace or not //if more than one schema : namespaces are mandatory ! (optional only for 1) StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false); String schemaLocations = null; String noNamespaceSchemaLocation = null; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); //check that it is an URL URI uri = null; try { uri = new java.net.URI(token); } catch (java.net.URISyntaxException ex) { if (LOGGER.isDebugEnabled()) LOGGER.debug(token + " is not an URI"); } if (uri != null) { String ns; try { ns = this.getSchemaNamespace(uri); if (ns != null && !ns.equals("")) { if (schemaLocations == null) schemaLocations = ns + " " + token; else schemaLocations = schemaLocations + " " + ns + " " + token; ///add the namespace declaration if it is not on the instance? //TODO: how to know with which prefix ? String nsPrefix = NamespaceResolver.getPrefix(el, ns); if (nsPrefix == null) { //namespace not declared ! LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token + " is not declared in instance: declaring it as default..."); el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns); } } else if (noNamespaceSchemaLocation == null) noNamespaceSchemaLocation = token; else { //we have more than one schema without namespace LOGGER.warn("SchemaValidator: There is more than one schema without namespace !"); } } catch (Exception ex) { LOGGER.warn( "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(), ex); //in case there was an exception: do nothing, do not set the schema } } } //write schemaLocations found if (schemaLocations != null && !schemaLocations.equals("")) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation", noNamespaceSchemaLocation); //save and parse the doc ValidationErrorHandler handler = null; File f; try { //save document f = File.createTempFile("instance", ".xml"); f.deleteOnExit(); TransformerFactory trFact = TransformerFactory.newInstance(); Transformer trans = trFact.newTransformer(); DOMSource source = new DOMSource(el); StreamResult result = new StreamResult(f); trans.transform(source, result); if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath()); //parse it with error handler to validate it handler = new ValidationErrorHandler(); SAXParserFactory parserFact = SAXParserFactory.newInstance(); parserFact.setValidating(true); parserFact.setNamespaceAware(true); SAXParser parser = parserFact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //validation activated reader.setFeature("http://xml.org/sax/features/validation", true); //schema validation activated reader.setFeature("http://apache.org/xml/features/validation/schema", true); //used only to validate the schema, not the instance //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); //validate only if there is a grammar reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); parser.parse(f, handler); } catch (Exception ex) { LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex); //throw new XFormsException("XMLSchema validation failed. "+message); } //if no exception if (handler != null && handler.isValid()) valid = true; else { message = handler.getMessage(); //TODO: find a way to get the error message displayed throw new XFormsException("XMLSchema validation failed. " + message); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: result=" + valid); } return valid; }
From source file:org.openremote.controller.protocol.telnet.TelnetCommand.java
public void send(boolean readResponse) { TelnetClient tc = null;// w ww . j av a 2s .c om if (readResponse) { setResponse(""); } try { tc = new TelnetClient(); tc.connect(getIp(), Integer.parseInt(getPort())); StringTokenizer st = new StringTokenizer(getCommand(), "|"); int count = 0; if (getCommand().startsWith("|")) { count++; } String waitFor = ""; while (st.hasMoreElements()) { String cmd = (String) st.nextElement(); if (count % 2 == 0) { waitFor = cmd; if (!"null".equals(cmd)) { waitForString(cmd, tc); } } else { sendString(cmd, tc); if (readResponse) { readString(waitFor, tc); } } count++; } } catch (Exception e) { logger.error("could not perform telnetEvent", e); } finally { if (tc != null) { try { tc.disconnect(); } catch (IOException e) { logger.error("could not disconnect from telnet", e); } } } }
From source file:org.openiam.idm.srvc.synch.service.IdentitySynchServiceImpl.java
private Role parseRole(String roleStr) { String roleId = null;//w ww . j a v a 2 s .c o m StringTokenizer st = new StringTokenizer(roleStr, "*"); if (st.hasMoreElements()) { roleId = st.nextToken(); } Role r = new Role(); r.setId(roleId); return r; }
From source file:org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback.java
/** * Set claims from a Users claims Map object to a JWTClaimsSet object * @param claims Users claims//from ww w . j a v a 2 s .c om * @param jwtClaimsSet JWTClaimsSet object */ private void setClaimsToJwtClaimSet(Map<String, Object> claims, JWTClaimsSet jwtClaimsSet) { JSONArray values; Object claimSeparator = claims.get(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null) { String claimSeparatorString = (String) claimSeparator; if (StringUtils.isNotBlank(claimSeparatorString)) { userAttributeSeparator = (String) claimSeparator; } claims.remove(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR); } for (Map.Entry<String, Object> entry : claims.entrySet()) { String value = entry.getValue().toString(); values = new JSONArray(); if (userAttributeSeparator != null && value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String attributeValue = st.nextElement().toString(); if (StringUtils.isNotBlank(attributeValue)) { values.add(attributeValue); } } jwtClaimsSet.setClaim(entry.getKey(), values); } else { jwtClaimsSet.setClaim(entry.getKey(), value); } } }
From source file:com.amalto.core.history.accessor.record.DataRecordAccessor.java
@SuppressWarnings({ "rawtypes" }) @Override//from w w w . j ava 2s . co m public boolean exist() { if (cachedExist != null) { return cachedExist; } StringTokenizer tokenizer = new StringTokenizer(path, "/"); //$NON-NLS-1$ DataRecord current = dataRecord; while (tokenizer.hasMoreElements()) { String element = tokenizer.nextToken(); if (element.indexOf('@') == 0) { cachedExist = true; return true; } else { if (current == null) { cachedExist = false; return false; } if (element.indexOf('[') > 0) { String fieldName = StringUtils.substringBefore(element, "["); //$NON-NLS-1$ if (!current.getType().hasField(fieldName)) { cachedExist = false; return false; } FieldMetadata field = current.getType().getField(fieldName); if (!field.isMany()) { throw new IllegalStateException( "Expected a repeatable field for '" + element + "' in path '" + path //$NON-NLS-1$ //$NON-NLS-2$ + "'."); //$NON-NLS-1$ } int indexStart = element.indexOf('['); int indexEnd = element.indexOf(']'); if (indexStart < 0 || indexEnd < 0) { throw new RuntimeException( "Field name '" + element + "' did not match many field pattern in path '" //$NON-NLS-1$ //$NON-NLS-2$ + path + "'."); //$NON-NLS-1$ } int index = Integer.parseInt(element.substring(indexStart + 1, indexEnd)) - 1; List list = (List) current.get(field); if (list == null || index > list.size() - 1) { cachedExist = false; return false; } Object value = list.get(index); if (value instanceof DataRecord) { current = (DataRecord) value; } } else { if (!current.getType().hasField(element) || current.get(element) == null) { cachedExist = false; return false; } FieldMetadata field = current.getType().getField(element); if (field instanceof ContainedTypeFieldMetadata) { Object value = current.get(field); if (value instanceof DataRecord) { current = (DataRecord) value; } } } } } cachedExist = true; return true; }
From source file:com.konakart.actions.gateways.PayjunctionAction.java
public String execute() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String errorDesc = null;//w w w . j a v a 2 s. c o m String gatewayResult = null; String transactionId = null; if (log.isDebugEnabled()) { log.debug("PayJunctionAction: code = " + code); } // Create these outside of try / catch since they are needed in the case of a general // exception IpnHistoryIf ipnHistory = new IpnHistory(); ipnHistory.setModuleCode(code); KKAppEng kkAppEng = null; try { int custId; kkAppEng = this.getKKAppEng(request, response); boolean payJunctionDebugMode = log.isDebugEnabled(); // Check to see whether the user is logged in custId = this.loggedIn(request, response, kkAppEng, "Checkout"); if (custId < 0) { if (log.isDebugEnabled()) { log.debug("PayJunctionAction: NotLoggedIn"); } return KKLOGIN; } // Ensure we are using the correct protocol. Redirect if not. String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */false); if (redirForward != null) { if (log.isDebugEnabled()) { log.debug("PayJunctionAction: Redirect SSL"); } setupResponseForSSLRedirect(response, redirForward); return null; } // Get the order OrderIf order = kkAppEng.getOrderMgr().getCheckoutOrder(); validateOrder(order, code); if (log.isDebugEnabled()) { log.debug("PayJunctionAction: Order " + order.getId() + " validated"); } // Set the order id for the ipnHistory object ipnHistory.setOrderId(order.getId()); // Get the parameter list for the payment that have been set up earlier PaymentDetailsIf pd = order.getPaymentDetails(); // Now make a second parameter list containing parameters we don't save List<NameValueIf> parmList = new ArrayList<NameValueIf>(); parmList.add(new NameValue("dc_name", encode(pd.getCcOwner()))); parmList.add(new NameValue("dc_number", encode(pd.getCcNumber()))); parmList.add(new NameValue("dc_expiration_month", encode(pd.getCcExpiryMonth()))); parmList.add(new NameValue("dc_expiration_year", encode(pd.getCcExpiryYear()))); if (pd.isShowCVV()) { parmList.add(new NameValue("dc_verification_number", encode(pd.getCcCVV()))); } parmList.add(new NameValue("dc_address", encode(pd.getCcStreetAddress()))); parmList.add(new NameValue("dc_zipcode", encode(pd.getCcPostcode()))); parmList.add(new NameValue("dc_notes", encode("KonaKart OrderId = " + order.getId()))); if (log.isDebugEnabled()) { log.debug("PayJunctionAction: Post the payment details to the gateway"); } // Do the post String gatewayResp = postData(pd, parmList); gatewayResp = URLDecoder.decode(gatewayResp, "UTF-8"); if (log.isDebugEnabled()) { log.debug("Unformatted GatewayResp = \n" + gatewayResp); } if (payJunctionDebugMode) { // Write the response to a file which is handy for diagnosing problems try { String outputFilename = getLogFileDirectory(kkAppEng) + "payjunction_resp_" + order.getId() + ".txt"; File myOutFile = new File(outputFilename); if (log.isDebugEnabled()) { log.debug("Write gateway response to " + myOutFile.getAbsolutePath()); } BufferedWriter bw = new BufferedWriter(new FileWriter(myOutFile)); bw.write(gatewayResp); bw.close(); } catch (Exception e) { // dump the exception and continue e.printStackTrace(); } } StringBuffer sb = new StringBuffer(); HashMap<String, String> response_hash = new HashMap<String, String>(); StringTokenizer st1 = new StringTokenizer(gatewayResp.toString(), new Character((char) 0x1C).toString()); // process results so they are in an easy-to-access format while (st1.hasMoreTokens()) { String key = null, value = null; StringTokenizer st2 = new StringTokenizer(st1.nextToken(), "="); key = st2.nextToken(); if (st2.hasMoreElements()) { value = st2.nextToken(); } response_hash.put(key, value); if (log.isDebugEnabled()) { log.debug("Add to hash: " + key + " = " + value); } sb.append(key + " = " + value + "\n"); } gatewayResult = response_hash.get("dc_response_code"); transactionId = response_hash.get("dc_transaction_id"); errorDesc = response_hash.get("dc_response_message"); // Put the response in the ipnHistory record ipnHistory.setGatewayFullResponse(sb.toString()); ipnHistory.setGatewayTransactionId(transactionId); ipnHistory.setGatewayResult(gatewayResult); if (log.isDebugEnabled()) { log.debug("Response data:"); log.debug(sb.toString()); } // See if we need to send an email, by looking at the configuration String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS); boolean sendEmail = false; if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) { sendEmail = true; } OrderUpdateIf updateOrder = new OrderUpdate(); updateOrder.setUpdatedById(kkAppEng.getActiveCustId()); // Determine whether the request was successful or not.If successful, we update the // inventory as well as changing the state of the order if (gatewayResult != null && (gatewayResult.equals("00") || gatewayResult.equals("85"))) { String comment = ORDER_HISTORY_COMMENT_OK + transactionId; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Update the inventory kkAppEng.getOrderMgr().updateInventory(order.getId()); // Save the ipnHistory ipnHistory.setKonakartResultDescription(RESULT_APPROVED_DESC + " (" + errorDesc + ")"); ipnHistory.setKonakartResultId(RESULT_APPROVED); ipnHistory.setOrderId(order.getId()); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // If we received no exceptions, delete the basket kkAppEng.getBasketMgr().emptyBasket(); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */true); } return "Approved"; } else if (gatewayResult != null) { String comment = ORDER_HISTORY_COMMENT_KO + errorDesc; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Save the ipnHistory ipnHistory.setKonakartResultDescription( RESULT_DECLINED_DESC + " (" + gatewayResult + ") " + errorDesc); ipnHistory.setKonakartResultId(RESULT_DECLINED); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */false); } String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { errorDesc }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } else { /* * We only get to here if there was an unknown response from the gateway */ String comment = RESULT_UNKNOWN_GATEWAY_ERROR_DESC; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Save the ipnHistory ipnHistory.setKonakartResultDescription(RESULT_UNKNOWN_GATEWAY_ERROR_DESC); ipnHistory.setKonakartResultId(RESULT_UNKNOWN_GATEWAY_ERROR); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */false); } String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { "?" }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } } catch (Exception e) { try { if (kkAppEng != null) { ipnHistory.setKonakartResultDescription(RESULT_UNKNOWN_EXCEPTION_DESC + e.getMessage()); ipnHistory.setKonakartResultId(RESULT_UNKNOWN_EXCEPTION); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); ipnHistory.setGatewayResult(e.toString()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); } if (log.isWarnEnabled()) { log.warn("Exception communicating with PayJunction"); e.printStackTrace(); } } catch (KKException e1) { return super.handleException(request, e1); } return super.handleException(request, e); } }
From source file:org.jahia.services.importexport.FilesAclImportHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("file".equals(localName) && ImportExportBaseService.JAHIA_URI.equals(uri)) { String path = attributes.getValue(ImportExportBaseService.JAHIA_URI, "path"); String acl = attributes.getValue(ImportExportBaseService.JAHIA_URI, "fileacl"); InputStream content = null; try {//from ww w . j av a 2 s .co m boolean contentFound = false; if (this.filePath != null) { content = findExtractedContent(path); } else { contentFound = findContent(path); } if (path.startsWith("/shared") || path.startsWith("/users")) { path = "/sites/" + site.getSiteKey() + "/files" + path; } /* // DB-HOT-28 else if (path.startsWith("/users/")) { Matcher m = Pattern.compile("/users/([^/]+)(/.*)?").matcher(path); if (m.matches()) { path = ServicesRegistry.getInstance().getJahiaUserManagerService().getUserSplittingRule().getPathForUsername(m.group(1)); path = path + "/files" + ((m.group(2) != null) ? m.group(2) : ""); } }*/ if (session.itemExists(path)) { return; } JCRNodeWrapper f; path = JCRContentUtils.escapeNodePath(path); path = Patterns.COLON.matcher(path).replaceAll("_"); String parentPath = StringUtils.substringBeforeLast(path, "/"); try { f = session.getNode(parentPath); } catch (PathNotFoundException e) { f = ImportExportBaseService.getInstance().ensureDir(session, parentPath, site); } Calendar created = new GregorianCalendar(); String creationDate = attributes.getValue("dav:creationdate"); if (creationDate != null) { if (creationDate.endsWith("Z")) { created.setTime(DATE_FORMAT_Z.parseDateTime(creationDate).toDate()); } else { created.setTime(DATE_FORMAT.parseDateTime(creationDate).toDate()); } } Calendar lastModified = new GregorianCalendar(); String modificationDate = attributes.getValue("dav:modificationdate"); if (modificationDate != null) { if (modificationDate.endsWith("Z")) { lastModified.setTime(DATE_FORMAT_Z.parseDateTime(modificationDate).toDate()); } else { lastModified.setTime(DATE_FORMAT.parseDateTime(modificationDate).toDate()); } } String createdBy = attributes.getValue("dav:creationuser"); String lastModifiedBy = attributes.getValue("dav:modificationuser"); final String itemType = "file".equals(attributes.getValue("jahia:itemType")) || StringUtils.isNotBlank(attributes.getValue("dav:getcontenttype")) ? "file" : "folder"; final boolean binaryAvailable = content != null && !contentFound; final boolean isCorruptedFile = !binaryAvailable && "file".equals(itemType); if (isCorruptedFile) { logger.error(MessageFormat.format("Impossible to import the file {0} as its binary is missing", path)); corruptedFilesLogger.error(path); } else { checkoutNode(f); if (!binaryAvailable) { f = f.addNode(StringUtils.substringAfterLast(path, "/"), "jnt:folder", null, created, createdBy, lastModified, lastModifiedBy); } else { f = f.addNode(StringUtils.substringAfterLast(path, "/"), "jnt:file", null, created, createdBy, lastModified, lastModifiedBy); String contentType = attributes.getValue("dav:getcontenttype"); if (content != null) { if (contentType == null || contentType.length() == 0 || "application/binary".equals(contentType)) { if (logger.isDebugEnabled()) { logger.debug( "We don't have a proper content type for file content {}, let's force its detection", f.getPath()); } // We don't have a proper content type, let's force its detection contentType = null; } f.getFileContent().uploadFile(content, contentType); } else { f.getFileContent().uploadFile(zis, contentType); } } if (acl != null && acl.length() > 0) { StringTokenizer st = new StringTokenizer(acl, "|"); while (st.hasMoreElements()) { String s = st.nextToken(); int beginIndex = s.lastIndexOf(":"); String principal = s.substring(0, beginIndex); Set<String> grantedRoles = new HashSet<String>(); Set<String> removedRoles = new HashSet<String>(); String perm = s.substring(beginIndex + 1); if (perm.charAt(0) == 'r') { if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_READ_ROLES)) { grantedRoles.addAll(LegacyImportHandler.READ_ROLES); } else { grantedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_READ_ROLES); } } else { if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_READ_ROLES)) { removedRoles.addAll(LegacyImportHandler.READ_ROLES); } else { removedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_READ_ROLES); } } if (perm.charAt(1) == 'w') { if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES)) { grantedRoles.addAll(LegacyImportHandler.WRITE_ROLES); } else { grantedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES); } } else { if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES)) { removedRoles.addAll(LegacyImportHandler.WRITE_ROLES); } else { removedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES); } } if (!grantedRoles.isEmpty()) { f.grantRoles(principal, grantedRoles); } if (!removedRoles.isEmpty()) { f.denyRoles(principal, removedRoles); } } } for (int i = 0; i < attributes.getLength(); i++) { String attUri = attributes.getURI(i); String attName = attributes.getLocalName(i); if (!ImportExportBaseService.JAHIA_URI.equals(attUri) || (!"path".equals(attName) && !"fileacl".equals(attName) && !"lastModification".equals(attName))) { try { setPropertyField(f.getPrimaryNodeType(), localName, f, getMappedProperty(f.getPrimaryNodeType(), attributes.getQName(i)), attributes.getValue(i)); } catch (RepositoryException e) { logger.warn("Error importing " + localName + " " + path, e); } } } session.save(JCRObservationManager.IMPORT); } } catch (Exception e) { logger.error("error", e); } finally { IOUtils.closeQuietly(content); } } }
From source file:org.squale.squalix.tools.rsm.RSMPersistor.java
/** * @param pCSVOutputFile nom du fichier pars pour le mettre au format CSV correct * @param pCSVOutputFileAux nom du fichier auxilliaire utilis pour supprimer les doublons * @param pMarker la chaine repre/*ww w .j a v a 2 s . c o m*/ * @throws IOException en cas de problemes avec le prprocessing du fichier */ private void preProcess(String pCSVOutputFile, String pCSVOutputFileAux, String pMarker) throws IOException { // Ecrit a partir du deuxime fichier File f = new File(pCSVOutputFile); BufferedWriter bw = new BufferedWriter(new FileWriter(pCSVOutputFile)); BufferedReader br = new BufferedReader(new FileReader(pCSVOutputFileAux)); String line = ""; List results = new ArrayList(0); while (line != null) { line = br.readLine(); // Null signifie fin de fichier if (line != null) { // Si on a trouv une ligne commencant par le repre pass en paramtre, on la rcupre // Pour plus de suret on vrifie galement que la ligne contient une virgule // Traitement diffrent suivant les classes ou les fichiers, pour les classes on ne s'occupe // pas du nom du fichier, pour les mthodes oui if (pMarker.equals(CLASS_LOCATOR)) { if (isValidCSVLine(line, pMarker)) { bw.write(line + "\n"); } } else { if (isValidCSVLine(line, pMarker)) { results.add(line); } else if (isFileLine(line)) { // On est sur la ligne indiquant le fichier dans lequel se trouve tous les lments // obtenus aux lignes prcdentes // on crit les rsultats prcdents avec le nom du fichier en plus StringTokenizer st = new StringTokenizer(line, ","); String fileName = ""; int counter = 0; while (st.hasMoreElements() && counter < 2) { fileName = st.nextToken().trim(); counter++; } // on crit la ligne for (int i = 0; i < results.size(); i++) { // efface le retour la ligne String result = ((String) (results.get(i))).replaceAll("\n", ""); // efface paramtres 3 5 et function points result = result.replaceFirst(mREGEXPREMOVEPARAMS, "") .replaceAll(mREGEXPREMOVEFUNCTIONPOINT, ",$1"); // Dans ce cas il faut rajouter un " " sinon le parser ne tient pas compte de la colonne if (result.charAt(result.length() - 1) != ' ') { bw.write(result + " ," + fileName + "\n"); } else { bw.write(result + "," + fileName + "\n"); } } // reset la liste des rsultats results = new ArrayList(0); } } } } // ferme les buffers bw.close(); br.close(); }
From source file:org.pentaho.platform.engine.core.system.PentahoSystem.java
public static boolean init(final IApplicationContext pApplicationContext, final Map listenerMap) { if (debug) {/* w w w . j a va2s . c o m*/ Logger.debug(PentahoSystem.class, "PentahoSystem init called"); //$NON-NLS-1$ } if (PentahoSystem.initializedStatus == PentahoSystem.SYSTEM_INITIALIZED_OK) { // TODO: Removing the catching of this IllegalStateException. It's being trapped here now as too many existing // tests call init more than once without an intervening shutdown(). try { throw new IllegalStateException("'Init' method was run twice without 'shutdown'"); } catch (IllegalStateException e) { Logger.error(PentahoSystem.class, "PentahoSystem was already initialized when init() called again without a preceding shutdown(). " + "This is likely in error", e); } } PentahoSystem.initializedStatus = PentahoSystem.SYSTEM_INITIALIZED_OK; // PDI-3438 Scheduled job fails to open a transformation // Kettle jobs spawn threads which may require authentication to load transformations from // the kettle repository, by using the INHERITABLETHREADLOCAL strategy, spawned threads will // enjoy the same SecurityContext as their parent! SecurityContextHolder.setStrategyName(securityContextHolderStrategy); PentahoSystem.globalAttributes = Collections.synchronizedMap(new HashMap()); PentahoSystem.globalParameters = new SimpleParameterProvider(PentahoSystem.globalAttributes); PentahoSystem.applicationContext = pApplicationContext; if (debug) { Logger.debug(PentahoSystem.class, "Setting property path"); //$NON-NLS-1$ } System.setProperty("pentaho.solutionpath", "solution:"); //$NON-NLS-1$ if (LocaleHelper.getLocale() == null) { LocaleHelper.setLocale(Locale.getDefault()); } if (PentahoSystem.systemSettingsService != null) { if (debug) { Logger.debug(PentahoSystem.class, "Reading ACL list from pentaho.xml"); //$NON-NLS-1$ } // Set Up ACL File Extensions by reading pentaho.xml for acl-files // // Read the files that are permitted to have ACLs on them from // the pentaho.xml. // String aclFiles = PentahoSystem.getSystemSetting("acl-files", "xaction,url"); //$NON-NLS-1$ //$NON-NLS-2$ StringTokenizer st = new StringTokenizer(aclFiles, ","); //$NON-NLS-1$ String extn; while (st.hasMoreElements()) { extn = st.nextToken(); if (!extn.startsWith(".")) { //$NON-NLS-1$ extn = "." + extn; //$NON-NLS-1$ } PentahoSystem.ACLFileExtensionList.add(extn); } } if (debug) { Logger.debug(PentahoSystem.class, "Initialize XML Factories"); //$NON-NLS-1$ } PentahoSystem.initXMLFactories(); if (debug) { Logger.debug(PentahoSystem.class, "Set Logging Level from pentaho.xml setting"); //$NON-NLS-1$ } PentahoSystem.loggingLevel = ILogger.ERROR; if (PentahoSystem.systemSettingsService != null) { PentahoSystem.loggingLevel = Logger .getLogLevel(PentahoSystem.systemSettingsService.getSystemSetting("log-level", "ERROR")); //$NON-NLS-1$//$NON-NLS-2$ } Logger.setLogLevel(PentahoSystem.loggingLevel); // to guarantee hostnames in SSL mode are not being spoofed if (debug) { Logger.debug(PentahoSystem.class, "Register host name verifier"); //$NON-NLS-1$ } PentahoSystem.registerHostnameVerifier(); assert null != aggObjectFactory : "aggObjectFactory must be non-null"; //$NON-NLS-1$ try { if (debug) { Logger.debug(PentahoSystem.class, "Validating object factory"); //$NON-NLS-1$ } PentahoSystem.validateObjectFactory(); } catch (PentahoSystemException e1) { throw new RuntimeException(e1); // this is fatal } // store a list of the system listeners try { if (debug) { Logger.debug(PentahoSystem.class, "Start System Listeners"); //$NON-NLS-1$ } PentahoSystem.notifySystemListenersOfStartup(); } catch (PentahoSystemException e) { String msg = e.getLocalizedMessage(); Logger.error(PentahoSystem.class.getName(), msg, e); PentahoSystem.initializedStatus |= PentahoSystem.SYSTEM_LISTENERS_FAILED; PentahoSystem.addInitializationFailureMessage(PentahoSystem.SYSTEM_LISTENERS_FAILED, msg); return false; } // once everything else is initialized, start global actions if (debug) { Logger.debug(PentahoSystem.class, "Global startup"); //$NON-NLS-1$ } PentahoSystem.globalStartup(); if (debug) { Logger.debug(PentahoSystem.class, "PentahoSystem Init Complete"); //$NON-NLS-1$ } return true; }
From source file:com.amalto.core.history.accessor.record.DataRecordAccessor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//w w w . j a va 2 s .co m public void create() { try { StringTokenizer tokenizer = new StringTokenizer(path, "/"); //$NON-NLS-1$ DataRecord current = dataRecord; while (tokenizer.hasMoreElements()) { String element = tokenizer.nextToken(); if (element.indexOf('@') < 0) { if (current == null) { throw new IllegalStateException(); // TODO Message } if (element.indexOf('[') > 0) { FieldMetadata field = current.getType().getField(StringUtils.substringBefore(element, "[")); //$NON-NLS-1$ if (!field.isMany()) { throw new IllegalStateException( "Expected a repeatable field for '" + element + "' in path '" + path //$NON-NLS-1$ //$NON-NLS-2$ + "'."); //$NON-NLS-1$ } int indexStart = element.indexOf('['); int indexEnd = element.indexOf(']'); if (indexStart < 0 || indexEnd < 0) { throw new RuntimeException( "Field name '" + element + "' did not match many field pattern in path '" //$NON-NLS-1$ //$NON-NLS-2$ + path + "'."); //$NON-NLS-1$ } int index = Integer.parseInt(element.substring(indexStart + 1, indexEnd)) - 1; List list = (List) current.get(field); boolean newList = list == null; if (newList) { list = new LinkedList(); } while (index >= list.size()) { if (field instanceof ContainedTypeFieldMetadata) { DataRecord record = new DataRecord((ComplexTypeMetadata) field.getType(), UnsupportedDataRecordMetadata.INSTANCE); list.add(record); } else if (field instanceof ReferenceFieldMetadata) { DataRecord record = new DataRecord( ((ReferenceFieldMetadata) field).getReferencedType(), UnsupportedDataRecordMetadata.INSTANCE); list.add(record); } else { list.add(null); } } if (newList) { current.set(field, list); } Object value = list.get(index); if (value instanceof DataRecord) { current = (DataRecord) value; } } else { FieldMetadata field = current.getType().getField(element); if (field instanceof ContainedTypeFieldMetadata) { Object value = current.get(field); if (value == null) { DataRecord record = new DataRecord( ((ContainedTypeFieldMetadata) field).getContainedType(), UnsupportedDataRecordMetadata.INSTANCE); current.set(field, record); current = record; } else { current = (DataRecord) value; } } } } } } finally { cachedExist = true; } }