protected WebdavContentNode getChildNode(String name) throws ContentRepositoryException { // make sure this isn't a path if (name.contains("/")) { throw new ContentRepositoryException("Paths not allowed: " + name); } try { HttpURL url = getChildURL(getResource().getHttpURL(), name); logger.fine("[WebdavContentCollection] Get child " + name + " returns " + url + " from " + this); AuthenticatedWebdavResource resource = new AuthenticatedWebdavResource(getResource(), url); if (resource.getExistence()) { return getContentNode(resource); } return null; } catch (IOException ioe) { throw new ContentRepositoryException(ioe); } }
public WebdavContentNode removeChild(String name) throws ContentRepositoryException { // make sure this isn't a path if (name.contains("/")) { throw new ContentRepositoryException("Paths not allowed: " + name); } try { HttpURL removeURL = getChildURL(getResource().getHttpURL(), name); AuthenticatedWebdavResource removeResource = new AuthenticatedWebdavResource(getResource(), removeURL); if (removeResource.exists()) { removeResource.deleteMethod(); } return getContentNode(removeResource); } catch (IOException ioe) { throw new ContentRepositoryException(ioe); } }
@Override public boolean execute() throws Exception { String stateValue = _state.toLowerCase(); if ( ! stateValue.equals("enable") && ! stateValue.equals("disable") && ! stateValue.equals("drop")) { throw new IllegalArgumentException("Invalid value for state: " + _state + "\n Value must be one of enable|disable|drop"); } HttpClient httpClient = new HttpClient(); HttpURL url = new HttpURL(_controllerHost, Integer.parseInt(_controllerPort), URI_TABLES_PATH + _tableName); url.setQuery("state", stateValue); GetMethod httpGet = new GetMethod(url.getEscapedURI()); int status = httpClient.executeMethod(httpGet); if (status != 200) { throw new RuntimeException( "Failed to change table state, error: " + httpGet.getResponseBodyAsString()); } return true; }
@Override public boolean execute() throws Exception { if (_controllerHost == null) { _controllerHost = NetUtil.getHostAddress(); } String stateValue = _state.toLowerCase(); if (!stateValue.equals("enable") && !stateValue.equals("disable") && !stateValue.equals("drop")) { throw new IllegalArgumentException("Invalid value for state: " + _state + "\n Value must be one of enable|disable|drop"); } HttpClient httpClient = new HttpClient(); HttpURL url = new HttpURL(_controllerHost, Integer.parseInt(_controllerPort), URI_TABLES_PATH + _tableName); url.setQuery("state", stateValue); GetMethod httpGet = new GetMethod(url.getEscapedURI()); int status = httpClient.executeMethod(httpGet); if (status != 200) { throw new RuntimeException( "Failed to change table state, error: " + httpGet.getResponseBodyAsString()); } return true; }
protected void downloadFile(HttpURL url, String relativePath, CollectionScanner scanner) throws IOException { File target = new File(this.toDir, relativePath); long lastMod = scanner.getProperties().getLastModified(url.toString()); if (shallWeGetIt(target, lastMod)) { getAndStoreResource(url, target, lastMod, relativePath); } else { log("Omitted: " + relativePath + " (uptodate)", ifVerbose()); this.countOmittedFiles++; } }
/** * Retrieves the data of a resource and stores it in a file. * * Creates required directories and sets the last modified time of the file. * * @param url path of the resource to be retrieved * @param target file where the resource data ist stored * @param lastMod last modified date of the resource, used to set * the last modified date of the target file * @param relative path og the resource for logging purposes. * @throws IOException * @throws HttpException * @throws FileNotFoundException */ private void getAndStoreResource(HttpURL url, File target, long lastMod, String relative) throws IOException, HttpException, FileNotFoundException { log("downloading: " + relative, ifVerbose()); File directory = target.getParentFile(); if (!directory.exists()) { directory.mkdirs(); } InputStream in = Utils.getFile(getHttpClient(), url); if (!target.exists()) { target.createNewFile(); } FileOutputStream out = new FileOutputStream(target); copyStream(in, out, this.filterSets, this.encoding); out.close(); target.setLastModified(lastMod); this.countWrittenFiles++; }
/** * Returns <code>true</code> if the resource given as URL does exist. * @param client * @param httpURL * @return <code>true</code>if the resource exists * @throws IOException * @throws HttpException */ public static boolean resourceExists(HttpClient client, HttpURL httpURL) throws IOException, HttpException { HeadMethod head = new HeadMethod(httpURL.getURI()); head.setFollowRedirects(true); int status = client.executeMethod(head); switch (status) { case WebdavStatus.SC_OK: return true; case WebdavStatus.SC_NOT_FOUND: return false; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(head.getStatusText()); throw ex; } }
public static void putFile(HttpClient client, HttpURL url, InputStream is, String contentType, String lockToken) throws IOException, HttpException { PutMethod put = new PutMethod(url.getURI()); generateIfHeader(put, lockToken); put.setRequestHeader("Content-Type", contentType); put.setRequestBody(is); put.setFollowRedirects(true); int status = client.executeMethod(put); switch (status) { case WebdavStatus.SC_OK: case WebdavStatus.SC_CREATED: case WebdavStatus.SC_NO_CONTENT: return; default: HttpException ex = new HttpException(); ex.setReason(put.getStatusText()); ex.setReasonCode(status); throw ex; } }
public static InputStream getFile(HttpClient client, HttpURL url) throws IOException, HttpException { GetMethod get = new GetMethod(url.toString()); get.setFollowRedirects(true); int status = client.executeMethod(get); switch (status) { case WebdavStatus.SC_OK: return get.getResponseBodyAsStream(); default: HttpException ex = new HttpException(); ex.setReason(get.getStatusText()); ex.setReasonCode(status); throw ex; } }
public static void unlockResource(HttpClient client, HttpURL url, String lockToken) throws IOException, HttpException { UnlockMethod unlock = new UnlockMethod(url.getURI(), lockToken); unlock.setFollowRedirects(true); int status = client.executeMethod(unlock); switch (status) { case WebdavStatus.SC_OK: case WebdavStatus.SC_NO_CONTENT: return; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(unlock.getStatusText()); throw ex; } }
public static void copyResource(HttpClient client, HttpURL url, String destination, int depth, boolean overwrite) throws IOException, HttpException { CopyMethod copy = new CopyMethod( url.getURI(), destination, overwrite, depth); copy.setFollowRedirects(true); int status = client.executeMethod(copy); switch (status) { case WebdavStatus.SC_OK: case WebdavStatus.SC_CREATED: case WebdavStatus.SC_NO_CONTENT: return; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(copy.getStatusText()); throw ex; } }
public static void moveResource(HttpClient client, HttpURL url, String destination, boolean overwrite) throws IOException, HttpException { MoveMethod move = new MoveMethod(url.getURI(), destination, overwrite); move.setFollowRedirects(true); int status = client.executeMethod(move); switch (status) { case WebdavStatus.SC_OK: case WebdavStatus.SC_CREATED: case WebdavStatus.SC_NO_CONTENT: return; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(move.getStatusText()); throw ex; } }
public File getParentFile() { try { HttpURL httpURL = null; String parent = null; parent = this.getParent(); if (parent == null) { //System.out.println("getParentFile : at root so return null"); return null; } else { httpURL = this.rootUrl; httpURL.setPath(parent); //System.out.println("getParentFile : set path to " + parent); return new WebdavFile(httpURL, this.rootUrl); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); return null; } }
public RootWebdavResource(HttpURL url, String authCookieName, String authCookieValue) throws HttpException, IOException { super (url, authCookieName, authCookieValue); connectionManager = new MultiThreadedHttpConnectionManager(); }
public AuthenticatedWebdavResource(AuthenticatedWebdavResource parent, HttpURL url) throws HttpException, IOException { super (parent.connectionManager); setupResource(this, url, parent.getAuthCookieName(), parent.getAuthCookieValue()); }
protected AuthenticatedWebdavResource(HttpURL url, String authCookieName, String authCookieValue) throws HttpException, IOException { super (URIUtil.decode(url.getEscapedURI()), new TokenCredentials(authCookieName, authCookieValue), true); }
protected static void setupResource(AuthenticatedWebdavResource resource, HttpURL url, String authCookieName, String authCookieValue) throws HttpException, IOException { resource.setFollowRedirects(true); resource.setCredentials(new TokenCredentials(authCookieName, authCookieValue)); resource.setHttpURL(url); }
public WebdavContentNode createChild(String name, Type type) throws ContentRepositoryException { // make sure this isn't a path if (name.contains("/")) { throw new ContentRepositoryException("Paths not allowed: " + name); } try { HttpURL newURL = getChildURL(getResource().getHttpURL(), name); logger.fine("[WebdavContentCollection] Create child " + name + " returns " + newURL + " from " + this); AuthenticatedWebdavResource newResource = new AuthenticatedWebdavResource(getResource(), newURL); if (newResource.exists()) { throw new ContentRepositoryException("Path " + newURL + " already exists."); } switch (type) { case COLLECTION: newResource.mkcolMethod(); break; case RESOURCE: break; } return getContentNode(newResource); } catch (IOException ioe) { throw new ContentRepositoryException(ioe); } }
protected HttpURL getChildURL(HttpURL parent, String childPath) throws URIException { if (childPath.startsWith("/")) { childPath = childPath.substring(1); } if (!parent.getPath().endsWith("/")) { parent.setPath(parent.getPath() + "/"); } return new HttpURL(parent, childPath); }
/** * Create the davClient and authenticate with the resource. serviceContact * should be in the form of a url */ public void start() throws IllegalHostException, InvalidSecurityContextException, FileResourceException { ServiceContact serviceContact = getAndCheckServiceContact(); try { SecurityContext securityContext = getOrCreateSecurityContext("WebDAV", serviceContact); String contact = getServiceContact().getContact().toString(); if (!contact.startsWith("http")) { contact = "http://" + contact; } HttpURL hrl = new HttpURL(contact); PasswordAuthentication credentials = getCredentialsAsPasswordAuthentication(securityContext); String username = credentials.getUserName(); String password = String.valueOf(credentials.getPassword()); hrl.setUserinfo(username, password); davClient = new WebdavResource(hrl); setStarted(true); } catch (URIException ue) { throw new IllegalHostException( "Error connecting to the WebDAV server at " + serviceContact, ue); } catch (Exception e) { throw new IrrecoverableResourceException(e); } }
private void uploadFileSet(FileSet fileSet) throws IOException { DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject()); String basedir = scanner.getBasedir().getAbsolutePath(); // assert that all required collections does exist for(Iterator i = determineRequiredDirectories(scanner); i.hasNext();) { String dir = (String)i.next(); if (dir.equals("")) { Utils.assureExistingCollection(getHttpClient(), getUrl(), this.locktoken); } else { HttpURL collURL = Utils.createHttpURL(getUrl(), dir + "/"); Utils.assureExistingCollection(getHttpClient(), collURL, this.locktoken); } } // write all files String[] files = scanner.getIncludedFiles(); for (int i = 0; i < files.length; ++i) { File file = getProject().resolveFile(basedir + File.separator + files[i]); uploadFile(asDavPath(files[i]), file); } }
/** * Puts a file to a resource relative to the path attribute. * @param relative path relative * @param file file to be written * @throws IOException */ private void uploadFile(String relative, File file) throws IOException { HttpURL url = Utils.createHttpURL(getUrl(), relative); uploadFile(url, file, relative); }
private void uploadZipFileSet(ZipFileSet fileSet) throws IOException { DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject()); ZipFile zipFile = new ZipFile(fileSet.getSrc()); // assert that all required collections does exist for(Iterator i = determineRequiredDirectories(scanner); i.hasNext();) { String dir = (String)i.next(); if (dir.equals("")) { Utils.assureExistingCollection(getHttpClient(), getUrl(), this.locktoken); } else { HttpURL collURL = Utils.createHttpURL(getUrl(), dir + "/"); Utils.assureExistingCollection(getHttpClient(), collURL, this.locktoken); } } // write all files String[] files = scanner.getIncludedFiles(); for (int i = 0; i < files.length; ++i) { uploadZipEntry(Utils.createHttpURL(getUrl(), files[i]), files[i], zipFile); } }
private void uploadZipEntry(HttpURL url, String name, ZipFile zipFile) throws IOException { boolean putit = false; ZipEntry entry = zipFile.getEntry(name); try { if (this.overwrite) { putit = true; } else { // check last modified date (both GMT) long remoteLastMod = Utils.getLastModified(getHttpClient(), url); long localLastMod = entry.getTime(); putit = localLastMod > remoteLastMod; } } catch (HttpException e) { switch (e.getReasonCode()) { case HttpStatus.SC_NOT_FOUND: putit = true; break; default: throw Utils.makeBuildException("Can't get lastmodified!?", e); } } if (putit) { log("Uploading: " + name, ifVerbose()); String contentType = Mimetypes.getMimeType(name, DEFAULT_CONTENT_TYPE); Utils.putFile(getHttpClient(), url, zipFile.getInputStream(entry), contentType, this.locktoken); this.countWrittenFiles++; } else { countOmittedFiles++; log("Omitted: " + name + " (uptodate)", ifVerbose()); } }
protected void downloadFileset(WebdavFileSet fileSet) throws IOException { CollectionScanner scanner = fileSet.getCollectionScanner(getProject(), getHttpClient(), getUrl()); HttpURL baseUrl = scanner.getBaseURL(); String[] files = scanner.getIncludedFiles(); for (int i = 0; i < files.length; i++) { HttpURL url = Utils.createHttpURL(baseUrl, files[i]); downloadFile(url, files[i], scanner); } }
public static HttpURL assureCollectionUrl(HttpURL url) throws URIException { if (url.getPath().endsWith("/")) { return url; } else { HttpURL coll = Utils.createHttpURL(url, ""); coll.setPath(url.getPath() + "/"); return coll; } }
public Property getProperty(HttpURL baseUrl, String relative, PropertyName propertyName) throws URIException { HttpURL url = Utils.createHttpURL(baseUrl, relative); return getProperty(url.getURI(), propertyName); }
public static boolean collectionExists(HttpClient client, HttpURL httpURL) throws IOException, HttpException { Vector props = new Vector(1); props.add(RESOURCETYPE); PropFindMethod propFind = new PropFindMethod(httpURL.getURI(), 0, PropFindMethod.BY_NAME); propFind.setFollowRedirects(true); propFind.setPropertyNames(props.elements()); int status = client.executeMethod(propFind); switch (status) { case WebdavStatus.SC_MULTI_STATUS: Property p = findProperty(propFind, RESOURCETYPE, httpURL.getPath()); if (p instanceof ResourceTypeProperty) { return ((ResourceTypeProperty)p).isCollection(); } else { throw new WebdavException("PROPFFIND does not return resourcetype"); } case WebdavStatus.SC_NOT_FOUND: return false; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(propFind.getStatusText()); throw ex; } }
public static long getLastModified(HttpClient client, HttpURL url) throws IOException, HttpException { Vector props = new Vector(1); props.add(GETLASTMODIFIED); PropFindMethod propFind = new PropFindMethod(url.getURI(), 0); propFind.setPropertyNames(props.elements()); propFind.setFollowRedirects(true); int status = client.executeMethod(propFind); switch (status) { case WebdavStatus.SC_MULTI_STATUS: Property p = findProperty(propFind, GETLASTMODIFIED, url.getPath()); if (p != null) { try { Date d = GETLASTMODIFIED_FORMAT.parse(p.getPropertyAsString()); return d.getTime(); } catch (ParseException e) { throw new HttpException("Invalid lastmodified property: " + p.getPropertyAsString()); } } throw new HttpException("PROPFIND does not return lastmodified."); default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(propFind.getStatusText()); throw ex; } }
/** * * @param client * @param httpURL * @param lockToken the locktoken to be used or <code>null</code> if * none is to be used * @throws IOException * @throws HttpException */ public static boolean assureExistingCollection(HttpClient client, HttpURL httpURL, String lockToken) throws IOException, HttpException { String path = httpURL.getPath(); if (!path.endsWith("/")) { path = path + "/"; } Stack toBeCreated = new Stack(); while (!path.equals("/")) { HttpURL parent = Utils.createHttpURL(httpURL, path); if (!collectionExists(client, parent)) { toBeCreated.push(path); path = path.substring(0, path.lastIndexOf("/", path.length()-2)+1); } else { break; } } boolean created = !toBeCreated.empty(); while(!toBeCreated.empty()) { HttpURL newColl = Utils.createHttpURL(httpURL, (String)toBeCreated.pop()); MkcolMethod mkcol = new MkcolMethod(newColl.getURI()); mkcol.setFollowRedirects(true); generateIfHeader(mkcol, lockToken); int status = client.executeMethod(mkcol); if (status != WebdavStatus.SC_CREATED) { HttpException ex = new HttpException("Can't create collection " + newColl); ex.setReasonCode(status); ex.setReason(mkcol.getStatusText()); throw ex; } } return created; }
public static HttpURL createHttpURL(HttpURL base, String relative) throws URIException { if (base instanceof HttpsURL) { return new HttpsURL((HttpsURL)base, relative); } else { return new HttpURL(base, relative); } }
public static HttpURL createHttpURL(String url) throws URIException { if (url.startsWith("https://")) { return new HttpsURL(url); } else { return new HttpURL(url); } }
public CollectionScanner getCollectionScanner( Project project, HttpClient httpClient, HttpURL baseUrl) { validate(); CollectionScanner scanner = new CollectionScanner(); try { scanner.setBaseURL(Utils.createHttpURL(baseUrl, directory)); } catch (URIException e) { throw new BuildException("Invalid URL. " + e.toString(), e); } scanner.setHttpClient(httpClient); scanner.setCaseSensitive(this.isCaseSensitive); if (this.patterns.getExcludePatterns(project) == null && this.patterns.getIncludePatterns(project) == null && this.patternSets.size() == 0) { scanner.setIncludes(DEFAULT_INCLUDES); } else { scanner.setExcludes(this.patterns.getExcludePatterns(project)); scanner.setIncludes(this.patterns.getIncludePatterns(project)); for (Iterator i = this.patternSets.iterator(); i.hasNext();) { PatternSet patternSet = (PatternSet)i.next(); scanner.addExcludes(patternSet.getExcludePatterns(project)); scanner.addIncludes(patternSet.getIncludePatterns(project)); } } scanner.scan(); return scanner; }
/** * The constructor. * * @param httpURL The specified http URL. * @param followRedirects shall redirects from the server be accepted */ public WebdavResource(HttpURL httpURL, boolean followRedirects) throws HttpException, IOException { setFollowRedirects(followRedirects); setHttpURL(httpURL); }
public WebdavResource(HttpURL httpURL, String proxyHost, int proxyPort, boolean followRedirects) throws HttpException, IOException { setFollowRedirects(followRedirects); setProxy(proxyHost, proxyPort); setHttpURL(httpURL); }
public WebdavResource(HttpURL httpURL, String proxyHost, int proxyPort, Credentials proxyCredentials, boolean followRedirects) throws HttpException, IOException { setFollowRedirects(followRedirects); setProxy(proxyHost, proxyPort); setProxyCredentials(proxyCredentials); setHttpURL(httpURL); }
/** * Set the client for this resource and the given http URL. * * @param httpURL The http URL. * @exception IOException */ protected synchronized void setClient(HttpURL httpURL) throws IOException { if (client == null) { client = getSessionInstance(httpURL); } else if (!isTheClient()) { closeSession(); client = getSessionInstance(httpURL); } }
/** * Get the HttpURL except for userinfo. * * @return httpURL the http URL. */ public HttpURL getHttpURLExceptForUserInfo() throws URIException { return httpURL instanceof HttpsURL ? new HttpsURL(httpURL.getRawURI()) : new HttpURL(httpURL.getRawURI()); }
/** * Execute the REPORT method. */ public Enumeration reportMethod(HttpURL httpURL, int depth) throws HttpException, IOException { setClient(); // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), depth); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); client.executeMethod(method); Vector results = new Vector(); Enumeration responses = method.getResponses(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = response.getHref(); String sResult = href; // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; Enumeration responseProperties = method.getResponseProperties(href); while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); sResult += "\n" + property.getName() + ":\t" + DOMUtils.getTextValue(property.getElement()); } results.addElement(sResult); } return results.elements(); }
public Enumeration reportMethod(HttpURL httpURL, Vector properties) throws HttpException, IOException { setClient(); // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), DepthSupport.DEPTH_0, properties.elements()); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); client.executeMethod(method); return method.getResponses(); }