List of usage examples for java.net MalformedURLException MalformedURLException
public MalformedURLException(String msg)
From source file:org.nordapp.web.servlet.IOServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//ww w. j a v a 2 s .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(); ctrl.setAll(); ctrl.saveTempSession(); // // Session service // 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(); //String sessionId = session.getId(); mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); String[] elem = RequestPath.getPath(req); if (elem.length != 2) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "/function-id/file-uuid' but was '" + req.getRequestURI() + "'"); BigInteger engineId = ctrl.decodeCert(); String functionId = elem.length >= 1 ? elem[0] : null; String fileUuid = elem.length >= 2 ? elem[1] : null; mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.getCertID()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } DatabaseService dbService = DatabaseServiceImpl.getDatabase(context, cert, ctrl.getMandatorID()); if (dbService == null) { throw new UnavailableException( "Needs a valid database service for mandator " + ctrl.getMandatorID() + "."); } ResponseHandler rsHdl = new ResponseHandler(context, ctrl); Map<String, String> headers = new HashMap<String, String>(); try { // // Gets the engine base service // EngineBaseService engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(), String.valueOf(baseIndex)); if (engineBaseService == null) throw new IOException( "The mandator base service is not available (maybe down or a version conflict)."); // // Run the step // Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) throw new IOException( "The mandator service is not available (maybe down or a version conflict)."); Engine engine = engineBaseService.getEngine(engineId); if (!engine.isLogin()) throw new IllegalAccessException("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()); ioc.setField(openFileByID, fileUuid); engine.setLocalValue(httpIOContainer, ioc); // // Call script // try { engine.call(functionId); } catch (Exception e) { e.printStackTrace(); } //Prints a file out //rsHdl.getSessionData(buffer, mSession); InputStream in = null; try { //DbDatabase dbs = dbService.getDatabase(); //DbFileStore dbf = dbs.getFileStore(); //DbFile file = dbf.getFileFromId( (String)engine.getLocalValue(openFileByRef) ); String[] fn = ioc.getFilenames(); if (fn.length == 0) throw new IllegalArgumentException("There is no file specified to open (empty array)."); DbFile file = (DbFile) ioc.getFile(fn[0]); in = file.getInputStream(); headers.put("Content-Type", file.getMimetype()); headers.put("Content-Length", String.valueOf(file.getLength())); rsHdl.avoidCaching(resp); rsHdl.sendFile(in, resp, headers); } finally { if (in != null) in.close(); ioc.cleanup(); engine.setLocalValue(httpSessionID, null); engine.setLocalValue(httpProcessID, null); engine.setLocalValue(httpIOContainer, null); } } catch (Exception e) { logger.error("Error running the step.", e); } } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.apache.nutch.watchlist.jcrew.JCrewParser.java
/** * Scan the HTML document looking at product information */// w ww . j av a 2s.c o m public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { String itemNumber = null; // Step 1: ignore non-product pages from JCrew URL base; try { base = new URL(content.getBaseUrl()); if (LOG.isInfoEnabled()) { LOG.info("Start parsing: " + base.toString()); } Matcher matcher = urlRegexp.matcher(base.toString()); if (matcher.find()) { int major, minor; major = Integer.parseInt(matcher.group(1)); minor = Integer.parseInt(matcher.group(2)); if (major != minor) { throw new MalformedURLException("URL Product Item number doesn't match."); } else { // We got the Product Item number from the URL itemNumber = Integer.toString(major); } } else { // matcher cannot find it throw new MalformedURLException("URL is not a JCrew Product Page."); } } catch (Exception e) { return parseResult; } // Step 2: Extract the Product Title LOG.info("Started parsing title for JCrew Product Item: " + itemNumber); try { // Trying to find the document's rel-tags Parser parser = new Parser(doc, itemNumber); String productTitle = parser.getProductTitle(); String price = parser.getPrice(); String imgURL = parser.getImageURL(); if (productTitle != null && price != null && imgURL != null) { // Parse successful Parse parse = parseResult.get(content.getUrl()); Metadata meta = parse.getData().getContentMeta(); // 1. associate meta data to the index of this page LOG.info("Adding brand: jcrew"); meta.add(META_BRAND, "jcrew"); LOG.info("Adding item: " + itemNumber); meta.add(META_ITEMNUM, itemNumber); LOG.info("Adding productTitle: " + productTitle); meta.add(META_PRODUCT_TITLE, productTitle); LOG.info("Adding price: " + price); meta.add(META_PRICE, price); LOG.info("Adding imgURL: " + imgURL); meta.add(META_IMG_URL, imgURL); String htmlProductTitle = parse.getData().getTitle(); LOG.info("Adding jcrew title: " + htmlProductTitle); meta.add(META_JCREW_TITLE, htmlProductTitle); // 2. write these information into database long id = idGenerator.generate(""); LOG.info("Got ID: " + id); } else { long id = idGenerator.generate(""); LOG.info("Got ID: " + id); // At least something wrong if (LOG.isWarnEnabled()) { LOG.warn("Partially parsed " + base + ": "); if (productTitle == null) { LOG.warn("productTitle is null."); } if (price == null) { LOG.warn("price is null."); } if (imgURL == null) { LOG.warn("imgURL is null."); } } } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to parse: " + base + ": " + e); e.printStackTrace(); } // e.printStackTrace(); return parseResult; } // Finally, log the finish of parsing this product LOG.info("Finished parsing title for JCrew Product Item: " + itemNumber); return parseResult; }
From source file:api.wireless.gdata.docs.client.DocsClient.java
public FolderEntry getFolderByTitle(String title) throws ServiceException, IOException, ParseException { String[] parameters = null;/*from ww w.j ava 2 s. c o m*/ try { parameters = new String[] { "title=" + URLEncoder.encode(title, "UTF-8"), "showfolders=true" }; } catch (UnsupportedEncodingException e) { throw new MalformedURLException("Unable to create parameters"); } URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED, parameters); FolderEntry fld = null; Feed<FolderEntry> flds = getFeed(FolderEntry.class, url); if (flds.getEntries().size() > 0) fld = flds.getEntries().get(0); return fld; }
From source file:org.openmrs.module.web.controller.ModuleListController.java
/** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db/* w w w . j a v a2 s .co m*/ * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(HttpServletRequest, * HttpServletResponse, Object, * BindException) */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { if (!Context.hasPrivilege(PrivilegeConstants.MANAGE_MODULES)) { throw new APIAuthenticationException("Privilege required: " + PrivilegeConstants.MANAGE_MODULES); } HttpSession httpSession = request.getSession(); String moduleId = ServletRequestUtils.getStringParameter(request, "moduleId", ""); String view = getFormView(); String success = ""; String error = ""; MessageSourceAccessor msa = getMessageSourceAccessor(); String action = ServletRequestUtils.getStringParameter(request, "action", ""); if (ServletRequestUtils.getStringParameter(request, "start.x", null) != null) { action = "start"; } else if (ServletRequestUtils.getStringParameter(request, "stop.x", null) != null) { action = "stop"; } else if (ServletRequestUtils.getStringParameter(request, "unload.x", null) != null) { action = "unload"; } // handle module upload if ("upload".equals(action)) { // double check upload permissions if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowUploads", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } else { InputStream inputStream = null; File moduleFile = null; Module module = null; Boolean updateModule = ServletRequestUtils.getBooleanParameter(request, "update", false); Boolean downloadModule = ServletRequestUtils.getBooleanParameter(request, "download", false); List<Module> dependentModulesStopped = null; try { if (downloadModule) { String downloadURL = request.getParameter("downloadURL"); if (downloadURL == null) { throw new MalformedURLException("Couldn't download module because no url was provided"); } String fileName = downloadURL.substring(downloadURL.lastIndexOf("/") + 1); final URL url = new URL(downloadURL); inputStream = ModuleUtil.getURLStream(url); moduleFile = ModuleUtil.insertModuleFile(inputStream, fileName); } else if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartModuleFile = multipartRequest.getFile("moduleFile"); if (multipartModuleFile != null && !multipartModuleFile.isEmpty()) { String filename = WebUtil.stripFilename(multipartModuleFile.getOriginalFilename()); // if user is using the "upload an update" form instead of the main form if (updateModule) { // parse the module so that we can get the id Module tmpModule = new ModuleFileParser(multipartModuleFile.getInputStream()) .parse(); Module existingModule = ModuleFactory.getModuleById(tmpModule.getModuleId()); if (existingModule != null) { dependentModulesStopped = ModuleFactory.stopModule(existingModule, false, true); // stop the module with these parameters so that mandatory modules can be upgraded for (Module depMod : dependentModulesStopped) { WebModuleUtil.stopModule(depMod, getServletContext()); } WebModuleUtil.stopModule(existingModule, getServletContext()); ModuleFactory.unloadModule(existingModule); } inputStream = new FileInputStream(tmpModule.getFile()); moduleFile = ModuleUtil.insertModuleFile(inputStream, filename); // copy the omod over to the repo folder } else { // not an update, or a download, just copy the module file right to the repo folder inputStream = multipartModuleFile.getInputStream(); moduleFile = ModuleUtil.insertModuleFile(inputStream, filename); } } } module = ModuleFactory.loadModule(moduleFile); } catch (ModuleException me) { log.warn("Unable to load and start module", me); error = me.getMessage(); } finally { // clean up the module repository folder try { if (inputStream != null) { inputStream.close(); } } catch (IOException io) { log.warn("Unable to close temporary input stream", io); } if (module == null && moduleFile != null) { moduleFile.delete(); } } // if we didn't have trouble loading the module, start it if (module != null) { ModuleFactory.startModule(module); WebModuleUtil.startModule(module, getServletContext(), false); if (module.isStarted()) { success = msa.getMessage("Module.loadedAndStarted", new String[] { module.getName() }); if (updateModule && dependentModulesStopped != null) { for (Module depMod : sortStartupOrder(dependentModulesStopped)) { ModuleFactory.startModule(depMod); WebModuleUtil.startModule(depMod, getServletContext(), false); } } } else { success = msa.getMessage("Module.loaded", new String[] { module.getName() }); } } } } else if ("".equals(moduleId)) { if (action.equals(msa.getMessage("Module.startAll"))) { boolean someModuleNeedsARefresh = false; Collection<Module> modules = ModuleFactory.getLoadedModules(); Collection<Module> modulesInOrder = ModuleFactory.getModulesInStartupOrder(modules); for (Module module : modulesInOrder) { if (ModuleFactory.isModuleStarted(module)) { continue; } ModuleFactory.startModule(module); boolean thisModuleCausesRefresh = WebModuleUtil.startModule(module, getServletContext(), true); someModuleNeedsARefresh = someModuleNeedsARefresh || thisModuleCausesRefresh; } if (someModuleNeedsARefresh) { WebModuleUtil.refreshWAC(getServletContext(), false, null); } } else { ModuleUtil.checkForModuleUpdates(); } } else if (action.equals(msa.getMessage("Module.installUpdate"))) { // download and install update if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowAdministration", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } Module mod = ModuleFactory.getModuleById(moduleId); if (mod.getDownloadURL() != null) { ModuleFactory.stopModule(mod, false, true); // stop the module with these parameters so that mandatory modules can be upgraded WebModuleUtil.stopModule(mod, getServletContext()); Module newModule = ModuleFactory.updateModule(mod); WebModuleUtil.startModule(newModule, getServletContext(), false); } } else { // moduleId is not empty if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowAdministration", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } else { log.debug("Module id: " + moduleId); Module mod = ModuleFactory.getModuleById(moduleId); // Argument to pass to the success/error message Object[] args = new Object[] { moduleId }; if (mod == null) { error = msa.getMessage("Module.invalid", args); } else { if ("stop".equals(action)) { mod.clearStartupError(); ModuleFactory.stopModule(mod); WebModuleUtil.stopModule(mod, getServletContext()); success = msa.getMessage("Module.stopped", args); } else if ("start".equals(action)) { ModuleFactory.startModule(mod); WebModuleUtil.startModule(mod, getServletContext(), false); if (mod.isStarted()) { success = msa.getMessage("Module.started", args); } else { error = msa.getMessage("Module.not.started", args); } } else if ("unload".equals(action)) { if (ModuleFactory.isModuleStarted(mod)) { ModuleFactory.stopModule(mod); // stop the module so that when the web stop is done properly WebModuleUtil.stopModule(mod, getServletContext()); } ModuleFactory.unloadModule(mod); success = msa.getMessage("Module.unloaded", args); } } } } view = getSuccessView(); if (!"".equals(success)) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success); } if (!"".equals(error)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error); } return new ModelAndView(new RedirectView(view)); }
From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java
/** * Sets a query string./*from w w w . ja va 2 s . c o m*/ */ @Override public RestRequestHolder setQueryString(String query) { String[] params = query.split("&"); for (String param : params) { String[] keyValue = param.split("="); if (keyValue.length > 2) { throw new RuntimeException( new MalformedURLException("QueryString parameter should not have more than 2 = per part")); } else if (keyValue.length >= 2) { this.setQueryParameter(keyValue[0], keyValue[1]); } else if (keyValue.length == 1 && param.charAt(0) != '=') { this.setQueryParameter(keyValue[0], null); } else { throw new RuntimeException( new MalformedURLException("QueryString part should not start with an = and not be empty")); } } return this; }
From source file:org.springframework.richclient.image.Handler.java
protected URLConnection openConnection(URL url) throws IOException { if (!StringUtils.hasText(url.getPath())) { throw new MalformedURLException("must provide an image key."); } else if (StringUtils.hasText(url.getHost())) { throw new MalformedURLException("host part should be empty."); } else if (url.getPort() != -1) { throw new MalformedURLException("port part should be empty."); } else if (StringUtils.hasText(url.getQuery())) { throw new MalformedURLException("query part should be empty."); } else if (StringUtils.hasText(url.getRef())) { throw new MalformedURLException("ref part should be empty."); } else if (StringUtils.hasText(url.getUserInfo())) { throw new MalformedURLException("user info part should be empty."); }/* w w w . java 2 s . co m*/ urlHandlerImageSource.getImage(url.getPath()); Resource image = urlHandlerImageSource.getImageResource(url.getPath()); if (image != null) return image.getURL().openConnection(); throw new IOException("null image returned for key [" + url.getFile() + "]."); }
From source file:nz.net.kallisti.emusicj.download.HTTPDownloader.java
/** * Loads the downloader state from the provided element * /*from w w w. j ava2s . c o m*/ * @param el * the element to load from * @throws MalformedURLException * if the URL in the XML is wrong or missing */ public void setDownloader(Element el) throws MalformedURLException { String tUrl = el.getAttribute("url"); if (!"".equals(tUrl)) url = new URL(tUrl); else throw new MalformedURLException("Missing URL"); String tFname = el.getAttribute("outputfile"); if (!"".equals(tFname)) outputFile = new File(tFname); else throw new MalformedURLException("Missing output filename"); createMonitor(); setState(DLState.NOTSTARTED); String tOut = el.getAttribute("outputfile"); if (!"".equals(tOut)) outputFile = new File(tOut); String tMime = el.getAttribute("mimetype"); if (!"".equals(tMime)) { try { String[] parts = tMime.split(","); mimeType = new IMimeType[parts.length]; for (int i = 0; i < parts.length; i++) mimeType[i] = new MimeType(parts[i]); } catch (MimeTypeParseException e) { e.printStackTrace(); } } String tExpiry = el.getAttribute("expiry"); if (!"".equals(tExpiry)) { try { expiry = new Date(Long.parseLong(tExpiry)); } catch (NumberFormatException e) { logger.warning("Invalid expiry value in state file (" + tExpiry + ") - ignoring"); } } // This should come last to ensure everything is set up before we risk // executing start() String tState = el.getAttribute("state"); if (!"".equals(tState)) { if (tState.equals("CONNECTING") || tState.equals("DOWNLOADING")) { setState(DLState.CONNECTING); start(); } else if (tState.equals("STOPPED") || tState.equals("CANCELLED")) { // in v.0.14-svn, STOPPED became CANCELLED. This double-check is // for backwards compatability setState(DLState.CANCELLED); } else if (tState.equals("PAUSED")) { setState(DLState.PAUSED); } else if (tState.equals("FINISHED")) { setState(DLState.FINISHED); } else if (tState.equals("EXPIRED")) { setState(DLState.EXPIRED); } } hasExpired(); }
From source file:xanthanov.droid.funrun.PlaceSearcher.java
public List<GooglePlace> getNearbyPlaces(String search, LatLng currentLocation, int radiusMeters) throws UnknownHostException, GmapException, JSONException, MalformedURLException, java.io.UnsupportedEncodingException { URL url = null;/*from w ww .j av a2 s .c o m*/ HttpURLConnection conn = null; String urlString = null; CharSequence queryStr = stringToQuery.get(search); if (queryStr == null) {//If we didn't get a fixed category, must have been passed a custom search string, so search by name. queryStr = "name=" + java.net.URLEncoder.encode(search.toString(), "UTF-8"); System.out.println("Custom query string: " + queryStr); } try { urlString = mapsApiUrl + "?" + buildLocationString(currentLocation) + "&radius=" + radiusMeters + "&" + queryStr + "&sensor=true" + "&key=" + apiKey; url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); return parseJsonResult(new BufferedReader(new InputStreamReader(conn.getInputStream()))); } catch (MalformedURLException e) { throw new MalformedURLException( "Invalid URL: " + urlString + "\nPlease check your internet connection and try again."); } catch (UnknownHostException e) { throw new UnknownHostException( "Unable to connect to Google Maps.\nPlease check your internet connection and try again."); } catch (JSONException e) { throw new JSONException( "Failure parsing place info retreived from Google Maps.\nPlease try again later."); } catch (IOException e) { throw new JSONException( "Error downloading info from Google Maps.\nPlease check your internet connection and try again."); } catch (GmapException e) { throw new GmapException(e.getMessage() + "\nPlease check your internet connection and try again."); } finally { if (conn != null) conn.disconnect(); } }
From source file:org.droid2droid.ui.connect.AbstractConnectFragment.java
@Override public Object onTryConnect(String uri, int flags) throws IOException, RemoteException { if (getConnectActivity() == null) return null; if (getConnectActivity().isBroadcast()) { AbstractProtoBufRemoteAndroid binder = null; try {/*from ww w. j av a 2 s . co m*/ final Uri uuri = Uri.parse(uri); Driver driver = Droid2DroidManagerImpl.sDrivers.get(uuri.getScheme()); if (driver == null) throw new MalformedURLException("Unknown " + uri); binder = (AbstractProtoBufRemoteAndroid) driver.factoryBinder(RAApplication.sAppContext, RAApplication.getManager(), uuri); if (binder.connect(Type.CONNECT_FOR_BROADCAST, 0, 0, ETHERNET_TRY_TIMEOUT)) return ProgressJobs.OK; // Hack, simulate normal connection else throw new IOException("Connection impossible"); } finally { if (binder != null) binder.close(); } } else { Pair<RemoteAndroidInfoImpl, Long> msg = RAApplication.getManager().askMsgCookie(Uri.parse(uri), flags); if (msg == null || msg.second == 0) throw new SecurityException(); RemoteAndroidInfoImpl remoteInfo = msg.first; final long cookie = msg.second; if (cookie != COOKIE_NO && cookie != COOKIE_EXCEPTION && cookie != COOKIE_SECURITY) RAApplication.sDiscover.addCookie(remoteInfo, cookie); return msg.first; } }