001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.fcrepo.camel.processor;
019
020import static org.apache.camel.Exchange.CONTENT_TYPE;
021import static org.apache.camel.Exchange.HTTP_METHOD;
022import static org.apache.http.entity.ContentType.parse;
023import static org.apache.jena.rdf.model.ModelFactory.createDefaultModel;
024import static org.apache.jena.riot.RDFDataMgr.read;
025import static org.apache.jena.riot.RDFLanguages.contentTypeToLang;
026import static org.fcrepo.camel.FcrepoHeaders.FCREPO_NAMED_GRAPH;
027import static org.fcrepo.camel.processor.ProcessorUtils.insertData;
028import static java.net.URLEncoder.encode;
029
030import java.io.ByteArrayOutputStream;
031import java.io.InputStream;
032import java.io.IOException;
033
034import org.apache.jena.rdf.model.Model;
035import org.apache.camel.Exchange;
036import org.apache.camel.Message;
037import org.apache.camel.Processor;
038
039/**
040 * Represents a processor for creating the sparql-update message to
041 * be passed to an external triplestore.
042 *
043 * @author Aaron Coburn
044 * @since Nov 8, 2014
045 */
046public class SparqlInsertProcessor implements Processor {
047    /**
048     * Define how the message is processed.
049     *
050     * @param exchange the current camel message exchange
051     */
052    public void process(final Exchange exchange) throws IOException {
053
054        final Message in = exchange.getIn();
055        final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
056        final String namedGraph = in.getHeader(FCREPO_NAMED_GRAPH, "", String.class);
057        final Model model = createDefaultModel();
058
059        read(model, in.getBody(InputStream.class),
060                contentTypeToLang(parse(in.getHeader(CONTENT_TYPE, String.class)).getMimeType()));
061
062        model.write(serializedGraph, "N-TRIPLE");
063
064        exchange.getIn().setBody("update=" +
065                encode(insertData(serializedGraph.toString("UTF-8"), namedGraph), "UTF-8"));
066        exchange.getIn().setHeader(HTTP_METHOD, "POST");
067        exchange.getIn().setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8");
068    }
069}