Created
July 17, 2016 14:17
-
-
Save gejiaheng/eb24dcd66de187de1bbf15ed5553e9fc to your computer and use it in GitHub Desktop.
Parser for Dribbble paging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import retrofit2.Response; | |
/** | |
* Page link class to be used to determine the links to other pages of request | |
* responses encoded in the current response. These will be present if the | |
* result set size exceeds the per page limit. | |
* | |
* @author gejiaheng | |
* @since 04-08-2016 | |
*/ | |
public class PageLinks { | |
private static final String DELIM_LINKS = ","; | |
private static final String DELIM_LINK_PARAM = ";"; | |
private static final String HEAD_LINK = "Link"; | |
private static final String META_REL = "rel"; | |
private static final String META_NEXT = "next"; | |
private static final String META_PREV = "prev"; | |
private String next; | |
private String prev; | |
/** | |
* Parse links from executed method | |
* | |
* @param response | |
*/ | |
public PageLinks(Response response) { | |
String linkHeader = response.headers().get(HEAD_LINK); | |
if (linkHeader != null) { | |
String[] links = linkHeader.split(DELIM_LINKS); | |
for (String link : links) { | |
String[] segments = link.split(DELIM_LINK_PARAM); | |
if (segments.length < 2) | |
continue; | |
String linkPart = segments[0].trim(); | |
if (!linkPart.startsWith("<") || !linkPart.endsWith(">")) | |
continue; | |
linkPart = linkPart.substring(1, linkPart.length() - 1); | |
for (int i = 1; i < segments.length; i++) { | |
String[] rel = segments[i].trim().split("="); | |
if (rel.length < 2 || !META_REL.equals(rel[0])) | |
continue; | |
String relValue = rel[1]; | |
if (relValue.startsWith("\"") && relValue.endsWith("\"")) | |
relValue = relValue.substring(1, relValue.length() - 1); | |
if (META_NEXT.equals(relValue)) | |
next = linkPart; | |
else if (META_PREV.equals(relValue)) | |
prev = linkPart; | |
} | |
} | |
} | |
} | |
/** | |
* @return next | |
*/ | |
public String getNext() { | |
return next; | |
} | |
/** | |
* @return prev | |
*/ | |
public String getPrev() { | |
return prev; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment