Example usage for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY

List of usage examples for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY.

Prototype

int SC_MOVED_PERMANENTLY

To view the source code for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY.

Click Source Link

Document

Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests.

Usage

From source file:org.webcurator.ui.tools.controller.BrowseController.java

/**
 * The handle method is the entry method into the browse controller.
 *//*from w w  w .j  a  va2 s.co m*/
@Override
protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm,
        BindException errors) throws Exception {

    // Cast the command to the correct command type.
    BrowseCommand command = (BrowseCommand) comm;

    // Build a command with the items from the URL.
    String base = req.getContextPath() + req.getServletPath();

    String line = req.getRequestURI().substring(base.length());

    Matcher matcher = p.matcher(line);
    if (matcher.matches()) {
        command.setHrOid(Long.parseLong(matcher.group(1)));
        command.setResource(matcher.group(2));
    }

    if (req.getQueryString() != null) {
        command.setResource(command.getResource() + "?" + req.getQueryString());
    }

    // Check if the command is prefixed with a forward slash.
    if (command.getResource().startsWith("/")) {
        command.setResource(command.getResource().substring(1));
    }

    // Now make sure that the domain name is in lowercase.
    Pattern urlBreakerPattern = Pattern.compile("(.*?)://(.*?)/(.*)");
    Matcher urlBreakerMatcher = urlBreakerPattern.matcher(command.getResource());
    if (urlBreakerMatcher.matches()) {
        command.setResource(urlBreakerMatcher.group(1) + "://" + urlBreakerMatcher.group(2).toLowerCase() + "/"
                + urlBreakerMatcher.group(3));
    }

    // Load the HarvestResourceDTO from the quality review facade.
    HarvestResourceDTO dto = qualityReviewFacade.getHarvestResourceDTO(command.getHrOid(),
            command.getResource());

    // If the resource is not found, go to an error page.
    if (dto == null) {
        log.debug("Resource not found: " + command.getResource());
        return new ModelAndView("browse-tool-not-found", "resourceName", command.getResource());
    } else {
        Header[] headers = null;
        // catch any DigitalAssetStoreException and log assumptions
        try {
            headers = qualityReviewFacade.getHttpHeaders(dto);
        } catch (DigitalAssetStoreException e) {
            log.info("Failed to get header for ti " + dto.getTargetInstanceOid());
            // throw new DigitalAssetStoreException(e);
        } catch (Exception e) {
            log.error("Unexpected exception encountered when retrieving WARC headers for ti "
                    + dto.getTargetInstanceOid());
            throw new Exception(e);
        }

        // Send the headers for a redirect.
        if (dto.getStatusCode() == HttpServletResponse.SC_MOVED_TEMPORARILY
                || dto.getStatusCode() == HttpServletResponse.SC_MOVED_PERMANENTLY) {
            res.setStatus(dto.getStatusCode());
            String location = getHeaderValue(headers, "Location");
            if (location != null) {
                String newUrl = browseHelper.convertUrl(command.getHrOid(), command.getResource(), location);
                res.setHeader("Location", newUrl);
            }
        }

        // Get the content type.
        String realContentType = getHeaderValue(headers, "Content-Type");
        String simpleContentType = this.getSimpleContentType(realContentType);

        String charset = null;
        if (realContentType != null) {
            Matcher charsetMatcher = CHARSET_PATTERN.matcher(realContentType);
            if (charsetMatcher.find()) {
                charset = charsetMatcher.group(1);
                log.debug("Desired charset: " + charset + " for " + command.getResource());
            } else {
                log.debug("No charset: " + charset + " (" + command.getResource());
            }
        }

        // If the content has been registered with the browseHelper to
        // require replacements, load the content and perform the
        // necessary replacements.
        if (browseHelper.isReplaceable(simpleContentType)) {
            StringBuilder content = null;

            try {
                content = readFile(dto, charset);
            } catch (DigitalAssetStoreException e) {
                if (log.isWarnEnabled()) {
                    log.warn(e.getMessage());
                }
            }
            ModelAndView mav = new ModelAndView("browse-tool-html");

            if (content != null) {
                // We might need to use a different base URL if a BASE HREF
                // tag
                // is used. We use the TagMagix class to perform the search.
                // Note that TagMagix leaves leading/trailing slashes on the
                // URL, so we need to do that
                String baseUrl = command.getResource();
                Pattern baseUrlGetter = BrowseHelper.getTagMagixPattern("BASE", "HREF");
                Matcher m = baseUrlGetter.matcher(content);
                if (m.find()) {
                    String u = m.group(1);
                    if (u.startsWith("\"") && u.endsWith("\"") || u.startsWith("'") && u.endsWith("'")) {

                        // Ensure the detected Base HREF is not commented
                        // out (unusual case, but we have seen it).
                        int lastEndComment = content.lastIndexOf("-->", m.start());
                        int lastStartComment = content.lastIndexOf("<!--", m.start());
                        if (lastStartComment < 0 || lastEndComment > lastStartComment) {
                            baseUrl = u.substring(1, u.length() - 1);
                        }
                    }

                }

                browseHelper.fix(content, simpleContentType, command.getHrOid(), baseUrl);
                mav.addObject("content", content.toString());
            } else {
                mav.addObject("content", "");
            }

            mav.addObject("Content-Type", realContentType);
            return mav;
        }

        // If there are no replacements, send the content back directly.
        else {
            if (dto.getLength() > MAX_MEMORY_SIZE) {
                Date dt = new Date();
                File f = qualityReviewFacade.getResource(dto);
                ModelAndView mav = new ModelAndView("browse-tool-other");
                mav.addObject("file", f);
                mav.addObject("contentType", realContentType);

                log.info("TIME TO GET RESOURCE(old): " + (new Date().getTime() - dt.getTime()));
                return mav;
            } else {
                Date dt = new Date();
                byte[] bytesBuffer = null;
                try {
                    bytesBuffer = qualityReviewFacade.getSmallResource(dto);
                } catch (org.webcurator.core.exceptions.DigitalAssetStoreException e) {
                    if (log.isWarnEnabled()) {
                        log.warn("Could not retrieve resource: " + dto.getName());
                    }
                }
                ModelAndView mav = new ModelAndView("browse-tool-other-small");
                mav.addObject("bytesBuffer", bytesBuffer);
                mav.addObject("contentType", realContentType);
                log.debug("TIME TO GET RESOURCE(new): " + (new Date().getTime() - dt.getTime()));
                return mav;
            }
        }
    }
}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

