List of usage examples for java.net MalformedURLException MalformedURLException
public MalformedURLException()
From source file:com.github.benchdoos.weblocopener.weblocOpener.gui.EditDialog.java
private void onOK() { try {//from w w w . j ava 2 s . c o m URL url = new URL(textField.getText()); UrlValidator urlValidator = new UrlValidator(); if (urlValidator.isValid(textField.getText())) { UrlsProceed.createWebloc(path, url); dispose(); } else { throw new MalformedURLException(); } } catch (MalformedURLException e) { log.warn("Can not parse URL: [" + textField.getText() + "]", e); String message = incorrectUrlMessage + ": ["; String incorrectUrl = textField.getText().substring(0, Math.min(textField.getText().length(), 10)); //Fixes EditDialog long url message showing issue message += textField.getText().length() > incorrectUrl.length() ? incorrectUrl + "...]" : incorrectUrl + "]"; UserUtils.showWarningMessageToUser(this, errorTitle, message); } }
From source file:org.bibsonomy.webapp.controller.admin.AdminRecommenderController.java
private void handleAddRecommender(final AdminRecommenderViewCommand command) { try {/* w w w.j av a 2 s.c o m*/ if (!UrlUtils.isValid(command.getNewrecurl())) { throw new MalformedURLException(); } mp.addRecommender(new URL(command.getNewrecurl())); command.setAdminResponse("Successfully added and activated new recommender!"); } catch (final MalformedURLException e) { command.setAdminResponse("Could not add new recommender. Please check if '" + command.getNewrecurl() + "' is a valid url."); } catch (final Exception e) { log.error("Error testing 'set recommender'", e); command.setAdminResponse("Failed to add new recommender"); } command.setTab(Tab.ADD); }
From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java
/** * Send REST call/*w ww .j ava 2 s. c o m*/ */ public boolean sendRESTCall(String url, String urlParameters) throws IOException { HttpsURLConnection connection = null; try { URL smsProviderUrl = new URL(url + urlParameters); connection = (HttpsURLConnection) smsProviderUrl.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod(SMSOTPConstants.HTTP_METHOD); if (connection.getResponseCode() == 200) { if (log.isDebugEnabled()) { log.debug("Code is successfully sent to your mobile number"); } return true; } connection.disconnect(); } catch (MalformedURLException e) { if (log.isDebugEnabled()) { log.error("Invalid URL", e); } throw new MalformedURLException(); } catch (ProtocolException e) { if (log.isDebugEnabled()) { log.error("Error while setting the HTTP method", e); } throw new ProtocolException(); } catch (IOException e) { if (log.isDebugEnabled()) { log.error("Error while getting the HTTP response", e); } throw new IOException(); } finally { connection.disconnect(); } return false; }
From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelperTest.java
@Test public void testInvokePluginEndpoint() throws Exception { Response r;//from w w w .j a va 2s .co m String pluginName = "platform", endpointPath = "myEndpoint", httpMethod = "GET"; Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("param1", "value1"); queryParameters.put("param2", "value2"); queryParameters.put("param3", "value3"); doReturn(null).when(httpConnectionHelperSpy).getPluginManager(); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertEquals(r.getResult(), (new Response()).getResult()); IPluginManager pluginManager = mock(IPluginManager.class); doReturn(pluginManager).when(httpConnectionHelperSpy).getPluginManager(); doReturn(null).when(httpConnectionHelperSpy).getPluginClassLoader(pluginName, pluginManager); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertEquals(r.getResult(), (new Response()).getResult()); ClassLoader pluginClassLoader = mock(ClassLoader.class); doReturn(pluginClassLoader).when(httpConnectionHelperSpy).getPluginClassLoader(pluginName, pluginManager); doReturn(null).when(httpConnectionHelperSpy).getListableBeanFactory(pluginName, pluginManager); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertEquals(r.getResult(), (new Response()).getResult()); ListableBeanFactory beanFactory = mock(ListableBeanFactory.class); doReturn(beanFactory).when(httpConnectionHelperSpy).getListableBeanFactory(pluginName, pluginManager); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertEquals(r.getResult(), (new Response()).getResult()); JAXRSPluginServlet pluginServlet = mock(JAXRSPluginServlet.class); doReturn(pluginServlet).when(httpConnectionHelperSpy).getJAXRSPluginServlet(beanFactory); doThrow(new MalformedURLException()).when(httpConnectionHelperSpy).getUrl(); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertTrue(r.getResult().equals(new Response().getResult())); String serverUrl = "http://localhost:8080/pentaho"; URL url = new URL(serverUrl); doReturn(url).when(httpConnectionHelperSpy).getUrl(); doThrow(new ServletException()).when(pluginServlet).service(any(InternalHttpServletRequest.class), any(InternalHttpServletResponse.class)); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertTrue(r.getResult().equals(new Response().getResult())); doThrow(new IOException()).when(pluginServlet).service(any(InternalHttpServletRequest.class), any(InternalHttpServletResponse.class)); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertTrue(r.getResult().equals(new Response().getResult())); doNothing().when(pluginServlet).service(any(InternalHttpServletRequest.class), any(InternalHttpServletResponse.class)); r = httpConnectionHelperSpy.invokePluginEndpoint(pluginName, endpointPath, httpMethod, queryParameters); assertEquals(r.getStatusCode(), 404); assertEquals(r.getResponseTime(), 0); }
From source file:org.mulesoft.restx.clientapi.RestxServer.java
/** * Create a new client-side representation of a RestxServer. A request is sent * for the server's meta data information. Some basic sanity checking is * performed on the received data.//from w w w . j a v a2s . co m * * @param serverUri The absolute URI at which the server can be found. For * example: "http://localhost:8001". * @throws MalformedURLException * @throws RestxClientException */ public RestxServer(String serverUri) throws MalformedURLException, RestxClientException { // Don't need any trailing '/' int i = serverUri.length() - 1; while (i > 0 && serverUri.charAt(i) == '/') { --i; } if (i > 0) { serverUri = serverUri.substring(0, i + 1); } else { throw new MalformedURLException(); } this.serverUri = serverUri; DEFAULT_REQ_HEADERS = new HashMap<String, String>(); DEFAULT_REQ_HEADERS.put("Accept", "application/json"); final URL url = new URL(serverUri); // Some sanity checking on the URI. this.serverUri = url.getProtocol() + "://" + url.getHost(); if (url.getPort() > -1) { this.serverUri += ":" + Integer.toString(url.getPort()); } if (!url.getPath().isEmpty()) { docRoot = url.getPath(); } else { docRoot = ""; } if (!url.getProtocol().equals("http")) { throw new RestxClientException("Only 'http' schema is currently supported."); } // Receive server meta data final HttpResult res = jsonSend(docRoot + META_URI, null, HttpMethod.GET, 200, null); @SuppressWarnings("unchecked") final Map<String, String> hm = (Map<String, String>) res.data; // Sanity check on received information try { checkKeyset(hm, REQUIRED_KEYS); } catch (final RestxClientException e) { throw new RestxClientException("Server error: Malformed server meta data: " + e.getMessage()); } // Store the meta data for later use try { componentUri = hm.get(CODE_URI_KEY); docUri = hm.get(DOC_URI_KEY); name = hm.get(NAME_KEY); resourceUri = hm.get(RESOURCE_URI_KEY); specializedUri = hm.get(SPECIALIZED_URI_KEY); staticUri = hm.get(STATIC_URI_KEY); version = hm.get(VERSION_KEY); } catch (final Exception e) { throw new RestxClientException("Malformed server meta data: " + e.getMessage()); } doc = null; resources = null; components = null; }
From source file:org.jboss.pressgang.ccms.contentspec.client.commands.BuildCommandTest.java
@Test public void shouldShutdownWhenGetPubsnumberFromKojiWithInvalidURL() throws MalformedURLException, KojiException { final ContentSpecProcessor processor = mock(ContentSpecProcessor.class); // Given a command with an id command.setIds(Arrays.asList(id.toString())); // and the content spec exists given(contentSpecProvider.getContentSpec(anyInt(), anyInt())).willReturn(contentSpecWrapper); given(contentSpecWrapper.getChildren()).willReturn(contentSpecChildren); given(contentSpecChildren.isEmpty()).willReturn(false); // and the transform works PowerMockito.mockStatic(CSTransformer.class); final ContentSpec contentSpec = new ContentSpec(); when(CSTransformer.transform(eq(contentSpecWrapper), eq(providerFactory), anyBoolean())) .thenReturn(contentSpec);/* ww w.j a va 2 s . c o m*/ // and a valid content spec given(processor.processContentSpec(any(ContentSpec.class), anyString(), any(ContentSpecParser.ParsingMode.class))).willReturn(true); given(command.getCsp()).willReturn(processor); // and the fetch pubsnumber is set command.setFetchPubsnum(true); PowerMockito.mockStatic(ClientUtilities.class); when(ClientUtilities.getPubsnumberFromKoji(any(ContentSpec.class), anyString(), anyString())) .thenThrow(new MalformedURLException()); // and the helper method to get the content spec works TestUtil.setUpContentSpecHelper(contentSpecProvider); // and getting error messages works TestUtil.setUpMessages(); ; // When processing the command try { command.process(); // Then an error is printed and the program is shut down fail(SYSTEM_EXIT_ERROR); } catch (CheckExitCalled e) { assertThat(e.getStatus(), is(4)); } // Then check that an error was printed assertThat(getStdOutLogs(), containsString("Fetching the pubsnumber from " + Constants.KOJI_NAME + "...")); assertThat(getStdOutLogs(), containsString("The " + Constants.KOJI_NAME + " Hub URL is invalid or is blank. Please ensure that the URL is valid.")); }
From source file:com.funambol.admin.settings.panels.EditServerConfigurationPanel.java
/** * Validates the inputs anf throws an Exception in case of any invalid data. * * @throws IllegalArgumentException in case of invalid input */// ww w. ja va 2 s . c om private void validateInput() throws IllegalArgumentException { String value = null; value = man.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_MAN) }); throw new IllegalArgumentException(msg); } value = mod.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_MOD) }); throw new IllegalArgumentException(msg); } value = swV.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_SWV) }); throw new IllegalArgumentException(msg); } value = hwV.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_HWV) }); throw new IllegalArgumentException(msg); } value = fwV.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_FWV) }); throw new IllegalArgumentException(msg); } value = oem.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_OEM) }); throw new IllegalArgumentException(msg); } value = devId.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_DEV_ID) }); throw new IllegalArgumentException(msg); } value = devTyp.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_DEV_TYP) }); throw new IllegalArgumentException(msg); } value = verDTD.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_VER_DTD) }); throw new IllegalArgumentException(msg); } value = serverUri.getText(); if (StringUtils.isNotEmpty(value)) { try { // // Checks if serverURI is a well formed URI. // Used the URL because the URI does not throw // URISyntaxException in some cases when expected // (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4668181) // URL url = new URL(value); // // The serverUri must start with http:// or https:// in order to // be used as a valid URL // if (!value.startsWith("http://") && !value.startsWith("https://")) { throw new MalformedURLException(); } } catch (MalformedURLException e) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_SERVER_URI_NOT_VALID), new String[] { value }); throw new IllegalArgumentException(msg); } } value = officer.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_OFFICER) }); throw new IllegalArgumentException(msg); } value = deviceInventory.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_DEVICE_INVENTORY) }); throw new IllegalArgumentException(msg); } value = handler.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_HANDLER) }); throw new IllegalArgumentException(msg); } value = strategy.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_STRATEGY) }); throw new IllegalArgumentException(msg); } value = userManager.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_USER_MANAGER) }); throw new IllegalArgumentException(msg); } value = smsService.getText(); if (StringUtils.isEmpty(value)) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_EMPTY_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_SMS_SERVICE) }); throw new IllegalArgumentException(msg); } try { int i = Integer.parseInt(minMaxMsgSize.getText()); if (i < 1 || i > 100000) { throw new NumberFormatException(); } } catch (NumberFormatException e) { String msg = MessageFormat.format(Bundle.getMessage(Bundle.ERROR_NUMERIC_INPUT), new String[] { Bundle.getMessage(Bundle.LABEL_MIN_MAX_MSG_SIZE), "1", String.valueOf("100000") }); throw new IllegalArgumentException(msg); } }
From source file:org.lockss.util.UrlUtil.java
private static MalformedURLException newMalformedURLException(Throwable cause) { MalformedURLException ex = new MalformedURLException(); ex.initCause(cause);//from w ww. j a v a2 s. co m return ex; }
From source file:org.opentravel.schemacompiler.repository.RepositoryManager.java
/** * @see org.opentravel.schemacompiler.repository.Repository#createRootNamespace(java.lang.String) *//*www . j a va2s. co m*/ @Override public void createRootNamespace(String rootNamespace) throws RepositoryException { String rootNS = RepositoryNamespaceUtils.normalizeUri(rootNamespace); boolean success = false; try { fileManager.startChangeSet(); File rootNSFolder = fileManager.getNamespaceFolder(rootNS, null); File nsidFile = new File(rootNSFolder, RepositoryFileManager.NAMESPACE_ID_FILENAME); // Validation Check - Make sure the namespace follows a proper URL format try { URL nsUrl = new URL(rootNamespace); if ((nsUrl.getProtocol() == null) || (nsUrl.getAuthority() == null)) { throw new MalformedURLException(); // URLs without protocols or authorities are // not valid for the repository } if (rootNamespace.indexOf('?') >= 0) { throw new RepositoryException("Query strings are not allowed on root namespace URIs."); } } catch (MalformedURLException e) { throw new RepositoryException("The root namespace does not conform to the required URI format."); } // Validation Check - Look for a file conflict with an existing namespace if (nsidFile.exists()) { throw new RepositoryException( "The root namespace cannot be created because it conflicts with an existing one."); } // Validation Check - Check to see if the new root is a parent or child of an existing // root namespace String repositoryBaseFolder = fileManager.getRepositoryLocation().getAbsolutePath(); List<String> existingRootNSFolderPaths = new ArrayList<String>(); String rootNSTestPath = rootNSFolder.getAbsolutePath(); if (!rootNSTestPath.endsWith("/")) { rootNSTestPath += "/"; } for (String existingRootNS : listRootNamespaces()) { File existingRootNSFolder = fileManager.getNamespaceFolder(existingRootNS, null); if (rootNSTestPath.startsWith(existingRootNSFolder.getAbsolutePath())) { throw new RepositoryException( "The root namespace cannot be created because it conflicts with an existing one."); } while ((existingRootNSFolder != null) && !repositoryBaseFolder.equals(existingRootNSFolder.getAbsolutePath())) { existingRootNSFolderPaths.add(existingRootNSFolder.getAbsolutePath()); existingRootNSFolder = existingRootNSFolder.getParentFile(); } } if (existingRootNSFolderPaths.contains(rootNSFolder.getAbsolutePath())) { throw new RepositoryException( "The root namespace cannot be created because it conflicts with an existing one."); } // Create the new root namespace if all of the validation checks passed fileManager.createNamespaceIdFiles(rootNS); rootNamespaces.add(rootNS); saveLocalRepositoryMetadata(); success = true; log.info("Successfully created root namespace: " + rootNS + " by " + fileManager.getCurrentUserId()); } finally { // Commit or roll back the changes based on the result of the operation if (success) { fileManager.commitChangeSet(); } else { try { fileManager.rollbackChangeSet(); } catch (Throwable t) { log.error("Error rolling back the current change set.", t); } } } }
From source file:com.isencia.passerelle.hmi.HMIBase.java
/** * Given the name of a file or a URL, convert it to a URL. This first * attempts to do that directly by invoking a URL constructor. If that * fails, then it tries to interpret the spec as a file name on the local * file system. If that fails, then it tries to interpret the spec as a * resource accessible to the classloader, which uses the classpath to find * the resource. If that fails, then it throws an exception. The * specification can give a file name relative to current working directory, * or the directory in which this application is started up. * // www .ja v a 2 s. c o m * @param spec * The specification. * @exception IOException * If it cannot convert the specification to a URL. */ public static URL specToURL(final String spec) throws IOException { try { // First argument is null because we are only // processing absolute URLs this way. Relative // URLs are opened as ordinary files. return new URL(null, spec); } catch (final MalformedURLException ex) { try { final File file = new File(spec); if (!file.exists()) { throw new MalformedURLException(); } return file.getCanonicalFile().toURL(); } catch (final MalformedURLException ex2) { try { // Try one last thing, using the classpath. // Need a class context, and this is a static method, so... // NOTE: There doesn't seem to be any way to convert // this a canonical name, so if a model is opened this // way, and then later opened as a file, the model // directory will think it has two different files. final Class refClass = Class.forName("ptolemy.kernel.util.NamedObj"); final URL inurl = refClass.getClassLoader().getResource(spec); if (inurl == null) { throw new Exception(); } else { return inurl; } } catch (final Exception exception) { throw new IOException("File not found: " + spec); } } } }