Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

In this page you can find the example usage for javax.naming Context lookup.

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.headstrong.fusion.messaging.model.endpoint.binding.JmsBindingEndPointModeler.java

/**
 * Creates a {@link JmsComponent} using the parameters set.
 * //www.  jav a  2  s.  c  om
 * @param routeBuilder
 * @return {@link JmsComponent}
 * @throws ProcessModellingException
 */
@SuppressWarnings("unchecked")
private Component getJmsComponent(RouteBuilder routeBuilder) throws ProcessModellingException {
    JmsComponent jmsComponent = null;
    if (this.getProvider().equals(Provider.activemq.toString())) {
        jmsComponent = ActiveMQComponent.activeMQComponent();
        jmsComponent.setConnectionFactory(new PooledConnectionFactory(this.getBrokerUrl()));
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else if (this.getProvider().equals(Provider.ibmmq.toString())) {
        JmsConnectionFactory factory = null;
        try {
            JmsFactoryFactory jmsFactoryFactory;
            jmsFactoryFactory = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER);
            factory = jmsFactoryFactory.createConnectionFactory();
            factory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            factory.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, this.getQueueManager());
            factory.setStringProperty(WMQConstants.WMQ_HOST_NAME, this.getBrokerUrl());
            factory.setIntProperty(WMQConstants.WMQ_PORT, this.getPort());
            if (this.getChannel() != null && !this.getChannel().isEmpty())
                factory.setStringProperty(WMQConstants.WMQ_CHANNEL, this.getChannel());
            factory.setIntProperty(WMQConstants.DELIVERY_MODE, this.getDeliveryMode());
        } catch (JMSException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(factory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else {
        Hashtable<String, String> prop = new Hashtable<String, String>();
        // Mandatory property.
        prop.put(Context.PROVIDER_URL, this.getLdapConfiguration().getProviderUrl());
        prop.put(Context.INITIAL_CONTEXT_FACTORY, this.getLdapConfiguration().getInitialContextFactory());

        // Only these optional properties supported now.
        if (this.getLdapConfiguration().getSecurityAuthentication() != null) {
            prop.put(Context.SECURITY_AUTHENTICATION, this.getLdapConfiguration().getSecurityAuthentication());
        }
        if (this.getLdapConfiguration().getSecutiryPrincipal() != null) {
            prop.put(Context.SECURITY_PRINCIPAL, this.getLdapConfiguration().getSecutiryPrincipal());
        }
        if (this.getLdapConfiguration().getSecutiryCredentials() != null) {
            prop.put(Context.SECURITY_CREDENTIALS, this.getLdapConfiguration().getSecutiryCredentials());
        }
        Context context;
        ConnectionFactory connectionFactory;
        try {
            // HACK required to avoid ClassNotFoundException while
            // retrieving the
            // InitialContext.
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                context = new InitialContext(prop);
                connectionFactory = (ConnectionFactory) context
                        .lookup(this.getLdapConfiguration().getConnectionFactoryJndiName());
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
            // HACK -- Finished
        } catch (NamingException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(connectionFactory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    }

    if (jmsComponent != null) {
        jmsComponent.setConcurrentConsumers(getThreadCount());
    }
    return jmsComponent;
}

From source file:org.dhatim.routing.jms.JMSRouter.java

@Initialize
public void initialize() throws SmooksConfigurationException, JMSException {
    Context context = null;
    boolean initialized = false;

    if (beanId == null) {
        throw new SmooksConfigurationException("Mandatory 'beanId' property not defined.");
    }/*from www  .j a  va  2s .c  o m*/
    if (jmsProperties.getDestinationName() == null) {
        throw new SmooksConfigurationException("Mandatory 'destinationName' property not defined.");
    }

    try {
        if (correlationIdPattern != null) {
            correlationIdTemplate = new FreeMarkerTemplate(correlationIdPattern);
        }

        Properties jndiContextProperties = jndiProperties.toProperties();

        if (jndiContextProperties.isEmpty()) {
            context = new InitialContext();
        } else {
            context = new InitialContext(jndiContextProperties);
        }
        destination = (Destination) context.lookup(jmsProperties.getDestinationName());
        msgProducer = createMessageProducer(destination, context);
        setMessageProducerProperties();

        initialized = true;
    } catch (NamingException e) {
        final String errorMsg = "NamingException while trying to lookup [" + jmsProperties.getDestinationName()
                + "]";
        logger.error(errorMsg, e);
        throw new SmooksConfigurationException(errorMsg, e);
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException e) {
                logger.debug("NamingException while trying to close initial Context");
            }
        }

        if (!initialized) {
            releaseJMSResources();
        }
    }
}

From source file:jndi.view.JndiView.java

/**
 * @param ctx/*from  w w  w .  j  a v  a  2 s.c o  m*/
 *        the Context we're examining
 * @param path
 *        the path to examine
 * @param bindings
 *        the {@link NamingEnumeration} of {@link Binding}s
 * @return List of {@link JndiEntry}
 * @throws NamingException
 *         on exception
 */
private List<JndiEntry> examineBindings(final Context ctx, final String path,
        final NamingEnumeration<Binding> bindings) throws NamingException {
    if (null == bindings) {
        throw new NullPointerException("bindings is null!");
    }
    final List<JndiEntry> entries = new ArrayList<JndiEntry>();
    while (bindings.hasMore()) {
        final Binding binding = bindings.next();
        final String name = binding.getName();
        final String className = binding.getClassName();

        logger.finest("name: " + name + " [" + className + "]");
        final JndiEntry entry = new JndiEntry(name, className);
        final Object obj = binding.getObject();
        if (obj instanceof Context) {
            entry.setContext(true);
            String link = name;
            if (!path.isEmpty()) {
                link = path + "/" + name;
            }
            entry.setLink(link);
        } else if (obj instanceof Reference) {
            final Reference ref = (Reference) obj;
            entry.setTargetClassName(ref.getClassName());
        } else if ("org.glassfish.javaee.services.ResourceProxy".equals(className)) {
            // SUPPRESS CHECKSTYLE AvoidInlineConditionals
            final Object lookup = ctx.lookup(path.isEmpty() ? name : path + "/" + name);
            if (lookup != null) {
                final String lookedUpClassName = lookup.getClass().getName();
                logger.finest("lookup(\"" + name + "\") returned " + lookedUpClassName);
                entry.setTargetClassName(lookedUpClassName);
            }
        } else if ("com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy".equals(className)) {
            inspectJndiNamingObjectProxy(entry, obj);
        }
        entries.add(entry);
    }
    return entries;
}

From source file:com.google.gsa.Kerberos.java

/**
 * Reads the valve configuration path//ww w  .  jav  a2 s  . c  o m
 * 
 * @return
 */
public String readValveConfigPath() {

    String valveConfigPath = null;

    try {
        //Get Config
        javax.naming.Context ctx = new javax.naming.InitialContext();
        javax.naming.Context env = (javax.naming.Context) ctx.lookup("java:comp/env");

        //Get gsaValveConfigPath
        valveConfigPath = (String) env.lookup("gsaValveConfigPath");
    } catch (NamingException e) {
        logger.debug("Error when reading the Valve Config Path " + e);
    }

    return valveConfigPath;
}

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8Schema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }/*from  ww  w  . j  a  v  a  2  s .  c  o  m*/

    if (configuration != null) {
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:postgresql://" + dbServer + ":" + Integer.toString(dbPort) + "/" + dbDatabase;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.rollback();
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }

    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }

    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Get the servlet configuration//from w  w w  .  jav a 2  s.  c o m
 * <p>
 * @return HTTP response containing the Servlet configuration in JSON format
 */
