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