Example usage for com.google.gwt.user.server.rpc UnexpectedException UnexpectedException

List of usage examples for com.google.gwt.user.server.rpc UnexpectedException UnexpectedException

Introduction

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

Prototype

public UnexpectedException(String message, Throwable cause) 

Source Link

Document

Construct an UnexpectedException.

Usage

From source file:com.apress.progwt.server.gwt.RPC1524.java

License:Apache License

/**
 * Returns a string that encodes an exception. If method is not
 * <code>null</code>, it is an error if the exception is not in the
 * method's list of checked exceptions./* ww  w .j a  v  a  2 s  .c om*/
 * 
 * <p>
 * If the serializationPolicy parameter is not <code>null</code>,
 * it is used to determine what types can be encoded as part of this
 * response. If this parameter is <code>null</code>, then only
 * subtypes of
 * {@link com.google.gwt.user.client.rpc.IsSerializable IsSerializable}
 * or types which have custom field serializers may be encoded.
 * </p>
 * 
 * @param serviceMethod
 *            the method that threw the exception, may be
 *            <code>null</code>
 * @param cause
 *            the {@link Throwable} that was thrown
 * @param serializationPolicy
 *            determines the serialization policy to be used
 * @return a string that encodes the exception
 * 
 * @throws NullPointerException
 *             if the the cause or the serializationPolicy are
 *             <code>null</code>
 * @throws SerializationException
 *             if the result cannot be serialized
 * @throws UnexpectedException
 *             if the result was an unexpected exception (a checked
 *             exception not declared in the serviceMethod's
 *             signature)
 */
public static String encodeResponseForFailure(Method serviceMethod, Throwable cause,
        ServerSerializationStreamWriter_1_5_3 streamWriter) throws SerializationException {
    if (cause == null) {
        throw new NullPointerException("cause cannot be null");
    }

    if (streamWriter == null) {
        throw new NullPointerException("streamWriter");
    }

    if (serviceMethod != null && !RPC1524.isExpectedException(serviceMethod, cause)) {
        throw new UnexpectedException("Service method '" + getSourceRepresentation(serviceMethod)
                + "' threw an unexpected exception: " + cause.toString(), cause);
    }

    return encodeResponse(cause.getClass(), cause, true, streamWriter);
}

From source file:com.brightedu.server.util.MyRPC.java

License:Apache License

public static String encodeResponseForFailure(Method serviceMethod, Throwable cause,
        SerializationPolicy serializationPolicy, int flags) throws SerializationException {
    if (cause == null) {
        throw new NullPointerException("cause cannot be null");
    }//from  www .ja  va 2s .  com

    if (serializationPolicy == null) {
        throw new NullPointerException("serializationPolicy");
    }

    if (serviceMethod != null && !RPCServletUtils.isExpectedException(serviceMethod, cause)) {
        throw new UnexpectedException("Service method '" + getSourceRepresentation(serviceMethod)
                + "' threw an unexpected exception: " + cause.toString(), cause);
    }

    return encodeResponse(cause.getClass(), cause, true, flags, serializationPolicy);
}

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

License:Apache License

public static String encodeResponseForFailure(Method serviceMethod, Throwable cause,
        ServerSerializationStreamWriterSenasa streamWriter, int flags) throws SerializationException {
    if (cause == null) {
        throw new NullPointerException("cause cannot be null");
    }//from  w ww  .ja v  a 2s .  com

    if (streamWriter == null) {
        throw new NullPointerException("streamWriter");
    }

    if (serviceMethod != null && !RPCServletUtils.isExpectedException(serviceMethod, cause)) {
        throw new UnexpectedException("Service method '" + getSourceRepresentation(serviceMethod)
                + "' threw an unexpected exception: " + cause.toString(), cause);
    }

    return encodeResponse(cause.getClass(), cause, true, flags, streamWriter);
}

From source file:com.google.mobile.trippy.web.server.service.LPSearchServiceImpl.java

License:Apache License