@GET
@Path("config")
@Produces(MediaType.APPLICATION_JSON)
public Response getConfig() {

    log.info("GET raml/config");

    Map<String, Object> configMap = new LinkedHashMap<String, Object>();

    try {
        Context initialContext = new InitialContext();
        Context envContext = (Context) initialContext.lookup("java:comp/env");

        configMap.put("vseServerUrl", envContext.lookup("vseServerUrl"));
        configMap.put("vseServicePortRange", envContext.lookup("vseServicePortRange"));
        configMap.put("vseServiceReadyWaitSeconds", envContext.lookup("vseServiceReadyWaitSeconds"));

    } catch (NamingException e) {
        e.printStackTrace();
        log.error("Failed to obtain servlet configuration", e.getCause());
    }

    GsonBuilder gsonBuilder = new GsonBuilder();

    gsonBuilder.setPrettyPrinting();
    gsonBuilder.serializeNulls();

    Gson gson = gsonBuilder.create();

    Response response = Response.status(200).entity(gson.toJson(configMap)).build();

    return response;
}

From source file:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Retrieves the adaptor class from the application context given the
 * parameter values./*  w ww.  j a  v a  2 s. c  o  m*/
 * 
 * @param source the JNDI string or url mapped to the query's app in the YADA index
 * @param version the version of the framework, for selection of the proper adaptor
 * @return the {@link Class} of the appropriate adaptor
 * @throws YADAResourceException when {@code source} can't be found, or there is an issue with the
 *           application context
 * @throws YADAUnsupportedAdaptorException when the adaptor class mapped to {@code source} can't be found
 * @deprecated since 8.0.0           
 */
