List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:it.geosolutions.geofence.gui.server.service.impl.RulesManagerServiceImpl.java
/** * @param rule//from w ww.j a v a 2s .c o m * @return List<LayerAttribUI> */ private List<LayerAttribUI> loadAttribute(Rule rule) { List<LayerAttribUI> layerAttributesDTO = new ArrayList<LayerAttribUI>(); Set<LayerAttribute> layerAttributes = null; GSInstance gsInstance = rule.getInstance(); GeoServerRESTReader gsreader; try { gsreader = new GeoServerRESTReader(gsInstance.getBaseURL(), gsInstance.getUsername(), gsInstance.getPassword()); RESTLayer layer = gsreader.getLayer(rule.getLayer()); if (layer.getType().equals(RESTLayer.TYPE.VECTOR)) { layerAttributes = new HashSet<LayerAttribute>(); // /////////////////////// // Vector Layer // /////////////////////// RESTFeatureType featureType = gsreader.getFeatureType(layer); for (RESTFeatureType.Attribute attribute : featureType.getAttributes()) { LayerAttribute attr = new LayerAttribute(); attr.setName(attribute.getName()); attr.setDatatype(attribute.getBinding()); layerAttributes.add(attr); } layerAttributesDTO = new ArrayList<LayerAttribUI>(); Iterator<LayerAttribute> iterator = layerAttributes.iterator(); while (iterator.hasNext()) { LayerAttribute layerAttribute = iterator.next(); LayerAttribUI layAttrUI = new LayerAttribUI(); layAttrUI.setName(layerAttribute.getName()); layAttrUI.setDataType(layerAttribute.getDatatype()); layerAttributesDTO.add(layAttrUI); } } else { // /////////////////////// // Raster Layer // /////////////////////// layerAttributesDTO = null; } } catch (MalformedURLException e) { logger.error(e.getMessage(), e); throw new ApplicationException(e.getMessage(), e); } return layerAttributesDTO; }
From source file:net.di2e.ecdr.commons.CDRMetacard.java
@Override public String getMetadata() { String metadata = null;/*w ww . ja v a2 s .c o m*/ // We can't call getString here because it will get in an endless loop because of the explicit checks in // getAttribute (for METADATA), so instead we check the values ourselves then try to pull from the link (on // demand) Attribute metadataAttribute = (wrappedMetacard != null) ? wrappedMetacard.getAttribute(METADATA) : map.get(METADATA); if (metadataAttribute == null || StringUtils.isBlank(getAttributeValue(metadataAttribute, String.class))) { URI metadataURI = getMetadataURL(); if (metadataURI != null) { try (InputStream in = metadataURI.toURL().openStream()) { metadata = IOUtils.toString(in); if (getAttribute(CDRMetacard.WRAP_METADATA) != null) { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); sb.append(metadata); sb.append("</xml>"); metadata = sb.toString(); } setAttribute(new AttributeImpl(Metacard.METADATA, metadata)); } catch (MalformedURLException e) { LOGGER.warn("Cannot read metadata due to Invalid metadata URL[" + metadataURI + "]: " + e.getMessage(), e); } catch (IOException e) { LOGGER.warn("Could not read metadata from remote URL[" + metadataURI + "] due to: " + e.getMessage(), e); } } } else { metadata = getAttributeValue(metadataAttribute, String.class); } return metadata; }
From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed try {/*ww w . j a v a 2s.co m*/ final Request request = _requestPanel.getRequest(); if (request == null) { return; } testButton.setEnabled(false); final Component parent = this; new SwingWorker() { public Object construct() { try { _sa.setRequest(request); _sa.fetchResponse(); return _sa.getResponse(); } catch (IOException ioe) { return ioe; } } //Runs on the event-dispatching thread. public void finished() { Object obj = getValue(); if (obj instanceof Response) { Response response = (Response) getValue(); if (response != null) { _responsePanel.setResponse(response); String name = nameTextField.getText(); String regex = regexTextField.getText(); try { Map<String, SessionID> ids = _sa.getIDsFromResponse(response, name, regex); String[] keys = ids.keySet().toArray(new String[0]); for (int i = 0; i < keys.length; i++) { SessionID id = ids.get(keys[i]); keys[i] = keys[i] + " = " + id.getValue(); } if (keys.length == 0) keys = new String[] { "No session identifiers found!" }; JOptionPane.showMessageDialog(parent, keys, "Extracted Sessionids", JOptionPane.INFORMATION_MESSAGE); } catch (PatternSyntaxException pse) { JOptionPane.showMessageDialog(parent, pse.getMessage(), "Patter Syntax Exception", JOptionPane.WARNING_MESSAGE); } } } else if (obj instanceof Exception) { JOptionPane.showMessageDialog(null, new String[] { "Error fetching response: ", obj.toString() }, "Error", JOptionPane.ERROR_MESSAGE); _logger.severe("Exception fetching response: " + obj); } testButton.setEnabled(true); } }.start(); } catch (MalformedURLException mue) { JOptionPane.showMessageDialog(this, new String[] { "The URL requested is malformed", mue.getMessage() }, "Malformed URL", JOptionPane.ERROR_MESSAGE); } catch (ParseException pe) { JOptionPane.showMessageDialog(this, new String[] { "The request is malformed", pe.getMessage() }, "Malformed Request", JOptionPane.ERROR_MESSAGE); } }
From source file:org.eclipse.b3.p2.maven.loader.Maven2RepositoryLoader.java
private boolean robotSafe(String baseURL, String path) throws CoreException { String robotStr = baseURL + "/robots.txt"; URL robotURL;/*w w w. jav a2s . c o m*/ try { robotURL = new URL(robotStr); } catch (MalformedURLException e) { throw ExceptionUtils.fromMessage(e.getMessage()); } StringBuilder commands = new StringBuilder(); InputStream robotStream = null; try { robotStream = robotURL.openStream(); byte buffer[] = new byte[1024]; int read; while ((read = robotStream.read(buffer)) != -1) commands.append(new String(buffer, 0, read)); } catch (IOException e) { // no robots.txt file => safe to crawl return true; } finally { if (robotStream != null) try { robotStream.close(); } catch (IOException e) { // ignore } } // search for "Disallow:" commands. int index = 0; String disallow = "Disallow:"; while ((index = commands.indexOf(disallow, index)) != -1) { index += disallow.length(); String commandPath = commands.substring(index); StringTokenizer tokenizer = new StringTokenizer(commandPath); if (!tokenizer.hasMoreTokens()) break; String disallowedPath = tokenizer.nextToken(); // if the URL starts with a disallowed path, it is not safe if (path.indexOf(disallowedPath) == 0) return false; } return true; }
From source file:TextureByReference.java
public void init() { if (urls == null) { urls = new java.net.URL[defaultFiles.length]; for (int i = 0; i < defaultFiles.length; i++) { try { urls[i] = new java.net.URL(getCodeBase().toString() + defaultFiles[i]); } catch (java.net.MalformedURLException ex) { System.out.println(ex.getMessage()); System.exit(1);/*from w w w .ja va 2 s . c om*/ } } } setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); Canvas3D canvas = new Canvas3D(config); add("Center", canvas); // create a simple scene graph and attach it to a simple universe BranchGroup scene = createSceneGraph(); universe = new SimpleUniverse(canvas); universe.getViewingPlatform().setNominalViewingTransform(); universe.addBranchGraph(scene); // create the gui JPanel gui = buildGui(); this.add("South", gui); }
From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java
/** * Initializes the request and specifies the method, URL, and authentication information for the request. * @param method the HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND; * for XMLHTTP, this parameter is not case-sensitive; the verbs TRACE and TRACK are not allowed. * @param url the requested URL; this can be either an absolute URL or a relative URL * @param asyncParam indicator of whether the call is asynchronous; the default is {@code true} (the call * returns immediately); if set to {@code true}, attach an <code>onreadystatechange</code> property * callback so that you can tell when the <code>send</code> call has completed * @param user the name of the user for authentication * @param password the password for authentication *///from ww w . ja v a 2 s . com @JsxFunction public void open(final String method, final Object url, final Object asyncParam, final Object user, final Object password) { if (method == null || "null".equals(method)) { throw Context.reportRuntimeError("Type mismatch (method is null)."); } if (url == null || "null".equals(url)) { throw Context.reportRuntimeError("Type mismatch (url is null)."); } state_ = STATE_UNSENT; openedMultipleTimes_ = webRequest_ != null; sent_ = false; webRequest_ = null; webResponse_ = null; if ("".equals(method) || "TRACE".equalsIgnoreCase(method)) { throw Context.reportRuntimeError("Invalid procedure call or argument (method is invalid)."); } if ("".equals(url)) { throw Context.reportRuntimeError("Invalid procedure call or argument (url is empty)."); } // defaults to true if not specified boolean async = true; if (asyncParam != Undefined.instance) { async = ScriptRuntime.toBoolean(asyncParam); } final String urlAsString = Context.toString(url); // (URL + Method + User + Password) become a WebRequest instance. containingPage_ = (HtmlPage) getWindow().getWebWindow().getEnclosedPage(); try { final URL fullUrl = containingPage_.getFullyQualifiedUrl(urlAsString); final WebRequest request = new WebRequest(fullUrl); request.setCharset("UTF-8"); request.setAdditionalHeader("Referer", containingPage_.getUrl().toExternalForm()); request.setHttpMethod(HttpMethod.valueOf(method.toUpperCase(Locale.ROOT))); // password is ignored if no user defined final boolean userIsNull = null == user || Undefined.instance == user; if (!userIsNull) { final String userCred = user.toString(); final boolean passwordIsNull = null == password || Undefined.instance == password; String passwordCred = ""; if (!passwordIsNull) { passwordCred = password.toString(); } request.setCredentials(new UsernamePasswordCredentials(userCred, passwordCred)); } webRequest_ = request; } catch (final MalformedURLException e) { LOG.error("Unable to initialize XMLHTTPRequest using malformed URL '" + urlAsString + "'."); return; } catch (final IllegalArgumentException e) { LOG.error("Unable to initialize XMLHTTPRequest using illegal argument '" + e.getMessage() + "'."); webRequest_ = null; } // Async stays a boolean. async_ = async; // Change the state! setState(STATE_OPENED, null); }
From source file:com.zimbra.cs.html.DefangFilter.java
/** * sanitize an attr value. For now, this means stirpping out Java Script entity tags &{...}, * and <script> tags./*from www. ja v a 2 s . c om*/ * * */ private void sanitizeAttrValue(String eName, String aName, XMLAttributes attributes, int i) { String value = attributes.getValue(i); boolean canAllowScript = ATTRIBUTES_CAN_ALLOW_SCRIPTS.contains(aName.toLowerCase()); String result = sanitize(value, canAllowScript); if (aName.equalsIgnoreCase("style")) { result = sanitizeStyleValue(value); } if (!result.equals(value)) { attributes.setValue(i, result); } if (aName.equalsIgnoreCase("action") && sameHostFormPostCheck == true && this.reqVirtualHost != null) { try { URL url = new URL(value); String formActionHost = url.getHost().toLowerCase(); if (formActionHost.equalsIgnoreCase(reqVirtualHost)) { value = value.replace(formActionHost, "SAMEHOSTFORMPOST-BLOCKED"); attributes.setValue(i, value); } } catch (MalformedURLException e) { ZimbraLog.soap.info("Failure while trying to block mailicious code. Check for URL " + " match between the host and the action URL of a FORM." + "Error parsing URL, possible relative URL." + e.getMessage()); attributes.setValue(i, "SAMEHOSTFORMPOST-BLOCKED"); } } }
From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java
/** * Detect Header manager in subConfigs,// w w w. j a va2 s . c om * Find(if any) Authorization header * Construct Authentication object * Removes Authorization if present * * @param subConfigs {@link TestElement}[] * @param sampler {@link HTTPSamplerBase} * @return {@link Authorization} */ private Authorization createAuthorization(final TestElement[] subConfigs, HTTPSamplerBase sampler) { Header authHeader; Authorization authorization = null; // Iterate over subconfig elements searching for HeaderManager for (TestElement te : subConfigs) { if (te instanceof HeaderManager) { List<TestElementProperty> headers = (ArrayList<TestElementProperty>) ((HeaderManager) te) .getHeaders().getObjectValue(); for (Iterator<?> iterator = headers.iterator(); iterator.hasNext();) { TestElementProperty tep = (TestElementProperty) iterator.next(); if (tep.getName().equals(HTTPConstants.HEADER_AUTHORIZATION)) { //Construct Authorization object from HEADER_AUTHORIZATION authHeader = (Header) tep.getObjectValue(); String[] authHeaderContent = authHeader.getValue().split(" ");//$NON-NLS-1$ String authType = null; String authCredentialsBase64; if (authHeaderContent.length >= 2) { authType = authHeaderContent[0]; authCredentialsBase64 = authHeaderContent[1]; authorization = new Authorization(); try { authorization.setURL(sampler.getUrl().toExternalForm()); } catch (MalformedURLException e) { LOG.error("Error filling url on authorization, message:" + e.getMessage(), e); authorization.setURL("${AUTH_BASE_URL}");//$NON-NLS-1$ } // if HEADER_AUTHORIZATION contains "Basic" // then set Mechanism.BASIC_DIGEST, otherwise Mechanism.KERBEROS authorization.setMechanism(authType.equals(BASIC_AUTH) || authType.equals(DIGEST_AUTH) ? AuthManager.Mechanism.BASIC_DIGEST : AuthManager.Mechanism.KERBEROS); if (BASIC_AUTH.equals(authType)) { String authCred = new String(Base64.decodeBase64(authCredentialsBase64)); String[] loginPassword = authCred.split(":"); //$NON-NLS-1$ authorization.setUser(loginPassword[0]); authorization.setPass(loginPassword[1]); } else { // Digest or Kerberos authorization.setUser("${AUTH_LOGIN}");//$NON-NLS-1$ authorization.setPass("${AUTH_PASSWORD}");//$NON-NLS-1$ } } // remove HEADER_AUTHORIZATION from HeaderManager // because it's useless after creating Authorization object iterator.remove(); } } } } return authorization; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.FedoraDatastreamController.java
/** * The get will present a form to the user. *//*from w w w . ja va 2 s. c om*/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { try { super.doGet(req, res); log.debug("In doGet"); VitroRequest vreq = new VitroRequest(req); OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel(); synchronized (FedoraDatastreamController.class) { if (fedoraUrl == null) { setup(sessionOntModel, getServletContext()); if (fedoraUrl == null) throw new FdcException("Connection to the file repository is " + "not setup correctly. Could not read fedora.properties file"); } else { if (!canConnectToFedoraServer()) { fedoraUrl = null; throw new FdcException("Could not connect to Fedora."); } } } FedoraClient fedora; try { fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword); } catch (MalformedURLException e) { throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl); } FedoraAPIM apim; try { apim = fedora.getAPIM(); } catch (Exception e) { throw new FdcException("could not create fedora APIM:" + e.getMessage()); } //check if logged in //get URI for file individual if (req.getParameter("uri") == null || "".equals(req.getParameter("uri"))) throw new FdcException("No file uri specified in request"); boolean isDelete = (req.getParameter("delete") != null && "true".equals(req.getParameter("delete"))); String fileUri = req.getParameter("uri"); //check if file individual has a fedora:PID for a data stream IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao(); Individual entity = iwDao.getIndividualByURI(fileUri); if (entity == null) throw new FdcException("No entity found in system for file uri " + fileUri); //System.out.println("Entity == null:" + (entity == null)); //get the fedora PID //System.out.println("entity data property " + entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID)); if (entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID) == null) throw new FdcException("No fedora:pid found in system for file uri " + fileUri); List<DataPropertyStatement> stmts = entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID) .getDataPropertyStatements(); if (stmts == null || stmts.size() == 0) throw new FdcException("No fedora:pid found in system for file uri " + fileUri); String pid = null; for (DataPropertyStatement stmt : stmts) { if (stmt.getData() != null && stmt.getData().length() > 0) { pid = stmt.getData(); break; } } //System.out.println("pid is " + pid + " and comparison is " + (pid == null)); if (pid == null) throw new FdcException("No fedora:pid found in system for file uri " + fileUri); req.setAttribute("pid", pid); req.setAttribute("fileUri", fileUri); //get current file name to use on form req.setAttribute("fileName", entity.getName()); if (isDelete) { //Execute a 'deletion', i.e. unlink dataset and file, without removing file //Also save deletion as a deleteEvent entity which can later be queried String datasetUri = null; //Get dataset uri by getting the fromDataSet property edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty fromDataSet = entity.getObjectPropertyMap() .get(fedoraNs + "fromDataSet"); if (fromDataSet != null) { List<ObjectPropertyStatement> fromDsStmts = fromDataSet.getObjectPropertyStatements(); if (fromDsStmts.size() > 0) { datasetUri = fromDsStmts.get(0).getObjectURI(); //System.out.println("object uri should be " + datasetUri); } else { //System.out.println("No matching dataset uri could be found"); } } else { //System.out.println("From dataset is null"); } req.setAttribute("dataseturi", datasetUri); boolean success = deleteFile(req, entity, iwDao, sessionOntModel); req.setAttribute("deletesuccess", (success) ? "success" : "error"); req.setAttribute("bodyJsp", "/edit/fileDeleteConfirm.jsp"); RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP); rd.forward(req, res); } else { //check if the data stream exists in the fedora repository Datastream ds = apim.getDatastream(pid, DEFAULT_DSID, null); if (ds == null) throw new FdcException( "There was no datastream in the " + "repository for " + pid + " " + DEFAULT_DSID); req.setAttribute("dsid", DEFAULT_DSID); //forward to form req.setAttribute("bodyJsp", "/fileupload/datastreamModification.jsp"); RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP); rd.forward(req, res); } } catch (FdcException ex) { req.setAttribute("errors", ex.getMessage()); RequestDispatcher rd = req.getRequestDispatcher("/edit/fileUploadError.jsp"); rd.forward(req, res); return; } }
From source file:com.xpn.xwiki.render.macro.rss.RSSMacro.java
/** * Transform the input parameters into <code>RSSMacroParameters</code> object. * /* w w w . java2 s.c o m*/ * @param parameter the parameters as prepared by the Radeox system. * @throws java.lang.IllegalArgumentException if the 'feed' named parameter is missing, or is a malformed URL, or if * any of the other parameter values are not of the correct types. Note that unknown parameters will * simply be ignored, and all parameters must be passed using names. * @return a parameters helper object * @see RSSMacroParameters */ private RSSMacroParameters processParameters(MacroParameter parameter) throws java.lang.IllegalArgumentException { Map<String, String> paramMap = new HashMap<String, String>(); RSSMacroParameters paramObj = new RSSMacroParameters(); String feedURLString = parameter.get("feed"); if (feedURLString == null) { throw new IllegalArgumentException( "Requires at least one named parameter,'feed', a URL of an RSS feed."); } try { paramObj.setFeed(feedURLString); } catch (MalformedURLException ex) { Logger.warn("Invalid feed URL: " + feedURLString); throw new IllegalArgumentException("Invalid feed URL: " + feedURLString); } for (int i = 0; i < PARAM_NAMES.length; i++) { String paramName = parameter.get(PARAM_NAMES[i]); if (paramName != null) { paramMap.put(PARAM_NAMES[i], paramName); } } try { BeanUtils.populate(paramObj, paramMap); } catch (NoClassDefFoundError e) { throw new IllegalStateException("Some libraries are not installed: " + e.getMessage()); } catch (Exception ex) { throw new IllegalArgumentException("Error processing arguments: " + ex.getMessage()); } return paramObj; }