Example usage for com.liferay.portal.kernel.util HttpUtil URLtoByteArray

List of usage examples for com.liferay.portal.kernel.util HttpUtil URLtoByteArray

Introduction

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

Prototype

public static byte[] URLtoByteArray(String location) throws IOException 

Source Link

Usage

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 {//w  ww . j  a va2 s .  c o m
        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  www  . j a va 2s .com*/
        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.opensocial.shindig.service.LiferayMediaItemService.java

License:Open Source License

protected void doUpdateMediaItem(UserId userId, String appId, String albumId, String mediaItemId,
        MediaItem mediaItem, SecurityToken securityToken) throws Exception {

    long userIdLong = GetterUtil.getLong(userId.getUserId(securityToken));

    User user = UserLocalServiceUtil.getUserById(userIdLong);

    if (!ShindigUtil.isValidUser(user)) {
        return;/*from   w ww .j  av a 2  s  . c  om*/
    }

    Group group = user.getGroup();

    long groupIdLong = group.getGroupId();

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

    options.setLocation(mediaItem.getUrl());

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

    String fileName = getFileName(mediaItem, options);
    String contentType = MimeTypesUtil.getContentType(fileName);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    serviceContext.setAttribute("sourceFileName", fileName);

    serviceContext.setExpandoBridgeAttributes(SerializerUtil.toExpandoAttributes(mediaItem, _MEDIA_ITEM_FIELDS,
            user.getCompanyId(), DLFileEntry.class.getName()));
    serviceContext.setScopeGroupId(groupIdLong);

    if (mediaItemId == null) {
        long albumIdLong = GetterUtil.getLong(albumId);

        DLAppServiceUtil.addFileEntry(groupIdLong, albumIdLong, fileName, contentType, mediaItem.getTitle(),
                mediaItem.getDescription(), StringPool.BLANK, byteArray, serviceContext);
    } else {
        long mediaItemIdLong = GetterUtil.getLong(mediaItemId);

        FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(mediaItemIdLong);

        serviceContext.setCreateDate(fileEntry.getCreateDate());
        serviceContext.setModifiedDate(fileEntry.getModifiedDate());

        DLAppServiceUtil.updateFileEntry(fileEntry.getFileEntryId(), fileName, contentType,
                mediaItem.getTitle(), mediaItem.getDescription(), StringPool.BLANK, false, byteArray,
                serviceContext);
    }
}

From source file:com.liferay.portlet.blogs.util.LinkbackProducerUtil.java

License:Open Source License

private static String _discoverPingbackServer(String targetUri) {
    String serverUri = null;//from  ww w . j  ava2 s.c  om

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

        options.addHeader(HttpHeaders.USER_AGENT, ReleaseInfo.getServerInfo());
        options.setLocation(targetUri);
        options.setHead(true);

        HttpUtil.URLtoByteArray(options);

        Http.Response response = options.getResponse();

        serverUri = response.getHeader("X-Pingback");
    } catch (Exception e) {
        _log.error("Unable to call HEAD of " + targetUri, e);
    }

    if (Validator.isNull(serverUri)) {
        try {
            Source clientSource = new Source(HttpUtil.URLtoString(targetUri));

            List<StartTag> startTags = clientSource.getAllStartTags("link");

            for (StartTag startTag : startTags) {
                String rel = startTag.getAttributeValue("rel");

                if (rel.equalsIgnoreCase("pingback")) {
                    String href = startTag.getAttributeValue("href");

                    serverUri = HtmlUtil.escape(href);

                    break;
                }
            }
        } catch (Exception e) {
            _log.error("Unable to call GET of " + targetUri, e);
        }
    }

    return serverUri;
}

From source file:com.liferay.portlet.shopping.service.impl.ShoppingItemLocalServiceImpl.java

License:Open Source License

protected void doAddBookItems(long userId, long groupId, long categoryId, String[] isbns)
        throws IOException, PortalException, SystemException {

    if (!AmazonRankingsUtil.isEnabled()) {
        throw new AmazonException("Amazon integration is not enabled");
    }//from ww  w.  ja v  a  2  s  . c om

    String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);

    for (int i = 0; (i < isbns.length) && (i < 50); i++) {
        String isbn = isbns[i];

        AmazonRankings amazonRankings = AmazonRankingsUtil.getAmazonRankings(isbn);

        if (amazonRankings == null) {
            continue;
        }

        String name = amazonRankings.getProductName();
        String description = StringPool.BLANK;
        String properties = getBookProperties(amazonRankings);

        int minQuantity = 0;
        int maxQuantity = 0;
        double price = amazonRankings.getListPrice();
        double discount = 1 - amazonRankings.getOurPrice() / price;
        boolean taxable = true;
        double shipping = 0.0;
        boolean useShippingFormula = true;

        ShoppingItemPrice itemPrice = shoppingItemPricePersistence.create(0);

        itemPrice.setMinQuantity(minQuantity);
        itemPrice.setMaxQuantity(maxQuantity);
        itemPrice.setPrice(price);
        itemPrice.setDiscount(discount);
        itemPrice.setTaxable(taxable);
        itemPrice.setShipping(shipping);
        itemPrice.setUseShippingFormula(useShippingFormula);
        itemPrice.setStatus(ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT);

        boolean requiresShipping = true;
        int stockQuantity = 0;
        boolean featured = false;
        Boolean sale = null;

        // Small image

        boolean smallImage = true;
        String smallImageURL = StringPool.BLANK;
        File smallImageFile = new File(tmpDir + File.separatorChar
                + PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");

        byte[] smallImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getSmallImageURL());

        if (smallImageBytes.length < 1024) {
            smallImage = false;
        } else {
            OutputStream os = new FileOutputStream(smallImageFile);

            os.write(smallImageBytes);

            os.close();
        }

        // Medium image

        boolean mediumImage = true;
        String mediumImageURL = StringPool.BLANK;
        File mediumImageFile = new File(tmpDir + File.separatorChar
                + PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");

        byte[] mediumImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getMediumImageURL());

        if (mediumImageBytes.length < 1024) {
            mediumImage = false;
        } else {
            OutputStream os = new FileOutputStream(mediumImageFile);

            os.write(mediumImageBytes);

            os.close();
        }

        // Large image

        boolean largeImage = true;
        String largeImageURL = StringPool.BLANK;
        File largeImageFile = new File(tmpDir + File.separatorChar
                + PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");

        byte[] largeImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getLargeImageURL());

        if (largeImageBytes.length < 1024) {
            largeImage = false;
        } else {
            OutputStream os = new FileOutputStream(largeImageFile);

            os.write(largeImageBytes);

            os.close();
        }

        List<ShoppingItemField> itemFields = new ArrayList<ShoppingItemField>();

        List<ShoppingItemPrice> itemPrices = new ArrayList<ShoppingItemPrice>();

        itemPrices.add(itemPrice);

        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setAddGroupPermissions(true);
        serviceContext.setAddGuestPermissions(true);

        addItem(userId, groupId, categoryId, isbn, name, description, properties, StringPool.BLANK,
                requiresShipping, stockQuantity, featured, sale, smallImage, smallImageURL, smallImageFile,
                mediumImage, mediumImageURL, mediumImageFile, largeImage, largeImageURL, largeImageFile,
                itemFields, itemPrices, serviceContext);

        smallImageFile.delete();
        mediumImageFile.delete();
        largeImageFile.delete();
    }
}

