List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
public Map<?, ?> sendSPARQL(String query, String format, int retries) { PostMethod post = null; try {/*from w w w. java 2 s .c om*/ String postUrl = this.getSparqlEndpointURL(); if (format != null) { postUrl += "?format=" + format; } post = new PostMethod(postUrl); post.setRequestHeader("Content-Type", "application/sparql-query"); post.addParameter("query", query); log.debug("SPARQL URL: " + postUrl); log.debug("SPARQL Query: " + query); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("SPARQL POST method failed: " + post.getStatusLine()); } else { log.debug("SPARQL POST method succeeded: " + post.getStatusLine()); byte[] resultBytes = post.getResponseBody(); log.debug(new String(resultBytes, "utf-8")); if (format != null && format.endsWith("json")) { return (Map<?, ?>) mapper.readValue(new ByteArrayInputStream(resultBytes), Object.class); } else { Map<String, String> resultMap = new HashMap<String, String>(); String resultString = new String(resultBytes, "utf-8"); resultMap.put("results", resultString); return resultMap; } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (post != null) post.releaseConnection(); } }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected void processPostMethod(PostMethod postMethod, List<Http.FilePart> fileParts, Map<String, String> parts) { if ((fileParts == null) || fileParts.isEmpty()) { if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { postMethod.addParameter(entry.getKey(), value); }/*from ww w .j ava2 s . co m*/ } } } else { List<Part> partsList = new ArrayList<Part>(); if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { StringPart stringPart = new StringPart(entry.getKey(), value); partsList.add(stringPart); } } } for (Http.FilePart filePart : fileParts) { partsList.add(toCommonsFilePart(filePart)); } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( partsList.toArray(new Part[partsList.size()]), postMethod.getParams()); postMethod.setRequestEntity(multipartRequestEntity); } }
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
public void login(String username, String password) throws RemoteAdminException, EngineException { PostMethod loginMethod = null; try {// ww w . j a v a 2 s . com String loginServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/engine.Authenticate"; Protocol myhttps = null; hostConfiguration = httpClient.getHostConfiguration(); if (bHttps) { if (bTrustAllCertificates) { ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory(); myhttps = new Protocol("https", socketFactory, serverPort); Protocol.registerProtocol("https", myhttps); hostConfiguration.setHost(host, serverPort, myhttps); } } if (("").equals(username) || username == null) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: \"Server administrator\" field is empty."); } if (("").equals(password) || password == null) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: \"Password\" field is empty."); } URL url = new URL(loginServiceURL); HttpState httpState = new HttpState(); httpClient.setState(httpState); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); loginMethod = new PostMethod(loginServiceURL); loginMethod.addParameter("authType", "login"); loginMethod.addParameter("authUserName", username); loginMethod.addParameter("authPassword", password); int returnCode = httpClient.executeMethod(loginMethod); String httpResponse = loginMethod.getResponseBodyAsString(); if (returnCode == HttpStatus.SC_OK) { Document domResponse; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: wrong username or password."); } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo server login.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } } else { decodeResponseError(httpResponse); } } catch (HttpException e) { throw new RemoteAdminException("An unexpected error has occured during the Convertigo server login.\n" + "Cause: " + e.getMessage(), e); } catch (UnknownHostException e) { throw new RemoteAdminException( "Unable to find the Convertigo server (unknown host): " + e.getMessage()); } catch (IOException e) { String message = e.getMessage(); if (message.indexOf("unable to find valid certification path") != -1) { throw new RemoteAdminException( "The SSL certificate of the Convertigo server is not trusted.\nPlease check the 'Trust all certificates' checkbox."); } else throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(GeneralSecurityException) " + e.getMessage(), e); } finally { Protocol.unregisterProtocol("https"); if (loginMethod != null) loginMethod.releaseConnection(); } }
From source file:com.cloudbees.api.BeesClient.java
/** * Sends a request in JSON and expects a JSON response back. * * @param urlTail The end point to hit. Appended to {@link #base}. Shouldn't start with '/' * @param headers HTTP headers/*from ww w. j a va 2 s . c om*/ * @param params * Form parameters */ /*package*/ HttpReply formUrlEncoded(String urlTail, Map<String, String> headers, Map<String, List<String>> params) throws IOException { String urlString = absolutize(urlTail); trace("API call: " + urlString); PostMethod httpMethod = new PostMethod(urlString); httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); for (Entry<String, List<String>> e : params.entrySet()) { for (String v : e.getValue()) { httpMethod.addParameter(e.getKey(), v); } } return executeRequest(httpMethod, headers); }
From source file:net.mumie.cocoon.msg.TUBWorksheetsMessageImpl.java
/** * Adds the contents of the grade to the message. *///w w w. j a v a 2 s . co m protected void init(PostMethod method, MessageDestination destination) throws Exception { final String METHOD_NAME = "init"; this.logDebug(METHOD_NAME + " 1/2: Started"); DbHelper dbHelper = null; try { dbHelper = (DbHelper) this.serviceManager.lookup(DbHelper.ROLE); ResultSet resultSet = dbHelper.queryWorksheetContext(this.worksheetIds); StringWriter out = new StringWriter(); Map<Integer, Integer> courseVCThreads = new HashMap<Integer, Integer>(); int comaClassId = -1; out.write("<?xml version=\"1.0\" encoding=\"ASCII\"?>"); out.write("<grades:worksheets xmlns:grades=\"http://www.mumie.net/xml-namespace/grades\">"); while (resultSet.next()) { Integer courseId = new Integer(resultSet.getInt(DbColumn.COURSE_ID)); String label = resultSet.getString(DbColumn.LABEL); int points = resultSet.getInt(DbColumn.POINTS); int classId = resultSet.getInt(DbColumn.CLASS_ID); if (comaClassId == -1) comaClassId = classId; else if (classId != comaClassId) throw new IllegalArgumentException("Multiple classes: " + comaClassId + ", " + classId); if (!label.trim().endsWith(".1")) { out.write("<grades:worksheet" + " id=\"" + resultSet.getInt(DbColumn.ID) + "\"" + " vc_thread_id=\"" + resultSet.getInt(DbColumn.VC_THREAD_ID) + "\"" + " label=\"" + label + "\"" + " points=\"" + points + "\"" + " course_id=\"" + courseId + "\"" + "/>"); if (!courseVCThreads.containsKey(courseId)) courseVCThreads.put(courseId, new Integer(resultSet.getInt(DbColumn.COURSE_VC_THREAD_ID))); } } for (Map.Entry entry : courseVCThreads.entrySet()) { out.write("<grades:course" + " id=\"" + entry.getKey() + "\"" + " vc_thread_id=\"" + entry.getValue() + "\"" + " class_id=\"" + comaClassId + "\"" + "/>"); } out.write("<grades:class" + " id=\"" + comaClassId + "\"" + " sync_id=\"" + COMA_CLASS_SYNC_ID + "\"" + "/>"); out.write("</grades:worksheets>"); method.addParameter("body", out.toString()); this.logDebug(METHOD_NAME + " 2/2: Done"); } finally { this.serviceManager.release(dbHelper); } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page./* w w w . ja va2s.c om*/ */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:davmail.exchange.dav.DavExchangeSession.java
/** * create a fake event to get VTIMEZONE body *///w ww.ja v a2 s . c om @Override protected void loadVtimezone() { try { // create temporary folder String folderPath = getFolderPath("davmailtemp"); createCalendarFolder(folderPath, null); String fakeEventUrl = null; if ("Exchange2003".equals(serverVersion)) { PostMethod postMethod = new PostMethod(URIUtil.encodePath(folderPath)); postMethod.addParameter("Cmd", "saveappt"); postMethod.addParameter("FORMTYPE", "appointment"); try { // create fake event int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { fakeEventUrl = StringUtil.getToken(postMethod.getResponseBodyAsString(), "<span id=\"itemHREF\">", "</span>"); if (fakeEventUrl != null) { fakeEventUrl = URIUtil.decode(fakeEventUrl); } } } finally { postMethod.releaseConnection(); } } // failover for Exchange 2007, use PROPPATCH with forced timezone if (fakeEventUrl == null) { ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>(); propertyList.add(Field.createDavProperty("contentclass", "urn:content-classes:appointment")); propertyList.add(Field.createDavProperty("outlookmessageclass", "IPM.Appointment")); propertyList.add(Field.createDavProperty("instancetype", "0")); // get forced timezone id from settings String timezoneId = Settings.getProperty("davmail.timezoneId"); if (timezoneId == null) { // get timezoneid from OWA settings timezoneId = getTimezoneIdFromExchange(); } // without a timezoneId, use Exchange timezone if (timezoneId != null) { propertyList.add(Field.createDavProperty("timezoneid", timezoneId)); } String patchMethodUrl = folderPath + '/' + UUID.randomUUID().toString() + ".EML"; PropPatchMethod patchMethod = new PropPatchMethod(URIUtil.encodePath(patchMethodUrl), propertyList); try { int statusCode = httpClient.executeMethod(patchMethod); if (statusCode == HttpStatus.SC_MULTI_STATUS) { fakeEventUrl = patchMethodUrl; } } finally { patchMethod.releaseConnection(); } } if (fakeEventUrl != null) { // get fake event body GetMethod getMethod = new GetMethod(URIUtil.encodePath(fakeEventUrl)); getMethod.setRequestHeader("Translate", "f"); try { httpClient.executeMethod(getMethod); this.vTimezone = new VObject( "BEGIN:VTIMEZONE" + StringUtil.getToken(getMethod.getResponseBodyAsString(), "BEGIN:VTIMEZONE", "END:VTIMEZONE") + "END:VTIMEZONE\r\n"); } finally { getMethod.releaseConnection(); } } // delete temporary folder deleteFolder("davmailtemp"); } catch (IOException e) { LOGGER.warn("Unable to get VTIMEZONE info: " + e, e); } }
From source file:au.org.emii.portal.composer.MapComposer.java
private void loadDistributionMap(String lsids, String wkt) { String newWkt = wkt;/*from w ww. j ava 2s.co m*/ if (CommonData.WORLD_WKT.equals(newWkt)) { newWkt = null; } //test for a valid lsid match String[] wmsNames = CommonData.getSpeciesDistributionWMS(lsids); String[] spcode = CommonData.getSpeciesDistributionSpcode(lsids); MapLayer ml; JSONParser jp = new JSONParser(); if (wmsNames.length > 0 && (newWkt == null || newWkt.equals(CommonData.WORLD_WKT))) { //add all for (int i = 0; i < wmsNames.length; i++) { if (getMapLayerWMS(wmsNames[i]) == null) { //map this layer with its recorded scientific name try { JSONObject jo = ((JSONObject) jp.parse(Util.readUrl( CommonData.getLayersServer() + "/distribution/" + spcode[i] + "?nowkt=true"))); String scientific = jo.get(StringConstants.SCIENTIFIC).toString(); String distributionAreaName = jo.get("area_name").toString(); String layerName = getNextAreaLayerName(scientific); String html = Util.getMetadataHtmlForDistributionOrChecklist(spcode[i], null, layerName); ml = addWMSLayer(layerName, getNextAreaLayerName(distributionAreaName), wmsNames[i], 0.35f, html, null, LayerUtilitiesImpl.WKT, null, null); ml.setSPCode(spcode[i]); setupMapLayerAsDistributionArea(ml); } catch (Exception e) { LOGGER.error("failed to parse for distribution: " + spcode[i]); } } } } else if (wmsNames.length > 0 && newWkt != null && !newWkt.equals(CommonData.WORLD_WKT)) { String url = CommonData.getLayersServer() + "/distributions"; try { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter(StringConstants.WKT, newWkt); post.addParameter(StringConstants.LSIDS, lsids); post.addRequestHeader(StringConstants.ACCEPT, StringConstants.JSON_JAVASCRIPT_ALL); int result = client.executeMethod(post); if (result == 200) { String txt = post.getResponseBodyAsString(); JSONArray ja = (JSONArray) jp.parse(txt); List<String> found = new ArrayList(); for (int i = 0; i < ja.size(); i++) { JSONObject jo = (JSONObject) ja.get(i); if (jo.containsKey(StringConstants.WMSURL)) { found.add(jo.get(StringConstants.WMSURL).toString()); } } for (int i = 0; i < wmsNames.length; i++) { if (getMapLayerWMS(wmsNames[i]) == null) { String scientific = ((JSONObject) jp.parse(Util.readUrl( CommonData.getLayersServer() + "/distribution/" + spcode[i] + "?nowkt=true"))) .get(StringConstants.SCIENTIFIC).toString(); String layerName = getNextAreaLayerName(scientific + " area " + (i + 1)); String html = Util.getMetadataHtmlForDistributionOrChecklist(spcode[i], null, layerName); ml = addWMSLayer(layerName, getNextAreaLayerName("Expert distribution: " + scientific), found.get(i), 0.35f, html, null, LayerUtilitiesImpl.WKT, null, null); ml.setSPCode(spcode[i]); setupMapLayerAsDistributionArea(ml); } } } } catch (Exception e) { LOGGER.error("error posting distributions: " + url); } } openChecklistSpecies(lsids, newWkt, true); }
From source file:davmail.exchange.ExchangeSession.java
protected HttpMethod submitLanguageSelectionForm(HttpMethod logonMethod) throws IOException { PostMethod postLanguageFormMethod; // create an instance of HtmlCleaner HtmlCleaner cleaner = new HtmlCleaner(); try {// w w w . j ava 2s.c om TagNode node = cleaner.clean(logonMethod.getResponseBodyAsStream()); List forms = node.getElementListByName("form", true); TagNode languageForm; // select form if (forms.size() == 1) { languageForm = (TagNode) forms.get(0); } else { throw new IOException("Form not found"); } String languageMethodPath = languageForm.getAttributeByName("action"); postLanguageFormMethod = new PostMethod(getAbsoluteUri(logonMethod, languageMethodPath)); List inputList = languageForm.getElementListByName("input", true); for (Object input : inputList) { String name = ((TagNode) input).getAttributeByName("name"); String value = ((TagNode) input).getAttributeByName("value"); if (name != null && value != null) { postLanguageFormMethod.addParameter(name, value); } } List selectList = languageForm.getElementListByName("select", true); for (Object select : selectList) { String name = ((TagNode) select).getAttributeByName("name"); List optionList = ((TagNode) select).getElementListByName("option", true); String value = null; for (Object option : optionList) { if (((TagNode) option).getAttributeByName("selected") != null) { value = ((TagNode) option).getAttributeByName("value"); break; } } if (name != null && value != null) { postLanguageFormMethod.addParameter(name, value); } } } catch (IOException e) { String errorMessage = "Error parsing language selection form at " + logonMethod.getURI(); LOGGER.error(errorMessage); throw new IOException(errorMessage); } finally { logonMethod.releaseConnection(); } return DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, postLanguageFormMethod); }
From source file:fr.msch.wissl.server.TestIndexer.java
public void test() throws Exception { HttpClient client = new HttpClient(); // /indexer/status as user: 401 GetMethod get = new GetMethod(URL + "indexer/status"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get);//from w w w . ja va 2 s . c om Assert.assertEquals(401, get.getStatusCode()); // /indexer/status as admin: 200 get = new GetMethod(URL + "indexer/status"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); JSONObject obj = new JSONObject(get.getResponseBodyAsString()); // won't try to check the actual content of this object, // since I can't predict easily and accurately if // the Indexer will be in Running or Sleeping state at a given time. assertTrue(obj.has("running")); assertTrue(obj.has("percentDone")); assertTrue(obj.has("secondsLeft")); assertTrue(obj.has("songsDone")); assertTrue(obj.has("songsTodo")); // /indexer/rescan as user: 401 PostMethod post = new PostMethod(URL + "indexer/rescan"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // /indexer/rescan as amdin post = new PostMethod(URL + "indexer/rescan"); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); Assert.assertEquals(204, post.getStatusCode()); // /folders as user: 401 get = new GetMethod(URL + "folders"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); Assert.assertEquals(401, get.getStatusCode()); // /folders: should be empty get = new GetMethod(URL + "folders"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("folders").length()); // /folders/listing as user: 401 get = new GetMethod(URL + "folders/listing"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); Assert.assertEquals(401, get.getStatusCode()); // /folders/listing on some file that does not exist: 404 get = new GetMethod(URL + "folders/listing?directory=/does/not/exist"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(404, get.getStatusCode()); File exp_home = new File(System.getProperty("user.home")); // /folders/listing with no arg: homedir get = new GetMethod(URL + "folders/listing"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(File.separator, obj.getString("separator")); File dir = new File(obj.getString("directory")); assertEquals(exp_home.getAbsolutePath(), dir.getAbsolutePath()); assertEquals(exp_home.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath()); assertTrue(obj.getJSONArray("listing").length() > 0); // /folders/listing with arg '$ROOT' get = new GetMethod(URL + "folders/listing?directory=$ROOT"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(File.separator, obj.getString("separator")); File[] dirs = File.listRoots(); assertEquals("", obj.getString("directory")); assertEquals("$ROOT", obj.getString("parent")); JSONArray arr = obj.getJSONArray("listing"); HashSet<String> hs = new HashSet<String>(arr.length()); for (int i = 0; i < arr.length(); i++) { hs.add(new File(arr.getString(i)).getAbsolutePath()); } for (File d : dirs) { // on windows, listRoots returns a bunch of drive names that don't exist if (d.exists()) { assertTrue(hs.remove(d.getAbsolutePath())); } } assertTrue(hs.isEmpty()); // lists test resources folder File f = new File("src/test/resources/data2"); get = new GetMethod(URL + "folders/listing?directory=" + URIUtil.encodeQuery(f.getAbsolutePath())); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(File.separator, obj.getString("separator")); dir = new File(obj.getString("directory")); assertEquals(f.getAbsolutePath(), dir.getAbsolutePath()); assertEquals(f.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath()); dirs = dir.listFiles(); arr = obj.getJSONArray("listing"); assertEquals(2, arr.length()); assertEquals(new File("src/test/resources/data2/sub1").getAbsolutePath(), arr.get(0)); assertEquals(new File("src/test/resources/data2/sub2").getAbsolutePath(), arr.get(1)); // /folders/add as user: 401 post = new PostMethod(URL + "folders/add"); post.addParameter("directory", "/"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // /folders/add : directory does not exist: 404 post = new PostMethod(URL + "folders/add"); post.addParameter("directory", "/does/not/exist"); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); Assert.assertEquals(404, post.getStatusCode()); // /folders/add : not a directory: 400 post = new PostMethod(URL + "folders/add"); post.addParameter("directory", new File("src/test/resources/data/1.mp3").getAbsolutePath()); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // /folders/add "/src/test/resources/data" f = new File("src/test/resources/data"); RuntimeStats rt = new RuntimeStats(); rt.songCount.set(15); rt.albumCount.set(5); rt.artistCount.set(2); rt.playlistCount.set(0); rt.userCount.set(2); rt.playtime.set(15); rt.downloaded.set(0); this.addMusicFolder(f.getAbsolutePath(), rt); // check /folders get = new GetMethod(URL + "folders"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(f.getAbsolutePath(), obj.getJSONArray("folders").getString(0)); // /folders/add "/src/test/resources/data2/sub1" f = new File("src/test/resources/data2/sub1"); rt.songCount.addAndGet(3); rt.albumCount.addAndGet(1); rt.artistCount.addAndGet(1); rt.playtime.addAndGet(3); this.addMusicFolder(f.getAbsolutePath(), rt); // /folders/add "/src/test/resources/data2/" f = new File("src/test/resources/data2/"); rt.songCount.addAndGet(6); rt.playtime.addAndGet(6); this.addMusicFolder(f.getAbsolutePath(), rt); // check /folders get = new GetMethod(URL + "folders"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); arr = obj.getJSONArray("folders"); assertEquals(3, arr.length()); for (int i = 0; i < 3; i++) { String s = new File(arr.getString(i)).getAbsolutePath(); String s1 = new File("src/test/resources/data").getAbsolutePath(); String s2 = new File("src/test/resources/data2/sub1").getAbsolutePath(); String s3 = new File("src/test/resources/data2").getAbsolutePath(); assertTrue(s.equals(s1) || s.equals(s2) || s.equals(s3)); } // /folders/remove as user: 401 post = new PostMethod(URL + "folders/remove"); post.addParameter("directory[]", "/"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // /folders/remove unknown dir: 400 post = new PostMethod(URL + "folders/remove"); post.addParameter("directory[]", "/does/not/exist"); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // /folders/remove "/src/test/resources/data","src/test/resources/data2" post = new PostMethod(URL + "folders/remove"); f = new File("src/test/resources/data"); post.addParameter("directory[]", f.getAbsolutePath()); f = new File("src/test/resources/data2"); post.addParameter("directory[]", f.getAbsolutePath()); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); assertEquals(204, post.getStatusCode()); rt.songCount.set(3); rt.albumCount.set(1); rt.artistCount.set(1); rt.userCount.set(2); rt.playtime.set(3); rt.downloaded.set(0); this.checkStats(rt); // /folders/remove "/src/test/resources/data/sub1" post = new PostMethod(URL + "folders/remove"); f = new File("src/test/resources/data2/sub1"); post.addParameter("directory[]", f.getAbsolutePath()); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); assertEquals(204, post.getStatusCode()); rt.songCount.set(0); rt.albumCount.set(0); rt.artistCount.set(0); rt.userCount.set(2); rt.playtime.set(0); rt.downloaded.set(0); this.checkStats(rt); // /folders: should be empty get = new GetMethod(URL + "folders"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("folders").length()); }