Example usage for org.apache.commons.lang StringUtils deleteWhitespace

List of usage examples for org.apache.commons.lang StringUtils deleteWhitespace

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils deleteWhitespace.

Prototype

public static String deleteWhitespace(String str) 

Source Link

Document

Deletes all whitespaces from a String as defined by Character#isWhitespace(char) .

Usage

From source file:org.apache.flume.sink.elasticsearch2.ElasticSearchSink.java

@Override
public void configure(Context context) {
    if (logger.isInfoEnabled()) {
        logger.info("Configuration: " + context.getParameters());
    }/*from   ww w.j  a  v  a2  s.c o m*/
    if (!isLocal) {
        if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.HOSTNAMES))) {
            serverAddresses = StringUtils
                    .deleteWhitespace(context.getString(ElasticSearchSinkConstants.HOSTNAMES)).split(",");
        }
        Preconditions.checkState(serverAddresses != null && serverAddresses.length > 0,
                MISSING_PARAM + ElasticSearchSinkConstants.HOSTNAMES);
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.INDEX_NAME))) {
        this.indexName = context.getString(ElasticSearchSinkConstants.INDEX_NAME);
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.INDEX_TYPE))) {
        this.indexType = context.getString(ElasticSearchSinkConstants.INDEX_TYPE);
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.CLUSTER_NAME))) {
        this.clusterName = context.getString(ElasticSearchSinkConstants.CLUSTER_NAME);
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.BATCH_SIZE))) {
        this.batchSize = Integer.parseInt(context.getString(ElasticSearchSinkConstants.BATCH_SIZE));
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.TTL))) {
        this.ttlMs = parseTTL(context.getString(ElasticSearchSinkConstants.TTL));
        Preconditions.checkState(ttlMs > 0,
                ElasticSearchSinkConstants.TTL + " must be greater than 0 or not set.");
    }

    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.CLIENT_TYPE))) {
        clientType = context.getString(ElasticSearchSinkConstants.CLIENT_TYPE);
    }

    elasticSearchClientContext = new Context();
    elasticSearchClientContext.putAll(context.getSubProperties(ElasticSearchSinkConstants.CLIENT_PREFIX));

    String serializerClazz = ElasticSearchSinkConstants.DEFAULT_SERIALIZER_CLASS;
    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.SERIALIZER))) {
        serializerClazz = context.getString(ElasticSearchSinkConstants.SERIALIZER);
    }

    Context serializerContext = new Context();
    serializerContext.putAll(context.getSubProperties(ElasticSearchSinkConstants.SERIALIZER_PREFIX));

    try {
        @SuppressWarnings("unchecked")
        Class<? extends Configurable> clazz = (Class<? extends Configurable>) Class.forName(serializerClazz);
        Configurable serializer = clazz.newInstance();

        if (serializer instanceof ElasticSearchIndexRequestBuilderFactory) {
            indexRequestFactory = (ElasticSearchIndexRequestBuilderFactory) serializer;
            indexRequestFactory.configure(serializerContext);
        } else if (serializer instanceof ElasticSearchEventSerializer) {
            eventSerializer = (ElasticSearchEventSerializer) serializer;
            eventSerializer.configure(serializerContext);
        } else {
            throw new IllegalArgumentException(serializerClazz + " is not an ElasticSearchEventSerializer");
        }
    } catch (Exception e) {
        logger.error("Could not instantiate event serializer.", e);
        Throwables.propagate(e);
    }

    if (sinkCounter == null) {
        sinkCounter = new SinkCounter(getName());
    }

    String indexNameBuilderClass = ElasticSearchSinkConstants.DEFAULT_INDEX_NAME_BUILDER_CLASS;
    if (StringUtils.isNotBlank(context.getString(ElasticSearchSinkConstants.INDEX_NAME_BUILDER))) {
        indexNameBuilderClass = context.getString(ElasticSearchSinkConstants.INDEX_NAME_BUILDER);
    }

    Context indexnameBuilderContext = new Context();
    serializerContext.putAll(context.getSubProperties(ElasticSearchSinkConstants.INDEX_NAME_BUILDER_PREFIX));

    try {
        @SuppressWarnings("unchecked")
        Class<? extends IndexNameBuilder> clazz = (Class<? extends IndexNameBuilder>) Class
                .forName(indexNameBuilderClass);
        indexNameBuilder = clazz.newInstance();
        indexnameBuilderContext.put(ElasticSearchSinkConstants.INDEX_NAME, indexName);
        indexNameBuilder.configure(indexnameBuilderContext);
    } catch (Exception e) {
        logger.error("Could not instantiate index name builder.", e);
        Throwables.propagate(e);
    }

    if (sinkCounter == null) {
        sinkCounter = new SinkCounter(getName());
    }

    Preconditions.checkState(StringUtils.isNotBlank(indexName),
            MISSING_PARAM + ElasticSearchSinkConstants.INDEX_NAME);
    Preconditions.checkState(StringUtils.isNotBlank(indexType),
            MISSING_PARAM + ElasticSearchSinkConstants.INDEX_TYPE);
    Preconditions.checkState(StringUtils.isNotBlank(clusterName),
            MISSING_PARAM + ElasticSearchSinkConstants.CLUSTER_NAME);
    Preconditions.checkState(batchSize >= 1, ElasticSearchSinkConstants.BATCH_SIZE + " must be greater than 0");
}

