Search in sources :

Example 11 with JSONException

use of org.codehaus.jettison.json.JSONException in project apex-core by apache.

the class WebServicesVersionConversionTest method testVersioning.

@Test
public void testVersioning() throws Exception {
    WebServicesClient wsClient = new WebServicesClient();
    Client client = wsClient.getClient();
    WebResource ws = client.resource("http://localhost:" + port).path("/new_path");
    WebServicesVersionConversion.Converter versionConverter = new WebServicesVersionConversion.Converter() {

        @Override
        public String convertCommandPath(String path) {
            if (path.equals("/new_path")) {
                return "/old_path";
            }
            return path;
        }

        @Override
        public String convertResponse(String path, String response) {
            if (path.equals("/new_path")) {
                try {
                    JSONObject json = new JSONObject(response);
                    json.put("new_key", json.get("old_key"));
                    json.remove("old_key");
                    return json.toString();
                } catch (JSONException ex) {
                    throw new RuntimeException(ex);
                }
            }
            return response;
        }
    };
    VersionConversionFilter versionConversionFilter = new VersionConversionFilter(versionConverter);
    client.addFilter(versionConversionFilter);
    JSONObject result = new JSONObject(ws.get(String.class));
    Assert.assertEquals(result.getString("url"), "/old_path");
    Assert.assertEquals(result.getString("new_key"), "value");
    Assert.assertEquals(result.getString("other_key"), "other_value");
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) WebResource(com.sun.jersey.api.client.WebResource) JSONException(org.codehaus.jettison.json.JSONException) WebServicesClient(com.datatorrent.stram.util.WebServicesClient) WebServicesClient(com.datatorrent.stram.util.WebServicesClient) Client(com.sun.jersey.api.client.Client) VersionConversionFilter(com.datatorrent.stram.client.WebServicesVersionConversion.VersionConversionFilter) Test(org.junit.Test)

Example 12 with JSONException

use of org.codehaus.jettison.json.JSONException in project apex-core by apache.

the class OperatorDiscoverer method getClassProperties.

private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {
        for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
                    // skip getDeclaringClass
                    continue;
                } else if ("class".equals(pd.getName())) {
                    // skip getClass
                    continue;
                }
            } else {
                // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7
                if ("up".equals(pd.getName()) && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
                    continue;
                }
            }
            //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());
            Class<?> propertyType = pd.getPropertyType();
            if (propertyType != null) {
                JSONObject propertyObj = new JSONObject();
                propertyObj.put("name", pd.getName());
                propertyObj.put("canGet", readMethod != null);
                propertyObj.put("canSet", pd.getWriteMethod() != null);
                if (readMethod != null) {
                    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
                        OperatorClassInfo oci = classInfo.get(c.getName());
                        if (oci != null) {
                            MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                            if (getMethodInfo != null) {
                                addTagsToProperties(getMethodInfo, propertyObj);
                                break;
                            }
                        }
                    }
                    // type can be a type symbol or parameterized type
                    td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
                } else {
                    if (pd.getWriteMethod() != null) {
                        td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj);
                    }
                }
                //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType
                // .getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
                //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
                //}
                arr.put(propertyObj);
            }
        }
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
    return arr;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) Method(java.lang.reflect.Method) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 13 with JSONException

use of org.codehaus.jettison.json.JSONException in project apex-core by apache.

the class OperatorDiscoverer method describeOperator.

