001/**
002 * Copyright 2015 DuraSpace, Inc.
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 */
016package org.fcrepo.camel.processor;
017
018import static com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel;
019import static org.fcrepo.camel.processor.ProcessorUtils.insertData;
020import static org.fcrepo.camel.processor.ProcessorUtils.langFromMimeType;
021import static java.net.URLEncoder.encode;
022
023import java.io.ByteArrayOutputStream;
024import java.io.InputStream;
025import java.io.IOException;
026
027import com.hp.hpl.jena.rdf.model.Model;
028import org.apache.camel.Exchange;
029import org.apache.camel.Message;
030import org.apache.camel.Processor;
031import org.fcrepo.camel.FcrepoHeaders;
032
033/**
034 * Represents a processor for creating the sparql-update message to
035 * be passed to an external triplestore.
036 *
037 * @author Aaron Coburn
038 * @since Nov 8, 2014
039 */
040public class SparqlInsertProcessor implements Processor {
041    /**
042     * Define how the message is processed.
043     *
044     * @param exchange the current camel message exchange
045     */
046    public void process(final Exchange exchange) throws IOException {
047
048        final Message in = exchange.getIn();
049
050        final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
051        final String subject = ProcessorUtils.getSubjectUri(in);
052        final String namedGraph = in.getHeader(FcrepoHeaders.FCREPO_NAMED_GRAPH, String.class);
053        final Model model = createDefaultModel().read(in.getBody(InputStream.class), subject,
054                langFromMimeType(in.getHeader(Exchange.CONTENT_TYPE, String.class)));
055
056        model.write(serializedGraph, "N-TRIPLE");
057
058        exchange.getIn().setBody("update=" +
059                encode(insertData(serializedGraph.toString("UTF-8"), namedGraph), "UTF-8"));
060        exchange.getIn().setHeader(Exchange.HTTP_METHOD, "POST");
061        exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8");
062    }
063}