From source file:com.liferay.wsrp.bind.MarkupServiceImpl.java

License:Open Source License

protected byte[] getBinaryContent(Http.Options httpOptions) throws Exception {

    HttpSession session = ServletUtil.getSession();

    Cookie[] cookies = (Cookie[]) session.getAttribute(WebKeys.COOKIES);

    if (cookies != null) {
        httpOptions.setCookies(cookies);
    }//from ww w .ja va  2s .  c  om

    byte[] binaryContent = HttpUtil.URLtoByteArray(httpOptions);

    cookies = HttpUtil.getCookies();

    if (cookies != null) {
        session.setAttribute(WebKeys.COOKIES, cookies);
    }

    return binaryContent;
}

From source file:com.liferay.wsrp.consumer.portlet.ConsumerPortlet.java

License:Open Source License

protected void proxyURL(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String url)
        throws Exception {

    PortletSession portletSession = resourceRequest.getPortletSession();

    WSRPConsumerPortlet wsrpConsumerPortlet = getWSRPConsumerPortlet();

    WSRPConsumer wsrpConsumer = WSRPConsumerLocalServiceUtil
            .getWSRPConsumer(wsrpConsumerPortlet.getWsrpConsumerId());

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

    options.setLocation(url);//w ww .  j a v  a2 s. c  o m

    String cookieKey = getSessionKey(WebKeys.COOKIE, resourceRequest, wsrpConsumer);

    String cookie = (String) portletSession.getAttribute(cookieKey, PortletSession.APPLICATION_SCOPE);

    if (Validator.isNotNull(cookie)) {
        Map<String, String> headers = new HashMap<String, String>();

        headers.put(HttpHeaders.COOKIE, cookie);

        options.setHeaders(headers);
    }

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

    Http.Response response = options.getResponse();

    String contentDisposition = response.getHeader(HttpHeaders.CONTENT_DISPOSITION);

    if (Validator.isNotNull(contentDisposition)) {
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
    }

    int contentLength = response.getContentLength();

    if (contentLength >= 0) {
        resourceResponse.setContentLength(contentLength);
    }

    String contentType = response.getContentType();

    if (Validator.isNotNull(contentType)) {
        resourceResponse.setContentType(contentType);
    }

    String charSet = getCharSet(contentType);

    if (ParamUtil.getBoolean(resourceRequest, "wsrp-requiresRewrite")) {
        String content = rewriteURLs(resourceRequest, resourceResponse, new String(bytes, charSet));

        PortletResponseUtil.write(resourceResponse, content);
    } else {
        PortletResponseUtil.write(resourceResponse, bytes);
    }
}

From source file:com.liferay.wsrp.portlet.ConsumerPortlet.java

License:Open Source License

protected void proxyURL(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String url)
        throws Exception {

    PortletSession portletSession = resourceRequest.getPortletSession();

    WSRPConsumerPortlet wsrpConsumerPortlet = getWSRPConsumerPortlet();

    WSRPConsumer wsrpConsumer = WSRPConsumerLocalServiceUtil
            .getWSRPConsumer(wsrpConsumerPortlet.getWsrpConsumerId());

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

    options.setLocation(url);// www . j av  a  2s  . co m

    String cookieKey = getSessionKey(WebKeys.COOKIE, resourceRequest, wsrpConsumer);

    String cookie = (String) portletSession.getAttribute(cookieKey, PortletSession.APPLICATION_SCOPE);

    if (Validator.isNotNull(cookie)) {
        Map<String, String> headers = new HashMap<String, String>();

        headers.put(HttpHeaders.COOKIE, cookie);

        options.setHeaders(headers);
    }

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

    Http.Response response = options.getResponse();

    int contentLength = response.getContentLength();

    if (contentLength >= 0) {
        resourceResponse.setContentLength(contentLength);
    }

    String contentType = response.getContentType();

    if (Validator.isNotNull(contentType)) {
        resourceResponse.setContentType(contentType);
    }

    PortletResponseUtil.write(resourceResponse, bytes);
}