/**
 * Get places, matching given string, using LonelyPlanet RESTful service.
 * //from  w w w.ja  v  a  2s.co  m
 * Sample XML :
 * 
 * <pre>
 * &lt;places&gt;
 *   &lt;place&gt;
 *      &lt;id&gt;31010&lt;/id&gt;
 *      &lt;full-name&gt;Pacific -&gt; Australia -&gt; New South Wales -&gt; Sydney&lt;
 *            /full-name&gt;
 *      &lt;short-name&gt;Sydney&lt;/short-name&gt;
 *      &lt;north-latitude&gt;-33.747799&lt;/north-latitude&gt;
 *      &lt;south-latitude&gt;-33.9673&lt;/south-latitude&gt;
 *      &lt;east-longitude&gt;151.376007&lt;/east-longitude&gt;
 *      &lt;west-longitude&gt;151.054993&lt;/west-longitude&gt;
 *   &lt;/place&gt;
 *   &lt;place&gt;
 *      &lt;id&gt;29135&lt;/id&gt;
 *      &lt;full-name&gt;North America -&gt; Canada -&gt; Nova Scotia -&gt; 
 *            Cape Breton Island -&gt; Sydney&lt;/full-name&gt;
 *      &lt;short-name&gt;Sydney&lt;/short-name&gt;
 *      &lt;north-latitude&gt;46.149038&lt;/north-latitude&gt;
 *      &lt;south-latitude&gt;46.110969&lt;/south-latitude&gt;
 *      &lt;east-longitude&gt;-60.161304&lt;/east-longitude&gt;
 *      &lt;west-longitude&gt;-60.230484&lt;/west-longitude&gt;
 *   &lt;/place&gt;
 * &lt;/places&gt;
 * </pre>
 * 
 * @return list of places
 */
@Override
public ArrayList<Place> getPlaces(String placeStr) throws MissingAttributeException, IOException {
    Preconditions.checkNotNull(placeStr, "Place must be provided.");
    Preconditions.checkArgument(!placeStr.isEmpty(), "Place must not be empty.");
    final ArrayList<Place> places = new ArrayList<Place>();
    try {
        final URL url = new URL(LP_PLACE_URL + placeStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        /*
         * mJ1pMpMk2AFq4EZ5dbuAoA => OAuth key for app "Trippy"
         * TfrrOxqWY7kGdvRwaSHWIX8E4RTgUSwFjX2Ojjhq9gA => consumer secret for app
         * "Trippy' The OAuth key is used as username and consumer secret is used
         * as password for basid authentication. The key and secret are provided
         * when a application is registered on lonely planet developer forum
         */
        connection.setRequestProperty("Authorization", "Basic " + Base64.encode((LP_KEY).getBytes()));
        final Document doc = dbfInst.parse(connection.getInputStream());

        final NodeList placeNodes = doc.getElementsByTagName(LP_PLACE);

        for (int i = 0, n = placeNodes.getLength(); i < n; ++i) {
            final Element placeElement = (Element) placeNodes.item(i);
            final Place place = new Place();

            final NodeList placeIdNodes = placeElement.getElementsByTagName(LP_PLACE_ID);
            if (placeIdNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_ID);
            }
            final Node placeIdNode = placeIdNodes.item(0);
            place.setId(Long.parseLong(placeIdNode.getFirstChild().getNodeValue()));

            final NodeList placeFullNameNodes = placeElement.getElementsByTagName(LP_PLACE_FULLNAME);
            if (placeFullNameNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_FULLNAME);
            }
            final Node placeFullNameNode = placeFullNameNodes.item(0);
            place.setFullName(placeFullNameNode.getFirstChild().getNodeValue());

            final NodeList placeShortNameNodes = placeElement.getElementsByTagName(LP_PLACE_SHORTNAME);
            if (placeShortNameNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_SHORTNAME);
            }
            final Node placeShortNameNode = placeShortNameNodes.item(0);
            place.setShortName(placeShortNameNode.getFirstChild().getNodeValue());

            final NodeList placeNorthLatNodes = placeElement.getElementsByTagName(LP_PLACE_NORTH_LAT);
            if (placeNorthLatNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_NORTH_LAT);
            }
            final Node placeNorthLatNode = placeNorthLatNodes.item(0).getFirstChild();
            if (placeNorthLatNode == null) {
                throw new MissingAttributeException(LP_PLACE_NORTH_LAT);
            }
            place.setNorthLatitude(Double.parseDouble(placeNorthLatNode.getNodeValue()));

            NodeList placeSouthLatNodes = placeElement.getElementsByTagName(LP_PLACE_SOUTH_LAT);
            if (placeSouthLatNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_SOUTH_LAT);
            }
            Node placeSouthLatNode = placeSouthLatNodes.item(0).getFirstChild();
            if (placeSouthLatNode == null) {
                throw new MissingAttributeException(LP_PLACE_SOUTH_LAT);
            }
            place.setSouthLatitude(Double.parseDouble(placeSouthLatNode.getNodeValue()));

            final NodeList placeEastLongNodes = placeElement.getElementsByTagName(LP_PLACE_EAST_LONG);
            if (placeEastLongNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_EAST_LONG);
            }
            final Node placeEastLongNode = placeEastLongNodes.item(0).getFirstChild();
            if (placeEastLongNode == null) {
                throw new MissingAttributeException(LP_PLACE_EAST_LONG);
            }
            place.setEastLongitude(Double.parseDouble(placeEastLongNode.getNodeValue()));

            final NodeList placeWestLongNodes = placeElement.getElementsByTagName(LP_PLACE_WEST_LONG);
            if (placeWestLongNodes.getLength() == 0) {
                throw new MissingAttributeException(LP_PLACE_WEST_LONG);
            }
            final Node placeWestLongNode = placeWestLongNodes.item(0).getFirstChild();
            if (placeWestLongNode == null) {
                throw new MissingAttributeException(LP_PLACE_WEST_LONG);
            }
            place.setWestLongitude(Double.parseDouble(placeWestLongNode.getNodeValue()));

            places.add(place);
        }
    } catch (MissingAttributeException e) {
        logger.warning(e.getMessage());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } catch (SAXException e) {
        e.printStackTrace();
        throw new UnexpectedException(e.getMessage(), e);
        // } catch (ParserConfigurationException e) {
        // e.printStackTrace();
        // throw new UnexpectedException(e.getMessage(), e);
    }
    return places;
}

