Example usage for com.liferay.portal.kernel.util FileUtil write

List of usage examples for com.liferay.portal.kernel.util FileUtil write

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util FileUtil write.

Prototype

public static void write(String fileName, String s) throws IOException 

Source Link

Usage

From source file:com.liferay.mail.util.SendmailHook.java

License:Open Source License

public void updateBlocked(long companyId, long userId, List<String> blocked) {

    String home = PropsUtil.get(PropsKeys.MAIL_HOOK_SENDMAIL_HOME);

    File file = new File(home + "/" + userId + "/.procmailrc");

    if ((blocked == null) || (blocked.size() == 0)) {
        file.delete();//from  w w w  . j  av a 2s. c  om

        return;
    }

    StringBundler sb = new StringBundler(blocked.size() * 9 + 3);

    sb.append("ORGMAIL /var/spool/mail/$LOGNAME\n");
    sb.append("MAILDIR $HOME/\n");
    sb.append("SENDMAIL /usr/smin/sendmail\n");

    for (int i = 0; i < blocked.size(); i++) {
        String emailAddress = blocked.get(i);

        sb.append("\n");
        sb.append(":0\n");
        sb.append("* ^From.*");
        sb.append(emailAddress);
        sb.append("\n");
        sb.append("{\n");
        sb.append(":0\n");
        sb.append("/dev/null\n");
        sb.append("}\n");
    }

    try {
        FileUtil.write(file, sb.toString());
    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.mail.util.SendmailHook.java

License:Open Source License

public void updateEmailAddress(long companyId, long userId, String emailAddress) {

    try {/*from w  w  w  .  j a v a  2 s  . c o m*/
        String virtusertable = PropsUtil.get(PropsKeys.MAIL_HOOK_SENDMAIL_VIRTUSERTABLE);

        FileReader fileReader = new FileReader(virtusertable);
        UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(fileReader);

        StringBundler sb = new StringBundler();

        for (String s = unsyncBufferedReader.readLine(); s != null; s = unsyncBufferedReader.readLine()) {

            if (!s.endsWith(" " + userId)) {
                sb.append(s);
                sb.append('\n');
            }
        }

        if ((emailAddress != null) && (!emailAddress.equals(""))) {
            sb.append(emailAddress);
            sb.append(" ");
            sb.append(userId);
            sb.append('\n');
        }

        unsyncBufferedReader.close();
        fileReader.close();

        FileUtil.write(virtusertable, sb.toString());

        String virtusertableRefreshCmd = PropsUtil.get(PropsKeys.MAIL_HOOK_SENDMAIL_VIRTUSERTABLE_REFRESH);

        Runtime rt = Runtime.getRuntime();

        Process p = rt.exec(virtusertableRefreshCmd);

        ProcessUtil.close(p);
    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.marketplace.app.manager.web.internal.portlet.MarketplaceAppManagerPortlet.java

License:Open Source License

protected int doInstallRemoteApp(String url, ActionRequest actionRequest, boolean failOnError)
        throws Exception {

    int responseCode = HttpServletResponse.SC_OK;

    try {/*from  w w w .  j  av a 2  s.  c  om*/
        String fileName = null;

        Http.Options options = new Http.Options();

        options.setFollowRedirects(false);
        options.setLocation(url);
        options.setPost(false);

        byte[] bytes = HttpUtil.URLtoByteArray(options);

        Http.Response response = options.getResponse();

        responseCode = response.getResponseCode();

        if ((responseCode == HttpServletResponse.SC_OK) && (bytes.length > 0)) {

            String deployDir = PrefsPropsUtil.getString(PropsKeys.AUTO_DEPLOY_DEPLOY_DIR);

            String destination = deployDir + StringPool.SLASH + fileName;

            File destinationFile = new File(destination);

            FileUtil.write(destinationFile, bytes);

            SessionMessages.add(actionRequest, "pluginDownloaded");
        } else {
            if (failOnError) {
                SessionErrors.add(actionRequest, UploadException.class.getName());
            }

            responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    } catch (MalformedURLException murle) {
        SessionErrors.add(actionRequest, "invalidUrl", murle);
    } catch (IOException ioe) {
        SessionErrors.add(actionRequest, "errorConnectingToUrl", ioe);
    }

    return responseCode;
}

From source file:com.liferay.marketplace.appmanager.portlet.AppManagerPortlet.java

License:Open Source License

protected int doInstallRemoteApp(String url, UploadPortletRequest uploadPortletRequest,
        ActionRequest actionRequest, boolean failOnError) throws Exception {

    int responseCode = HttpServletResponse.SC_OK;

    String deploymentContext = ParamUtil.getString(uploadPortletRequest, "deploymentContext");

    try {/*from w w  w  .ja  v  a 2 s  .c om*/
        String fileName = null;

        if (Validator.isNotNull(deploymentContext)) {
            fileName = DEPLOY_TO_PREFIX + deploymentContext + ".war";
        } else {
            fileName = url.substring(url.lastIndexOf(CharPool.SLASH) + 1);

            int pos = fileName.lastIndexOf(CharPool.PERIOD);

            if (pos != -1) {
                deploymentContext = fileName.substring(0, pos);
            }
        }

        Http.Options options = new Http.Options();

        options.setFollowRedirects(false);
        options.setLocation(url);
        options.setPortletRequest(actionRequest);
        options.setPost(false);

        String progressId = ParamUtil.getString(uploadPortletRequest, Constants.PROGRESS_ID);

        options.setProgressId(progressId);

        byte[] bytes = HttpUtil.URLtoByteArray(options);

        Http.Response response = options.getResponse();

        responseCode = response.getResponseCode();

        if ((responseCode == HttpServletResponse.SC_OK) && (bytes.length > 0)) {

            String deployDir = PrefsPropsUtil.getString(PropsKeys.AUTO_DEPLOY_DEPLOY_DIR);

            String destination = deployDir + StringPool.SLASH + fileName;

            File destinationFile = new File(destination);

            FileUtil.write(destinationFile, bytes);

            SessionMessages.add(actionRequest, "pluginDownloaded");
        } else {
            if (failOnError) {
                SessionErrors.add(actionRequest, UploadException.class.getName());
            }

            responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    } catch (MalformedURLException murle) {
        SessionErrors.add(actionRequest, "invalidUrl", murle);
    } catch (IOException ioe) {
        SessionErrors.add(actionRequest, "errorConnectingToUrl", ioe);
    }

    return responseCode;
}

From source file:com.liferay.marketplace.service.impl.AppLocalServiceImpl.java

License:Open Source License

@Override
public void installApp(long remoteAppId) throws PortalException {
    App app = appPersistence.findByRemoteAppId(remoteAppId);

    if (!DLStoreUtil.hasFile(app.getCompanyId(), CompanyConstants.SYSTEM, app.getFilePath())) {

        throw new NoSuchFileException();
    }//from  www  . ja  va 2s  .  c o m

    String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR) + StringPool.SLASH + Time.getTimestamp();

    InputStream inputStream = null;

    ZipFile zipFile = null;

    try {
        inputStream = DLStoreUtil.getFileAsStream(app.getCompanyId(), CompanyConstants.SYSTEM,
                app.getFilePath());

        if (inputStream == null) {
            throw new IOException("Unable to open file at " + app.getFilePath());
        }

        File liferayPackageFile = FileUtil.createTempFile(inputStream);

        zipFile = new ZipFile(liferayPackageFile);

        Enumeration<ZipEntry> enu = (Enumeration<ZipEntry>) zipFile.entries();

        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = enu.nextElement();

            String fileName = zipEntry.getName();

            if (!fileName.endsWith(".jar") && !fileName.endsWith(".war") && !fileName.endsWith(".xml")
                    && !fileName.endsWith(".zip") && !fileName.equals("liferay-marketplace.properties")) {

                continue;
            }

            if (_log.isInfoEnabled()) {
                _log.info("Extracting " + fileName + " from app " + app.getAppId());
            }

            InputStream zipInputStream = null;

            try {
                zipInputStream = zipFile.getInputStream(zipEntry);

                if (fileName.equals("liferay-marketplace.properties")) {
                    String propertiesString = StringUtil.read(zipInputStream);

                    Properties properties = PropertiesUtil.load(propertiesString);

                    processMarketplaceProperties(properties);
                } else {
                    File pluginPackageFile = new File(tmpDir + StringPool.SLASH + fileName);

                    FileUtil.write(pluginPackageFile, zipInputStream);

                    String bundleSymbolicName = StringPool.BLANK;
                    String bundleVersion = StringPool.BLANK;
                    String contextName = StringPool.BLANK;

                    AutoDeploymentContext autoDeploymentContext = new AutoDeploymentContext();

                    if (fileName.endsWith(".jar")) {
                        Manifest manifest = BundleUtil.getManifest(pluginPackageFile);

                        Attributes attributes = manifest.getMainAttributes();

                        bundleSymbolicName = GetterUtil.getString(attributes.getValue("Bundle-SymbolicName"));
                        bundleVersion = GetterUtil.getString(attributes.getValue("Bundle-Version"));
                        contextName = GetterUtil.getString(attributes.getValue("Web-ContextPath"));
                    } else {
                        contextName = getContextName(fileName);

                        autoDeploymentContext.setContext(contextName);
                    }

                    autoDeploymentContext.setFile(pluginPackageFile);

                    DeployManagerUtil.deploy(autoDeploymentContext);

                    if (Validator.isNotNull(bundleSymbolicName) || Validator.isNotNull(contextName)) {

                        moduleLocalService.addModule(app.getUserId(), app.getAppId(), bundleSymbolicName,
                                bundleVersion, contextName);
                    }
                }
            } finally {
                StreamUtil.cleanUp(zipInputStream);
            }
        }
    } catch (ZipException ze) {
        if (_log.isInfoEnabled()) {
            _log.info("Deleting corrupt package from app " + app.getAppId(), ze);
        }

        deleteApp(app);
    } catch (IOException ioe) {
        throw new PortalException(ioe.getMessage());
    } catch (Exception e) {
        _log.error(e, e);
    } finally {
        FileUtil.deltree(tmpDir);

        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ioe) {
            }
        }

        StreamUtil.cleanUp(inputStream);

        clearInstalledAppsCache();
    }
}

From source file:com.liferay.marketplace.store.portlet.StorePortlet.java

License:Open Source License

public void downloadApp(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String token = ParamUtil.getString(actionRequest, "token");
    long remoteAppId = ParamUtil.getLong(actionRequest, "appId");
    String url = ParamUtil.getString(actionRequest, "url");
    String version = ParamUtil.getString(actionRequest, "version");

    if (!url.startsWith(PortletPropsValues.MARKETPLACE_URL)) {
        JSONObject jsonObject = getAppJSONObject(remoteAppId);

        jsonObject.put("cmd", "downloadApp");
        jsonObject.put("message", "fail");

        writeJSON(actionRequest, actionResponse, jsonObject);

        return;//from   w ww  . j a  v  a  2  s.c  o m
    }

    url = getRemoteAppPackageURL(themeDisplay.getCompanyId(), themeDisplay.getUserId(), token, url);

    URL urlObj = new URL(url);

    File tempFile = null;

    try {
        InputStream inputStream = urlObj.openStream();

        tempFile = FileUtil.createTempFile();

        FileUtil.write(tempFile, inputStream);

        App app = AppServiceUtil.updateApp(remoteAppId, version, tempFile);

        JSONObject jsonObject = getAppJSONObject(app.getRemoteAppId());

        jsonObject.put("cmd", "downloadApp");
        jsonObject.put("message", "success");

        writeJSON(actionRequest, actionResponse, jsonObject);
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.liferay.marketplace.store.portlet.StorePortlet.java

License:Open Source License

public void updateApp(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String token = ParamUtil.getString(actionRequest, "token");
    long remoteAppId = ParamUtil.getLong(actionRequest, "appId");
    String version = ParamUtil.getString(actionRequest, "version");
    String url = ParamUtil.getString(actionRequest, "url");
    String orderUuid = ParamUtil.getString(actionRequest, "orderUuid");
    String productEntryName = ParamUtil.getString(actionRequest, "productEntryName");

    if (!url.startsWith(PortletPropsValues.MARKETPLACE_URL)) {
        JSONObject jsonObject = getAppJSONObject(remoteAppId);

        jsonObject.put("cmd", "downloadApp");
        jsonObject.put("message", "fail");

        writeJSON(actionRequest, actionResponse, jsonObject);

        return;//from  w  w w .j  a v a 2  s  .  c  om
    }

    url = getRemoteAppPackageURL(themeDisplay.getCompanyId(), themeDisplay.getUserId(), token, url);

    URL urlObj = new URL(url);

    File tempFile = null;

    try {
        InputStream inputStream = urlObj.openStream();

        tempFile = FileUtil.createTempFile();

        FileUtil.write(tempFile, inputStream);

        AppServiceUtil.updateApp(remoteAppId, version, tempFile);

        if (Validator.isNull(orderUuid) && Validator.isNotNull(productEntryName)) {

            orderUuid = MarketplaceLicenseUtil.getOrder(productEntryName);
        }

        if (Validator.isNotNull(orderUuid)) {
            MarketplaceLicenseUtil.registerOrder(orderUuid, productEntryName);
        }

        AppServiceUtil.installApp(remoteAppId);

        JSONObject jsonObject = getAppJSONObject(remoteAppId);

        jsonObject.put("cmd", "updateApp");
        jsonObject.put("message", "success");

        writeJSON(actionRequest, actionResponse, jsonObject);
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.liferay.marketplace.store.web.internal.portlet.MarketplaceStorePortlet.java

License:Open Source License

protected void downloadApp(PortletRequest portletRequest, PortletResponse portletResponse, long appPackageId,
        boolean unlicensed, File file) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, getServerPortletURL());

    setBaseRequestParameters(portletRequest, portletResponse, oAuthRequest);

    String serverNamespace = getServerNamespace();

    addOAuthParameter(oAuthRequest, serverNamespace.concat("appPackageId"), String.valueOf(appPackageId));

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "2");

    if (unlicensed) {
        addOAuthParameter(oAuthRequest, "p_p_resource_id", "serveUnlicensedApp");
    } else {//ww  w  . j a  v a2  s.c om
        addOAuthParameter(oAuthRequest, "p_p_resource_id", "serveApp");
    }

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    FileUtil.write(file, response.getStream());
}

From source file:com.liferay.maven.plugins.compatibility.WSDDBuilder.java

License:Open Source License

public void build() throws Exception {
    if (!FileUtil.exists(_serverConfigFileName)) {
        ClassLoader classLoader = getClass().getClassLoader();

        String serverConfigContent = StringUtil.read(classLoader,
                "com/liferay/portal/tools/dependencies/server-config.wsdd");

        FileUtil.write(_serverConfigFileName, serverConfigContent);
    }/*from w w  w .  j av a2 s  .c o m*/

    Document document = SAXReaderUtil.read(new File(_fileName), true);

    Element rootElement = document.getRootElement();

    String packagePath = rootElement.attributeValue("package-path");

    Element portletElement = rootElement.element("portlet");
    Element namespaceElement = rootElement.element("namespace");

    if (portletElement != null) {
        _portletShortName = portletElement.attributeValue("short-name");
    } else {
        _portletShortName = namespaceElement.getText();
    }

    _outputPath += StringUtil.replace(packagePath, ".", "/") + "/service/http";

    _packagePath = packagePath;

    List<Element> entityElements = rootElement.elements("entity");

    for (Element entityElement : entityElements) {
        String entityName = entityElement.attributeValue("name");

        boolean remoteService = GetterUtil.getBoolean(entityElement.attributeValue("remote-service"), true);

        if (remoteService) {
            _createServiceWSDD(entityName);

            WSDDMerger.merge(_outputPath + "/" + entityName + "Service_deploy.wsdd", _serverConfigFileName);
        }
    }
}

From source file:com.liferay.portlet.documentlibrary.antivirus.BaseFileAntivirusScanner.java

License:Open Source License

public void scan(byte[] bytes) throws AntivirusScannerException, SystemException {

    File file = null;/*from w  w w  . j a  va 2  s  .  co m*/

    try {
        file = FileUtil.createTempFile(_ANTIVIRUS_EXTENSION);

        FileUtil.write(file, bytes);

        scan(file);
    } catch (IOException ioe) {
        throw new SystemException("Unable to write temporary file", ioe);
    } finally {
        if (file != null) {
            file.delete();
        }
    }
}