Example usage for com.fasterxml.jackson.databind ObjectMapper getFactory

List of usage examples for com.fasterxml.jackson.databind ObjectMapper getFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper getFactory.

Prototype

@Override
public JsonFactory getFactory() 

Source Link

Document

Method that can be used to get hold of JsonFactory that this mapper uses if it needs to construct JsonParser s and/or JsonGenerator s.

Usage

From source file:com.irccloud.android.GCMIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

        if (extras != null && !extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                //Log.d("IRCCloud", "Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                //Log.d("IRCCloud", "Deleted messages on server: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                if (!IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0)
                        .getBoolean("gcm_registered", false)) {
                    String regId = IRCCloudApplication.getInstance().getApplicationContext()
                            .getSharedPreferences("prefs", 0).getString("gcm_reg_id", "");
                    if (regId.length() > 0) {
                        scheduleUnregisterTimer(100, regId, false);
                    }//from   w w w . j  a  va  2 s  . c  o m
                } else {
                    //Log.d("IRCCloud", "GCM K/V pairs: " + intent.getExtras().toString());
                    try {
                        String type = intent.getStringExtra("type");
                        if (type.equalsIgnoreCase("heartbeat_echo")) {
                            NetworkConnection conn = NetworkConnection.getInstance();
                            ObjectMapper mapper = new ObjectMapper();
                            JsonParser parser = mapper.getFactory()
                                    .createParser(intent.getStringExtra("seenEids"));
                            JsonNode seenEids = mapper.readTree(parser);
                            Iterator<Map.Entry<String, JsonNode>> iterator = seenEids.fields();
                            while (iterator.hasNext()) {
                                Map.Entry<String, JsonNode> entry = iterator.next();
                                JsonNode eids = entry.getValue();
                                Iterator<Map.Entry<String, JsonNode>> j = eids.fields();
                                while (j.hasNext()) {
                                    Map.Entry<String, JsonNode> eidentry = j.next();
                                    String bid = eidentry.getKey();
                                    long eid = eidentry.getValue().asLong();
                                    if (conn.ready && conn.getState() != NetworkConnection.STATE_CONNECTED)
                                        BuffersDataSource.getInstance().updateLastSeenEid(Integer.valueOf(bid),
                                                eid);
                                    Notifications.getInstance().deleteOldNotifications(Integer.valueOf(bid),
                                            eid);
                                    Notifications.getInstance().updateLastSeenEid(Integer.valueOf(bid), eid);
                                }
                            }
                            parser.close();
                        } else {
                            int cid = Integer.valueOf(intent.getStringExtra("cid"));
                            int bid = Integer.valueOf(intent.getStringExtra("bid"));
                            long eid = Long.valueOf(intent.getStringExtra("eid"));
                            if (Notifications.getInstance().getNotification(eid) != null) {
                                Log.e("IRCCloud", "GCM got EID that already exists");
                                return;
                            }
                            String from = intent.getStringExtra("from_nick");
                            String msg = intent.getStringExtra("msg");
                            if (msg != null)
                                msg = ColorFormatter
                                        .html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode(msg)))
                                        .toString();
                            String chan = intent.getStringExtra("chan");
                            if (chan == null)
                                chan = "";
                            String buffer_type = intent.getStringExtra("buffer_type");
                            String server_name = intent.getStringExtra("server_name");
                            if (server_name == null || server_name.length() == 0)
                                server_name = intent.getStringExtra("server_hostname");

                            String network = Notifications.getInstance().getNetwork(cid);
                            if (network == null)
                                Notifications.getInstance().addNetwork(cid, server_name);

                            Notifications.getInstance().addNotification(cid, bid, eid, from, msg, chan,
                                    buffer_type, type);

                            if (from == null || from.length() == 0)
                                Notifications.getInstance().showNotifications(server_name + ": " + msg);
                            else if (buffer_type.equals("channel")) {
                                if (type.equals("buffer_me_msg"))
                                    Notifications.getInstance()
                                            .showNotifications(chan + ":  " + from + " " + msg);
                                else
                                    Notifications.getInstance()
                                            .showNotifications(chan + ": <" + from + "> " + msg);
                            } else {
                                if (type.equals("buffer_me_msg"))
                                    Notifications.getInstance().showNotifications(" " + from + " " + msg);
                                else
                                    Notifications.getInstance().showNotifications(from + ": " + msg);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.w("IRCCloud", "Unable to parse GCM message");
                    }
                }
            }
        }
        GCMBroadcastReceiver.completeWakefulIntent(intent);
    }
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;//from   www.j  a  v  a  2s .co  m

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisTA);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

    } else {
        // error
        InputStream error = httpConTokenAcquisition.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:kr.ac.postech.lispconfig.LispConfigManager.java

public boolean registerDevice(String address, String port) {
    log.info("{} {}", address, port);
    InputStream is = null;/*w  ww  .  j a  va 2s .c  o m*/
    try {
        is = context.getBundleContext().getBundle().getEntry(DEVICE_CFG_JSON).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jsonParser = null;
    try {
        jsonParser = jsonFactory.createParser(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode jsonNode = null;
    try {
        jsonNode = mapper.readTree(jsonParser);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode deviceRoot = jsonNode.get(DEVICE_SUBJECT_CLASS_KEY);

    String deviceName = deviceRoot.fieldNames().next();
    JsonNode removed = ((ObjectNode) deviceRoot).remove(deviceName);

    String newDeviceName = "netconf:" + address + ":" + port;
    ((ObjectNode) deviceRoot).set(newDeviceName, removed);

    DeviceId deviceId = DeviceId.deviceId(newDeviceName);

    JsonNode subjectNode = deviceRoot.path(newDeviceName);

    Object result = cfgService.applyConfig(DEVICE_SUBJECT_CLASS_KEY, deviceId, DEVICE_CONFIG_KEY,
            subjectNode.get(DEVICE_CONFIG_KEY));
    return result != null ? true : false;
}

From source file:kr.ac.postech.lispconfig.LispConfigManager.java

public boolean configureDevice(String name, String password, String address, String port) {
    ApplicationId netConfAppId = coreService.getAppId(NETCONF_APP_NAME);

    InputStream is = null;//from w  w w .j a  va  2 s.c  o  m
    try {
        is = context.getBundleContext().getBundle().getEntry(DEVICE_CFG_JSON).openStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jsonParser = null;
    try {
        jsonParser = jsonFactory.createParser(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode jsonNode = null;
    try {
        jsonNode = mapper.readTree(jsonParser);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonNode appRoot = jsonNode.get(APP_SUBJECT_CLASS_KEY);
    appRoot = appRoot.get(NETCONF_APP_NAME);

    jsonNode = appRoot.get(APP_CONFIG_KEY).get(0);

    ((ObjectNode) jsonNode).put("name", name);
    ((ObjectNode) jsonNode).put("password", password);
    ((ObjectNode) jsonNode).put("ip", address);
    ((ObjectNode) jsonNode).put("port", port);

    log.info(appRoot.toString());

    Object result = cfgService.applyConfig(APP_SUBJECT_CLASS_KEY, netConfAppId, APP_CONFIG_KEY,
            appRoot.path(APP_CONFIG_KEY));

    return result != null ? true : false;
}

From source file:com.serendio.lingo3g.ProcessingResult.java

/**
 * Serializes this processing result as JSON to the provided <code>writer</code>.
 * Documents, clusters and other attributes can be included or skipped in the output
 * as requested./*from  w w w  .  j a  va 2s  .c  om*/
 * 
 * @param writer the writer to serialize this processing result to. The writer will
 *            <strong>not</strong> be closed.
 * @param callback JavaScript function name in which to wrap the JSON response or
 *            <code>null</code>.
 * @param indent if <code>true</code>, the output JSON will be pretty-printed
 * @param saveDocuments if <code>false</code>, documents will not be serialized.
 * @param saveClusters if <code>false</code>, clusters will not be serialized
 * @param saveOtherAttributes if <code>false</code>, other attributes will not be
 *            serialized
 * @throws IOException in case of any problems with serialization
 */
public void serializeJson(Writer writer, String callback, boolean indent, boolean saveDocuments,
        boolean saveClusters, boolean saveOtherAttributes) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    if (StringUtils.isNotBlank(callback)) {
        writer.write(callback + "(");
    }
    final Map<String, Object> attrs = prepareAttributesForSerialization(saveDocuments, saveClusters,
            saveOtherAttributes);

    mapper.writeValue(writer, attrs);
    if (StringUtils.isNotBlank(callback)) {
        writer.write(");");
    }
}

From source file:org.keycloak.testsuite.admin.client.authorization.ClaimInformationPointProviderTest.java

@Test
public void testBodyJsonClaimsInformationPoint() throws Exception {
    Map<String, List<String>> headers = new HashMap<>();

    headers.put("Content-Type", Arrays.asList("application/json"));

    ObjectMapper mapper = JsonSerialization.mapper;
    JsonParser parser = mapper.getFactory()
            .createParser("{\"a\": {\"b\": {\"c\": \"c-value\"}}, \"d\": [\"d-value1\", \"d-value2\"]}");
    TreeNode treeNode = mapper.readTree(parser);
    HttpFacade httpFacade = createHttpFacade(headers, new ByteArrayInputStream(treeNode.toString().getBytes()));

    Map<String, List<String>> claims = getClaimInformationProviderForPath("/claims-provider", "claims")
            .resolve(httpFacade);/*  w ww.j ava 2 s. c o m*/

    assertEquals("c-value", claims.get("claim-from-json-body-object").get(0));
    assertEquals("d-value2", claims.get("claim-from-json-body-array").get(0));
}

From source file:org.apache.unomi.web.ContextServlet.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    final Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }/*from   ww w  .j  av a 2 s.c  o  m*/
    // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the
    // script output.
    String profileId;

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String httpMethod = httpServletRequest.getMethod();
    //        logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest));

    // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors
    HttpUtils.setupCORSHeaders(httpServletRequest, response);

    if ("options".equals(httpMethod.toLowerCase())) {
        response.flushBuffer();
        return;
    }

    Profile profile = null;

    String cookieProfileId = null;
    Cookie[] cookies = httpServletRequest.getCookies();
    for (Cookie cookie : cookies) {
        if (profileIdCookieName.equals(cookie.getName())) {
            cookieProfileId = cookie.getValue();
        }
    }

    Session session = null;

    String personaId = request.getParameter("personaId");
    if (personaId != null) {
        PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId);
        if (personaWithSessions == null) {
            logger.error("Couldn't find persona with id=" + personaId);
            profile = null;
        } else {
            profile = personaWithSessions.getPersona();
            session = personaWithSessions.getLastSession();
        }
    }

    String sessionId = request.getParameter("sessionId");

    if (cookieProfileId == null && sessionId == null && personaId == null) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    boolean profileCreated = false;

    ContextRequest contextRequest = null;
    String scope = null;
    String stringPayload = HttpUtils.getPayload(httpServletRequest);
    if (stringPayload != null) {
        ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
        JsonFactory factory = mapper.getFactory();
        try {
            contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
        } catch (Exception e) {
            logger.error("Cannot read payload " + stringPayload, e);
            return;
        }
        scope = contextRequest.getSource().getScope();
    }

    int changes = EventService.NO_CHANGE;

    if (profile == null) {
        if (sessionId != null) {
            session = profileService.loadSession(sessionId, timestamp);
            if (session != null) {
                profileId = session.getProfileId();
                profile = profileService.load(profileId);
                profile = checkMergedProfile(response, profile, session);
            }
        }
        if (profile == null) {
            // profile not stored in session
            if (cookieProfileId == null) {
                // no profileId cookie was found, we generate a new one and create the profile in the profile service
                profile = createNewProfile(null, response, timestamp);
                profileCreated = true;
            } else {
                profile = profileService.load(cookieProfileId);
                if (profile == null) {
                    // this can happen if we have an old cookie but have reset the server,
                    // or if we merged the profiles and somehow this cookie didn't get updated.
                    profile = createNewProfile(null, response, timestamp);
                    profileCreated = true;
                    HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
                } else {
                    profile = checkMergedProfile(response, profile, session);
                }
            }
        } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId()))
                && !profile.isAnonymousProfile()) {
            // profile if stored in session but not in cookie
            HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
        }
        // associate profile with session
        if (sessionId != null && session == null) {
            session = new Session(sessionId, profile, timestamp, scope);
            changes |= EventService.SESSION_UPDATED;
            Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp);

            event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            changes |= eventService.send(event);
        }
    }

    if (profileCreated) {
        changes |= EventService.PROFILE_UPDATED;

        Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp);
        profileUpdated.setPersistent(false);
        profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
        profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);

        logger.debug("Received event {} for profile={} {} target={} timestamp={}",
                profileUpdated.getEventType(), profile.getItemId(),
                session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(),
                timestamp);
        changes |= eventService.send(profileUpdated);
    }

    ContextResponse data = new ContextResponse();
    data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId());

    if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
        profile = privacyService.getAnonymousProfile();
        session.setProfile(profile);
        changes = EventService.SESSION_UPDATED;
    }

    if (contextRequest != null) {
        changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp);
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) {
        profileService.saveSession(session);
    }

    String extension = httpServletRequest.getRequestURI()
            .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1);
    boolean noScript = "json".equals(extension);
    String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data);
    Writer responseWriter;
    if (noScript) {
        response.setCharacterEncoding("UTF-8");
        responseWriter = response.getWriter();
        response.setContentType("application/json");
        IOUtils.write(contextAsJSONString, responseWriter);
    } else {
        responseWriter = response.getWriter();
        responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ")
                .append(contextAsJSONString).append(";\n");

        // now we copy the base script source code
        InputStream baseScriptStream = getServletContext().getResourceAsStream(
                profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION);
        IOUtils.copy(baseScriptStream, responseWriter);
    }

    responseWriter.flush();
}