From source file:org.apache.juddi.xlt.action.SOAP.RegisterBusiness.java

@Override
protected void execute() throws Exception {
    //Business name in English.
    Name name = new Name();
    name.setLang("en");
    name.setValue(businessName);//w  ww .  j  a va 2s.co m

    //Business description in English.
    Description description = new Description();
    description.setLang("en");
    description.setValue(data.getText(2, 5, false));

    //Business URL.
    DiscoveryURL discoveryURL = new DiscoveryURL();
    discoveryURL.setUseType("General Description");
    discoveryURL.setValue("http://www." + StringUtils.deleteWhitespace(businessName) + ".com");

    //All business URLs if many (here we only give one).
    DiscoveryURLs discoveryURLs = new DiscoveryURLs();
    discoveryURLs.getDiscoveryURL().add(discoveryURL);

    //Contact info:
    //Name of contact in English.
    PersonName personName = new PersonName();
    personName.setLang("en");
    personName.setValue(data.getFirstName(true) + data.getLastName(true));

    //Address lines for contact.
    AddressLine addressLineOne = new AddressLine();
    addressLineOne.setKeyName("street");
    addressLineOne.setKeyValue("street");
    addressLineOne.setValue(data.getStreet(false));

    AddressLine addressLineTwo = new AddressLine();
    addressLineTwo.setKeyName("town");
    addressLineTwo.setKeyValue("town");
    addressLineTwo.setValue(data.getTown(false));

    AddressLine addressLineThree = new AddressLine();
    addressLineThree.setKeyName("zip");
    addressLineThree.setKeyValue("zip");
    addressLineThree.setValue(data.getZip(5));

    //One address for the contact. Can be more but only one here.
    Address address = new Address();
    address.setLang("en");
    address.setSortCode("1");
    address.setTModelKey("uddi:tmodelKey:address");
    address.setUseType("HQ");
    address.getAddressLine().add(addressLineOne);
    address.getAddressLine().add(addressLineTwo);
    address.getAddressLine().add(addressLineThree);

    //Contacts phone number details
    Phone phone = new Phone();
    phone.setUseType("Hotline");
    phone.setValue(data.getUSPhoneNumber());

    //Contact object
    Contact contact = new Contact();
    contact.setUseType("CEO");
    contact.getPersonName().add(personName);
    contact.getAddress().add(address);
    contact.getPhone().add(phone);

    //All contact for the business. Here only one is generated.
    Contacts contacts = new Contacts();
    contacts.getContact().add(contact);

    //Pass info to business entity.
    BusinessEntity businessEntity = new BusinessEntity();
    businessEntity.setDiscoveryURLs(discoveryURLs);
    businessEntity.getName().add(name);
    businessEntity.getDescription().add(description);
    businessEntity.setContacts(contacts);

    //Pass Entity to SaveBussiness object and publish.
    SaveBusiness saveBusiness = new SaveBusiness();
    saveBusiness.setAuthInfo(authenticationToken.getAuthInfo());
    saveBusiness.getBusinessEntity().add(businessEntity);

    //Business Details are returned.
    businessDetail = publishService.saveBusiness(saveBusiness);

}