@SuppressWarnings("unchecked")
@Deprecated
public Class<Adaptor> getAdaptorClass(String source, String version)
        throws YADAResourceException, YADAUnsupportedAdaptorException {
    String driverName = "";
    String className = REST_ADAPTOR_CLASS_NAME;
    l.debug("JNDI source is [" + source + "]");
    if (source.matches(RX_JDBC_JNDI)) {
        Context ctx;
        try {
            ctx = new InitialContext();
        } catch (NamingException e) {
            String msg = "Could not create context.";
            throw new YADAResourceException(msg, e);
        }
        DataSource ds;
        try {
            ds = (DataSource) ctx.lookup(source);
        } catch (NamingException e) {
            String msg = "Could not find data source at " + source;
            throw new YADAResourceException(msg, e);
        }

        //TODO add integration tests for multiple containers after breaking tomcat dbcp dependency
        //     http://docs.oracle.com/javase/1.5.0/docs/api/java/sql/DriverManager.html?is-external=true
        driverName = ((HikariDataSource) ds).getDriverClassName();
        l.debug("JDBC driver is [" + driverName + "]");
        className = Finder.getEnv("adaptor/" + driverName + version);
    } else if (source.matches(RX_SOAP)) {
        className = SOAP_ADAPTOR_CLASS_NAME;
    } else if (source.matches(RX_FILE)) {
        className = FILESYSTEM_ADAPTOR_CLASS_NAME;
    }
    l.debug("JDBCAdaptor class is [" + className + "]");

    Class<Adaptor> adaptorClass;
    try {
        adaptorClass = (Class<Adaptor>) Class.forName(className);
    } catch (ClassNotFoundException e) {
        String msg = "Could not find appropriate adaptor class";
        throw new YADAUnsupportedAdaptorException(msg, e);
    } catch (NoClassDefFoundError e) {
        String msg = "Could not find appropriate adaptor class";
        throw new YADAUnsupportedAdaptorException(msg, e);
    }
    return adaptorClass;
}

From source file:org.apache.torque.dsfactory.JndiDataSourceFactory.java

/**
 *
 * @param ctx//from  w  ww . j  a  v a  2  s . c  om
 * @param path
 * @param ds
 * @throws Exception
 */