public JSONObject describeOperator(String clazz) throws Exception {
    TypeGraphVertex tgv = typeGraph.getTypeGraphVertex(clazz);
    if (tgv.isInstantiable()) {
        JSONObject response = new JSONObject();
        JSONArray inputPorts = new JSONArray();
        JSONArray outputPorts = new JSONArray();
        // Get properties from ASM
        JSONObject operatorDescriptor = describeClassByASM(clazz);
        JSONArray properties = operatorDescriptor.getJSONArray("properties");
        properties = enrichProperties(clazz, properties);
        JSONArray portTypeInfo = operatorDescriptor.getJSONArray("portTypeInfo");
        List<CompactFieldNode> inputPortfields = typeGraph.getAllInputPorts(clazz);
        List<CompactFieldNode> outputPortfields = typeGraph.getAllOutputPorts(clazz);
        try {
            for (CompactFieldNode field : inputPortfields) {
                JSONObject inputPort = setFieldAttributes(clazz, field);
                if (!inputPort.has("optional")) {
                    // input port that is not annotated is default to be not optional
                    inputPort.put("optional", false);
                }
                if (!inputPort.has(SCHEMA_REQUIRED_KEY)) {
                    inputPort.put(SCHEMA_REQUIRED_KEY, false);
                }
                inputPorts.put(inputPort);
            }
            for (CompactFieldNode field : outputPortfields) {
                JSONObject outputPort = setFieldAttributes(clazz, field);
                if (!outputPort.has("optional")) {
                    // output port that is not annotated is default to be optional
                    outputPort.put("optional", true);
                }
                if (!outputPort.has("error")) {
                    outputPort.put("error", false);
                }
                if (!outputPort.has(SCHEMA_REQUIRED_KEY)) {
                    outputPort.put(SCHEMA_REQUIRED_KEY, false);
                }
                outputPorts.put(outputPort);
            }
            response.put("name", clazz);
            response.put("properties", properties);
            response.put(PORT_TYPE_INFO_KEY, portTypeInfo);
            response.put("inputPorts", inputPorts);
            response.put("outputPorts", outputPorts);
            String type = null;
            Class<?> genericOperator = classLoader.loadClass(clazz);
            if (Module.class.isAssignableFrom(genericOperator)) {
                type = GenericOperatorType.MODULE.getType();
            } else if (Operator.class.isAssignableFrom(genericOperator)) {
                type = GenericOperatorType.OPERATOR.getType();
            }
            if (type != null) {
                response.put("type", type);
            }
            OperatorClassInfo oci = classInfo.get(clazz);
            if (oci != null) {
                if (oci.comment != null) {
                    String[] descriptions;
                    // first look for a <p> tag
                    String keptPrefix = "<p>";
                    descriptions = oci.comment.split("<p>", 2);
                    if (descriptions.length == 0) {
                        keptPrefix = "";
                        // if no <p> tag, then look for a blank line
                        descriptions = oci.comment.split("\n\n", 2);
                    }
                    if (descriptions.length > 0) {
                        response.put("shortDesc", descriptions[0]);
                    }
                    if (descriptions.length > 1) {
                        response.put("longDesc", keptPrefix + descriptions[1]);
                    }
                }
                response.put("category", oci.tags.get("@category"));
                String displayName = oci.tags.get("@displayName");
                if (displayName == null) {
                    displayName = decamelizeClassName(ClassUtils.getShortClassName(clazz));
                }
                response.put("displayName", displayName);
                String tags = oci.tags.get("@tags");
                if (tags != null) {
                    JSONArray tagArray = new JSONArray();
                    for (String tag : StringUtils.split(tags, ',')) {
                        tagArray.put(tag.trim().toLowerCase());
                    }
                    response.put("tags", tagArray);
                }
                String doclink = oci.tags.get("@doclink");
                if (doclink != null) {
                    response.put("doclink", doclink + "?" + getDocName(clazz));
                } else if (clazz.startsWith("com.datatorrent.lib.") || clazz.startsWith("com.datatorrent.contrib.")) {
                    response.put("doclink", DT_OPERATOR_DOCLINK_PREFIX + "?" + getDocName(clazz));
                }
            }
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
        return response;
    } else {
        throw new UnsupportedOperationException();
    }
}
Also used : Operator(com.datatorrent.api.Operator) GenericOperator(com.datatorrent.api.DAG.GenericOperator) TypeGraphVertex(com.datatorrent.stram.webapp.TypeGraph.TypeGraphVertex) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) CompactFieldNode(com.datatorrent.stram.webapp.asm.CompactFieldNode) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 14 with JSONException

use of org.codehaus.jettison.json.JSONException in project apex-core by apache.

the class PubSubWebSocketClient method openConnectionAsync.