From source file:org.apache.juddi.xlt.action.SOAP.RegisterService.java

/**
 * The execute method will send the SOAP message to jUDDI. Here, we create a 
 * BusinessService object and fill the different values with random
 * information. The BusinessService is then given to a SaveService object
 * and published to the jUDDI node./* w  ww .  j av  a  2s . com*/
 */
@Override
protected void execute() throws Exception {
    GeneralDataProvider data = GeneralDataProvider.getInstance();
    serviceName = data.getCountry(false);// retrieves random service name from country file

    //Name of the service in English.
    Name name = new Name();
    name.setLang("en");
    name.setValue(serviceName);

    //Description of the service in English.
    Description description = new Description();
    description.setLang("en");
    description.setValue(data.getText(1, false));

    //Access Point details.
    AccessPoint accessPoint = new AccessPoint();
    accessPoint.setUseType("endPoint");
    accessPoint.setValue("http://www." + StringUtils.deleteWhitespace(businessName) + ".com:8080/uddi/services/"
            + StringUtils.deleteWhitespace(serviceName) + "?wsdl");

    //Description of the Access Point, in English.
    Description accessPointDescription = new Description();
    accessPointDescription.setLang("en");
    accessPointDescription.setValue(data.getText(1, 3, false));

    //Pass binging info to binding template.
    BindingTemplate bindingTemplate = new BindingTemplate();
    bindingTemplate.setAccessPoint(accessPoint);
    bindingTemplate.getDescription().add(accessPointDescription);

    //There can be several binding templates. Here only one is passed.
    BindingTemplates bindingTemplates = new BindingTemplates();
    bindingTemplates.getBindingTemplate().add(bindingTemplate);

    //Pass all info to BusinessService object.
    BusinessService businessService = new BusinessService();
    businessService.setBusinessKey(businessKey);
    businessService.setBindingTemplates(bindingTemplates);
    businessService.getName().add(name);
    businessService.getDescription().add(description);

    //Pass service to the SaveService object and publish
    SaveService saveService = new SaveService();
    saveService.setAuthInfo(authenticationToken.getAuthInfo());
    saveService.getBusinessService().add(businessService);

    // execute the SaveService operation and get back the ServiceDetail
    serviceDetail = publishService.saveService(saveService);

}