private void serveRedirect() throws IOException {

    RedirectInstruction redirectInstruction = response.getRedirectInstruction();

    int redirectStatus = redirectInstruction.isPermanentRedirect() ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    if (redirectInstruction.hasRedirectSitePath()) {
        serveRedirectToSitePath(redirectInstruction.getRedirectSitePath(), redirectStatus);
    } else if (redirectInstruction.hasRedirectUrl()) {
        serveRedirectResponse(redirectInstruction.getRedirectUrl(), redirectStatus);
    } else {/* w  ww.j a  va2  s  .com*/
        throw new IllegalStateException("Redirect must have target url or sitepath set");
    }
}

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

private ModelAndView serveRedirect(PortalResponse response, HttpServletResponse httpResponse,
        HttpServletRequest httpRequest) throws IOException {

    RedirectInstruction redirectInstruction = response.getRedirectInstruction();

    int redirectStatus = redirectInstruction.isPermanentRedirect() ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    if (redirectInstruction.hasRedirectSitePath()) {
        return serveRedirectToSitePath(redirectInstruction.getRedirectSitePath(), redirectStatus, httpResponse,
                httpRequest);/*w  w w.j  a  v  a 2 s.  co  m*/
    } else if (redirectInstruction.hasRedirectUrl()) {
        return serveRedirectResponse(redirectInstruction.getRedirectUrl());
    } else {
        throw new IllegalStateException("Redirect must have target url or sitepath set");
    }
}

From source file:org.codehaus.groovy.grails.web.metaclass.RedirectDynamicMethod.java

private Object redirectResponse(String serverBaseURL, String actualUri, HttpServletRequest request,
        HttpServletResponse response, boolean permanent) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Dynamic method [redirect] forwarding request to [" + actualUri + "]");
    }//from   w  ww . ja  v a 2  s  .c  o  m

    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing redirect with response [" + response + "]");
    }
    String processedActualUri = processedUrl(actualUri, request);
    String absoluteURL = processedActualUri.contains("://") ? processedActualUri
            : serverBaseURL + processedActualUri;
    String redirectUrl = useJessionId ? response.encodeRedirectURL(absoluteURL) : absoluteURL;
    int status = permanent ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    response.setStatus(status);
    response.setHeader(HttpHeaders.LOCATION, redirectUrl);

    if (redirectListeners != null) {
        for (RedirectEventListener redirectEventListener : redirectListeners) {
            redirectEventListener.responseRedirected(redirectUrl);
        }
    }

    request.setAttribute(GRAILS_REDIRECT_ISSUED, processedActualUri);
    return null;
}

From source file:org.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from  w  w  w.jav a  2s .c o m
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.elissa.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from w  w w  .ja  v a2 s. com
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                } else {
                    // file field
                    //System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    if (name.equals("csvFile")) {
                        CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream),
                                CsvPreference.EXCEL_PREFERENCE);
                        csvHeader = csvFileReader.getCSVHeader(true);
                        if (columnPropertyMapping != null || columnPropertyMapping.length > 0) {
                            csvHeader = columnPropertyMapping;
                        }
                        Map<String, String> row;
                        while ((row = csvFileReader.read(csvHeader)) != null) {
                            stencilPropertyMatrix.add(row);
                        }
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.oryxeditor.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from w ww . j  av a 2  s .c  om
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                } else {
                    // file field
                    //System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    if (name.equals("csvFile")) {
                        CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream),
                                CsvPreference.EXCEL_PREFERENCE);
                        csvHeader = csvFileReader.getCSVHeader(true);
                        if (columnPropertyMapping != null && columnPropertyMapping.length > 0) {
                            csvHeader = columnPropertyMapping;
                        }
                        Map<String, String> row;
                        while ((row = csvFileReader.read(csvHeader)) != null) {
                            stencilPropertyMatrix.add(row);
                        }
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.kie.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in// w w w .  ja v  a 2s. co  m
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                } else {
                    // file field
                    //System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    if (name.equals("csvFile")) {
                        CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream, "UTF-8"),
                                CsvPreference.EXCEL_PREFERENCE);
                        csvHeader = csvFileReader.getCSVHeader(true);
                        if (columnPropertyMapping != null || columnPropertyMapping.length > 0) {
                            csvHeader = columnPropertyMapping;
                        }
                        Map<String, String> row;
                        while ((row = csvFileReader.read(csvHeader)) != null) {
                            stencilPropertyMatrix.add(row);
                        }
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

