de.elomagic.carafile.server.bl.RegistryClientBean.java Source code

Java tutorial

Introduction

Here is the source code for de.elomagic.carafile.server.bl.RegistryClientBean.java

Source

/*
 * Copyright 2014 Carsten Rambow, elomagic.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.elomagic.carafile.server.bl;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.log4j.Logger;

import de.elomagic.carafile.client.CaraFileClient;
import de.elomagic.carafile.server.Constants;
import de.elomagic.carafile.share.JsonUtil;
import de.elomagic.carafile.share.MetaData;
import de.elomagic.carafile.share.PeerData;

/**
 * REST client implementation of registry services.
 *
 * @author carsten.rambow
 */
public class RegistryClientBean {
    private static final Logger LOG = Logger.getLogger(RegistryClientBean.class);
    private static final String REGISTRY = "registry";
    private final CaraFileClient caraFileClient = new CaraFileClient();

    @Resource(lookup = Constants.JNDI_REGISTRY_URI)
    private String registryURI;
    @Resource(lookup = Constants.JNDI_OWN_PEER_URI)
    private String ownPeerURI;

    @Inject
    private RegistryBean registryBean;

    /**
     *
     * @param metaData
     * @throws IOException Thrown when unable to call REST service at the registry
     * @throws java.net.URISyntaxException
     */
    public void registerMetaData(final MetaData metaData) throws IOException, URISyntaxException {
        LOG.debug("Registering meta data at registry: " + metaData);

        if (ownPeerURI.equals(registryURI)) {
            registryBean.registerFile(metaData);
        } else {
            URI restURI = UriBuilder.fromUri(registryURI).path(REGISTRY).path("register").build();
            Request.Post(restURI).addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
                    .bodyStream(JsonUtil.write(metaData, Charset.forName("utf-8")), ContentType.APPLICATION_JSON)
                    .execute();
        }
    }

    /**
     * Register a chunk of a file at the registry.
     *
     * @param chunkHash SHA-1 hash of the chunk
     * @throws IOException Thrown when unable to call REST service at the registry
     */
    public void registerChunk(final String chunkHash) throws IOException {
        LOG.debug("Registering chunk at registry");

        URI own = UriBuilder.fromUri(ownPeerURI).build();

        if (ownPeerURI.equals(registryURI)) {
            registryBean.registerChunk(chunkHash, own);
        } else {
            URI restURI = UriBuilder.fromUri(registryURI).path(REGISTRY).path("registerChunk").path(chunkHash)
                    .path(URLEncoder.encode(ownPeerURI, "utf-8")).build();

            Request.Post(restURI).execute();
        }
    }

    /**
     * Returns a set all known file identifier of the registry.
     *
     * @return A set but never null
     * @throws IOException Thrown when unable to call REST service at the registry
     */
    public Set<String> getFileIdSet() throws IOException {
        LOG.debug("Getting set of file ID's from registry");

        Set<String> fileIdSet;

        if (ownPeerURI.equals(registryURI)) {
            fileIdSet = registryBean.getFileIdSet();
        } else {
            URI restURI = UriBuilder.fromUri(registryURI).path(REGISTRY).path("listFiles")
                    .path(URLEncoder.encode(ownPeerURI, "utf-8")).build();

            HttpResponse response = Request.Get(restURI).addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
                    .execute().returnResponse();

            Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();
            fileIdSet = JsonUtil.read(new InputStreamReader(response.getEntity().getContent(), charset),
                    HashSet.class);
            fileIdSet = fileIdSet == null ? new HashSet<>() : fileIdSet;
        }

        LOG.debug("Registry response a set of " + fileIdSet.size() + " file ID('s).");

        return fileIdSet;
    }

    /**
     * Try to find a file at the registry.
     *
     * @param fileId identifier of the file
     * @return {@link MetaData} of the file. Null when doesn't exists at the registry
     * @throws IOException Thrown when unable to call REST service at the registry
     */
    public MetaData findMetaData(final String fileId) throws IOException {
        LOG.debug("Finding meta data " + fileId + " at registry");
        MetaData md;
        if (ownPeerURI.equals(registryURI)) {
            md = registryBean.findFile(fileId);
        } else {
            md = caraFileClient.setRegistryURI(UriBuilder.fromUri(registryURI).build()).findFile(fileId);
        }

        LOG.debug("Registry response meta data: " + md);
        return md;
    }

    /**
     * Register this peer at the registry.
     * <p/>
     * To registry a peer is very important. Otherwise no other peers will find you.
     *
     * @throws IOException Thrown when unable to call REST service at the registry
     * @throws java.net.URISyntaxException When unable to read URI
     */
    public void registerPeer() throws IOException, URISyntaxException {
        LOG.debug("Registering this peer " + ownPeerURI + " at registry " + registryURI);

        PeerData peerData = new PeerData();
        peerData.setPeerURI(UriBuilder.fromUri(ownPeerURI).build());

        if (ownPeerURI.equalsIgnoreCase(registryURI)) {
            registryBean.registerPeer(peerData);
        } else {
            URI registry = UriBuilder.fromUri(registryURI).path(REGISTRY).path("registerPeer").build();
            HttpResponse response = Request.Post(registry)
                    .bodyString(JsonUtil.write(peerData), ContentType.APPLICATION_JSON).execute().returnResponse();

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                LOG.debug("Peer registration successful");
            } else {
                LOG.error("Unable to registry peer at registry. Status Code "
                        + response.getStatusLine().getStatusCode() + ";Phrase="
                        + response.getStatusLine().getReasonPhrase());
            }
        }
    }
}