From source file:com.google.mobile.trippy.web.server.service.LPSearchServiceImpl.java

License:Apache License

/**
 * Search places-of-interest in the given bounding box values
 * ({north},{south},{east},{west}) and place of type (POIType).
 * //from   w w  w  . j  a v  a 2 s. c om
 * Sample XML :
 * 
 * <pre>
 * &lt;pois&gt;
 *  &lt;poi&gt;
 *    &lt;id&gt;367907&lt;/id&gt;
 *    &lt;name&gt;Coogee Bay Hotel&lt;/name&gt;
 *    &lt;digital-latitude&gt;-33.920940998916&lt;/digital-latitude&gt;
 *    &lt;digital-longitude&gt;151.256557703018&lt;/digital-longitude&gt;
 *    &lt;poi-type&gt;Night&lt;/poi-type&gt;
 *  &lt;/poi&gt;
 *  &lt;poi&gt;
 *    &lt;id&gt;367711&lt;/id&gt;
 *    &lt;name&gt;New Theatre&lt;/name&gt;
 *    &lt;digital-latitude&gt;-33.9031756797962&lt;/digital-latitude&gt;
 *    &lt;digital-longitude&gt;151.179843842983&lt;/digital-longitude&gt;
 *    &lt;poi-type&gt;Night&lt;/poi-type&gt;
 *  &lt;/poi&gt;
 * &lt;/pois&gt;
 * </pre>
 */
