List of usage examples for java.net MalformedURLException MalformedURLException
public MalformedURLException(String msg)
From source file:eionet.gdem.utils.InputFile.java
/** * Stores the URL of remote file.//from ww w. ja v a 2 s . c o m * * @param strUrl URL of input file * @throws MalformedURLException Invalid URL. */ private void setURL(String strUrl) throws MalformedURLException { try { URI uri = new URI(escapeSpaces(strUrl)); parseUri(uri); this.url = uri.toURL(); } catch (URISyntaxException ue) { throw new MalformedURLException(ue.toString()); } catch (IllegalArgumentException ae) { throw new MalformedURLException(ae.toString()); } }
From source file:org.nordapp.web.servlet.IOServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w .j a va 2s . c o m*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); // // Session and other services // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue(); //The 'user' session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } EngineBaseService engineBaseService = null; try { engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(), String.valueOf(baseIndex)); } catch (InvalidSyntaxException e1) { } if (engineBaseService == null) throw new IOException( "The mandator base service is not available (maybe down or a version conflict)."); // // Get some data // FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); // // prepare the engine // String[] elem = RequestPath.getPath(req); if (elem.length == 0) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/function-id' but was '" + req.getRequestURI() + "'"); BigInteger engineId = ctrl.decodeCert(); String functionId = elem.length >= 1 ? elem[0] : null; Engine engine = null; try { engine = engineBaseService.getEngine(engineId); } catch (Exception e1) { throw new ServletException(e1); } if (!engine.isLogin()) throw new ServletException("There is no login to this session."); // // Initialize the work // engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString() IdRep processUUID = IdGen.getUUID(); engine.setLocalValue(httpProcessID, processUUID); IOContainer ioc = new IOContainer(); ioc.setProcessUUID(processUUID.toString()); engine.setLocalValue(httpIOContainer, ioc); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data ioc.setField(item.getFieldName(), item); } else { ioc.setFile(IdGen.getUUID().toString(), item); } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } // // Call script // try { engine.call(functionId); } catch (Exception e) { e.printStackTrace(); } ioc.cleanup(); engine.setLocalValue(httpSessionID, null); engine.setLocalValue(httpProcessID, null); engine.setLocalValue(httpIOContainer, null); // // Prints the result from the user-session // StringBuffer buffer = new StringBuffer(); ResponseHandler rsHdl = new ResponseHandler(context, ctrl); logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.", (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID()); rsHdl.getSessionData(buffer, mSession); // // // byte[] bytes = buffer.toString().getBytes(); // // Send the resource // rsHdl.avoidCaching(resp); rsHdl.sendData(bytes, resp); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:pcgen.gui2.tools.Utility.java
/** * View a URL in a browser// w w w . j ava 2s . c o m * * @param url URL to display in browser. * @throws IOException if the URL is bad or the browser can not be launched * @see DesktopBrowserLauncher */ static void viewInBrowser(URL url) throws IOException { try { viewInBrowser(url.toURI()); } catch (final URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } }
From source file:edu.mit.mobile.android.locast.net.NetworkClient.java
private void setBaseUrl(String baseUrlString) throws MalformedURLException { final URL baseUrl = new URL(baseUrlString); try {// www. j a v a 2s . c o m mBaseUrl = baseUrl.toURI(); mAuthScope = new AuthScope(mBaseUrl.getHost(), mBaseUrl.getPort()); } catch (final URISyntaxException e) { final MalformedURLException me = new MalformedURLException(e.getLocalizedMessage()); me.initCause(e); throw me; } }
From source file:org.kawanfw.file.api.client.RemoteSession.java
/** * Creates an Awake FILE session with a proxy and protocol parameters. * /* ww w.j av a 2 s . c om*/ * @param url * the URL of the path to the {@code ServerFileManager} Servlet * @param username * the username for authentication on the Awake Server (may be * null for <code>call()</code> * @param password * the user password for authentication on the Awake Server (may * be null) * @param proxy * the proxy to use, may be null for direct access * @param passwordAuthentication * the proxy credentials, null if no proxy or if the proxy does * not require authentication * @param sessionParameters * the session parameters to use (may be null) * * @throws MalformedURLException * if the url is malformed * @throws UnknownHostException * if host URL (http://www.acme.org) does not exists or no * Internet Connection. * @throws ConnectException * if the Host is correct but the {@code ServerFileManager} * Servlet is not reachable * (http://www.acme.org/ServerFileManager) and access failed * with a status != OK (200). (If the host is incorrect, or is * impossible to connect to - Tomcat down - the * {@code ConnectException} will be the sub exception * {@code HttpHostConnectException}.) * @throws SocketException * if network failure during transmission * @throws InvalidLoginException * the username or password is invalid * @throws SecurityException * Scheme is required to be https (SSL/TLS) * @throws RemoteException * an exception has been thrown on the server side. This traps * an Awake product failure and should not happen. * @throws IOException * for all other IO / Network / System Error */ public RemoteSession(String url, String username, char[] password, Proxy proxy, PasswordAuthentication passwordAuthentication, SessionParameters sessionParameters) throws MalformedURLException, UnknownHostException, ConnectException, SocketException, InvalidLoginException, RemoteException, SecurityException, IOException { if (url == null) { throw new MalformedURLException("url is null!"); } @SuppressWarnings("unused") URL asUrl = new URL(url); // Try to raise a MalformedURLException; this.username = username; this.url = url; this.proxy = proxy; this.passwordAuthentication = passwordAuthentication; this.sessionParameters = sessionParameters; // username & password may be null: for call() if (username == null) { return; } // Launch the Servlet httpTransfer = HttpTransferUtil.HttpTransferFactory(url, proxy, passwordAuthentication, sessionParameters); // TestReload if SSL required by host if (this.url.toLowerCase().startsWith("http://") && isForceHttps()) { throw new SecurityException( Tag.PRODUCT_SECURITY + " Remote Host requires a SSL url that starts with \"https\" scheme"); } String passwordStr = new String(password); // Prepare the request parameters List<SimpleNameValuePair> requestParams = new Vector<SimpleNameValuePair>(); requestParams.add(new SimpleNameValuePair(Parameter.TEST_CRYPTO, Parameter.TEST_CRYPTO)); requestParams.add(new SimpleNameValuePair(Parameter.ACTION, Action.LOGIN_ACTION)); requestParams.add(new SimpleNameValuePair(Parameter.USERNAME, username)); requestParams.add(new SimpleNameValuePair(Parameter.PASSWORD, passwordStr)); httpTransfer.send(requestParams); // If everything is OK, we have in our protocol a response that // 1) starts with "OK". 2) Is followed by the Authentication Token // else: response starts with "INVALID_LOGIN_OR_PASSWORD". String receive = httpTransfer.recv(); debug("receive: " + receive); if (receive.startsWith(ReturnCode.INVALID_LOGIN_OR_PASSWORD)) { throw new InvalidLoginException("Invalid username or password."); } else if (receive.startsWith(ReturnCode.OK)) { // OK! We are logged in & and correctly authenticated // Keep in static memory the Authentication Token for next api // commands (First 20 chars) String theToken = receive.substring(ReturnCode.OK.length() + 1); authenticationToken = StringUtils.left(theToken, Parameter.TOKEN_LEFT_SIZE); } else { this.username = null; // Should never happen throw new InvalidLoginException(Tag.PRODUCT_PRODUCT_FAIL + " Please contact support."); } }
From source file:de.bayern.gdi.gui.Controller.java
private void openLinkFromFile(String pathToFile) throws IOException { InputStream is = Misc.getResource(pathToFile); String contents = IOUtils.toString(is, "UTF-8"); if (contents == null || contents.isEmpty() || contents.equals("null")) { throw new MalformedURLException("URL is Empty"); }// w ww . j ava2 s .c om URL helpURL = new URL(contents); Misc.startExternalBrowser(helpURL.toString()); }
From source file:org.apache.ojb.broker.metadata.RepositoryPersistor.java
private URL buildURL(String repositoryFileName) throws MalformedURLException { //j2ee compliant lookup of resources URL url = ClassHelper.getResource(repositoryFileName); // don't be too strict: if resource is not on the classpath, try ordinary file lookup if (url == null) { try {/*from ww w . j a v a 2 s .c om*/ url = new File(repositoryFileName).toURL(); } catch (MalformedURLException ignore) { } } if (url != null) { log.info("OJB Descriptor Repository: " + url); } else { throw new MalformedURLException("did not find resource " + repositoryFileName); } return url; }
From source file:org.apache.nifi.processors.elasticsearch.FetchElasticsearchHttp.java
private URL buildRequestURL(String baseUrl, String docId, String index, String type, String fields) throws MalformedURLException { if (StringUtils.isEmpty(baseUrl)) { throw new MalformedURLException("Base URL cannot be null"); }/* w w w . j ava 2 s . com*/ HttpUrl.Builder builder = HttpUrl.parse(baseUrl).newBuilder(); builder.addPathSegment(index); builder.addPathSegment((StringUtils.isEmpty(type)) ? "_all" : type); builder.addPathSegment(docId); if (!StringUtils.isEmpty(fields)) { String trimmedFields = Stream.of(fields.split(",")).map(String::trim).collect(Collectors.joining(",")); builder.addQueryParameter(FIELD_INCLUDE_QUERY_PARAM, trimmedFields); } return builder.build().url(); }
From source file:org.apache.struts.taglib.TagUtils.java
/** * Compute a hyperlink URL based on the <code>forward</code>, * <code>href</code>, <code>action</code> or <code>page</code> parameter * that is not null. The returned URL will have already been passed to * <code>response.encodeURL()</code> for adding a session identifier. * * @param pageContext PageContext for the tag making this call * @param forward Logical forward name for which to look up the * context-relative URI (if specified) * @param href URL to be utilized unmodified (if specified) * @param page Module-relative page for which a URL should be * created (if specified) * @param action Logical action name for which to look up the * context-relative URI (if specified) * @param params Map of parameters to be dynamically included * (if any)//from www. ja v a 2 s. c o m * @param anchor Anchor to be dynamically included (if any) * @param redirect Is this URL for a <code>response.sendRedirect()</code>? * @param encodeSeparator This is only checked if redirect is set to * false (never encoded for a redirect). If true, * query string parameter separators are encoded * as >amp;, else & is used. * @param useLocalEncoding If set to true, urlencoding is done on the * bytes of character encoding from * ServletResponse#getCharacterEncoding. Use UTF-8 * otherwise. * @return URL with session identifier * @throws java.net.MalformedURLException if a URL cannot be created for * the specified parameters */ public String computeURLWithCharEncoding(PageContext pageContext, String forward, String href, String page, String action, String module, Map params, String anchor, boolean redirect, boolean encodeSeparator, boolean useLocalEncoding) throws MalformedURLException { String charEncoding = "UTF-8"; if (useLocalEncoding) { charEncoding = pageContext.getResponse().getCharacterEncoding(); } // TODO All the computeURL() methods need refactoring! // Validate that exactly one specifier was included int n = 0; if (forward != null) { n++; } if (href != null) { n++; } if (page != null) { n++; } if (action != null) { n++; } if (n != 1) { throw new MalformedURLException(messages.getMessage("computeURL.specifier")); } // Look up the module configuration for this request ModuleConfig moduleConfig = getModuleConfig(module, pageContext); // Calculate the appropriate URL StringBuffer url = new StringBuffer(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); if (forward != null) { ForwardConfig forwardConfig = moduleConfig.findForwardConfig(forward); if (forwardConfig == null) { throw new MalformedURLException(messages.getMessage("computeURL.forward", forward)); } // **** removed - see bug 37817 **** // if (forwardConfig.getRedirect()) { // redirect = true; // } if (forwardConfig.getPath().startsWith("/")) { url.append(request.getContextPath()); url.append(RequestUtils.forwardURL(request, forwardConfig, moduleConfig)); } else { url.append(forwardConfig.getPath()); } } else if (href != null) { url.append(href); } else if (action != null) { ActionServlet servlet = (ActionServlet) pageContext.getServletContext() .getAttribute(Globals.ACTION_SERVLET_KEY); String actionIdPath = RequestUtils.actionIdURL(action, moduleConfig, servlet); if (actionIdPath != null) { action = actionIdPath; url.append(request.getContextPath()); url.append(actionIdPath); } else { url.append(instance.getActionMappingURL(action, module, pageContext, false)); } } else /* if (page != null) */ { url.append(request.getContextPath()); url.append(this.pageURL(request, page, moduleConfig)); } // Add anchor if requested (replacing any existing anchor) if (anchor != null) { String temp = url.toString(); int hash = temp.indexOf('#'); if (hash >= 0) { url.setLength(hash); } url.append('#'); url.append(this.encodeURL(anchor, charEncoding)); } // Add dynamic parameters if requested if ((params != null) && (params.size() > 0)) { // Save any existing anchor String temp = url.toString(); int hash = temp.indexOf('#'); if (hash >= 0) { anchor = temp.substring(hash + 1); url.setLength(hash); temp = url.toString(); } else { anchor = null; } // Define the parameter separator String separator = null; if (redirect) { separator = "&"; } else if (encodeSeparator) { separator = "&"; } else { separator = "&"; } // Add the required request parameters boolean question = temp.indexOf('?') >= 0; Iterator keys = params.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); Object value = params.get(key); if (value == null) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); // Interpret null as "no value" } else if (value instanceof String) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL((String) value, charEncoding)); } else if (value instanceof String[]) { String[] values = (String[]) value; for (int i = 0; i < values.length; i++) { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL(values[i], charEncoding)); } } else /* Convert other objects to a string */ { if (!question) { url.append('?'); question = true; } else { url.append(separator); } url.append(this.encodeURL(key, charEncoding)); url.append('='); url.append(this.encodeURL(value.toString(), charEncoding)); } } // Re-add the saved anchor (if any) if (anchor != null) { url.append('#'); url.append(this.encodeURL(anchor, charEncoding)); } } // Perform URL rewriting to include our session ID (if any) // but only if url is not an external URL if ((href == null) && (pageContext.getSession() != null)) { HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); if (redirect) { return (response.encodeRedirectURL(url.toString())); } return (response.encodeURL(url.toString())); } return (url.toString()); }
From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java
private String getJobBuildPart(final JenkinsClient client, final String jobUrlString, final String jenkinsUrlString) throws Exception { final String jobPath = getJobPath(jobUrlString, jenkinsUrlString); final Matcher jobMatch = JOB_BUILD_PATTERN.matcher(jobPath); if (!jobMatch.find()) { throw new MalformedURLException("Cannot find job name in path " + jobPath); }/*w ww .ja v a 2 s . co m*/ return jobMatch.group(2); }