List of usage examples for java.util Properties put
@Override public synchronized Object put(Object key, Object value)
From source file:com.openkm.util.impexp.RepositoryImporter.java
/** * Import mail.// w w w . j a va 2 s . c om */ private static ImpExpStats importMail(String token, String fldPath, String fileName, File fDoc, boolean metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { FileInputStream fisContent = new FileInputStream(fDoc); MetadataAdapter ma = MetadataAdapter.getInstance(token); MailModule mm = ModuleManager.getMailModule(); Properties props = System.getProperties(); props.put("mail.host", "smtp.dummydomain.com"); props.put("mail.transport.protocol", "smtp"); ImpExpStats stats = new ImpExpStats(); int size = fisContent.available(); Mail mail = new Mail(); Gson gson = new Gson(); boolean api = false; try { // Metadata if (metadata) { // Read serialized document metadata File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT); log.info("Document Metadata File: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); MailMetadata mmd = gson.fromJson(fr, MailMetadata.class); mail.setPath(fldPath + "/" + fileName); mmd.setPath(mail.getPath()); IOUtils.closeQuietly(fr); log.info("Mail Metadata: {}", mmd); // Apply metadata ma.importWithMetadata(mmd); // Add attachments if (fileName.endsWith(".eml")) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else if (fileName.endsWith(".msg")) { Message msg = new MsgParser().parseMsg(fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else { throw new MessagingException("Unknown mail format"); } FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath()); log.info("Created document '{}'", mail.getPath()); } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { if (fileName.endsWith(".eml")) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject())); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else if (fileName.endsWith(".msg")) { Message msg = new MsgParser().parseMsg(fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject())); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else { throw new MessagingException("Unknown mail format"); } FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath()); log.info("Created mail ''{}''", mail.getPath()); } if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + size); stats.setMails(stats.getMails() + 1); } catch (UnsupportedMimeTypeException e) { log.warn("UnsupportedMimeTypeException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath()); } catch (FileSizeExceededException e) { log.warn("FileSizeExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath()); } catch (UserQuotaExceededException e) { log.warn("UserQuotaExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath()); } catch (VirusDetectedException e) { log.warn("VirusWarningException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath()); } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath()); } catch (MessagingException e) { log.warn("MessagingException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Messaging")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath()); } catch (Exception e) { log.warn("Exception: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "General")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "Exception ''{0}''", mail.getPath()); } finally { IOUtils.closeQuietly(fisContent); } return stats; }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * Tests if a given SMTP configuration is valid. It will validate addresses and the port. Then it will test * connectivity of the smtp address. Lastly, it will AUTH to smtp server and ensure the information is good. * * @param address the SMTP address/* w ww.ja va2s. com*/ * @param port the SMTP port * @param email the email address * @param password the email address password * @param notify if popup dialogs will appear carrying the servers unsuccessful response message * * @return if the AUTH was successful */ public static boolean isValidSMTPConfiguration(String address, int port, String email, byte[] password, boolean notify) { if (!isValidAddress(address) || port <= 0 || !isValidEmail(email) || password.length == 0) return false; try { Properties smtpProperties = new Properties(); smtpProperties.put("mail.smtp.starttls.enable", "true"); smtpProperties.put("mail.smtp.auth", "true"); Session session = Session.getInstance(smtpProperties, null); Transport transport = session.getTransport("smtp"); transport.connect(address, port, email, new String(password)); transport.close(); return true; } catch (Exception e) { if (notify) { PopupManager.showMessage("Cause:\n" + e.getCause() + "\n\nMessage:\n" + e.getMessage(), "Bad SMTP"); System.out.println(e.getCause()); System.out.println(e.getMessage()); } return false; } }
From source file:org.eclipse.gemini.blueprint.test.internal.util.PropertiesUtil.java
/** * Apply placeholder expansion to the given properties object. * //w ww . j ava 2 s . c o m * Will return a new properties object, containing the expanded entries. Note that both keys and values will be * expanded. * * @param props * @return */ public static Properties expandProperties(Properties props) { Assert.notNull(props); Set entrySet = props.entrySet(); Properties newProps = (props instanceof OrderedProperties ? new OrderedProperties() : new Properties()); for (Iterator iter = entrySet.iterator(); iter.hasNext();) { // first expand the keys Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); String resultKey = expandProperty(key, props); String resultValue = expandProperty(value, props); // replace old entry newProps.put(resultKey, resultValue); } return newProps; }
From source file:Main.java
/** * Read a set of properties from the received input stream, strip * off any excess white space that exists in those property values, * and then add those newly-read properties to the received * Properties object; not explicitly removing the whitespace here can * lead to problems.//from w w w . j a v a2s .c o m * * This method exists because of the manner in which the jvm reads * properties from file--extra spaces are ignored after a _key_, but * if they exist at the _end_ of a property decl line (i.e. as part * of a _value_), they are preserved, as outlined in the Java API: * * "Any whitespace after the key is skipped; if the first non- * whitespace character after the key is = or :, then it is ignored * and any whitespace characters after it are also skipped. All * remaining characters on the line become part of the associated * element string." * * @param iStr An input stream from which the new properties are to be * loaded (should already be initialized). * @param prop A set of properties to which the properties from * iStr will be added (should already be initialized). * properties loaded from 'iStr' (with the extra whitespace (if any) * removed from all values), will be returned via the parameter. * **/ public static void loadWithTrimmedValues(InputStream iStr, Properties prop) throws IOException { if ((iStr == null) || (prop == null)) { // shouldn't happen; just ignore this call and return. return; } // Else, load the properties from the received input stream. Properties p = new Properties(); p.load(iStr); // Now, trim off any excess whitespace, if any, and then // add the properties from file to the received Properties // set. for (Enumeration propKeys = p.propertyNames(); propKeys.hasMoreElements();) { // get the value, trim off the whitespace, then store it // in the received properties object. String tmpKey = (String) propKeys.nextElement(); String tmpValue = p.getProperty(tmpKey); tmpValue = tmpValue.trim(); prop.put(tmpKey, tmpValue); } return; }
From source file:com.centurylink.mdw.services.util.AuthUtils.java
private static synchronized JWTVerifier createCustomTokenVerifier(String algorithmName, String issuer) { JWTVerifier tempVerifier = verifierCustom.get(issuer); if (tempVerifier == null) { Properties props = null;// w w w. ja va 2s .c o m if (customProviders == null) { props = PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT); customProviders = new HashMap<>(); for (String pn : props.stringPropertyNames()) { String[] pnParsed = pn.split("\\.", 4); if (pnParsed.length == 4) { String issuer_name = pnParsed[2]; String attrname = pnParsed[3]; Properties issuerSpec = customProviders.get(issuer_name); if (issuerSpec == null) { issuerSpec = new Properties(); customProviders.put(issuer_name, issuerSpec); } String v = props.getProperty(pn); issuerSpec.put(attrname, v); } } } props = customProviders.get(getCustomProviderGroupName(issuer)); if (props == null) { logger.severe("Exception creating Custom JWT Verifier for " + issuer + " - Missing 'key' Property"); return null; } String propAlg = props.getProperty(PropertyNames.MDW_JWT_ALGORITHM); if (StringHelper.isEmpty(algorithmName) || (!StringHelper.isEmpty(propAlg) && !algorithmName.equals(propAlg))) { String message = "Exception creating Custom JWT Verifier - "; message = StringHelper.isEmpty(algorithmName) ? "Missing 'alg' claim in JWT" : ("Mismatch algorithm with specified Property for " + issuer); logger.severe(message); return null; } String key = System.getenv("MDW_JWT_" + getCustomProviderGroupName(issuer).toUpperCase() + "_KEY"); if (StringHelper.isEmpty(key)) { if (!algorithmName.startsWith("HS")) { // Only allow use of Key in MDW properties for asymmetric algorithms key = props.getProperty(PropertyNames.MDW_JWT_KEY); if (StringHelper.isEmpty(key)) { logger.severe("Exception creating Custom JWT Verifier for " + issuer + " - Missing 'key' Property"); return null; } } else { logger.severe("Could not find properties for JWT issuer " + issuer); return null; } } try { maxAge = PropertyManager.getIntegerProperty(PropertyNames.MDW_AUTH_TOKEN_MAX_AGE, 0) * 1000L; Algorithm algorithm = null; Method algMethod = null; if (algorithmName.startsWith("HS")) { // HMAC String methodName = "HMAC" + algorithmName.substring(2); algMethod = Algorithm.none().getClass().getMethod(methodName, String.class); algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), key); } else if (algorithmName.startsWith("RS")) { // RSA String methodName = "RSA" + algorithmName.substring(2); byte[] publicBytes = Base64.decodeBase64(key.getBytes()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); algMethod = Algorithm.none().getClass().getMethod(methodName, RSAPublicKey.class, RSAPrivateKey.class); algorithm = (Algorithm) algMethod.invoke(Algorithm.none(), pubKey, null); } else { logger.severe( "Exception creating Custom JWT Verifier - Unsupported Algorithm: " + algorithmName); return null; } String subject = props.getProperty(PropertyNames.MDW_JWT_SUBJECT); Verification tmp = JWT.require(algorithm).withIssuer(issuer); tmp = StringHelper.isEmpty(subject) ? tmp : tmp.withSubject(subject); tempVerifier = tmp.build(); verifierCustom.put(issuer, tempVerifier); } catch (IllegalArgumentException | NoSuchAlgorithmException | NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException | InvalidKeySpecException e) { logger.severeException("Exception creating Custom JWT Verifier for " + issuer, e); } } return tempVerifier; }
From source file:com.linkedin.pinot.common.utils.KafkaStarterUtils.java
public static KafkaServerStartable startServer(final int port, final int brokerId, final String zkStr, final String logDirPath, final Properties configuration) { // Create the ZK nodes for Kafka, if needed int indexOfFirstSlash = zkStr.indexOf('/'); if (indexOfFirstSlash != -1) { String bareZkUrl = zkStr.substring(0, indexOfFirstSlash); String zkNodePath = zkStr.substring(indexOfFirstSlash); ZkClient client = new ZkClient(bareZkUrl); client.createPersistent(zkNodePath, true); client.close();/*from www.java2s .c om*/ } File logDir = new File(logDirPath); logDir.mkdirs(); configureKafkaPort(configuration, port); configureZkConnectionString(configuration, zkStr); configureBrokerId(configuration, brokerId); configureKafkaLogDirectory(configuration, logDir); configuration.put("zookeeper.session.timeout.ms", "60000"); KafkaConfig config = new KafkaConfig(configuration); KafkaServerStartable serverStartable = new KafkaServerStartable(config); serverStartable.startup(); return serverStartable; }
From source file:com.savy3.util.DBConfiguration.java
/** * Converts a String back to connection parameters. * @param input String from configuration * @return JDBC connection parameters// ww w . ja va 2 s. c o m */ protected static Properties propertiesFromString(String input) { if (input != null && !input.isEmpty()) { Properties result = new Properties(); StrTokenizer propertyTokenizer = StrTokenizer.getCSVInstance(input); StrTokenizer valueTokenizer = StrTokenizer.getCSVInstance(); valueTokenizer.setDelimiterChar('='); while (propertyTokenizer.hasNext()) { valueTokenizer.reset(propertyTokenizer.nextToken()); String[] values = valueTokenizer.getTokenArray(); if (values.length == 2) { result.put(values[0], values[1]); } } return result; } else { return null; } }
From source file:isl.FIMS.utils.Utils.java
public static boolean sendEmail(String to, String subject, String context) { boolean isSend = false; try {//from w w w. jav a 2s .c o m String host = "smtp.gmail.com"; String user = emailAdress; String password = emailPass; String port = "587"; String from = "no-reply-" + systemName + "@gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); // props.put("mail.smtp.socketFactory.port", port); // props.put("mail.smtp.socketFactory.class", // "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.port", "465"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); // To get the array of addresses message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject, "UTF-8"); message.setContent(context, "text/html; charset=UTF-8"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } isSend = true; } catch (MessagingException ex) { ex.printStackTrace(); } return isSend; }
From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java
/** * Sign a JAD file outputting the modified JAD to a different file. * * @param jadFile//from w ww.j av a 2s .c o m * JAD file * @param outputJadFile * Output JAD file * @param jarFile * JAR file * @param privateKey * Private RSA key to sign with * @param certificateChain * Certificate chain for private key * @param certificateNumber * Certificate number * @throws IOException * If an I/O problem occurs while signing the MIDlet * @throws CryptoException * If a crypto problem occurs while signing the MIDlet */ public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey, X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException { Properties jadProperties = readJadFile(jadFile); Properties newJadProperties = new Properties(); // Copy over existing attrs (excepting digest and any certificates at // provided number) for (Enumeration enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) { String propName = (String) enumPropNames.nextElement(); // Ignore digest attr if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) { continue; } // Ignore certificates at provided number if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) { continue; } newJadProperties.put(propName, jadProperties.getProperty(propName)); } // Get certificate attrs for (int i = 0; i < certificateChain.length; i++) { X509Certificate certificate = certificateChain[i]; String base64Cert = null; try { base64Cert = new String(Base64.encode(certificate.getEncoded())); } catch (CertificateEncodingException ex) { throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex); } String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber, (i + 1)); newJadProperties.put(midletCertificateAttr, base64Cert); } // Get signed Base 64 SHA-1 digest of JAR file as attr byte[] signedJarDigest = signJarDigest(jarFile, privateKey); String base64SignedJarDigest = new String(Base64.encode(signedJarDigest)); newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest); // Sort properties alphabetically TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>(); for (Enumeration names = newJadProperties.propertyNames(); names.hasMoreElements();) { String name = (String) names.nextElement(); String value = newJadProperties.getProperty(name); sortedJadProperties.put(name, value); } // Write out new JAD properties to JAD file FileWriter fw = null; try { fw = new FileWriter(outputJadFile); for (Iterator itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted.hasNext();) { Map.Entry property = (Map.Entry) itrSorted.next(); fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue())); fw.write(CRLF); } } finally { IOUtils.closeQuietly(fw); } }
From source file:com.glaf.core.config.DBConfiguration.java
public static Properties getTemplateProperties(String name) { if (name == null) { return null; }/*from w w w .j a v a2 s . c o m*/ if (jdbcTemplateProperties.isEmpty()) { init(); } logger.debug("name:" + name); Properties props = jdbcTemplateProperties.get(name); Properties p = new Properties(); Enumeration<?> e = props.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = props.getProperty(key); p.put(key, value); } return p; }