@Override
public ArrayList<POI> searchPOIByBoundingBox(double north, double south, double east, double west,
        String poiType) throws MissingAttributeException, IOException {
    final ArrayList<POI> pois = new ArrayList<POI>();
    Preconditions.checkNotNull(north, "North-latitude must be provided.");
    Preconditions.checkNotNull(south, "South-latitude must be provided.");
    Preconditions.checkNotNull(east, "East-longitude must be provided.");
    Preconditions.checkNotNull(west, "West-longitude must be provided.");
    Preconditions.checkNotNull(poiType, "Place of intrest type must be provided.");
    Preconditions.checkArgument(!poiType.isEmpty(), "Place of intrest type must not be empty.");
    try {
        final URL url = new URL(LP_BOUNDING_BOX_POI_URL.replace("{north}", "" + north)
                .replace("{south}", "" + south).replace("{east}", "" + east).replace("{west}", "" + west)
                .replace("{type-name}", poiType));

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        /*
         * mJ1pMpMk2AFq4EZ5dbuAoA => OAuth key for app "Trippy"
         * TfrrOxqWY7kGdvRwaSHWIX8E4RTgUSwFjX2Ojjhq9gA => consumer secret for app
         * "Trippy' The OAuth key is used as username and consumer secret is used
         * as password for basid authentication. The key and secret are provided
         * when a application is registered on lonely planet developer forum
         */
        connection.setRequestProperty("Authorization", "Basic " + Base64.encode((LP_KEY).getBytes()));
        final Document doc = dbfInst.parse(connection.getInputStream());

        final NodeList poiNodes = doc.getElementsByTagName(LP_POI);
        pois.addAll(parseForPOI(poiNodes));
    } catch (MissingAttributeException e) {
        logger.warning(e.getMessage());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } catch (SAXException e) {
        e.printStackTrace();
        throw new UnexpectedException(e.getMessage(), e);
    }
    return pois;
}

From source file:com.google.mobile.trippy.web.server.service.LPSearchServiceImpl.java

License:Apache License

/**
 * Search places-of-interest in the given place and of type (POIType).
 * /*from ww  w .  j a  va  2s  .c  o  m*/
 * Sample XML :
 * 
 * <pre>
 * &lt;pois&gt;
 *  &lt;poi&gt;
 *    &lt;id&gt;367907&lt;/id&gt;
 *    &lt;name&gt;Coogee Bay Hotel&lt;/name&gt;
 *    &lt;digital-latitude&gt;-33.920940998916&lt;/digital-latitude&gt;
 *    &lt;digital-longitude&gt;151.256557703018&lt;/digital-longitude&gt;
 *    &lt;poi-type&gt;Night&lt;/poi-type&gt;
 *  &lt;/poi&gt;
 *  &lt;poi&gt;
 *    &lt;id&gt;367711&lt;/id&gt;
 *    &lt;name&gt;New Theatre&lt;/name&gt;
 *    &lt;digital-latitude&gt;-33.9031756797962&lt;/digital-latitude&gt;
 *    &lt;digital-longitude&gt;151.179843842983&lt;/digital-longitude&gt;
 *    &lt;poi-type&gt;Night&lt;/poi-type&gt;
 *  &lt;/poi&gt;
 * &lt;/pois&gt;
 * </pre>
 * 
 * @throws MissingAttributeException
 */
@Override
public ArrayList<POI> searchPOI(long placeId, String poiType) throws MissingAttributeException, IOException {
    final ArrayList<POI> pois = new ArrayList<POI>();
    Preconditions.checkNotNull(placeId, "Place id must be provided.");
    Preconditions.checkNotNull(poiType, "Place of intrest type must be provided.");
    Preconditions.checkArgument(!poiType.isEmpty(), "Place of intrest type must not be empty.");
    try {
        final URL url = new URL(LP_POI_URL.replace("{placeID}", "" + placeId).replace("{poiType}", poiType));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        /*
         * mJ1pMpMk2AFq4EZ5dbuAoA => OAuth key for app "Trippy"
         * TfrrOxqWY7kGdvRwaSHWIX8E4RTgUSwFjX2Ojjhq9gA => consumer secret for app
         * "Trippy' The OAuth key is used as username and consumer secret is used
         * as password for basid authentication. The key and secret are provided
         * when a application is registered on lonely planet developer forum
         */
        connection.setRequestProperty("Authorization", "Basic " + Base64.encode((LP_KEY).getBytes()));
        final Document doc = dbfInst.parse(connection.getInputStream());

        final NodeList poiNodes = doc.getElementsByTagName(LP_POI);
        pois.addAll(parseForPOI(poiNodes));
    } catch (MissingAttributeException e) {
        logger.warning(e.getMessage());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } catch (SAXException e) {
        e.printStackTrace();
        throw new UnexpectedException(e.getMessage(), e);
    }
    return pois;
}

