protected void runScript(
      PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String language = ParamUtil.getString(actionRequest, "language");
    String script = ParamUtil.getString(actionRequest, "script");

    PortletContext portletContext = portletConfig.getPortletContext();

    Map<String, Object> portletObjects =
        ScriptingUtil.getPortletObjects(
            portletConfig, portletContext, actionRequest, actionResponse);

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream);

    portletObjects.put("out", unsyncPrintWriter);

    try {
      SessionMessages.add(actionRequest, "language", language);
      SessionMessages.add(actionRequest, "script", script);

      ScriptingUtil.exec(null, portletObjects, language, script);

      unsyncPrintWriter.flush();

      SessionMessages.add(actionRequest, "scriptOutput", unsyncByteArrayOutputStream.toString());
    } catch (ScriptingException se) {
      SessionErrors.add(actionRequest, ScriptingException.class.getName(), se);

      _log.error(se.getMessage());
    }
  }
  public static Throwable translateThrowable(Throwable throwable) {
    if (_useReflectionToTranslateThrowable) {
      try {
        UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(unsyncByteArrayOutputStream);

        objectOutputStream.writeObject(throwable);

        objectOutputStream.flush();
        objectOutputStream.close();

        UnsyncByteArrayInputStream unsyncByteArrayInputStream =
            new UnsyncByteArrayInputStream(
                unsyncByteArrayOutputStream.unsafeGetByteArray(),
                0,
                unsyncByteArrayOutputStream.size());

        Thread currentThread = Thread.currentThread();

        ClassLoader contextClassLoader = currentThread.getContextClassLoader();

        ObjectInputStream objectInputStream =
            new ClassLoaderObjectInputStream(unsyncByteArrayInputStream, contextClassLoader);

        throwable = (Throwable) objectInputStream.readObject();

        objectInputStream.close();

        return throwable;
      } catch (SecurityException se) {
        if (_log.isInfoEnabled()) {
          _log.info("Do not use reflection to translate throwable");
        }

        _useReflectionToTranslateThrowable = false;
      } catch (Throwable throwable2) {
        _log.error(throwable2, throwable2);

        return throwable2;
      }
    }

    Class<?> clazz = throwable.getClass();

    String className = clazz.getName();

    if (className.equals(PortalException.class.getName())) {
      return new PortalException();
    }

    if (className.equals(SystemException.class.getName())) {
      return new SystemException();
    }

    if (className.equals("com.ktree.timezone.model.dao.NoSuchWorldClockException")) {
      return new com.ktree.timezone.model.dao.NoSuchWorldClockException();
    }

    return throwable;
  }
示例#3
0
  public static Throwable translateThrowable(Throwable throwable) {
    if (_useReflectionToTranslateThrowable) {
      try {
        UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(unsyncByteArrayOutputStream);

        objectOutputStream.writeObject(throwable);

        objectOutputStream.flush();
        objectOutputStream.close();

        UnsyncByteArrayInputStream unsyncByteArrayInputStream =
            new UnsyncByteArrayInputStream(
                unsyncByteArrayOutputStream.unsafeGetByteArray(),
                0,
                unsyncByteArrayOutputStream.size());

        Thread currentThread = Thread.currentThread();

        ClassLoader contextClassLoader = currentThread.getContextClassLoader();

        ObjectInputStream objectInputStream =
            new ClassLoaderObjectInputStream(unsyncByteArrayInputStream, contextClassLoader);

        throwable = (Throwable) objectInputStream.readObject();

        objectInputStream.close();

        return throwable;
      } catch (ClassNotFoundException cnfe) {
        if (_log.isInfoEnabled()) {
          _log.info("Do not use reflection to translate throwable");
        }

        _useReflectionToTranslateThrowable = false;
      } catch (SecurityException se) {
        if (_log.isInfoEnabled()) {
          _log.info("Do not use reflection to translate throwable");
        }

        _useReflectionToTranslateThrowable = false;
      } catch (Throwable throwable2) {
        _log.error(throwable2, throwable2);

        return throwable2;
      }
    }

    Class<?> clazz = throwable.getClass();

    String className = clazz.getName();

    if (className.equals("com.liferay.pushnotifications.NoSuchDeviceException")) {
      return new com.liferay.pushnotifications.NoSuchDeviceException(
          throwable.getMessage(), throwable.getCause());
    }

    return throwable;
  }
示例#4
0
  public byte[] getBytes(RenderedImage renderedImage, String contentType) throws IOException {

    UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();

    write(renderedImage, contentType, baos);

    return baos.toByteArray();
  }
示例#5
0
  public static String list(Properties properties) {
    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    PrintStream printStream = new PrintStream(unsyncByteArrayOutputStream);

    properties.list(printStream);

    return unsyncByteArrayOutputStream.toString();
  }
示例#6
0
  @Override
  public String compactString() throws IOException {
    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    OutputFormat outputFormat = OutputFormat.createCompactFormat();

    XMLWriter xmlWriter = new XMLWriter(unsyncByteArrayOutputStream, outputFormat);

    xmlWriter.write(_node);

    return unsyncByteArrayOutputStream.toString(StringPool.UTF8);
  }
  protected void renderExclusive(
      HttpServletRequest request, HttpServletResponse response, ThemeDisplay themeDisplay)
      throws Exception {

    RenderRequestImpl renderRequestImpl =
        (RenderRequestImpl) request.getAttribute(JavaConstants.JAVAX_PORTLET_REQUEST);

    RenderResponseImpl renderResponseImpl =
        (RenderResponseImpl) request.getAttribute(JavaConstants.JAVAX_PORTLET_RESPONSE);

    StringServletResponse stringResponse =
        (StringServletResponse) renderRequestImpl.getAttribute(WebKeys.STRING_SERVLET_RESPONSE);

    if (stringResponse == null) {
      stringResponse = (StringServletResponse) renderResponseImpl.getHttpServletResponse();

      Portlet portlet = processPortletRequest(request, response, PortletRequest.RENDER_PHASE);

      InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, null);

      invokerPortlet.render(renderRequestImpl, renderResponseImpl);

      if (Validator.isNull(stringResponse.getString())) {
        stringResponse.setString(null);
      }
    }

    renderResponseImpl.transferHeaders(response);

    if (stringResponse.isCalledGetOutputStream()) {
      UnsyncByteArrayOutputStream ubaos = stringResponse.getUnsyncByteArrayOutputStream();

      InputStream is = new UnsyncByteArrayInputStream(ubaos.unsafeGetByteArray(), 0, ubaos.size());

      ServletResponseUtil.sendFile(
          request,
          response,
          renderResponseImpl.getResourceName(),
          is,
          renderResponseImpl.getContentType());
    } else if (stringResponse.isCalledGetWriter()) {
      byte[] content = stringResponse.getString().getBytes(StringPool.UTF8);

      ServletResponseUtil.sendFile(
          request,
          response,
          renderResponseImpl.getResourceName(),
          content,
          renderResponseImpl.getContentType());
    }

    renderRequestImpl.cleanUp();
  }
  @Test
  public void testURLTemplateResourceExternalization() throws Exception {
    String templateId = "testId";

    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    String resourcePath = clazz.getName();

    resourcePath = resourcePath.replace('.', '/') + ".class";

    URL url = classLoader.getResource(resourcePath);

    URLTemplateResource urlTemplateResource = new URLTemplateResource(templateId, url);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new MockObjectOutput(unsyncByteArrayOutputStream);

    urlTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    DataInputStream dataInputStream =
        new DataInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(templateId, dataInputStream.readUTF());
    Assert.assertEquals(url.toExternalForm(), dataInputStream.readUTF());

    // readExternal

    URLTemplateResource newURLTemplateResource = new URLTemplateResource();

    MockObjectInput mockObjectInput =
        new MockObjectInput(new DataInputStream(new UnsyncByteArrayInputStream(externalizedData)));

    newURLTemplateResource.readExternal(mockObjectInput);

    Assert.assertEquals(templateId, newURLTemplateResource.getTemplateId());

    Field templateURLField =
        ReflectionUtil.getDeclaredField(URLTemplateResource.class, "_templateURL");

    Assert.assertEquals(url, templateURLField.get(newURLTemplateResource));
  }
  public static void write(HttpServletResponse response, StringServletResponse stringResponse)
      throws IOException {

    if (stringResponse.isCalledGetOutputStream()) {
      UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
          stringResponse.getUnsyncByteArrayOutputStream();

      ByteBuffer byteBuffer = unsyncByteArrayOutputStream.unsafeGetByteBuffer();

      write(response, byteBuffer);
    } else {
      write(response, stringResponse.getString());
    }
  }
示例#10
0
  public static String transform(URL xmlURL, URL xslURL) throws IOException, TransformerException {

    String xml = HttpUtil.URLtoString(xmlURL);
    String xsl = HttpUtil.URLtoString(xslURL);

    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));
    StreamSource xslSource = new StreamSource(new UnsyncStringReader(xsl));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = transformerFactory.newTransformer(xslSource);

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));

    return unsyncByteArrayOutputStream.toString();
  }
  @Test
  public void testCacheTemplateResourceExternalization() throws Exception {
    StringTemplateResource stringTemplateResource =
        new StringTemplateResource("testId", "testContent");

    CacheTemplateResource cacheTemplateResource = new CacheTemplateResource(stringTemplateResource);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new ObjectOutputStream(unsyncByteArrayOutputStream);

    cacheTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    ObjectInput objectInput =
        new ObjectInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(cacheTemplateResource.getLastModified(), objectInput.readLong());
    Assert.assertEquals(stringTemplateResource, objectInput.readObject());

    // readExternal

    CacheTemplateResource newCacheTemplateResource = new CacheTemplateResource();

    objectInput = new ObjectInputStream(new UnsyncByteArrayInputStream(externalizedData));

    newCacheTemplateResource.readExternal(objectInput);

    Field templateResourceField =
        ReflectionUtil.getDeclaredField(CacheTemplateResource.class, "_templateResource");

    Assert.assertEquals(
        stringTemplateResource, templateResourceField.get(newCacheTemplateResource));

    Assert.assertEquals(
        cacheTemplateResource.getLastModified(), newCacheTemplateResource.getLastModified());
  }
  @Test
  public void testStringTemplateResourceExternalization() throws Exception {
    String templateId = "testId";
    String templateContent = "testContent";

    StringTemplateResource stringTemplateResource =
        new StringTemplateResource(templateId, templateContent);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new MockObjectOutput(unsyncByteArrayOutputStream);

    stringTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    DataInputStream dataInputStream =
        new DataInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(stringTemplateResource.getLastModified(), dataInputStream.readLong());
    Assert.assertEquals(templateContent, dataInputStream.readUTF());
    Assert.assertEquals(templateId, dataInputStream.readUTF());

    // readExternal

    StringTemplateResource newStringTemplateResource = new StringTemplateResource();

    MockObjectInput mockObjectInput =
        new MockObjectInput(new DataInputStream(new UnsyncByteArrayInputStream(externalizedData)));

    newStringTemplateResource.readExternal(mockObjectInput);

    Assert.assertEquals(
        stringTemplateResource.getLastModified(), newStringTemplateResource.getLastModified());
    Assert.assertEquals(templateContent, newStringTemplateResource.getContent());
    Assert.assertEquals(templateId, newStringTemplateResource.getTemplateId());
  }
  /**
   * This method only uses the default Commons HttpClient implementation when the URL object
   * represents a HTTP resource. The URL object could also represent a file or some JNDI resource.
   * In that case, the default Java implementation is used.
   *
   * @return A string representation of the resource referenced by the URL object
   */
  public String URLtoString(URL url) throws IOException {
    String xml = null;

    if (url != null) {
      String protocol = url.getProtocol().toLowerCase();

      if (protocol.startsWith(Http.HTTP) || protocol.startsWith(Http.HTTPS)) {

        return URLtoString(url.toString());
      }

      URLConnection urlConnection = url.openConnection();

      InputStream inputStream = urlConnection.getInputStream();

      UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

      byte[] bytes = new byte[512];

      for (int i = inputStream.read(bytes, 0, 512); i != -1; i = inputStream.read(bytes, 0, 512)) {

        unsyncByteArrayOutputStream.write(bytes, 0, i);
      }

      xml =
          new String(
              unsyncByteArrayOutputStream.unsafeGetByteArray(),
              0,
              unsyncByteArrayOutputStream.size());

      inputStream.close();

      unsyncByteArrayOutputStream.close();
    }

    return xml;
  }
  @Test
  public void testJournalTemplateResourceExternalization() throws Exception {
    String templateId = "testId";
    final long journalTemplateId = 100;

    JournalTemplate journalTemplate =
        (JournalTemplate)
            ProxyUtil.newProxyInstance(
                getClass().getClassLoader(),
                new Class<?>[] {JournalTemplate.class},
                new InvocationHandler() {

                  public Object invoke(Object proxy, Method method, Object[] arguments)
                      throws Throwable {

                    String methodName = method.getName();

                    if (methodName.equals("getId")) {
                      return journalTemplateId;
                    }

                    throw new UnsupportedOperationException();
                  }
                });

    JournalTemplateResource journalTemplateResource =
        new JournalTemplateResource(templateId, journalTemplate);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new MockObjectOutput(unsyncByteArrayOutputStream);

    journalTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    DataInputStream dataInputStream =
        new DataInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(journalTemplateId, dataInputStream.readLong());
    Assert.assertEquals(templateId, dataInputStream.readUTF());

    // readExternal

    JournalTemplateResource newJournalTemplateResource = new JournalTemplateResource();

    MockObjectInput mockObjectInput =
        new MockObjectInput(new DataInputStream(new UnsyncByteArrayInputStream(externalizedData)));

    UnsyncByteArrayOutputStream hijackedUnsyncByteArrayOutputStream =
        ConsoleTestUtil.hijackStdErr();

    try {
      newJournalTemplateResource.readExternal(mockObjectInput);

      Assert.fail();
    } catch (IOException ioe) {
      Assert.assertEquals(
          "Unable to retrieve journal template with ID " + journalTemplateId, ioe.getMessage());
    } finally {
      ConsoleTestUtil.restoreStdErr(hijackedUnsyncByteArrayOutputStream);
    }

    Assert.assertEquals(null, newJournalTemplateResource.getTemplateId());
  }
示例#15
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script)
      throws Exception {

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    long companyId = GetterUtil.getLong(tokens.get("company_id"));
    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
    long groupId = GetterUtil.getLong(tokens.get("group_id"));
    String journalTemplatesPath =
        VelocityResourceListener.JOURNAL_SEPARATOR
            + StringPool.SLASH
            + companyId
            + StringPool.SLASH
            + groupId;
    String randomNamespace = PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE;
    Locale locale = LocaleUtil.fromLanguageId(languageId);

    XSLErrorListener xslErrorListener = new XSLErrorListener(locale);

    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    transformerFactory.setURIResolver(new URIResolver(tokens, languageId));
    transformerFactory.setErrorListener(xslErrorListener);

    try {
      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(script));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("viewMode", viewMode);
      transformer.setParameter("locale", locale);
      transformer.setParameter("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    } catch (Exception e1) {
      String errorTemplate = ContentUtil.get(PropsValues.JOURNAL_ERROR_TEMPLATE_XSL);

      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(errorTemplate));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("locale", locale);
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.setParameter("exception", xslErrorListener.getMessageAndLocation());
      transformer.setParameter("script", script);

      if (xslErrorListener.getLocation() != null) {
        transformer.setParameter("column", new Integer(xslErrorListener.getColumnNumber()));
        transformer.setParameter("line", new Integer(xslErrorListener.getLineNumber()));
      }

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    }

    return unsyncByteArrayOutputStream.toString(StringPool.UTF8);
  }