001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * matic 018 */ 019package org.nuxeo.ecm.automation.client.jaxrs.spi.marshallers; 020 021import java.io.IOException; 022 023import org.nuxeo.ecm.automation.client.Constants; 024import org.nuxeo.ecm.automation.client.RemoteException; 025import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshaller; 026import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshalling; 027 028import com.fasterxml.jackson.core.JsonGenerator; 029import com.fasterxml.jackson.core.JsonParser; 030import com.fasterxml.jackson.core.JsonToken; 031 032/** 033 * @author matic 034 */ 035public class ExceptionMarshaller implements JsonMarshaller<RemoteException> { 036 037 @Override 038 public String getType() { 039 return "exception"; 040 } 041 042 @Override 043 public Class<RemoteException> getJavaType() { 044 return RemoteException.class; 045 } 046 047 public static RemoteException readException(String content) throws IOException { 048 try (JsonParser jp = JsonMarshalling.getFactory().createParser(content)) { 049 jp.nextToken(); // skip { 050 return _read(jp); 051 } 052 } 053 054 @Override 055 public RemoteException read(JsonParser jp) throws IOException { 056 return _read(jp); 057 } 058 059 public static RemoteException _read(JsonParser jp) throws IOException { 060 int status = 0; 061 String type = null, message = null; 062 Throwable cause = null; 063 JsonToken tok = jp.nextToken(); 064 while (tok != null && tok != JsonToken.END_OBJECT) { 065 String key = jp.getCurrentName(); 066 tok = jp.nextToken(); 067 if ("status".equals(key)) { 068 if (tok == JsonToken.VALUE_NUMBER_INT) { 069 status = jp.getIntValue(); 070 } else { 071 status = Integer.parseInt(jp.getText()); 072 } 073 } else if (Constants.KEY_ENTITY_TYPE.equals(key) || "type".equals(key)) { 074 type = jp.getText(); 075 } else if ("message".equals(key)) { 076 message = jp.getText(); 077 } else if ("exception".equals(key) || "cause".equals(key)) { 078 cause = jp.readValueAs(Throwable.class); 079 } 080 tok = jp.nextToken(); 081 } 082 if (tok == null) { 083 throw new IllegalArgumentException("Unexpected end of stream."); 084 } 085 return new RemoteException(status, type, message, cause); 086 } 087 088 @Override 089 public void write(JsonGenerator jg, Object value) { 090 throw new UnsupportedOperationException(); 091 } 092 093}