From source file:javasnack.snacks.json.PojoEncodeJackson.java

@Override
public void run() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {//from  w ww  .j a va2s.co m
        String jsonout = objectMapper.writeValueAsString(new EncodePojo());
        System.out.println("--- simple jackson encode ---");
        System.out.println(jsonout);
        String jsonout2 = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new EncodePojo());
        System.out.println("--- default pretty-print jackson encode ---");
        System.out.println(jsonout2);
        System.out.println("--- streaming jackson encode ---");
        JsonFactory jsonFactory = objectMapper.getFactory();
        Writer out = new OutputStreamWriter(System.out);
        JsonGenerator jg = jsonFactory.createGenerator(out);
        jg.setPrettyPrinter(new DefaultPrettyPrinter());
        jg.writeStartObject();
        jg.writeStringField("message", "success");
        jg.writeNumberField("count", 10);
        jg.writeArrayFieldStart("records");
        for (int i = 0; i < 10; i++) {
            jg.writeObject(new EncodePojo());
            Thread.sleep(100);
            jg.flush();
        }
        jg.writeEndArray();
        jg.writeEndObject();
        jg.close();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.taverna.scufl2.api.io.structure.StructureReader.java

protected void parseLine(final String nextLine) throws ReaderException {
    try (Scanner scanner = new Scanner(nextLine.trim())) {
        // In case it is the last line
        if (!scanner.hasNext())
            return;
        // allow any whitespace
        String next = scanner.next();

        if (next.isEmpty())
            return;
        switch (next) {
        case "WorkflowBundle":
            parseWorkflowBundle(scanner);
            return;
        case "MainWorkflow":
            mainWorkflow = parseName(scanner);
            return;
        case "Workflow":
            parseWorkflow(scanner);//  w  ww.  java  2  s .  c o m
            return;
        case "In":
        case "Out":
            parsePort(scanner, next);
            return;
        case "Links":
            level = Level.Links;
            processor = null;
            return;
        case "Controls":
            level = Level.Controls;
            return;
        case "MainProfile":
            mainProfile = parseName(scanner);
            return;
        case "Profile":
            parseProfile(scanner);
            return;
        case "Type":
            parseType(nextLine);
            return;
        case "ProcessorBinding":
            parseProcessorBinding(scanner);
            return;
        case "InputPortBindings":
            level = Level.InputPortBindings;
            return;
        case "OutputPortBindings":
            level = Level.OutputPortBindings;
            return;
        case "Configuration":
            parseConfiguration(scanner);
            return;
        case "Configures":
            parseConfigures(scanner);
            return;
        case "Activity":
            switch (level) {
            case Profile:
            case Activity:
                level = Level.Activity;
                activity = new Activity();
                activity.setName(parseName(scanner));
                profile.getActivities().add(activity);
                return;
            case ProcessorBinding:
                Activity boundActivity = profile.getActivities().getByName(parseName(scanner));
                processorBinding.setBoundActivity(boundActivity);
                return;
            default:
                break;
            }
            break;
        case "Processor":
            switch (level) {
            case Workflow:
            case Processor:
                level = Level.Processor;
                processor = new Processor();
                processor.setName(parseName(scanner));
                processor.setParent(workflow);
                workflow.getProcessors().add(processor);
                return;
            case ProcessorBinding:
                String[] wfProcName = parseName(scanner).split(":");
                Workflow wf = wb.getWorkflows().getByName(wfProcName[0]);
                Processor boundProcessor = wf.getProcessors().getByName(wfProcName[1]);
                processorBinding.setBoundProcessor(boundProcessor);
                return;
            default:
                break;
            }
            break;
        }

        if (next.equals("block")) {
            Matcher blockMatcher = blockPattern.matcher(nextLine);
            blockMatcher.find();
            String block = blockMatcher.group(1);
            String untilFinish = blockMatcher.group(2);

            Processor blockProc = workflow.getProcessors().getByName(block);
            Processor untilFinishedProc = workflow.getProcessors().getByName(untilFinish);
            new BlockingControlLink(blockProc, untilFinishedProc);
        }
        if (next.startsWith("'") && level.equals(Level.Links)) {
            Matcher linkMatcher = linkPattern.matcher(nextLine);
            linkMatcher.find();
            String firstLink = linkMatcher.group(1);
            String secondLink = linkMatcher.group(2);

            SenderPort senderPort;
            if (firstLink.contains(":")) {
                String[] procPort = firstLink.split(":");
                Processor proc = workflow.getProcessors().getByName(procPort[0]);
                senderPort = proc.getOutputPorts().getByName(procPort[1]);
            } else
                senderPort = workflow.getInputPorts().getByName(firstLink);

            ReceiverPort receiverPort;
            if (secondLink.contains(":")) {
                String[] procPort = secondLink.split(":");
                Processor proc = workflow.getProcessors().getByName(procPort[0]);
                receiverPort = proc.getInputPorts().getByName(procPort[1]);
            } else
                receiverPort = workflow.getOutputPorts().getByName(secondLink);

            new DataLink(workflow, senderPort, receiverPort);
            return;
        }

        if (next.startsWith("'") && (level == Level.InputPortBindings || level == Level.OutputPortBindings)) {
            Matcher linkMatcher = linkPattern.matcher(nextLine);
            linkMatcher.find();
            String firstLink = linkMatcher.group(1);
            String secondLink = linkMatcher.group(2);
            if (level == Level.InputPortBindings) {
                InputProcessorPort processorPort = processorBinding.getBoundProcessor().getInputPorts()
                        .getByName(firstLink);
                InputActivityPort activityPort = processorBinding.getBoundActivity().getInputPorts()
                        .getByName(secondLink);
                new ProcessorInputPortBinding(processorBinding, processorPort, activityPort);
            } else {
                OutputActivityPort activityPort = processorBinding.getBoundActivity().getOutputPorts()
                        .getByName(firstLink);
                OutputProcessorPort processorPort = processorBinding.getBoundProcessor().getOutputPorts()
                        .getByName(secondLink);
                new ProcessorOutputPortBinding(processorBinding, activityPort, processorPort);
            }
            return;
        }
        if (level == Level.JSON) {
            /*
             * A silly reader that feeds (no more than) a single line at a
             * time from our parent scanner, starting with the current line
             */
            Reader reader = new Reader() {
                char[] line = nextLine.toCharArray();
                int pos = 0;

                @Override
                public int read(char[] cbuf, int off, int len) throws IOException {
                    if (pos >= line.length) {
                        // Need to read next line to fill buffer
                        if (!StructureReader.this.scanner.hasNextLine())
                            return -1;
                        String newLine = StructureReader.this.scanner.nextLine();
                        pos = 0;
                        line = newLine.toCharArray();
                        // System.out.println("Read new line: " + newLine);
                    }
                    int length = Math.min(len, line.length - pos);
                    if (length <= 0)
                        return 0;
                    arraycopy(line, pos, cbuf, off, length);
                    pos += length;
                    return length;
                }

                @Override
                public void close() throws IOException {
                    line = null;
                }
            };

            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonParser parser = mapper.getFactory().createParser(reader);
                JsonNode jsonNode = parser.readValueAs(JsonNode.class);
                // System.out.println("Parsed " + jsonNode);
                configuration.setJson(jsonNode);
            } catch (IOException e) {
                throw new ReaderException("Can't parse json", e);
            }
            level = Level.Configuration;
            return;
        }
    }
}