Example usage for com.google.gwt.user.server Base64Utils toBase64

List of usage examples for com.google.gwt.user.server Base64Utils toBase64

Introduction

In this page you can find the example usage for com.google.gwt.user.server Base64Utils toBase64.

Prototype

public static String toBase64(long value) 

Source Link

Document

Return a string containing a base-64 encoded version of the given long value.

Usage

From source file:com.acme.gwt.server.TvViewerJsonBootstrap.java

License:Apache License

public String getViewerAsJson() {
    SimpleRequestProcessor p = new SimpleRequestProcessor(ServiceLayer.create(isld));
    TvViewer user = viewerProvider.get();
    if (user == null) {
        return "";
    }//from   www .j  a va 2  s.c o m

    MessageFactory factory = MessageFactoryHolder.FACTORY;
    AutoBean<IdMessage> id = factory.id();
    try {
        id.as().setServerId(Base64Utils.toBase64(user.getId().toString().getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        return "";
    }
    id.as().setStrength(Strength.PERSISTED);
    id.as().setTypeToken(TvViewerProxy.class.getName());

    AutoBean<RequestMessage> msg = factory.request();
    msg.as().setInvocations(new ArrayList<InvocationMessage>());
    InvocationMessage invocation = factory.invocation().as();
    invocation.setOperation("com.google.gwt.requestfactory.shared.impl.FindRequest::find");
    invocation.setParameters(new ArrayList<Splittable>());
    invocation.getParameters().add(AutoBeanCodex.encode(id));
    msg.as().getInvocations().add(invocation);

    String value = p.process(AutoBeanCodex.encode(msg).getPayload());

    ResponseMessage response = AutoBeanCodex.decode(factory, ResponseMessage.class, value).as();
    OperationMessage opMsg = response.getOperations().get(0);
    DefaultProxyStore store = new DefaultProxyStore();
    store.put(TvViewerProxy.STORE_KEY, AutoBeanCodex.encode(AutoBeanUtils.getAutoBean(opMsg)));

    return store.encode();
}

From source file:com.cgxlib.xq.vm.AjaxTransportJre.java

License:Apache License

private Response httpClient(Settings s, boolean cors) throws Exception {
    String url = s.getUrl();/*from ww  w  .ja v a  2 s .  c o  m*/
    assert url.toLowerCase().startsWith("http");

    URL u = new URL(url);
    HttpURLConnection c = (HttpURLConnection) u.openConnection();

    c.setInstanceFollowRedirects(followRedirections);

    c.setRequestMethod(s.getType());
    c.setRequestProperty("User-Agent", USER_AGENT);
    if (s.getUsername() != null && s.getPassword() != null) {
        c.setRequestProperty("Authorization",
                "Basic " + Base64Utils.toBase64((s.getUsername() + ":" + s.getPassword()).getBytes()));
    }
    if (cookieManager != null) {
        cookieManager.setCookies(c);
    }

    boolean isCORS = cors && localDomain != null && !s.getUrl().contains(localDomain);
    if (isCORS) {
        // TODO: fetch options previously to the request
        // >> OPTIONS
        // Origin: http://127.0.0.1:8888
        //   Access-Control-Allow-Origin: http://127.0.0.1:8888
        //   Access-Control-Allow-Credentials: true
        // Access-Control-Request-Headers: content-type
        //   Access-Control-Allow-Headers
        // Access-Control-Request-Method
        //   Access-Control-Allow-Methods: POST, GET
        //   Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS

        // >> POST/GET
        // Origin: http://127.0.0.1:8888
        //   Access-Control-Allow-Origin: http://127.0.0.1:8888
        //   Access-Control-Allow-Credentials: true
        c.setRequestProperty("Origin", localDomain);
    }

    if (s.getTimeout() > 0) {
        c.setConnectTimeout(s.getTimeout());
        c.setReadTimeout(s.getTimeout());
    }

    IsProperties headers = s.getHeaders();
    if (headers != null) {
        for (String h : headers.getFieldNames()) {
            c.setRequestProperty(h, "" + headers.get(h));
        }
    }

    if (s.getType().matches("POST|PUT")) {
        c.setRequestProperty("Content-Type", s.getContentType());

        debugRequest(c, s.getDataString());

        c.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(c.getOutputStream());
        wr.writeBytes(s.getDataString());
        wr.flush();
        wr.close();
    } else {
        debugRequest(c, null);
    }

    int code = c.getResponseCode();
    if (isCORS) {
        if (!localDomain.equals(c.getHeaderField("Access-Control-Allow-Origin"))) {
            code = 0;
        }
        if (s.getWithCredentials() && c.getHeaderField("Access-Control-Allow-Credentials") == null) {
            code = 0;
        }
    }

    String payload = "";

    InputStream is = code >= 400 ? c.getErrorStream() : c.getInputStream();
    if (is != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\n");
        }
        in.close();
        payload = response.toString();
    }

    if (cookieManager != null) {
        cookieManager.storeCookies(c);
    }

    return new ResponseJre(code, c.getResponseMessage(), payload, c.getHeaderFields());
}

From source file:com.foo.server.rpc230.ServerSerializationStreamWriterSenasa.java

License:Apache License

@Override
public void writeLong(long value) {
    if (getVersion() == SERIALIZATION_STREAM_MIN_VERSION) {
        // Write longs as a pair of doubles for backwards compatibility
        double[] parts = getAsDoubleArray(value);
        assert parts != null && parts.length == 2;
        writeDouble(parts[0]);//from   w w w  .j  a  v  a 2 s  .  co  m
        writeDouble(parts[1]);
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append('\'');
        sb.append(Base64Utils.toBase64(value));
        sb.append('\'');
        append(sb.toString());
    }
}

From source file:com.foo.server.rpc230.ServerSerializationStreamWriterSenasa.java

License:Apache License

private void serializeClass(Object instance, Class<?> instanceClass) throws SerializationException {
    assert (instance != null);
    Field[] serializableFields = SerializabilityUtil.applyFieldSerializationPolicy(instanceClass);

    /**/*from  w  ww .  j  a  v  a2 s.  co  m*/
     * If clientFieldNames is non-null, identify any additional server-only
     * fields and serialize them separately. Java serialization is used to
     * construct a byte array, which is encoded as a String and written
     * prior to the rest of the field data.
     */
    Set<String> clientFieldNames = serializationPolicy.getClientFieldNamesForEnhancedClass(instanceClass);
    if (clientFieldNames != null) {
        List<Field> serverFields = new ArrayList<Field>();
        for (Field declField : serializableFields) {
            assert (declField != null);

            // Identify server-only fields
            if (!clientFieldNames.contains(declField.getName())) {
                serverFields.add(declField);
                continue;
            }
        }

        // Serialize the server-only fields into a byte array and encode as
        // a String
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeInt(serverFields.size());
            for (Field f : serverFields) {
                oos.writeObject(f.getName());
                f.setAccessible(true);
                Object fieldData = f.get(instance);
                oos.writeObject(fieldData);
            }
            oos.close();

            byte[] serializedData = baos.toByteArray();
            String encodedData = Base64Utils.toBase64(serializedData);
            writeString(encodedData);
        } catch (IllegalAccessException e) {
            throw new SerializationException(e);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }

    // Write the client-visible field data
    for (Field declField : serializableFields) {
        if ((clientFieldNames != null) && !clientFieldNames.contains(declField.getName())) {
            // Skip server-only fields
            continue;
        }

        boolean isAccessible = declField.isAccessible();
        boolean needsAccessOverride = !isAccessible && !Modifier.isPublic(declField.getModifiers());
        if (needsAccessOverride) {
            // Override the access restrictions
            declField.setAccessible(true);
        }

        Object value;
        try {
            value = declField.get(instance);
            serializeValue(value, declField.getType());

        } catch (IllegalArgumentException e) {
            throw new SerializationException(e);

        } catch (IllegalAccessException e) {
            throw new SerializationException(e);
        }
    }

    Class<?> superClass = instanceClass.getSuperclass();
    if (serializationPolicy.shouldSerializeFields(superClass)) {
        serializeImpl(instance, superClass);
    }
}

From source file:com.google.gwt.sample.dynatable.utils.ServerSerializationStreamWriter_2_0_1.java

License:Apache License

private void serializeClass(Object instance, Class<?> instanceClass) throws SerializationException {
    assert (instance != null);
    Field[] serializableFields = SerializabilityUtil.applyFieldSerializationPolicy(instanceClass);

    /**// w w w . ja  va 2 s .  c  o  m
     * If clientFieldNames is non-null, identify any additional server-only fields and serialize
     * them separately.  Java serialization is used to construct a byte array, which is encoded
     * as a String and written prior to the rest of the field data.
     */
    Set<String> clientFieldNames = serializationPolicy.getClientFieldNamesForEnhancedClass(instanceClass);
    if (clientFieldNames != null) {
        List<Field> serverFields = new ArrayList<Field>();
        for (Field declField : serializableFields) {
            assert (declField != null);

            // Identify server-only fields
            if (!clientFieldNames.contains(declField.getName())) {
                serverFields.add(declField);
                continue;
            }
        }

        // Serialize the server-only fields into a byte array and encode as a String
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeInt(serverFields.size());
            for (Field f : serverFields) {
                oos.writeObject(f.getName());
                f.setAccessible(true);
                Object fieldData = f.get(instance);
                oos.writeObject(fieldData);
            }
            oos.close();

            byte[] serializedData = baos.toByteArray();
            String encodedData = Base64Utils.toBase64(serializedData);
            writeString(encodedData);
        } catch (IllegalAccessException e) {
            throw new SerializationException(e);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }

    // Write the client-visible field data
    for (Field declField : serializableFields) {
        if ((clientFieldNames != null) && !clientFieldNames.contains(declField.getName())) {
            // Skip server-only fields
            continue;
        }

        boolean isAccessible = declField.isAccessible();
        boolean needsAccessOverride = !isAccessible && !Modifier.isPublic(declField.getModifiers());
        if (needsAccessOverride) {
            // Override the access restrictions
            declField.setAccessible(true);
        }

        Object value;
        try {
            value = declField.get(instance);
            serializeValue(value, declField.getType());

        } catch (IllegalArgumentException e) {
            throw new SerializationException(e);

        } catch (IllegalAccessException e) {
            throw new SerializationException(e);
        }
    }

    Class<?> superClass = instanceClass.getSuperclass();
    if (serializationPolicy.shouldSerializeFields(superClass)) {
        serializeImpl(instance, superClass);
    }
}

From source file:com.google.web.bindery.requestfactory.server.SimpleRequestProcessor.java

License:Apache License

static String toBase64(String data) {
    try {//from   w w w .ja  v a2s.c  o m
        return Base64Utils.toBase64(data.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new UnexpectedException(e);
    }
}

From source file:com.google.web.bindery.requestfactory.vm.impl.OperationKey.java

License:Apache License

/**
 * Compute a base64-encoded SHA1 hash of the input string's UTF8
 * representation. The result is a {@value #HASH_LENGTH}-character sequence.
 *///from ww  w. jav  a2s . c om
public static String hash(String raw) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] data = md.digest(raw.getBytes("UTF-8"));
        return Base64Utils.toBase64(data);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("No MD5 algorithm", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("No UTF-8", e);
    }
}

From source file:com.threerings.nexus.io.ServerOutput.java

License:Open Source License

@Override
public void writeLong(long value) {
    _output._buffer.append('\'').append(Base64Utils.toBase64(value)).append('\'');
    _output.appendSeparator();/*  www .  j  av a  2  s .  com*/
}

From source file:cz.fi.muni.xkremser.editor.server.fedora.utils.RESTHelper.java

License:Open Source License

/**
 * Open connection./* ww  w .  j av  a  2s  . c  o  m*/
 * 
 * @param urlString
 *        the url string
 * @param user
 *        the user
 * @param pass
 *        the pass
 * @param method
 *        the method
 * @param content
 *        the content
 * @return the uRL connection
 * @throws MalformedURLException
 *         the malformed url exception
 * @throws IOException
 *         Signals that an I/O exception has occurred.
 */
private static URLConnection openConnection(String urlString, String user, String pass, final int method,
        String content, boolean robustMode) throws MalformedURLException, IOException {
    try {
        Thread.sleep(Constants.REST_DELAY);
    } catch (InterruptedException e) {
        LOGGER.error(e.getMessage());
        e.printStackTrace();
    }
    URL url = new URL(urlString);
    boolean auth = false;
    String encoded = null;
    if (auth = (user != null && pass != null && !"".equals(user) && !"".equals(pass))) {
        String userPassword = user + ":" + pass;
        encoded = Base64Utils.toBase64(userPassword.getBytes());
    }
    URLConnection uc = null;
    OutputStreamWriter out = null;
    try {
        uc = url.openConnection();
        if (auth) {
            uc.setRequestProperty("Authorization", "Basic " + encoded);
        }
        switch (method) {
        case GET:
            break;
        case PUT:
            uc.setDoOutput(true);
            ((HttpURLConnection) uc).setRequestMethod("PUT");
            ((HttpURLConnection) uc).setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            try {
                out = new OutputStreamWriter(uc.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            try {
                if (content != null)
                    out.write(content);
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            out.flush();
            break;
        case POST:
            uc.setDoOutput(true);
            uc.setDoInput(true);
            ((HttpURLConnection) uc).setRequestMethod("POST");
            ((HttpURLConnection) uc).setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            try {
                out = new OutputStreamWriter(uc.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            try {
                if (content != null)
                    out.write(content);
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            out.flush();
            break;
        case DELETE:
            uc.setDoOutput(true);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            ((HttpURLConnection) uc).setRequestMethod("DELETE");
            break;
        }

        int resp = ((HttpURLConnection) uc).getResponseCode();
        if (resp < 200 || resp >= 308) {
            if (robustMode) {
                return null;
            } else {
                if (uc != null)
                    LOGGER.error(convertStreamToString(uc.getInputStream()));
                LOGGER.error("Unable to open connection on " + urlString + "  response code: " + resp);
                throw new ConnectionException("connection to " + urlString + " cannot be established");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new ConnectionException("connection to " + urlString + " cannot be established");
    }
    return uc;
}

From source file:cz.mzk.editor.server.util.RESTHelper.java

License:Open Source License

/**
 * Open connection./*from  ww  w.j a  va2  s. c  om*/
 * 
 * @param urlString
 *        the url string
 * @param user
 *        the user
 * @param pass
 *        the pass
 * @param method
 *        the method
 * @param content
 *        the content
 * @return the uRL connection
 * @throws MalformedURLException
 *         the malformed url exception
 * @throws IOException
 *         Signals that an I/O exception has occurred.
 */
private static URLConnection openConnection(String urlString, String user, String pass, final int method,
        String content, InputStream contentIs, boolean robustMode) throws MalformedURLException, IOException {
    try {
        Thread.sleep(Constants.REST_DELAY);
    } catch (InterruptedException e) {
        LOGGER.error(e.getMessage());
        e.printStackTrace();
    }
    URL url = new URL(urlString);
    boolean auth = false;
    String encoded = null;
    if (auth = (user != null && pass != null && !"".equals(user) && !"".equals(pass))) {
        String userPassword = user + ":" + pass;
        encoded = Base64Utils.toBase64(userPassword.getBytes());
    }
    URLConnection uc = null;
    OutputStreamWriter out = null;
    try {
        uc = url.openConnection();
        if (auth) {
            uc.setRequestProperty("Authorization", "Basic " + encoded);
        }
        switch (method) {
        case GET:
            break;
        case PUT:
            uc.setDoOutput(true);
            ((HttpURLConnection) uc).setRequestMethod("PUT");
            ((HttpURLConnection) uc).setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            try {
                out = new OutputStreamWriter(uc.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            try {
                if (content != null)
                    out.write(content);
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            out.flush();
            break;
        case POST:
            uc.setDoOutput(true);
            uc.setDoInput(true);
            ((HttpURLConnection) uc).setRequestMethod("POST");
            ((HttpURLConnection) uc).setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            try {
                out = new OutputStreamWriter(uc.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            OutputStream os = null;
            try {
                if (content != null) {
                    out.write(content);
                } else if (contentIs != null) {
                    os = uc.getOutputStream();
                    IOUtils.copyStreams(contentIs, os);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return uc;
            }
            if (os != null) {
                os.flush();
            } else {
                out.flush();
            }

            break;
        case DELETE:
            uc.setDoOutput(true);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            ((HttpURLConnection) uc).setRequestMethod("DELETE");
            break;
        }

        int resp = ((HttpURLConnection) uc).getResponseCode();
        if (resp < 200 || resp >= 308) {
            if (robustMode) {
                return null;
            } else {
                if (uc != null)
                    LOGGER.error(convertStreamToString(uc.getInputStream()));
                LOGGER.error("Unable to open connection on " + urlString + "  response code: " + resp);
                throw new ConnectionException("connection to " + urlString + " cannot be established");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new ConnectionException("connection to " + urlString + " cannot be established");
    }
    return uc;
}