From source file:com.google.mobile.trippy.web.server.service.LPSearchServiceImpl.java

License:Apache License

/**
 * Get complete detail for a place.//  www .j av a 2  s  .  c  o  m
 * 
 * getPlaces above returns only short snippets of a POI. This service is used
 * on event to add search result to the trip.
 * 
 * Sample :
 * 
 * <pre>
 *  &lt;poi&gt;
 *    &lt;name&gt;Cannon Bar&lt;/name&gt;
 *    &lt;alt-name/&gt;
 *    &lt;digital-latitude&gt;36.1394949838271&lt;/digital-latitude&gt;
 *    &lt;digital-longitude&gt;-5.3531742095947&lt;/digital-longitude&gt;
 *    &lt;emails&gt;
 *    &lt;/emails&gt;
 *    &lt;hours/&gt;
 *    &lt;prac-string&gt;
 *      &lt;icon type=&quot;phone&quot;&gt;tel&lt;/icon&gt;77288; 27 Cannon Lane; mains 5.50-9.50
 *    &lt;/prac-string&gt;
 *    &lt;price-range&gt;2&lt;/price-range&gt;
 *    &lt;price-string/&gt;
 *    &lt;urls&gt;
 *    &lt;/urls&gt;
 *    &lt;poi-type&gt;Eat&lt;/poi-type&gt;
 *    &lt;address&gt;
 *      &lt;street&gt;27 Cannon Lane&lt;/street&gt;
 *      &lt;locality&gt;Town Centre&lt;/locality&gt;
 *      &lt;postcode/&gt;
 *      &lt;extras/&gt;
 *    &lt;/address&gt;
 *    &lt;review&gt;
 *      &lt;p&gt;Justly famous for some of the best fish and chips in town, and 
 *            in big portions.&lt;/p&gt; 
 *    &lt;/review&gt;
 *    &lt;telephones&gt;
 *      &lt;telephone&gt;
 *        &lt;area-code/&gt;
 *        &lt;number&gt;77288&lt;/number&gt;
 *        &lt;text&gt;tel, info&lt;/text&gt;
 *      &lt;/telephone&gt;
 *    &lt;/telephones&gt;
 *    &lt;transports&gt;
 *    &lt;/transports&gt;
 *    &lt;representations&gt;
 *      &lt;representation type=&quot;msite&quot; href=&quot;http://m.lonelyplanet.com/
 *            et-1000587244&quot;/&gt;
 *      &lt;representation type=&quot;msite.touch&quot; href=&quot;http://touch.lonelyplanet.com/
 *            et-1000587244&quot;/&gt;
 *      &lt;representation type=&quot;lp.com&quot; href=&quot;http://www.lonelyplanet.com/
 *            poiRedirector?poiId=363499&quot;/&gt;
 *    &lt;/representations&gt;
 *  &lt;/poi&gt;
 * </pre>
 */
