Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:net.lightbody.bmp.proxy.jetty.http.ContextLoader.java

/** Constructor.
 * @param classPath Comma separated path of filenames or URLs
 * pointing to directories or jar files. Directories should end
 * with '/'./*from  www.jav  a 2s .  co m*/
 * @exception IOException
 */
public ContextLoader(HttpContext context, String classPath, ClassLoader parent, PermissionCollection permisions)
        throws MalformedURLException, IOException {
    super(new URL[0], parent);
    _context = context;
    _permissions = permisions;
    _parent = parent;

    if (_parent == null)
        _parent = getSystemClassLoader();

    if (classPath == null) {
        _urlClassPath = "";
    } else {
        StringTokenizer tokenizer = new StringTokenizer(classPath, ",;");

        while (tokenizer.hasMoreTokens()) {
            Resource resource = Resource.newResource(tokenizer.nextToken());
            if (log.isDebugEnabled())
                log.debug("Path resource=" + resource);

            // Resolve file path if possible
            File file = resource.getFile();

            if (file != null) {
                URL url = resource.getURL();
                addURL(url);
                _urlClassPath = (_urlClassPath == null) ? url.toString()
                        : (_urlClassPath + "," + url.toString());
            } else {
                // Add resource or expand jar/
                if (!resource.isDirectory() && file == null) {
                    InputStream in = resource.getInputStream();
                    File lib = new File(context.getTempDirectory(), "lib");
                    if (!lib.exists()) {
                        lib.mkdir();
                        lib.deleteOnExit();
                    }
                    File jar = File.createTempFile("Jetty-", ".jar", lib);

                    jar.deleteOnExit();
                    if (log.isDebugEnabled())
                        log.debug("Extract " + resource + " to " + jar);
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(jar);
                        IO.copy(in, out);
                    } finally {
                        IO.close(out);
                    }

                    URL url = jar.toURL();
                    addURL(url);
                    _urlClassPath = (_urlClassPath == null) ? url.toString()
                            : (_urlClassPath + "," + url.toString());
                } else {
                    URL url = resource.getURL();
                    addURL(url);
                    _urlClassPath = (_urlClassPath == null) ? url.toString()
                            : (_urlClassPath + "," + url.toString());
                }
            }
        }
    }

    if (log.isDebugEnabled()) {
        if (log.isDebugEnabled())
            log.debug("ClassPath=" + _urlClassPath);
        if (log.isDebugEnabled())
            log.debug("Permissions=" + _permissions);
        if (log.isDebugEnabled())
            log.debug("URL=" + Arrays.asList(getURLs()));
    }
}

From source file:com.openmeap.services.ApplicationManagementServlet.java

private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) {

    Result res = new Result();
    Error err = new Error();
    res.setError(err);//from w w  w  .  jav a2s  .  c  o  m

    GlobalSettings settings = modelManager.getGlobalSettings();
    Map properties = this.getServicesWebProperties();
    String nodeKey = (String) properties.get("clusterNodeUrlPrefix");
    ClusterNode clusterNode = settings.getClusterNode(nodeKey);
    if (nodeKey == null || clusterNode == null) {
        // TODO: create a configuration error code
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error(
                "For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface.  This value is currently "
                        + nodeKey + ".");
        return res;
    }

    String pathValidation = clusterNode.validateFileSystemStoragePathPrefix();
    if (pathValidation != null) {
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error(
                "There is an issue with the location at \"File-system Storage Prefix\".  " + pathValidation);
        return res;
    }

    String hash = request.getParameter(UrlParamConstants.APPARCH_HASH);
    String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG);
    String fileName = null;

    if (hash == null || hashAlg == null) {
        // look in the apps directory for the archive specified
        String appName = request.getParameter(UrlParamConstants.APP_NAME);
        String versionId = request.getParameter(UrlParamConstants.APP_VERSION);

        ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName,
                versionId);
        if (appVersion == null) {
            String mesg = "The application version " + versionId + " was not found for application " + appName;
            err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND);
            err.setMessage(mesg);
            logger.warn(mesg);
            return res;
        }

        String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN);
        com.openmeap.model.dto.Application app = appVersion.getApplication();
        try {
            if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) {
                err.setCode(ErrorCode.AUTHENTICATION_FAILURE);
                err.setMessage("The \"auth\" token presented is not recognized, missing, or empty.");
                return res;
            }
        } catch (DigestException e) {
            throw new GenericRuntimeException(e);
        }

        hash = appVersion.getArchive().getHash();
        hashAlg = appVersion.getArchive().getHashAlgorithm();
        fileName = app.getName() + " - " + appVersion.getIdentifier();
    } else {
        fileName = hashAlg + "-" + hash;
    }

    File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash);
    if (!file.exists()) {
        String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found.";
        // TODO: create an enumeration for this error
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage(mesg);
        logger.warn(mesg);
        return res;
    }

    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(file.length()).intValue());
        URLCodec codec = new URLCodec();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";");

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            //if(outputStream!=null) {outputStream.close();}
        }
        response.flushBuffer();
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
    }

    return null;
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * This method will be used to create a Definition based on the
 * WSDL file generated by WsGen.//w  ww. j av  a 2  s  .co  m
 */
