com.conwet.xjsp.features.DefaultXJSPHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.conwet.xjsp.features.DefaultXJSPHandler.java

Source

package com.conwet.xjsp.features;

/*
 * #%L
 * eXtensible JSON Streaming Protocol
 * %%
 * Copyright (C) 2011 - 2014 CoNWeT Lab., Universidad Politcnica de Madrid
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * #L%
 */

import com.conwet.xjsp.XJSPConstants;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author sortega
 */
public class DefaultXJSPHandler implements FeatureHandler {

    private static final Logger logger = LoggerFactory.getLogger(DefaultXJSPHandler.class);

    @Override
    public void handleMessage(Message message, Session session) throws Exception {
        if ("error".equals(message.getMessageType())) {
            ErrorMessage error;
            try {
                error = toErrorMessage(message.getPayload());
            } catch (IllegalArgumentException ex) {
                logger.error("Malformed error message", ex);
                return;
            }
            doHandleError(error, session);

        } else {
            logger.warn("Unhandled xjsp message of type {}", message.getMessageType());
        }
    }

    @Override
    public String getFeatureName() {
        return XJSPConstants.XJSP_FEATURE;
    }

    public void doHandleError(ErrorMessage message, Session session) throws Exception {
        logger.warn("Unhandled error message {}", message);
    }

    private ErrorMessage toErrorMessage(Object payload) throws IllegalArgumentException {
        try {
            JSONObject object = (JSONObject) payload;
            long code = (Long) object.get("code");
            String message = (String) object.get("message");
            String id = null;
            if (object.containsKey("id")) {
                id = (String) object.get("id");
            }
            return new ImmutableErrorMessage(code, message, id);
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("Malformed error message");
        }
    }
}