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