private void bindDStoJndi(Context ctx, String path, Object ds) throws Exception {
    debugCtx(ctx);

    // add subcontexts, if not added already
    int start = path.indexOf(':') + 1;
    if (start > 0) {
        path = path.substring(start);
    }
    StringTokenizer st = new StringTokenizer(path, "/");
    while (st.hasMoreTokens()) {
        String subctx = st.nextToken();
        if (st.hasMoreTokens()) {
            try {
                ctx.createSubcontext(subctx);
                log.debug("Added sub context: " + subctx);
            } catch (NameAlreadyBoundException nabe) {
                // ignore
                log.debug("Sub context " + subctx + " already exists");
            } catch (NamingException ne) {
                log.debug("Naming exception caught " + "when creating subcontext" + subctx, ne);
                // even though there is a specific exception
                // for this condition, some implementations
                // throw the more general one.
                /*
                 *                      if (ne.getMessage().indexOf("already bound") == -1 )
                 *                      {
                 *                      throw ne;
                 *                      }
                 */
                // ignore
            }
            ctx = (Context) ctx.lookup(subctx);
        } else {
            // not really a subctx, it is the ds name
            ctx.bind(subctx, ds);
        }
    }
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Deploys an OData virtual service from an uploaded RAML file
 * <p>/*w  ww.  j  av a  2s.  com*/
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @param baseUri the baseUri to use in the returned WADL file.  Optionally provided, this will override that which is defined in the uploaded RAML.
 * @param authorization basic authorization string (user:password) used to grant access to LISA/DevTest REST APIs (when required)
 * @return HTTP response containing a status of OData virtual service deployed from uploaded RAML file
 */
@POST
@Path("odataVs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response deployOdataVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("") @FormDataParam("authorization") String authorization) {

    log.info("POST raml/odataVs");

    Response response = null;
    File uploadedFile = null;
    File ramlFile = null;
    FileInputStream ramlFileStream = null;

    try {

        if (fileDetail == null || fileDetail.getFileName() == null || fileDetail.getName() == null) {
            throw new InvalidParameterException("file");
        }

        if (!baseUri.isEmpty()) { // validate URI syntax
            try {

                new URI(baseUri);

            } catch (URISyntaxException uriEx) {

                throw new InvalidParameterException(String.format("baseUri - %s", uriEx.getMessage()));

            }
        }

        uploadedFile = FileUtil.getUploadedFile(uploadedInputStream, fileDetail);

        if (uploadedFile.isDirectory()) { // find RAML file in directory

            // First, look for a raml file that has the same base name as the uploaded file
            String targetName = Files.getNameWithoutExtension(fileDetail.getFileName()) + ".raml";

            ramlFile = FileUtil.selectRamlFile(uploadedFile, targetName);

        } else {

            ramlFile = uploadedFile;

        }

        List<ValidationResult> results = null;

        try {

            results = RamlUtil.validateRaml(ramlFile);

        } catch (IOException e) {

            String msg = String.format("RAML validation failed catastrophically for %s", ramlFile.getName());
            throw new Exception(msg, e.getCause());
        }

        // If the RAML file is valid, get to work...
        if (ValidationResult.areValid(results)) {

            try {

                ramlFileStream = new FileInputStream(ramlFile.getAbsolutePath());

            } catch (FileNotFoundException e) {

                String msg = String.format("Failed to open input stream from %s", ramlFile.getAbsolutePath());

                throw new Exception(msg, e.getCause());

            }

            FileResourceLoader resourceLoader = new FileResourceLoader(ramlFile.getParentFile());
            RamlDocumentBuilder rdb = new RamlDocumentBuilder(resourceLoader);
            Raml raml = rdb.build(ramlFileStream, ramlFile.getAbsolutePath());

            ramlFileStream.close();
            ramlFileStream = null;

            if (!baseUri.isEmpty()) {
                raml.setBaseUri(baseUri);
            }

            try {

                Context initialContext = new InitialContext();
                Context envContext = (Context) initialContext.lookup("java:comp/env");

                String vseServerUrl = (String) envContext.lookup("vseServerUrl");
                String vseServicePortRange = (String) envContext.lookup("vseServicePortRange");
                int vseServiceReadyWaitSeconds = (Integer) envContext.lookup("vseServiceReadyWaitSeconds");

                // Generate mar and deploy VS
                VirtualServiceBuilder vs = new VirtualServiceBuilder(vseServerUrl, vseServicePortRange,
                        vseServiceReadyWaitSeconds, false, authorization);
                response = vs.setInputFile(raml, ramlFile.getParentFile(), false);

            } catch (Exception e) {

                String msg = String.format("Failed to deploy service - %s", e.getMessage());

                throw new Exception(msg, e.getCause());

            }

        } else { // RAML file failed validation

            StringBuilder sb = new StringBuilder();

            for (ValidationResult result : results) {

                sb.append(result.getLevel());

                if (result.getLine() > 0) {

                    sb.append(String.format(" (line %d)", result.getLine()));

                }

                sb.append(String.format(" - %s\n", result.getMessage()));
            }

            response = Response.status(Status.BAD_REQUEST).entity(sb.toString()).build();

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex);

        if (ex instanceof JsonSyntaxException) {

            response = Response.status(Status.BAD_REQUEST).entity(msg).build();

        } else if (ex instanceof InvalidParameterException) {

            response = Response.status(Status.BAD_REQUEST)
                    .entity(String.format("Invalid form parameter - %s", ex.getMessage())).build();

        } else {

            response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build();

        }

        return response;

    } finally {

        if (null != ramlFileStream) {

            try {

                ramlFileStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        if (null != uploadedFile) {

            if (uploadedFile.isDirectory()) {

                try {

                    System.gc(); // To help release files that snakeyaml abandoned open streams on -- otherwise, some files may not delete

                    // Wait a bit for the system to close abandoned streams
                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    FileUtils.deleteDirectory(uploadedFile);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                uploadedFile.delete();
            }

        }
    }

    return response;
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Deploys an REST virtual service from an uploaded RAML file
 * <p>//from   ww w. j  av a 2  s .c o  m
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @param baseUri the baseUri to use in the returned WADL file.  Optionally provided, this will override that which is defined in the uploaded RAML.
 * @param authorization basic authorization string (user:password) used to grant access to LISA/DevTest REST APIs (when required)
 * @return HTTP response containing a status of REST virtual service deployed from uploaded RAML file
 */
@POST
@Path("restVs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response deployRestVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument,
        @DefaultValue("") @FormDataParam("authorization") String authorization) {

    log.info("POST raml/restVs");

    Response response = null;
    File uploadedFile = null;
    File ramlFile = null;
    FileInputStream ramlFileStream = null;

    try {

        if (fileDetail == null || fileDetail.getFileName() == null || fileDetail.getName() == null) {
            throw new InvalidParameterException("file");
        }

        if (!baseUri.isEmpty()) { // validate URI syntax
            try {

                new URI(baseUri);

            } catch (URISyntaxException uriEx) {

                throw new InvalidParameterException(String.format("baseUri - %s", uriEx.getMessage()));

            }
        }

        uploadedFile = FileUtil.getUploadedFile(uploadedInputStream, fileDetail);

        if (uploadedFile.isDirectory()) { // find RAML file in directory

            // First, look for a raml file that has the same base name as the uploaded file
            String targetName = Files.getNameWithoutExtension(fileDetail.getFileName()) + ".raml";

            ramlFile = FileUtil.selectRamlFile(uploadedFile, targetName);

        } else {

            ramlFile = uploadedFile;

        }

        List<ValidationResult> results = null;

        try {

            results = RamlUtil.validateRaml(ramlFile);

        } catch (IOException e) {

            String msg = String.format("RAML validation failed catastrophically for %s", ramlFile.getName());
            throw new Exception(msg, e.getCause());
        }

        // If the RAML file is valid, get to work...
        if (ValidationResult.areValid(results)) {

            try {

                ramlFileStream = new FileInputStream(ramlFile.getAbsolutePath());

            } catch (FileNotFoundException e) {

                String msg = String.format("Failed to open input stream from %s", ramlFile.getAbsolutePath());

                throw new Exception(msg, e.getCause());

            }

            FileResourceLoader resourceLoader = new FileResourceLoader(ramlFile.getParentFile());
            RamlDocumentBuilder rdb = new RamlDocumentBuilder(resourceLoader);
            Raml raml = rdb.build(ramlFileStream, ramlFile.getAbsolutePath());

            ramlFileStream.close();
            ramlFileStream = null;

            if (!baseUri.isEmpty()) {
                raml.setBaseUri(baseUri);
            }

            try {

                Context initialContext = new InitialContext();
                Context envContext = (Context) initialContext.lookup("java:comp/env");

                String vseServerUrl = (String) envContext.lookup("vseServerUrl");
                String vseServicePortRange = (String) envContext.lookup("vseServicePortRange");
                int vseServiceReadyWaitSeconds = (Integer) envContext.lookup("vseServiceReadyWaitSeconds");

                // Generate mar and deploy VS
                VirtualServiceBuilder vs = new VirtualServiceBuilder(vseServerUrl, vseServicePortRange,
                        vseServiceReadyWaitSeconds, generateServiceDocument, authorization);
                response = vs.setInputFile(raml, ramlFile.getParentFile(), true);

            } catch (Exception e) {

                String msg = String.format("Failed to deploy service - %s", e.getMessage());

                throw new Exception(msg, e.getCause());

            }

        } else { // RAML file failed validation

            StringBuilder sb = new StringBuilder();

            for (ValidationResult result : results) {

                sb.append(result.getLevel());

                if (result.getLine() > 0) {

                    sb.append(String.format(" (line %d)", result.getLine()));

                }

                sb.append(String.format(" - %s\n", result.getMessage()));
            }

            response = Response.status(Status.BAD_REQUEST).entity(sb.toString()).build();

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex);

        if (ex instanceof JsonSyntaxException) {

            response = Response.status(Status.BAD_REQUEST).entity(msg).build();

        } else if (ex instanceof InvalidParameterException) {

            response = Response.status(Status.BAD_REQUEST)
                    .entity(String.format("Invalid form parameter - %s", ex.getMessage())).build();

        } else {

            response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build();

        }

        return response;

    } finally {

        if (null != ramlFileStream) {

            try {

                ramlFileStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        if (null != uploadedFile) {

            if (uploadedFile.isDirectory()) {

                try {

                    System.gc(); // To help release files that snakeyaml abandoned open streams on -- otherwise, some files may not delete

                    // Wait a bit for the system to close abandoned streams
                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    FileUtils.deleteDirectory(uploadedFile);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                uploadedFile.delete();
            }

        }
    }

    return response;
}