private HashMap<String, Definition> readInWSDL(String localOutputDirectory) throws Exception {
    List<File> wsdlFiles = getWSDLFiles(localOutputDirectory);
    HashMap<String, Definition> wsdlDefMap = new HashMap<String, Definition>();
    for (File wsdlFile : wsdlFiles) {
        if (wsdlFile != null) {
            try {
                WSDLFactory wsdlFactory = WSDLFactory.newInstance();
                WSDLReader wsdlReader = wsdlFactory.newWSDLReader();
                InputStream is = wsdlFile.toURL().openStream();
                Definition definition = wsdlReader.readWSDL(localOutputDirectory, new InputSource(is));
                try {
                    definition.setDocumentBaseURI(wsdlFile.toURI().toString());
                    if (log.isDebugEnabled()) {
                        log.debug("Set base document URI for generated WSDL: " + wsdlFile.toURI().toString());
                    }
                } catch (Throwable t) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not set base document URI for generated " + "WSDL: "
                                + wsdlFile.getAbsolutePath() + " : " + t.toString());
                    }
                }
                wsdlDefMap.put(wsdlFile.getName().toLowerCase(), definition);
            } catch (WSDLException e) {
                String msg = "Error occurred while attempting to create Definition from "
                        + "generated WSDL file {" + wsdlFile.getName() + "}";
                log.error(msg, e);
                throw new Exception(msg);
            } catch (IOException e) {
                String msg = "Error occurred while attempting to create Definition from "
                        + "generated WSDL file  {" + wsdlFile.getName() + "}";
                log.error(msg, e);
                throw new Exception(msg);
            }
        }
    }
    return wsdlDefMap;
}

From source file:org.globus.gatekeeper.jobmanager.AbstractJobManager.java

protected String stageFile(String url) throws MalformedURLException, IOException, UrlCopyException {
    // it is a url
    GlobusURL remoteUrl;//w  w w .  j  a v a  2 s. co m
    GlobusURL localUrl;

    remoteUrl = new GlobusURL(url);

    File localFile = null;

    localFile = File.createTempFile("staged", getExtension(remoteUrl));

    fileList.add(localFile);

    localUrl = new GlobusURL(localFile.toURL());

    UrlCopy c = new UrlCopy();
    c.setCredentials(_credential);
    c.setSourceUrl(remoteUrl);
    c.setDestinationUrl(localUrl);
    c.copy();

    return localFile.getAbsolutePath();
}

From source file:be.docarch.odt2braille.PEF.java

private void extractPrintPageRange(File bodyFile, Volume volume, Configuration settings) throws IOException {

    String volumeNode = "dtb:volume";
    String id = volume.getIdentifier();
    if (id != null) {
        volumeNode += "[@id='" + id + "']";
    }//from  w w  w  .j a  v  a 2  s .c  o  m

    String s;
    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(), "//" + volumeNode
            + "/*[not(self::dtb:pagebreak or ancestor::dtb:div[@class='not-in-volume'])][1][self::dtb:pagenum]",
            namespace)) {
        s = XPathUtils.evaluateString(bodyFile.toURL().openStream(), "//" + volumeNode
                + "/*[not(self::dtb:pagebreak or ancestor::dtb:div[@class='not-in-volume'])][1][self::dtb:pagenum]",
                namespace);
    } else {
        s = XPathUtils.evaluateString(bodyFile.toURL().openStream(),
                "//" + volumeNode
                        + "/*[not(ancestor::dtb:div[@class='not-in-volume'])][1]/preceding::dtb:pagenum[1]",
                namespace);
    }
    if (s.equals("")) {
        if (settings.getMergeUnnumberedPages()) {
            s = XPathUtils.evaluateString(bodyFile.toURL().openStream(), "//" + volumeNode
                    + "/*[not(self::dtb:div[@class='not-in-volume'])][1]/preceding::dtb:pagenum[text()][1]",
                    namespace);
        } else {
            s = XPathUtils.evaluateString(bodyFile.toURL().openStream(),
                    "//" + volumeNode
                            + "//dtb:pagenum[text() and not(ancestor::dtb:div[@class='not-in-volume'])][1]",
                    namespace);
        }
    }
    if (!s.equals("")) {
        volume.setFirstPrintPage(s);
        s = XPathUtils.evaluateString(bodyFile.toURL().openStream(), "//" + volumeNode + "//dtb:pagenum["
                + "text() and not(ancestor::dtb:div[@class='not-in-volume']) and not(following::dtb:pagenum[ancestor::"
                + volumeNode + " and text() and not(ancestor::dtb:div[@class='not-in-volume'])])]", namespace);
        if (!(s.equals("") || s.equals(volume.getFirstPrintPage()))) {
            volume.setLastPrintPage(s);
        }
    }
}