public void openConnectionAsync() throws IOException {
    throwable.set(null);
    if (loginUrl != null && userName != null && password != null) {
        // get the session key first before attempting web socket
        JSONObject json = new JSONObject();
        try {
            json.put("userName", userName);
            json.put("password", password);
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
        client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()).execute(new AsyncCompletionHandler<Response>() {

            @Override
            public Response onCompleted(Response response) throws Exception {
                List<Cookie> cookies = response.getCookies();
                BoundRequestBuilder brb = client.prepareGet(uri.toString());
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        brb.addCookie(cookie);
                    }
                }
                connection = brb.execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()).get();
                return response;
            }
        });
    } else {
        final PubSubWebSocket webSocket = new PubSubWebSocket() {

            @Override
            public void onOpen(WebSocket ws) {
                connection = ws;
                super.onOpen(ws);
            }
        };
        client.prepareGet(uri.toString()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(webSocket).build());
    }
}
Also used : Cookie(org.apache.apex.shaded.ning19.com.ning.http.client.cookie.Cookie) BoundRequestBuilder(org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) JSONException(org.codehaus.jettison.json.JSONException) WebSocketUpgradeHandler(org.apache.apex.shaded.ning19.com.ning.http.client.ws.WebSocketUpgradeHandler) TimeoutException(java.util.concurrent.TimeoutException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) JsonParseException(org.codehaus.jackson.JsonParseException) JSONException(org.codehaus.jettison.json.JSONException) WebSocket(org.apache.apex.shaded.ning19.com.ning.http.client.ws.WebSocket) Response(org.apache.apex.shaded.ning19.com.ning.http.client.Response) BoundRequestBuilder(org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) JSONObject(org.codehaus.jettison.json.JSONObject) List(java.util.List)

Example 15 with JSONException

use of org.codehaus.jettison.json.JSONException in project apex-core by apache.

the class StramWebServices method getOperatorClasses.

@GET
@Path(PATH_OPERATOR_CLASSES)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getOperatorClasses(@QueryParam("q") String searchTerm, @QueryParam("parent") String parent) {
    init();
    JSONObject result = new JSONObject();
    JSONArray classNames = new JSONArray();
    if (parent != null) {
        if (parent.equals("chart")) {
            parent = "com.datatorrent.lib.chart.ChartOperator";
        } else if (parent.equals("filter")) {
            parent = "com.datatorrent.common.util.SimpleFilterOperator";
        }
    }
    try {
        Set<String> operatorClasses = operatorDiscoverer.getOperatorClasses(parent, searchTerm);
        for (String clazz : operatorClasses) {
            JSONObject j = new JSONObject();
            j.put("name", clazz);
            classNames.put(j);
        }
        result.put("operatorClasses", classNames);
    } catch (ClassNotFoundException ex) {
        throw new NotFoundException();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
    return result;
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) NotFoundException(org.apache.hadoop.yarn.webapp.NotFoundException) JSONException(org.codehaus.jettison.json.JSONException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

JSONException (org.codehaus.jettison.json.JSONException)281 JSONObject (org.codehaus.jettison.json.JSONObject)256 Response (javax.ws.rs.core.Response)183 Builder (javax.ws.rs.client.Invocation.Builder)179 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)179 Test (org.testng.annotations.Test)174 BaseTest (org.xdi.oxauth.BaseTest)174 Parameters (org.testng.annotations.Parameters)171 RegisterRequest (org.xdi.oxauth.client.RegisterRequest)78 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)68 JSONArray (org.codehaus.jettison.json.JSONArray)44 RegisterResponse (org.xdi.oxauth.client.RegisterResponse)43 URISyntaxException (java.net.URISyntaxException)35 TokenRequest (org.xdi.oxauth.client.TokenRequest)35 ResponseType (org.xdi.oxauth.model.common.ResponseType)35 WebApplicationException (javax.ws.rs.WebApplicationException)18 IOException (java.io.IOException)17 OxAuthCryptoProvider (org.xdi.oxauth.model.crypto.OxAuthCryptoProvider)17 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14