public POIDetail getPOI(final long poiId) throws MissingAttributeException, IOException {
    final POIDetail detail = new POIDetail();
    Preconditions.checkNotNull(poiId, "Place of intrest id must be provided.");
    try {
        final URL url = new URL(LP_POI_DETAIL_URL.replace("{poi-id}", "" + poiId));

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        /*
         * mJ1pMpMk2AFq4EZ5dbuAoA => OAuth key for app "Trippy"
         * TfrrOxqWY7kGdvRwaSHWIX8E4RTgUSwFjX2Ojjhq9gA => consumer secret for app
         * "Trippy' The OAuth key is used as username and consumer secret is used
         * as password for basid authentication. The key and secret are provided
         * when a application is registered on lonely planet developer forum
         */
        connection.setRequestProperty("Authorization", "Basic " + Base64.encode((LP_KEY).getBytes()));

        final Document doc = dbfInst.parse(connection.getInputStream());

        final NodeList poiNodes = doc.getElementsByTagName(LP_POI);

        String docText = doc.getTextContent();
        // System.out.println(docText);

        if (poiNodes.getLength() == 0) {
            throw new MissingAttributeException(LP_POI);
        }
        final Element poiElement = (Element) poiNodes.item(0);

        detail.setId(poiId);

        final NodeList poiNameNodes = poiElement.getElementsByTagName(LP_POI_NAME);
        if (poiNameNodes.getLength() == 0) {
            throw new MissingAttributeException(LP_POI_NAME);
        }
        final Node poiNameNode = poiNameNodes.item(0);
        detail.setName(poiNameNode.getFirstChild().getNodeValue());

        final NodeList poiTypeNodes = poiElement.getElementsByTagName(LP_POI_TYPE);
        if (poiTypeNodes.getLength() == 0) {
            throw new MissingAttributeException(LP_POI_TYPE);
        }
        final Node poiTypeNode = poiTypeNodes.item(0);
        detail.setPoiType(poiTypeNode.getFirstChild().getNodeValue());

        final NodeList poiLatNodes = poiElement.getElementsByTagName(LP_POI_LAT);
        if (poiLatNodes.getLength() == 0) {
            throw new MissingAttributeException(LP_POI_LAT);
        }
        final Node poiLatNode = poiLatNodes.item(0).getFirstChild();
        if (poiLatNode == null) {
            throw new MissingAttributeException(LP_POI_LAT);
        }
        detail.setLatitude(Double.parseDouble(poiLatNode.getNodeValue()));

        final NodeList poiLngNodes = poiElement.getElementsByTagName(LP_POI_LONG);
        if (poiLngNodes.getLength() == 0) {
            throw new MissingAttributeException(LP_POI_LONG);
        }
        final Node poiLngNode = poiLngNodes.item(0).getFirstChild();
        if (poiLngNode == null) {
            throw new MissingAttributeException(LP_POI_LAT);
        }
        detail.setLongitude(Double.parseDouble(poiLngNode.getNodeValue()));

        final NodeList poiAddressNodes = poiElement.getElementsByTagName(LP_POI_ADDR);
        if (poiAddressNodes.getLength() > 0) {
            detail.setAddress(getAddress((Element) poiAddressNodes.item(0)));
        }

        final NodeList poiPhonesNodes = poiElement.getElementsByTagName(LP_POI_PHONES);
        if (poiPhonesNodes.getLength() > 0) {
            detail.setPhones(getPhones((Element) poiPhonesNodes.item(0)));
        }

        final NodeList poiSearchUrlNodes = poiElement.getElementsByTagName(LP_POI_SEARCH_URLS);
        if (poiSearchUrlNodes.getLength() > 0) {
            detail.setSearchResultUrl(getSearchUrl((Element) poiSearchUrlNodes.item(0)));
        }

        final NodeList poiReviewNodes = poiElement.getElementsByTagName(LP_POI_REVIEW);
        if (poiReviewNodes.getLength() > 0) {
            detail.setReview(getReview((Element) poiReviewNodes.item(0)));
        }
    } catch (MissingAttributeException e) {
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } catch (SAXException e) {
        e.printStackTrace();
        throw new UnexpectedException(e.getMessage(), e);
    }
    return detail;
}

From source file:com.guit.server.guice.GuiceGwtServlet.java

License:Apache License