From source file:org.codehaus.enunciate.modules.BasicAppModule.java

/**
 * Whether to exclude a file from copying to the WEB-INF/lib directory.
 *
 * @param file The file to exclude.//from  w  w w  . ja  v a 2  s.c om
 * @return Whether to exclude a file from copying to the lib directory.
 */
protected boolean knownExclude(File file) throws IOException {
    //instantiate a loader with this library only in its path...
    URLClassLoader loader = new URLClassLoader(new URL[] { file.toURL() }, null);
    if (loader.findResource("META-INF/enunciate/preserve-in-war") != null) {
        debug("%s is a known include because it contains the entry META-INF/enunciate/preserve-in-war.", file);
        //if a jar happens to have the enunciate "preserve-in-war" file, it is NOT excluded.
        return false;
    } else if (loader
            .findResource(com.sun.tools.apt.Main.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be tools.jar.", file);
        //exclude tools.jar.
        return true;
    } else if (loader.findResource(
            net.sf.jelly.apt.Context.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be apt-jelly.", file);
        //exclude apt-jelly-core.jar
        return true;
    } else if (loader.findResource(net.sf.jelly.apt.freemarker.FreemarkerModel.class.getName().replace('.', '/')
            .concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the apt-jelly-freemarker libs.", file);
        //exclude apt-jelly-freemarker.jar
        return true;
    } else if (loader.findResource(
            freemarker.template.Configuration.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the freemarker libs.", file);
        //exclude freemarker.jar
        return true;
    } else if (loader.findResource(Enunciate.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the enunciate core jar.", file);
        //exclude enunciate-core.jar
        return true;
    } else if (loader.findResource("javax/servlet/ServletContext.class") != null) {
        debug("%s is a known exclude because it appears to be the servlet api.", file);
        //exclude the servlet api.
        return true;
    } else if (loader.findResource(
            "org/codehaus/enunciate/modules/xfire_client/EnunciatedClientSoapSerializerHandler.class") != null) {
        debug("%s is a known exclude because it appears to be the enunciated xfire client tools jar.", file);
        //exclude xfire-client-tools
        return true;
    } else if (loader.findResource("javax/swing/SwingBeanInfoBase.class") != null) {
        debug("%s is a known exclude because it appears to be dt.jar.", file);
        //exclude dt.jar
        return true;
    } else if (loader.findResource("HTMLConverter.class") != null) {
        debug("%s is a known exclude because it appears to be htmlconverter.jar.", file);
        return true;
    } else if (loader.findResource("sun/tools/jconsole/JConsole.class") != null) {
        debug("%s is a known exclude because it appears to be jconsole.jar.", file);
        return true;
    } else if (loader.findResource("sun/jvm/hotspot/debugger/Debugger.class") != null) {
        debug("%s is a known exclude because it appears to be sa-jdi.jar.", file);
        return true;
    } else if (loader.findResource("sun/io/ByteToCharDoubleByte.class") != null) {
        debug("%s is a known exclude because it appears to be charsets.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/deploy/ClientContainer.class") != null) {
        debug("%s is a known exclude because it appears to be deploy.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/javaws/Globals.class") != null) {
        debug("%s is a known exclude because it appears to be javaws.jar.", file);
        return true;
    } else if (loader.findResource("javax/crypto/SecretKey.class") != null) {
        debug("%s is a known exclude because it appears to be jce.jar.", file);
        return true;
    } else if (loader.findResource("sun/net/www/protocol/https/HttpsClient.class") != null) {
        debug("%s is a known exclude because it appears to be jsse.jar.", file);
        return true;
    } else if (loader.findResource("sun/plugin/JavaRunTime.class") != null) {
        debug("%s is a known exclude because it appears to be plugin.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/corba/se/impl/activation/ServerMain.class") != null) {
        debug("%s is a known exclude because it appears to be rt.jar.", file);
        return true;
    } else if (ServiceLoader.load(DeploymentModule.class, loader).iterator().hasNext()) {
        debug("%s is a known exclude because it appears to be an enunciate module.", file);
        //exclude by default any deployment module libraries.
        return true;
    }

    return false;
}

From source file:org.apache.maven.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request)
        throws CheckstyleExecutorException, CheckstyleException {
    // Checkstyle will always use the context classloader in order
    // to load resources (dtds),
    // so we have to fix it
    // olamy this hack is not anymore needed in Maven 3.x
    ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
    Thread.currentThread().setContextClassLoader(checkstyleClassLoader);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }/*  w  w w  . jav a 2 s. c om*/

    MavenProject project = request.getProject();

    configureResourceLocator(locator, request, null);

    configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts());

    // Config is less critical than License, locator can still be used.
    // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );

    List<File> files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }

    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);

    Checker checker = new Checker();

    // setup classloader, needed to avoid "Unable to get class information for ..." errors
    List<String> classPathStrings = new ArrayList<String>();
    List<String> outputDirectories = new ArrayList<String>();

    // stand-alone
    Collection<File> sourceDirectories = null;
    Collection<File> testSourceDirectories = request.getTestSourceDirectories();

    // aggregator
    Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();
    Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();

    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = new ArrayList<File>(childProject.getCompileSourceRoots().size());
            List<String> compileSourceRoots = childProject.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }
            sourceDirectoriesByProject.put(childProject, sourceDirectories);

            testSourceDirectories = new ArrayList<File>(childProject.getTestCompileSourceRoots().size());
            List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }
            testSourceDirectoriesByProject.put(childProject, testSourceDirectories);

            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories,
                    sourceDirectories, testSourceDirectories);
        }
    } else {
        sourceDirectories = request.getSourceDirectories();
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories,
                testSourceDirectories);
    }

    final List<URL> urls = new ArrayList<URL>(classPathStrings.size());

    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURL();
                    getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString()
                            + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
        }
    });

    checker.setClassloader(projectClassLoader);

    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());

    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);

    AuditListener listener = request.getListener();

    if (listener != null) {
        checker.addListener(listener);
    }

    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }

    CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = sourceDirectoriesByProject.get(childProject);
            testSourceDirectories = testSourceDirectoriesByProject.get(childProject);
            addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories,
                    childProject.getResources(), request);
        }
    } else {
        addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(),
                request);
    }

    checker.addListener(checkerListener);

    int nbErrors = checker.process(files);

    checker.destroy();

    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }

    if (request.getStringOutputStream() != null) {
        String message = request.getStringOutputStream().toString().trim();

        if (message.length() > 0) {
            getLogger().info(message);
        }
    }

    if (nbErrors > 0) {
        String message = "There are " + nbErrors + " checkstyle errors.";

        if (request.isFailsOnError()) {
            // TODO: should be a failure, not an error. Report is not meant to
            // throw an exception here (so site would
            // work regardless of config), but should record this information
            throw new CheckstyleExecutorException(message);
        } else {
            getLogger().info(message);
        }
    }

    return checkerListener.getResults();
}

