List of usage examples for java.lang Exception getLocalizedMessage
public String getLocalizedMessage()
From source file:cn.org.once.cstack.utils.MessageUtils.java
public static Message writeAfterThrowingSnapshotMessage(Exception e, User user, String type) { Message message = new Message(); String body = ""; message.setType(Message.ERROR);// www .j ava 2 s . c om message.setAuthor(user); switch (type) { case "CREATE": body = "Error create application - " + e.getLocalizedMessage(); break; case "REMOVE": body = "Error delete application - " + e.getLocalizedMessage(); break; case "CLONEFORMASNAPSHOT": body = "Error delete application - " + e.getLocalizedMessage(); break; default: body = "Error : unkown error"; break; } message.setEvent(body); return message; }
From source file:org.owasp.proxy.Main.java
private static SSLContextSelector getClientSSLContextSelector(Configuration config) { String type = config.keystoreType; char[] password = config.keyStorePassword == null ? null : config.keyStorePassword.toCharArray(); File location = config.keyStoreLocation == null ? null : new File(config.keyStoreLocation); if (type != null) { KeyStore ks = null;//from w ww . j ava2 s . com if (type.equals("PKCS11")) { try { int slot = config.pkcs11SlotLocation; ks = KeystoreUtils.getPKCS11Keystore("PKCS11", location, slot, password); } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.exit(2); } } else { try { FileInputStream in = new FileInputStream(location); ks = KeyStore.getInstance(type); ks.load(in, password); } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.exit(2); } } String alias = config.keyStoreAlias; if (alias == null) { try { Map<String, String> aliases = KeystoreUtils.getAliases(ks); if (aliases.size() > 0) { System.err.println("Keystore contains the following aliases: \n"); for (String a : aliases.keySet()) { System.err.println("Alias \"" + a + "\"" + " : " + aliases.get(a)); } alias = aliases.keySet().iterator().next(); System.err.println("Using " + alias + " : " + aliases.get(alias)); } else { System.err.println("Keystore contains no aliases!"); System.exit(3); } } catch (KeyStoreException kse) { System.err.println(kse.getLocalizedMessage()); System.exit(4); } } try { final X509KeyManager km = KeystoreUtils.getKeyManagerForAlias(ks, alias, password); return new DefaultClientContextSelector(km); } catch (GeneralSecurityException gse) { System.err.println(gse.getLocalizedMessage()); System.exit(5); } } return new DefaultClientContextSelector(); }
From source file:com.microsoft.tfs.client.common.ui.wit.form.Helpers.java
public static IWorkItemControl getControlCustom(final WIFormElement formElement, final WorkItem workItem, final boolean usePreferredType) { if (!(formElement instanceof WIFormControl)) { // Custom controls are only valid for form controls (not tabs, // splitters etc) return null; }/*from w w w.j a v a2 s . com*/ IWorkItemControl control = null; try { synchronized (customControlLock) { if (customControls == null) { loadCustomControls(); } final WIFormControl controlDescription = (WIFormControl) formElement; final String controlType = usePreferredType ? controlDescription.getPreferredType() : controlDescription.getType(); final CustomControlLoader loader = (CustomControlLoader) customControls.get(controlType); if (loader != null) { control = loader.getControl(); } } } catch (final Exception e) { // We encountered an error loading the control, return an error // control with the error message. log.error("Error loading custom control", e); //$NON-NLS-1$ control = new ErrorBoxControl(e.getLocalizedMessage()); } return control; }
From source file:it.geosolutions.tools.compress.file.Compressor.java
public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) { if (zipFile.exists() && overwrite) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + zipFile + " overvriting"); return zipFile; }// ww w . jav a 2 s .c o m // Create a buffer for reading the files byte[] buf = new byte[Conf.getBufferSize()]; ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(zipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { continue; } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(file.getName())); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } } finally { try { // Complete the entry out.closeEntry(); } catch (Exception e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(out); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); } return zipFile; }
From source file:com.wonders.bud.freshmommy.web.content.controller.ChannelController.java
/** * <p>// w w w .j a v a2s. c o m * Description:[?] * </p> * * Created by [Dy] [20141127] * Midified by [] [] * @param sourcePath * @param targetPath * @param actionPath action * @return List<String> ?sourcePath? */ public static List<String> moveImg(String[] sourcePath, String[] targetPath, String actionPath) { List<String> list = new ArrayList<String>(); if (sourcePath.length == targetPath.length) { if (sourcePath.length > 0) { try { for (int i = 0; i < sourcePath.length; i++) { if (StringUtils.isNotBlank(sourcePath[i])) { File cacheFile = new File(actionPath + File.separator + sourcePath[i]); // StringBuffer fileName = new StringBuffer(); fileName.append(actionPath).append(File.separator).append(targetPath[i]) .append(cacheFile.getName()); File folder = new File(fileName.toString()); if (!folder.getParentFile().exists()) { // folder.getParentFile().mkdirs(); } Thumbnails.of(cacheFile).scale(1).toFile(fileName.toString()); // FileUtil.deleteFiles(actionPath, sourcePath[i]); list.add(targetPath[i] + cacheFile.getName()); } } return list; } catch (Exception e) { log.error(e.getLocalizedMessage()); return null; } } } return null; }
From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetiler.java
public static void reTile(File inFile, File tiledTiffFile, double compressionRatio, String compressionType, int tileW, int tileH, boolean forceBigTiff) throws IOException { ///*from w w w . j ava 2 s .c o m*/ // look for a valid file that we can read // AbstractGridFormat format = null; AbstractGridCoverage2DReader reader = null; GridCoverage2D inCoverage = null; AbstractGridCoverageWriter writer = null; final Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE); // getting a format for the given input format = (AbstractGridFormat) GridFormatFinder.findFormat(inFile, hints); if (format == null || (format instanceof UnknownFormat)) { throw new IllegalArgumentException("Unable to find the GridFormat for the provided file: " + inFile); } try { // // ACQUIRING A READER // if (LOGGER.isInfoEnabled()) { LOGGER.info("Acquiring a reader for the provided file..."); } // can throw UnsupportedOperationsException reader = (AbstractGridCoverage2DReader) format.getReader(inFile, hints); if (reader == null) { final IOException ioe = new IOException("Unable to find a reader for the provided file: " + inFile); throw ioe; } // // ACQUIRING A COVERAGE // if (LOGGER.isInfoEnabled()) { LOGGER.info("Acquiring a coverage provided file..."); } inCoverage = (GridCoverage2D) reader.read(null); if (inCoverage == null) { final IOException ioe = new IOException("inCoverage == null"); throw ioe; } // // PREPARING A WRITE // if (LOGGER.isInfoEnabled()) { LOGGER.info("Writing down the file in the decoded directory..."); } final GeoTiffFormat wformat = new GeoTiffFormat(); final GeoTiffWriteParams wp = new GeoTiffWriteParams(); if (!Double.isNaN(compressionRatio) && compressionType != null) { wp.setCompressionMode(GeoTiffWriteParams.MODE_EXPLICIT); wp.setCompressionType(compressionType); wp.setCompressionQuality((float) compressionRatio); } wp.setForceToBigTIFF(forceBigTiff); wp.setTilingMode(GeoToolsWriteParams.MODE_EXPLICIT); wp.setTiling(tileW, tileH); final ParameterValueGroup wparams = wformat.getWriteParameters(); wparams.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp); // // ACQUIRING A WRITER AND PERFORMING A WRITE // writer = (AbstractGridCoverageWriter) new GeoTiffWriter(tiledTiffFile); writer.write(inCoverage, (GeneralParameterValue[]) wparams.values().toArray(new GeneralParameterValue[1])); } finally { // // PERFORMING FINAL CLEAN UP AFTER THE WRITE PROCESS // if (reader != null) { try { reader.dispose(); } catch (Exception e) { if (LOGGER.isWarnEnabled()) LOGGER.warn(e.getLocalizedMessage(), e); } } if (writer != null) { try { writer.dispose(); } catch (Exception e) { if (LOGGER.isWarnEnabled()) LOGGER.warn(e.getLocalizedMessage(), e); } } if (inCoverage != null) { final RenderedImage initImage = inCoverage.getRenderedImage(); ImageReader r = (ImageReader) initImage.getProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER); try { r.dispose(); } catch (Exception e) { if (LOGGER.isWarnEnabled()) LOGGER.warn("GeotiffRetiler::reTile(): " + e.getLocalizedMessage(), e); } // dispose ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(initImage)); } } }
From source file:com.mpower.mintel.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * //from w w w .ja v a 2s .c o m * @param urlString * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient, String auth) { URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase() .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) { try { // don't really care about the stream... InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (Exception e) { e.printStackTrace(); } } if (statusCode != 200) { String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { e.printStackTrace(); String cause; if (e.getCause() != null) { cause = e.getCause().getMessage(); } else { cause = e.getMessage(); } String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.clavain.alerts.Methods.java
private static void sendMail(String title, String message, String emailaddy) { try {// www .j ava 2s. c om Email email = new SimpleEmail(); email.setHostName(p.getProperty("mailserver.host")); email.setSmtpPort(Integer.parseInt(p.getProperty("mailserver.port"))); if (p.getProperty("mailserver.useauth").equals("true")) { email.setAuthentication(p.getProperty("mailserver.user"), p.getProperty("mailserver.pass")); } if (p.getProperty("mailserver.usessl").equals("true")) { email.setSSLOnConnect(true); } else { email.setSSLOnConnect(false); } email.setFrom(p.getProperty("mailserver.from")); email.setSubject("[MuninMX] " + title); email.setMsg(message); email.addTo(emailaddy); email.send(); } catch (Exception ex) { logger.warn("Unable to send Mail: " + ex.getLocalizedMessage()); } }
From source file:it.cloudicaro.disit.kb.BusinessConfigurationResource.java
static public String putBusinessConfiguration(String name, String content, HttpServletRequest request) throws Exception { Date start = new Date(); String op = (name.equals("") ? "POST" : "PUT"); Configuration conf = Configuration.getInstance(); String validationResult = null; String bcAbout = ""; boolean check = (request != null || conf.get("kb.recover.force_checkBC", "false").equals("true")); if (check) {//from ww w .j a va 2s. c o m //validate 'content' using xml schema validationResult = ValidateResource.validateContent(content, "schema-icaro-kb-businessConfiguration.xsd"); if (validationResult != null) { IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-XML-VALIDATION", validationResult, content, request); throw new KbException(validationResult, 400); } } //get the BusinessConfiguration rdf:about and check if the resource name from the url is the ending part of the rdf:about Document doc = ValidateResource.parseXml(content); NodeList bc = doc.getElementsByTagNameNS(IcaroKnowledgeBase.NS_ICARO_CORE, "BusinessConfiguration"); if (bc.getLength() == 1) bcAbout = bc.item(0).getAttributes().getNamedItemNS(IcaroKnowledgeBase.NS_RDF, "about").getNodeValue(); String bcPrefix = conf.get("kb.bcPrefix", "urn:cloudicaro:BusinessConfiguration:"); if (check && name.equals("")) { if (!bcAbout.startsWith(bcPrefix)) { String error = "BusinessConfiguration rdf:about='" + bcAbout + "' does not start with '" + bcPrefix + "'"; IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-ID-CHECK1", error, content, request); throw new KbException(error, 400); } name = bcAbout.substring(bcPrefix.length()); } if (check && conf.get("kb.validateBCAbout", "true").equalsIgnoreCase("true") && !bcAbout.endsWith(name)) { String error = "BusinessConfiguration rdf:about='" + bcAbout + "' does not end with '" + name + "'"; IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-ID-CHECK2", error, content, request); throw new KbException(error, 400); } RDFStoreInterface rdfStore = RDFStore.getInstance(); //check if the business configuration is already present or not Boolean toUpdate = false; QueryResult qr = rdfStore.query("SELECT * WHERE { <" + bcAbout + "> ?p ?o } LIMIT 1"); toUpdate = (qr.results().size() >= 1); //upload to a new temporary context, if ok rename the context otherwise remove String tmpGraph = "urn:cloudicaro:context:BusinessConfiguration:tmp:" + UUID.randomUUID(); String graph = "urn:cloudicaro:context:BusinessConfiguration:" + name; String data = ValidateResource.transformBlankNodes(doc); rdfStore.addStatements(data, "application/rdf+xml", tmpGraph); try { if (check) validationResult = ValidateResource.validateBusinessConfigurationGraph(tmpGraph); } finally { if (validationResult != null) { rdfStore.removeGraph(tmpGraph); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-KB-VALIDATION", validationResult, content, request); throw new KbException(validationResult, 400); } else { //remove context associated with id and then rename the graph to the new one rdfStore.removeGraph(graph); if (conf.get("kb.bcUpdateFix", "false").equals("false")) rdfStore.update("MOVE <" + tmpGraph + "> TO <" + graph + ">"); else { rdfStore.removeGraph(tmpGraph); rdfStore.addStatements(data, "application/rdf+xml", graph); } } } Date mid = new Date(); //post content on RDF store in the context //???rdfStore.addStatements(content, "application/rdf+xml", graph); if (request != null) { rdfStore.flush(); // save the request to disk IcaroKnowledgeBase.storePut(start, content, name, "BC"); if (conf.get("kb.sm.forward.BusinessConfiguration", "false").equals("true")) { try { String smUrl = conf.get("kb.sm.url", "http://192.168.0.37/icaro/api/configurator"); if (toUpdate) smUrl = smUrl + "/" + bcAbout; ServerMonitoringClient client = new ServerMonitoringClient(smUrl); client.setUsernamePassword(conf.get("kb.sm.user", "test"), conf.get("kb.sm.passwd", "12345")); String result; if (toUpdate) { System.out.println("PUT BC " + bcAbout + " to SM"); result = client.putXml(content); } else { System.out.println("POST BC to SM"); result = client.postXml(content); } System.out.println("SM result:\n" + result); client.close(); Date end = new Date(); System.out.println(start + " KB-PERFORMANCE " + op + " BC " + name + " kb:" + (mid.getTime() - start.getTime()) + "ms sm:" + (end.getTime() - mid.getTime()) + "ms"); IcaroKnowledgeBase.log(start, op, "BC", name, "OK", request); /*if(conf.get("kb.sce.forward.BusinessConfiguration", "false").equals("true")) { try { String sceUrl=conf.get("kb.sce.url", ""); } catch(Exception e) { e.printStackTrace(); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-SCE", e.getLocalizedMessage(), content, request); } }*/ return result; } catch (Exception e) { e.printStackTrace(); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-SM", e.getLocalizedMessage(), content, request); throw new KbException("Failed setting monitoring: " + e.getLocalizedMessage(), 400); } } IcaroKnowledgeBase.log(start, op, "BC", name, "OK", request); } return ""; }
From source file:com.kylinolap.common.KylinConfig.java
private static UriType decideUriType(String metaUri) { try {//from w w w .java2s. c o m File file = new File(metaUri); if (file.exists()) { if (file.isDirectory()) { return UriType.LOCAL_FOLDER; } else if (file.isFile()) { if (file.getName().equalsIgnoreCase(KYLIN_CONF_PROPERTIES_FILE)) { return UriType.PROPERTIES_FILE; } else { throw new IllegalStateException( "Metadata uri : " + metaUri + " is a local file but not kylin.properties"); } } } else { if (RestClient.matchFullRestPattern(metaUri)) return UriType.REST_ADDR; else throw new IllegalStateException( "Metadata uri : " + metaUri + " is not a valid REST URI address"); } } catch (Exception e) { logger.info(e.getLocalizedMessage()); throw new IllegalStateException("Metadata uri : " + metaUri + " is not recognized"); } return null; }