List of usage examples for java.net MalformedURLException toString
public String toString()
From source file:eionet.gdem.conversion.datadict.DataDictUtil.java
public static String getInstanceUrl(String schema_url) throws GDEMException { try {/*from www.j a v a 2s . co m*/ // throws Exception, if not correct URL URL schemaURL = new URL(schema_url); String id = getSchemaIdParamFromUrl(schema_url); String type = id.substring(0, 3); id = id.substring(3); int path_idx = schema_url.toLowerCase().indexOf(SCHEMA_SERVLET.toLowerCase()); String path = schema_url.substring(0, path_idx); String instance_url = path + INSTANCE_SERVLET + "?id=" + id + "&type=" + type.toLowerCase(); // throws Exception, if not correct URL URL instanceURL = new URL(instance_url); return instance_url; } catch (MalformedURLException e) { throw new GDEMException("Error getting Instance file URL: " + e.toString() + " - " + schema_url); } catch (Exception e) { throw new GDEMException("Error getting Instance file URL: " + e.toString() + " - " + schema_url); } }
From source file:io.github.retz.mesosc.MesosHTTPFetcher.java
private static Optional<String> fetchSlaveAddr(String master, String slaveId) { String addr = "http://" + master + "/slaves"; try (UrlConnector conn = new UrlConnector(addr, "GET", true)) { return extractSlaveAddr(conn.getInputStream(), slaveId); } catch (MalformedURLException e) { LOG.error(e.toString(), e); return Optional.empty(); } catch (IOException e) { LOG.warn("Failed to fetch Slave address of {} from master {}", slaveId, master, e); return Optional.empty(); }// ww w. j av a 2 s. c o m }
From source file:biz.mosil.webtools.MosilWeb.java
/** * ? InputStream//w w w . j a v a2 s . c om * */ public static final InputStream getInputStream(final String _url) { InputStream result = null; try { URL url = new URL(_url); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) { throw new IOException("This URL Can't Connect!"); } HttpURLConnection httpConn = (HttpURLConnection) conn; //???? httpConn.setAllowUserInteraction(false); //?? httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); final int response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { result = httpConn.getInputStream(); } } catch (MalformedURLException _ex) { Log.e("getInputStream", "Malformed URL Exception: " + _ex.toString()); } catch (IOException _ex) { Log.e("getInputStream", "IO Exception: " + _ex.toString()); } return result; }
From source file:com.stacksync.desktop.Stacksync.java
public static void start() { Boolean deamonMode = false;//w w w .j a va 2 s . c o m Boolean extendedMode; try { try { File file = new File(env.getDefaultUserConfigDir() + File.separator + "conf" + File.separator + Constants.LOGGING_DEFAULT_FILENAME); DOMConfigurator.configure(file.toURI().toURL()); } catch (NullPointerException e) { System.out.println( "No log4j config file was found no logs will be saved for this stacksync instance please make sure LogProperties.xml file is correctly placed " + e.toString()); } catch (MalformedURLException ex) { System.out.println( "No log4j config file was found no logs will be saved for this stacksync instance please make sure LogProperties.xml file is correctly placed " + ex.toString()); } // create the command line parser Options options = createOptions(); CommandLine line = parser.parse(options, args); // Help if (line.hasOption("help")) { showHelp(options); } deamonMode = line.hasOption("daemon"); config.setDaemonMode(deamonMode); extendedMode = line.hasOption("extended"); config.setExtendedMode(extendedMode); // Load config if (line.hasOption("config")) { File configFolder = new File(line.getOptionValue("config")); File configFile = new File(line.getOptionValue("config") + File.separator + "config.xml"); if (configFolder.exists() && configFile.exists()) { config.load(configFolder); } else { if (!configFolder.exists()) { throw new ConfigException("config folder " + configFolder + " doesn't exist."); } else { throw new ConfigException(configFile + " doesn't exist."); } } if (config.getProfile() == null) { throw new ConfigException("Could not load a profile, check the configuration file."); } } else { File configurationDir = env.getAppConfDir(); if (configurationDir.exists()) { config.load(); if (config.getProfile() == null) { File folder = new File( config.getConfDir() + File.separator + Constants.CONFIG_DATABASE_DIRNAME); File configFile = new File( config.getConfDir() + File.separator + Constants.CONFIG_FILENAME); folder.delete(); configFile.delete(); config.load(); } } else { // new configuration config.load(); } } } catch (ConfigException e) { System.err.println("ERROR: Configuration exception: "); System.err.println(StringUtil.getStackTrace(e)); System.exit(1); } catch (ParseException e) { System.err.println("ERROR: Command line arguments invalid: "); System.err.println(StringUtil.getStackTrace(e)); System.exit(1); } // Start app! try { // TODO fixit //RemoteLogs.sendFailedLogs(); Application appStacksync = new Application(); appStacksync.start(); } catch (Exception e) { if (!deamonMode) { ErrorDialog.showDialog(e); } } }
From source file:com.ushahidi.android.app.net.MainHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *//*from w w w . j a va 2 s .co m*/ public static int PostFileUpload(String URL, HashMap<String, String> params) throws IOException { Log.d(CLASS_TAG, "PostFileUpload(): upload file to server."); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("incident_title", new StringBody(params.get("incident_title"), Charset.forName("UTF-8"))); entity.addPart("incident_description", new StringBody(params.get("incident_description"), Charset.forName("UTF-8"))); entity.addPart("incident_date", new StringBody(params.get("incident_date"))); entity.addPart("incident_hour", new StringBody(params.get("incident_hour"))); entity.addPart("incident_minute", new StringBody(params.get("incident_minute"))); entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm"))); entity.addPart("incident_category", new StringBody(params.get("incident_category"))); entity.addPart("latitude", new StringBody(params.get("latitude"))); entity.addPart("longitude", new StringBody(params.get("longitude"))); entity.addPart("location_name", new StringBody(params.get("location_name"), Charset.forName("UTF-8"))); entity.addPart("person_first", new StringBody(params.get("person_first"), Charset.forName("UTF-8"))); entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8"))); entity.addPart("person_email", new StringBody(params.get("person_email"), Charset.forName("UTF-8"))); if (!TextUtils.isEmpty(params.get("filename"))) { File file = new File(params.get("filename")); if (file.exists()) { entity.addPart("incident_photo[]", new FileBody(new File(params.get("filename")))); } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); return Util.extractPayloadJSON(GetText(serverInput)); } } } catch (MalformedURLException ex) { Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException"); ex.printStackTrace(); return 11; // fall through and return false } catch (IllegalArgumentException ex) { Log.e(CLASS_TAG, ex.toString()); //invalid URI return 12; } catch (IOException e) { Log.e(CLASS_TAG, e.toString()); //timeout return 13; } return 10; }
From source file:org.kalypso.commons.i18n.ResourceBundleUtils.java
/** * @param baseURL/*from w w w . ja v a2 s .com*/ * Base name for which to try to load the resource bundle.<br> * If <code>baseUrl</code> is something like <code>http://somehost/myfile.txt</code>, we try to load * properties like <code>http://somehost/myfile.properties</code>.<br> * Urls with query part or anchor are not supported. * @return <code>null</code>, if no such resource bundle is found. Any exceptions are reported to the {@link org.eclipse.core.runtime.ILog}-facilities. */ public static ResourceBundle loadResourceBundle(final URL baseURL) { try { // Unfinished: this does probably does not cover all cases... final URL _baseURL = extractBaseUrl(baseURL); final String path = baseURL.getPath(); final String baseName = FilenameUtils.getBaseName(path); // REMARK: the trick here is to use the special class loader, that just links back to the given url. // This allows us to use the full functionality of the ResourceBundle#getBundle implementation. final ClassLoader loader = new ClassLoader() { @Override protected URL findResource(final String name) { try { // The ResourceBundle replaces all '.' by '/' (assuming it is a classname) // but we know better. The name can never contain a real '/', because we // truncated it (see above). final String resourceName = name.replace('/', '.'); return new URL(_baseURL, resourceName); } catch (final MalformedURLException e) { e.printStackTrace(); return null; } } }; return ResourceBundle.getBundle(baseName, Locale.getDefault(), loader); } catch (final MissingResourceException e) { KalypsoCommonsDebug.DEBUG_I18N.printf(IStatus.INFO, "No resource bundle found for: %s%n", baseURL); //$NON-NLS-1$ return null; } catch (final MalformedURLException e) { KalypsoCommonsDebug.DEBUG_I18N.printf(IStatus.WARNING, "Could not load resource bundle found for: %s (%s)%n", baseURL, e.toString()); //$NON-NLS-1$ return null; } }
From source file:org.apache.ofbiz.solr.SolrProductSearch.java
/** * Adds a List of products to the solr index. * <p>/* www. j av a 2s . c o m*/ * This is faster than reflushing the index each time. */ public static Map<String, Object> addListToSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { String solrIndexName = (String) context.get("indexName"); Locale locale = (Locale) context.get("locale"); HttpSolrClient client = null; Map<String, Object> result; Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); // Construct Documents List<Map<String, Object>> fieldList = UtilGenerics .<Map<String, Object>>checkList(context.get("fieldList")); Debug.logInfo("Solr: Generating and adding " + fieldList.size() + " documents to solr index", module); for (Iterator<Map<String, Object>> fieldListIterator = fieldList.iterator(); fieldListIterator .hasNext();) { SolrInputDocument doc1 = SolrUtil.generateSolrDocument(fieldListIterator.next()); if (Debug.verboseOn()) { Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module); } docs.add(doc1); } // push Documents to server client = SolrUtil.getInstance().getHttpSolrClient(solrIndexName); client.add(docs); client.commit(); final String statusStr = UtilProperties.getMessage(resource, "SolrAddedDocumentsToSolrIndex", UtilMisc.toMap("fieldList", fieldList.size()), locale); Debug.logInfo("Solr: " + statusStr, module); result = ServiceUtil.returnSuccess(statusStr); } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "urlError"); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = UtilProperties.getMessage(resource, "SolrFailureConnectingToSolrServerToCommitProductList", UtilMisc.toMap("productId", context.get("productId")), locale); if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } result.put("errorType", "connectError"); } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "solrServerError"); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } finally { if (client != null) { try { client.close(); } catch (IOException e) { // do nothing } } } return result; }
From source file:org.apache.ofbiz.solr.SolrProductSearch.java
/** * Adds product to solr index./*from ww w .jav a 2 s.c om*/ */ public static Map<String, Object> addToSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { HttpSolrClient client = null; Locale locale = (Locale) context.get("locale"); Map<String, Object> result; String productId = (String) context.get("productId"); String solrIndexName = (String) context.get("indexName"); // connectErrorNonFatal is a necessary option because in some cases it may be considered normal that solr server is unavailable; // don't want to return error and abort transactions in these cases. Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { Debug.logInfo("Solr: Generating and indexing document for productId '" + productId + "'", module); client = SolrUtil.getInstance().getHttpSolrClient(solrIndexName); //Debug.log(server.ping().toString()); // Construct Documents SolrInputDocument doc1 = SolrUtil.generateSolrDocument(context); Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); if (Debug.verboseOn()) { Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module); } docs.add(doc1); // push Documents to server client.add(docs); client.commit(); final String statusStr = UtilProperties.getMessage(resource, "SolrDocumentForProductIdAddedToSolrIndex", UtilMisc.toMap("productId", context.get("productId")), locale); Debug.logInfo("Solr: " + statusStr, module); result = ServiceUtil.returnSuccess(statusStr); } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "urlError"); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = UtilProperties.getMessage(resource, "SolrFailureConnectingToSolrServerToCommitProductId", UtilMisc.toMap("productId", context.get("productId")), locale); if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } result.put("errorType", "connectError"); } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "solrServerError"); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } finally { if (client != null) { try { client.close(); } catch (IOException e) { // do nothing } } } return result; }
From source file:org.smilec.smile.ui.GeneralActivity.java
/** * Used for JSON data from node server.//from w w w .jav a 2s.com * @return the content of the <b>url</b> as a string. */ public static String getContents(String url) { String contents = ""; try { URLConnection conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); contents = convertStreamToString(in); } catch (MalformedURLException e) { Log.v("MALFORMED URL EXCEPTION", e.toString()); } catch (IOException e) { Log.e(e.getMessage(), e.toString()); } return contents; }
From source file:org.apache.ofbiz.solr.SolrProductSearch.java
/** * Rebuilds the solr index.// w w w.j a v a2 s.c om */ public static Map<String, Object> rebuildSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { HttpSolrClient client = null; Map<String, Object> result; GenericDelegator delegator = (GenericDelegator) dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String solrIndexName = (String) context.get("indexName"); Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { client = SolrUtil.getInstance().getHttpSolrClient(solrIndexName); // now lets fetch all products List<Map<String, Object>> solrDocs = new ArrayList<Map<String, Object>>(); List<GenericValue> products = delegator.findList("Product", null, null, null, null, true); int numDocs = 0; if (products != null) { numDocs = products.size(); } Debug.logInfo("Solr: Clearing solr index and rebuilding with " + numDocs + " found products", module); Iterator<GenericValue> productIterator = products.iterator(); while (productIterator.hasNext()) { GenericValue product = productIterator.next(); Map<String, Object> dispatchContext = ProductUtil.getProductContent(product, dctx, context); solrDocs.add(dispatchContext); } // this removes everything from the index client.deleteByQuery("*:*"); client.commit(); // THis adds all products to the Index (instantly) Map<String, Object> runResult = dispatcher.runSync("addListToSolrIndex", UtilMisc.toMap("fieldList", solrDocs, "userLogin", userLogin, "locale", locale, "indexName", solrIndexName, "treatConnectErrorNonFatal", treatConnectErrorNonFatal)); String runMsg = ServiceUtil.getErrorMessage(runResult); if (UtilValidate.isEmpty(runMsg)) { runMsg = null; } if (ServiceUtil.isError(runResult)) { result = ServiceUtil.returnError(runMsg); } else if (ServiceUtil.isFailure(runResult)) { result = ServiceUtil.returnFailure(runMsg); } else { final String statusMsg = UtilProperties.getMessage(resource, "SolrClearedSolrIndexAndReindexedDocuments", UtilMisc.toMap("numDocs", numDocs), locale); result = ServiceUtil.returnSuccess(statusMsg); } } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = UtilProperties.getMessage(resource, "SolrFailureConnectingToSolrServerToRebuildIndex", locale); if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (ServiceAuthException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (ServiceValidationException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (GenericServiceException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { // do nothing } } } return result; }