private void sendRedirectResponse(final String redirectUrl, final int redirectStatus) {
    if (redirectStatus == HttpServletResponse.SC_MOVED_PERMANENTLY) {
        httpResponse.setStatus(redirectStatus);
    } else {/*from ww w .j av  a  2  s .  co m*/
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    final String location = this.encodeRedirectUrl ? httpResponse.encodeRedirectURL(redirectUrl) : redirectUrl;
    httpResponse.setHeader("Location", location);
}

From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java

/** See if we have a url for the service. If not discover the real one.
 *
 * @param hi//from  w w w.j  av a 2s .co  m
 */
private void discover(final HostInfo hi) throws CalFacadeException {
    if (hi.getIScheduleUrl() != null) {
        return;
    }

    /* For the moment we'll try to find it via .well-known. We may have to
     * use DNS SRV lookups
     */
    //    String domain = hi.getHostname();

    //  int lpos = domain.lastIndexOf(".");
    //int lpos2 = domain.lastIndexOf(".", lpos - 1);

    //    if (lpos2 > 0) {
    //    domain = domain.substring(lpos2 + 1);
    //}

    int rcode = 0;

    BasicHttpClient cio = null;

    try {
        /*
        // XXX ioptest fix - remove
        String url;
        if ("example.com".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else if ("ken.name".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else {
          url = "https://" + hi.getHostname() + "/.well-known/ischedule";
        }
        */

        final String scheme;
        final String port;

        if (hi.getPort() == 0) {
            port = "";
        } else {
            port = ":" + hi.getPort();
        }

        if (hi.getSecure()) {
            scheme = "https://";
        } else {
            scheme = "http://";
        }

        String url = scheme + hi.getHostname() + port + "/.well-known/ischedule";

        cio = getCio(url);

        for (int redirects = 0; redirects < 10; redirects++) {
            rcode = cio.sendRequest("GET", url + "?action=capabilities", null, "application/xml", 0, null);

            if ((rcode == HttpServletResponse.SC_MOVED_PERMANENTLY)
                    || (rcode == HttpServletResponse.SC_MOVED_TEMPORARILY)
                    || (rcode == HttpServletResponse.SC_TEMPORARY_REDIRECT)) {
                //boolean permanent = rcode == HttpServletResponse.SC_MOVED_PERMANENTLY;

                Header locationHeader = cio.getFirstHeader("location");
                if (locationHeader != null) {
                    if (debug) {
                        debugMsg("Got redirected to " + locationHeader.getValue() + " from " + url);
                    }

                    String newLoc = locationHeader.getValue();
                    int qpos = newLoc.indexOf("?");

                    cioTable.remove(url);

                    if (qpos < 0) {
                        url = newLoc;
                    } else {
                        url = newLoc.substring(0, qpos);
                    }

                    cio.release();

                    // Try again
                    continue;
                }
            }

            if (rcode != HttpServletResponse.SC_OK) {
                // The response is invalid and did not provide the new location for
                // the resource.  Report an error or possibly handle the response
                // like a 404 Not Found error.
                if (debug) {
                    error("Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);

                    if (cio.getResponseContentLength() != 0) {
                        InputStream is = cio.getResponseBodyAsStream();

                        LineNumberReader in = new LineNumberReader(new InputStreamReader(is));

                        error("Content: ==========================");
                        while (true) {
                            String l = in.readLine();
                            if (l == null) {
                                break;
                            }

                            error(l);
                        }
                        error("End content: ==========================");
                    }
                }

                throw new CalFacadeException(
                        "Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);
            }

            /* Should have a capabilities record. */

            hi.setIScheduleUrl(url);
            return;
        }

        if (debug) {
            error("Too many redirects: Got response " + rcode + ", host " + hi.getHostname() + " and url "
                    + url);
        }

        throw new CalFacadeException("Too many redirects on " + url);
    } catch (CalFacadeException cfe) {
        throw cfe;
    } catch (Throwable t) {
        if (debug) {
            error(t);
        }

        throw new CalFacadeException(t);
    } finally {
        try {
            if (cio != null) {
                cio.release();
            }
        } catch (Throwable t) {
        }
    }
}