From source file:org.apache.openmeetings.servlet.outputhandler.DownloadHandler.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//www.  j  a  v  a2s. co  m
        httpServletRequest.setCharacterEncoding("UTF-8");

        log.debug("\nquery = " + httpServletRequest.getQueryString());
        log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName"));
        log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath"));

        String queryString = httpServletRequest.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getBean(SessiondataDao.class).checkSession(sid);
        Long user_level = getBean(UserManager.class).getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {
            String room_id = httpServletRequest.getParameter("room_id");
            if (room_id == null) {
                room_id = "default";
            }

            String moduleName = httpServletRequest.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "nomodule";
            }

            String parentPath = httpServletRequest.getParameter("parentPath");
            if (parentPath == null) {
                parentPath = "nomodule";
            }

            String requestedFile = httpServletRequest.getParameter("fileName");
            if (requestedFile == null) {
                requestedFile = "";
            }

            String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId");
            Long fileExplorerItemId = null;
            if (fileExplorerItemIdParam != null) {
                fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam);
            }

            // make a complete name out of domain(organisation) + roomname
            String roomName = room_id;
            // trim whitespaces cause it is a directory name
            roomName = StringUtils.deleteWhitespace(roomName);

            // Get the current User-Directory

            File working_dir;

            // Add the Folder for the Room
            if (moduleName.equals("lzRecorderApp")) {
                working_dir = OmFileHelper.getStreamsHibernateDir();
            } else if (moduleName.equals("videoconf1")) {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
                if (parentPath.length() != 0 && !parentPath.equals("/")) {
                    working_dir = new File(working_dir, parentPath);
                }
            } else if (moduleName.equals("userprofile")) {
                working_dir = OmFileHelper.getUploadProfilesUserDir(users_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofile")) {
                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofilebig")) {
                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getBigProfileUserName(working_dir);
            } else if (moduleName.equals("chat")) {
                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getChatUserName(working_dir);
            } else {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
            }

            if (!moduleName.equals("nomodule")) {

                log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir);

                File full_path = new File(working_dir, requestedFile);

                // If the File does not exist or is not readable show/load a
                // place-holder picture

                if (!full_path.exists() || !full_path.canRead()) {
                    if (!full_path.canRead()) {
                        log.debug("LOG DownloadHandler: The request file is not readable ");
                    } else {
                        log.debug(
                                "LOG DownloadHandler: The request file does not exist / has already been deleted");
                    }
                    log.debug("LOG ERROR requestedFile: " + requestedFile);
                    // replace the path with the default picture/document

                    if (requestedFile.endsWith(".jpg")) {
                        log.debug("LOG endsWith d.jpg");

                        log.debug("LOG moduleName: " + moduleName);

                        requestedFile = DownloadHandler.defaultImageName;
                        if (moduleName.equals("remoteuserprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("remoteuserprofilebig")) {
                            requestedFile = DownloadHandler.defaultProfileImageNameBig;
                        } else if (moduleName.equals("userprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("chat")) {
                            requestedFile = DownloadHandler.defaultChatImageName;
                        }
                    } else if (requestedFile.endsWith(".swf")) {
                        requestedFile = DownloadHandler.defaultSWFName;
                    } else {
                        requestedFile = DownloadHandler.defaultImageName;
                    }
                    full_path = new File(OmFileHelper.getDefaultDir(), requestedFile);
                }

                log.debug("full_path: " + full_path);

                if (!full_path.exists() || !full_path.canRead()) {
                    if (!full_path.canRead()) {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    } else {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    }
                    // no file to handle abort processing
                    return;
                }
                // Requested file is outside OM webapp folder
                File curDirFile = OmFileHelper.getOmHome();
                if (!full_path.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) {
                    throw new Exception("Invalid file requested: f2.cp == " + full_path.getCanonicalPath()
                            + "; curDir.cp == " + curDirFile.getCanonicalPath());
                }

                // Default type - Explorer, Chrome and others
                int browserType = 0;

                // Firefox and Opera browsers
                if (httpServletRequest.getHeader("User-Agent") != null) {
                    if ((httpServletRequest.getHeader("User-Agent").contains("Firefox"))
                            || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) {
                        browserType = 1;
                    }
                }

                log.debug("Detected browser type:" + browserType);

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream out = httpServletResponse.getOutputStream();

                if (requestedFile.endsWith(".swf")) {
                    // trigger download to SWF => THIS is a workaround for
                    // Flash Player 10, FP 10 does not seem
                    // to accept SWF-Downloads with the Content-Disposition
                    // in the Header
                    httpServletResponse.setContentType("application/x-shockwave-flash");
                    httpServletResponse.setHeader("Content-Length", "" + full_path.length());
                } else {
                    httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");

                    String fileNameResult = requestedFile;
                    if (fileExplorerItemId != null && fileExplorerItemId > 0) {
                        FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class)
                                .getFileExplorerItemsById(fileExplorerItemId);
                        if (fileExplorerItem != null) {

                            fileNameResult = fileExplorerItem.getFileName().substring(0,
                                    fileExplorerItem.getFileName().length() - 4)
                                    + fileNameResult.substring(fileNameResult.length() - 4,
                                            fileNameResult.length());

                        }
                    }

                    if (browserType == 0) {
                        httpServletResponse.setHeader("Content-Disposition",
                                "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    } else {
                        httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'"
                                + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    }

                    httpServletResponse.setHeader("Content-Length", "" + full_path.length());
                }

                OmFileHelper.copyFile(full_path, out);
                out.flush();
                out.close();
            }
        } else {
            log.error("ERROR DownloadHandler: not authorized FileDownload ");
        }

    } catch (ServerNotInitializedException e) {
        return;
    } catch (Exception er) {
        log.error("Error downloading: ", er);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.ScreenController.java

@RequestMapping(value = "/screen.upload")
public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
    try {/*from  w w  w . j a  v  a2  s .  c o  m*/
        String sid = request.getParameter("sid");
        Long users_id = sessiondataDao.checkSession(sid);
        String publicSID = request.getParameter("publicSID");
        if (publicSID == null) {
            throw new Exception("publicSID is empty: " + publicSID);
        }
        if (users_id == 0) {
            //checkSession will return 0 in case of invalid session
            throw new Exception("Request from invalid user " + users_id);
        }

        String domain = request.getParameter("domain");
        if (domain == null) {
            throw new Exception("domain is empty: " + domain);
        }

        String languageAsString = request.getParameter("languageAsString");
        if (languageAsString == null) {
            throw new Exception("languageAsString is empty: " + languageAsString);
        }
        Long language_id = Long.parseLong(languageAsString);

        String rtmphostlocal = request.getParameter("rtmphostlocal");
        if (rtmphostlocal == null) {
            throw new Exception("rtmphostlocal is empty: " + rtmphostlocal);
        }

        String red5httpport = request.getParameter("red5httpport");
        if (red5httpport == null) {
            throw new Exception("red5httpport is empty: " + red5httpport);
        }

        String httpRootKey = request.getParameter("httpRootKey");
        if (httpRootKey == null) {
            throw new Exception("httpRootKey is empty could not start sharer");
        }

        String baseURL = request.getScheme() + "://" + rtmphostlocal + ":" + red5httpport + httpRootKey;

        log.debug("httpRootKey " + httpRootKey);
        log.debug("language_id :: " + language_id);
        String label_sharer = "Sharer";

        try {
            label_sharer = getLabels(language_id, 730, 731, 732, 733, 734, 735, 737, 738, 739, 740, 741, 742,
                    844, 869, 870, 871, 872, 878, 1089, 1090, 1091, 1092, 1093, 1465, 1466, 1467, 1468, 1469,
                    1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477);
        } catch (Exception e) {
            log.error("Error resolving Language labels : ", e);
        }
        log.debug("Creating JNLP Template for TCP solution");

        //libs
        StringBuilder libs = new StringBuilder();
        File screenShareDir = OmFileHelper.getScreenSharingDir();
        for (File jar : screenShareDir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".jar");
            }
        })) {
            libs.append("\t\t<jar href=\"").append(jar.getName()).append("\"/>\n");
        }
        log.debug("RTMP Sharer labels :: " + label_sharer);

        ConnectionType conType = ConnectionType.valueOf(request.getParameter("connectionType"));

        String startUpClass;
        switch (conType) {
        case rtmp:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPScreenShare";
            break;
        case rtmps:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPSScreenShare";
            break;
        case rtmpt:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPTScreenShare";
            break;
        default:
            throw new Exception("Unknown connection type");
        }

        String orgIdAsString = request.getParameter("organization_id");
        if (orgIdAsString == null) {
            throw new Exception("orgIdAsString is empty could not start sharer");
        }

        String port = request.getParameter("port");
        if (port == null) {
            throw new Exception("port is empty: ");
        }
        Client rc = sessionManager.getClientByPublicSID(publicSID, false, null);
        if (rc == null) {
            throw new Exception("port is empty: ");
        }
        Long roomId = rc.getRoom_id();
        boolean allowRecording = rc.getAllowRecording() && (0 == sessionManager.getRecordingCount(roomId));
        boolean allowPublishing = (0 == sessionManager.getPublishingCount(roomId));

        Context ctx = new VelocityContext();
        ctx.put("APP_NAME", configurationDao.getAppName());
        ctx.put("PUBLIC_SID", publicSID);
        ctx.put("LABELSHARER", label_sharer);
        addKeystore(ctx);
        ctx.put("LIBRARIES", libs);
        ctx.put("organization_id", orgIdAsString);
        ctx.put("startUpClass", startUpClass);
        ctx.put("codebase", baseURL + OmFileHelper.SCREENSHARING_DIR);
        ctx.put("red5-host", rtmphostlocal);
        ctx.put("red5-app", OpenmeetingsVariables.webAppRootKey + "/" + roomId);
        ctx.put("default_quality_screensharing",
                configurationDao.getConfValue("default.quality.screensharing", String.class, "1"));
        //invited guest does not have valid user_id (have user_id == -1)
        ctx.put("user_id", users_id);
        ctx.put("port", port);
        ctx.put("allowRecording", allowRecording);
        ctx.put("allowPublishing", allowPublishing);

        String requestedFile = StringUtils.deleteWhitespace(domain + "_" + roomId) + ".jnlp";
        response.setContentType("application/x-java-jnlp-file");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "Inline; filename=\"" + requestedFile + "\"");

        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        ve.mergeTemplate("screenshare.vm", "UTF-8", ctx, response.getWriter());
    } catch (Exception er) {
        log.error("[ScreenController]", er);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/upload.upload", method = RequestMethod.POST)
public void handleFormUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from  w ww .ja  v  a 2 s .c  om*/
        UploadInfo info = validate(request, false);

        String room_id = request.getParameter("room_id");
        if (room_id == null) {
            room_id = "default";
        }
        String roomName = StringUtils.deleteWhitespace(room_id);

        String moduleName = request.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "nomodule";
        }
        if (moduleName.equals("nomodule")) {
            log.debug("module name missed");
            return;
        }
        boolean userProfile = moduleName.equals("userprofile");

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        String fileSystemName = info.filename;
        fileSystemName = StringUtils.deleteWhitespace(fileSystemName);

        UploadCompleteMessage uploadCompleteMessage = new UploadCompleteMessage();
        uploadCompleteMessage.setUserId(info.userId);

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        uploadFile(request, userProfile, info.userId, roomName, is, fileSystemName, uploadCompleteMessage);
        sendMessage(info, uploadCompleteMessage);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}

