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.client; 019 020import java.net.URI; 021 022/** 023 * A class representing the value of an HTTP Link header 024 * 025 * @author Aaron Coburn 026 */ 027public class FcrepoLink { 028 029 private static final String LINK_DELIM = ";"; 030 031 private static final String META_REL = "rel"; 032 033 private URI uri; 034 035 private String rel; 036 037 /** 038 * Create a representation of a Link header. 039 * 040 * @param link the value for a Link header 041 */ 042 public FcrepoLink(final String link) { 043 parse(link); 044 } 045 046 /** 047 * Retrieve the URI of the link 048 * 049 * @return the URI portion of a Link header 050 */ 051 public URI getUri() { 052 return uri; 053 } 054 055 /** 056 * Retrieve the REL portion of the link 057 * 058 * @return the "rel" portion of a Link header 059 */ 060 public String getRel() { 061 return rel; 062 } 063 064 /** 065 * Parse the value of a link header 066 */ 067 private void parse(final String link) { 068 if (link != null) { 069 final String[] segments = link.split(LINK_DELIM); 070 if (segments.length > 1) { 071 uri = getLinkPart(segments[0]); 072 if (uri != null) { 073 // inspect the remaining segments until a rel is found 074 for (int i = 1; i < segments.length && rel == null; i++) { 075 rel = getRelPart(segments[i]); 076 } 077 } 078 } 079 } 080 } 081 082 /** 083 * Extract the rel="..." part of the link header 084 */ 085 private static String getRelPart(final String relPart) { 086 final String[] segments = relPart.trim().split("="); 087 if (segments.length != 2 || !META_REL.equals(segments[0])) { 088 return null; 089 } 090 final String relValue = segments[1]; 091 if (relValue.startsWith("\"") && relValue.endsWith("\"")) { 092 return relValue.substring(1, relValue.length() - 1); 093 } else { 094 return relValue; 095 } 096 } 097 098 /** 099 * Extract the URI part of the link header 100 */ 101 private static URI getLinkPart(final String uriPart) { 102 final String linkPart = uriPart.trim(); 103 if (!linkPart.startsWith("<") || !linkPart.endsWith(">")) { 104 return null; 105 } else { 106 return URI.create(linkPart.substring(1, linkPart.length() - 1)); 107 } 108 } 109}