From source file:com.mellanox.hadoop.mapred.MapOutputLocation.java

protected void configureClasspath(JobConf conf) throws IOException {

    // get the task and the current classloader which will become the parent
    Task task = reduceTask;//from   w ww .  j a va2s  .c o  m
    ClassLoader parent = conf.getClassLoader();

    // get the work directory which holds the elements we are dynamically
    // adding to the classpath
    File workDir = new File(task.getJobFile()).getParentFile();
    ArrayList<URL> urllist = new ArrayList<URL>();

    // add the jars and directories to the classpath
    String jar = conf.getJar();
    if (jar != null) {
        File jobCacheDir = new File(new Path(jar).getParent().toString());

        File[] libs = new File(jobCacheDir, "lib").listFiles();
        if (libs != null) {
            for (int i = 0; i < libs.length; i++) {
                urllist.add(libs[i].toURL());
            }
        }
        urllist.add(new File(jobCacheDir, "classes").toURL());
        urllist.add(jobCacheDir.toURL());

    }
    urllist.add(workDir.toURL());

    // create a new classloader with the old classloader as its parent
    // then set that classloader as the one used by the current jobconf
    URL[] urls = urllist.toArray(new URL[urllist.size()]);
    URLClassLoader loader = new URLClassLoader(urls, parent);
    conf.setClassLoader(loader);
}