From source file:org.apache.roller.weblogger.business.FileContentManagerImpl.java

/**
 * @see org.apache.roller.weblogger.model.FileContentManager#canSave(
 * weblog, java.lang.String, java.lang.String, long, messages)
 *//*from  ww w. j a v a  2 s .c  om*/
public boolean canSave(Weblog weblog, String fileName, String contentType, long size, RollerMessages messages) {

    // first check, is uploading enabled?
    if (!WebloggerRuntimeConfig.getBooleanProperty("uploads.enabled")) {
        messages.addError("error.upload.disabled");
        return false;
    }

    // second check, does upload exceed max size for file?
    BigDecimal maxFileMB = new BigDecimal(WebloggerRuntimeConfig.getProperty("uploads.file.maxsize"));
    int maxFileBytes = (int) (1024000 * maxFileMB.doubleValue());
    log.debug("max allowed file size = " + maxFileBytes);
    log.debug("attempted save file size = " + size);
    if (size > maxFileBytes) {
        String[] args = { fileName, maxFileMB.toString() };
        messages.addError("error.upload.filemax", args);
        return false;
    }

    // third check, does file cause weblog to exceed quota?
    BigDecimal maxDirMB = new BigDecimal(WebloggerRuntimeConfig.getProperty("uploads.dir.maxsize"));
    long maxDirBytes = (long) (1024000 * maxDirMB.doubleValue());
    try {
        File storageDir = this.getRealFile(weblog, null);
        long userDirSize = getDirSize(storageDir, true);
        if (userDirSize + size > maxDirBytes) {
            messages.addError("error.upload.dirmax", maxDirMB.toString());
            return false;
        }
    } catch (Exception ex) {
        // shouldn't ever happen, means the weblogs uploads dir is bad somehow
        // rethrow as a runtime exception
        throw new RuntimeException(ex);
    }

    // fourth check, is upload type allowed?
    String allows = WebloggerRuntimeConfig.getProperty("uploads.types.allowed");
    String forbids = WebloggerRuntimeConfig.getProperty("uploads.types.forbid");
    String[] allowFiles = StringUtils.split(StringUtils.deleteWhitespace(allows), ",");
    String[] forbidFiles = StringUtils.split(StringUtils.deleteWhitespace(forbids), ",");
    if (!checkFileType(allowFiles, forbidFiles, fileName, contentType)) {
        String[] args = { fileName, contentType };
        messages.addError("error.upload.forbiddenFile", args);
        return false;
    }

    return true;
}