public String decodeRequest(String encodedRequest, Class<?> type,
        SerializationPolicyProvider serializationPolicyProvider) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    Method method = execute;//from   ww w . j av a  2  s. co  m
    try {
        ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(classLoader,
                serializationPolicyProvider);
        streamReader.prepareToRead(encodedRequest);

        SerializationPolicy serializationPolicy = streamReader.getSerializationPolicy();

        // Predecible values
        streamReader.readString();

        // Method name
        String methodName = streamReader.readString();

        // Ignore, we know the values
        streamReader.readInt();
        streamReader.readString();

        Object[] parameterValues = new Object[1];
        if ("execute".equals(methodName)) {
            method = execute;
            parameterValues[0] = streamReader.deserializeValue(Action.class);
        } else {
            method = executeBatch;
            parameterValues[0] = streamReader.deserializeValue(ArrayList.class);
        }

        int flags = streamReader.getFlags();
        try {
            return encodeResponse(method.getReturnType(), method.invoke(service, parameterValues), false, flags,
                    serializationPolicy);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (!(cause instanceof CommandException)) {
                throw new UnexpectedException(
                        "Service method threw an unexpected exception: " + cause.toString(), cause);
            }

            return encodeResponse(cause.getClass(), cause, true, flags, serializationPolicy);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

License:Apache License

protected String processInvocationException(HttpServletRequest servletRequest, Object service,
        RPCRequest rpcRequest, Throwable exception)
        throws ServletException, IOException, SerializationException, RuntimeException {
    final String responsePayload;

    if (RPCServletUtils.isExpectedException(rpcRequest.getMethod(), exception)) {
        if (log.isDebugEnabled()) {
            log.debug("Expected exception thrown when invoking method " + rpcRequest.getMethod()
                    + " on service " + service.getClass().getName(), exception);
        }//  www  . j  a v  a  2s .  c  o m
        responsePayload = processExpectedException(servletRequest, service, rpcRequest, exception);
    } else if (exception instanceof RuntimeException) {
        throw ((RuntimeException) exception);
    } else if (exception instanceof Error) {
        throw ((Error) exception);
    } else {
        throw new UnexpectedException("Unexpected checked exception " + "occured while invoking method "
                + rpcRequest.getMethod() + " on service " + service.getClass().getName(), exception);
    }

    return responsePayload;
}

From source file:org.ajax4jsf.gwt.server.GwtFacesServlet.java

License:Open Source License

/**
 * Handle the GWT RPC call by looking up the client ID specified in the request, and passing a callback
 * via JSF to the proper JSF component.//from ww  w  .  jav a  2 s  .co  m
 */
public String processCall(String requestPayload) throws SerializationException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    String clientId;
    String responsePayload = null;
    RPCRequest rpcRequest;
    rpcRequest = RPC.decodeRequest(requestPayload);

    if (null != facesContext) {
        clientId = (String) facesContext.getExternalContext().getRequestParameterMap().get("clientId");

        if (null != clientId) {

            // Invoke event on target component
            GwtFacesCallback callback = new GwtFacesCallback(rpcRequest);
            try {
                facesContext.getViewRoot().invokeOnComponent(facesContext, clientId, callback);
            } catch (Exception e) {
                // Hmm, for now, let's make this be a server-only exception.
                throw new UnexpectedException("Error send event to component", e);
            }
            responsePayload = callback.getResponsePayload();
        } else if (null != lifecycle) {
            // Invoke event on registered listeners.
            PhaseListener[] listeners = lifecycle.getPhaseListeners();
            for (int i = 0; i < listeners.length; i++) {
                PhaseListener listener = listeners[i];
                if (listener instanceof GwtCallListener) {
                    GwtCallListener gwtListener = (GwtCallListener) listener;
                    responsePayload = gwtListener.processRequest(rpcRequest);
                }
            }
        }
    } else {
        // Non-faces environment, attempt to load stub class for hosted mode
        HttpServletRequest threadLocalRequest = getThreadLocalRequest();
        String moduleName = threadLocalRequest.getParameter(ComponentEntryPoint.GWT_MODULE_NAME_PARAMETER);
        if (null == moduleName) {
            // Hackish here, not sure this will work properly.....
            throw new SecurityException("Module name not set in request");
        }
        // Find latest package delimiter. GWT not allow to use default package - since
        // always present.
        int i = moduleName.lastIndexOf('.');
        // Module class name
        String className = "Mock" + moduleName.substring(i + 1);
        // Module package name
        String packageName = moduleName.substring(0, i) + ".server.";
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        className = packageName + className;
        Class clazz = null;
        try {
            clazz = classLoader.loadClass(className);

            // assume it's looking for GwtFacesService.
            // TODO: figure out how to tell what it's actually looking for!
            // (probably just trust the call!?!)
            GwtFacesService service = (GwtFacesService) clazz.newInstance();
            // OK so it warns about varargs redundancy here, but what does it want????
            responsePayload = RPC.invokeAndEncodeResponse(service, rpcRequest.getMethod(),
                    rpcRequest.getParameters());
        } catch (ClassNotFoundException e) {
            throw new SecurityException("Could not find requested mock class " + className);
        } catch (Exception e) {
            throw new SecurityException("Could not construct mock service class " + clazz);
        }
    }
    return responsePayload;
}