From source file:org.geoserver.wfs.response.ShapeZipOutputFormat.java

/**
 * Creates a shapefile data store for the specified schema 
 * @param tempDir/*  w w  w .  ja v  a 2  s .  c  om*/
 * @param charset
 * @param schema
 * @return
 * @throws MalformedURLException
 * @throws FileNotFoundException
 * @throws IOException
 */
private ShapefileDataStore buildStore(File tempDir, Charset charset, SimpleFeatureType schema)
        throws MalformedURLException, FileNotFoundException, IOException {
    File file = new File(tempDir, schema.getTypeName() + ".shp");
    ShapefileDataStore sfds = new ShapefileDataStore(file.toURL());

    // handle shapefile encoding
    // and dump the charset into a .cst file, for debugging and control purposes
    // (.cst is not a standard extension)
    sfds.setCharset(charset);
    File charsetFile = new File(tempDir, schema.getTypeName() + ".cst");
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(charsetFile);
        pw.write(charset.name());
    } finally {
        if (pw != null)
            pw.close();
    }

    try {
        sfds.createSchema(schema);
    } catch (NullPointerException e) {
        LOGGER.warning(
                "Error in shapefile schema. It is possible you don't have a geometry set in the output. \n"
                        + "Please specify a <wfs:PropertyName>geom_column_name</wfs:PropertyName> in the request");
        throw new ServiceException(
                "Error in shapefile schema. It is possible you don't have a geometry set in the output.");
    }

    try {
        if (schema.getCoordinateReferenceSystem() != null)
            sfds.forceSchemaCRS(schema.getCoordinateReferenceSystem());
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Could not properly create the .prj file", e);
    }

    return sfds;
}

From source file:org.apache.catalina.manager.HTMLManagerServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *///from   w ww  .jav  a  2s. c  o  m
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    if (command == null || !command.equals("/upload")) {
        doGet(request, response);
        return;
    }

    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);

    String message = "";

    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    // Get the tempdir
    File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
    // Set upload parameters
    upload.setSizeMax(-1);
    upload.setRepositoryPath(tempdir.getCanonicalPath());

    // Parse the request
    String basename = null;
    File appBaseDir = null;
    String war = null;
    FileItem warUpload = null;
    try {
        List items = upload.parseRequest(request);

        // Process the uploaded fields
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("deployWar") && warUpload == null) {
                    warUpload = item;
                } else {
                    item.delete();
                }
            }
        }
        while (true) {
            if (warUpload == null) {
                message = sm.getString("htmlManagerServlet.deployUploadNoFile");
                break;
            }
            war = warUpload.getName();
            if (!war.toLowerCase().endsWith(".war")) {
                message = sm.getString("htmlManagerServlet.deployUploadNotWar", war);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (war.lastIndexOf('\\') >= 0) {
                war = war.substring(war.lastIndexOf('\\') + 1);
            }
            if (war.lastIndexOf('/') >= 0) {
                war = war.substring(war.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            String appBase = null;
            appBase = ((Host) context.getParent()).getAppBase();
            appBaseDir = new File(appBase);
            if (!appBaseDir.isAbsolute()) {
                appBaseDir = new File(System.getProperty("catalina.base"), appBase);
            }
            basename = war.substring(0, war.indexOf(".war"));
            File file = new File(appBaseDir, war);
            if (file.exists()) {
                message = sm.getString("htmlManagerServlet.deployUploadWarExists", war);
                break;
            }
            warUpload.write(file);
            try {
                URL url = file.toURL();
                war = url.toString();
                war = "jar:" + war + "!/";
            } catch (MalformedURLException e) {
                file.delete();
                throw e;
            }
            break;
        }
    } catch (Exception e) {
        message = sm.getString("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    } finally {
        if (warUpload != null) {
            warUpload.delete();
        }
        warUpload = null;
    }

    // Extract the nested context deployment file (if any)
    File localWar = new File(appBaseDir, basename + ".war");
    File localXml = new File(configBase, basename + ".xml");
    try {
        extractXml(localWar, localXml);
    } catch (IOException e) {
        log("managerServlet.extract[" + localWar + "]", e);
        return;
    }
    String config = null;
    try {
        if (localXml.exists()) {
            URL url = localXml.toURL();
            config = url.toString();
        }
    } catch (MalformedURLException e) {
        throw e;
    }

    // If there were no errors, deploy the WAR
    if (message.length() == 0) {
        message = deployInternal(config, null, war);
    }

    list(request, response, message);
}