From source file:org.apache.roller.weblogger.business.jpa.JPARefererManagerImpl.java

/**
 * Apply ignoreWord/spam filters to all referers in system.
 *//*from   ww  w.j a v  a  2 s .c o  m*/
public void applyRefererFilters() throws WebloggerException {
    String spamwords = WebloggerRuntimeConfig.getProperty("spam.blacklist");
    String[] blacklist = StringUtils.split(StringUtils.deleteWhitespace(spamwords), ",");
    if (blacklist.length == 0)
        return;
    List referers = getBlackListedReferer(blacklist);
    for (Iterator iterator = referers.iterator(); iterator.hasNext();) {
        WeblogReferrer referer = (WeblogReferrer) iterator.next();
        this.strategy.remove(referer);
    }
}

From source file:org.apache.roller.weblogger.business.jpa.JPARefererManagerImpl.java

/**
 * Apply ignoreWord/spam filters to all referers in website.
 *//*  w w  w  .ja v a  2 s .  c  om*/
public void applyRefererFilters(Weblog website) throws WebloggerException {
    if (null == website)
        throw new WebloggerException("website is null");
    if (null == website.getBlacklist())
        return;

    String[] blacklist = StringUtils.split(StringUtils.deleteWhitespace(website.getBlacklist()), ",");
    if (blacklist.length == 0)
        return;
    List referers = getBlackListedReferer(website, blacklist);
    for (Iterator iterator = referers.iterator(); iterator.hasNext();) {
        WeblogReferrer referer = (WeblogReferrer) iterator.next();
        this.strategy.remove(referer);
    }
}

From source file:org.apache.roller.weblogger.webservices.atomprotocol.RollerAtomService.java

/**
 * Build accept range by taking things that appear to be content-type rules 
 * from site's file-upload allowed extensions.
 *//*from  w  ww . j  av a  2  s  . c o  m*/
private List getAcceptedContentTypeRange() throws WebloggerException {
    List accepts = new ArrayList();
    Weblogger roller = WebloggerFactory.getWeblogger();
    Map config = roller.getPropertiesManager().getProperties();
    String allows = ((RuntimeConfigProperty) config.get("uploads.types.allowed")).getValue();
    String[] rules = StringUtils.split(StringUtils.deleteWhitespace(allows), ",");
    for (int i = 0; i < rules.length; i++) {
        if (rules[i].indexOf("/") == -1)
            continue;
        accepts.add(rules[i]);
    }
    return accepts;
}