proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MyreadingmangaRipper.java
|
MyreadingmangaRipper
|
getURLsFromPage
|
class MyreadingmangaRipper extends AbstractHTMLRipper {
public MyreadingmangaRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "myreadingmanga";
}
@Override
public String getDomain() {
return "myreadingmanga.info";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://myreadingmanga.info/([a-zA-Z_\\-0-9]+)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected myreadingmanga.info URL format: "
+ "myreadingmanga.info/title - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select("div * img[data-lazy-src]")) {
String imageSource = el.attr("data-lazy-src");
result.add(imageSource);
}
return result;
| 356
| 73
| 429
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/NatalieMuRipper.java
|
NatalieMuRipper
|
getURLsFromPage
|
class NatalieMuRipper extends AbstractHTMLRipper {
public int news_id = 0;
public NatalieMuRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
String host = this.url.getHost();
host = host.substring(0, host.lastIndexOf('.'));
if (host.contains(".")) {
// Host has subdomain (www)
host = host.substring(host.lastIndexOf('.') + 1);
}
String board = this.url.toExternalForm().split("/")[3];
return host + "_" + board;
}
@Override
public boolean canRip(URL url) {
//urls like:
// http://cdn2.natalie.mu/music/gallery/show/news_id/xxxxxx/image_id/xxxxxx
// http://cdn2.natalie.mu/music/news/140411
return url.toExternalForm().contains("natalie.mu") // Most chans
&& (url.toExternalForm().contains("/news_id/")
|| url.toExternalForm().contains("/news/")); // 4chan, archive.moe
}
/**
* For example the achrives are all known. (Check 4chan-x)
* Should be based on the software the specific chan uses.
* FoolFuuka uses the same (url) layout as 4chan
* */
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p; Matcher m;
String u = url.toExternalForm();
if (u.contains("/news_id/")) {
p = Pattern.compile("/news_id/([0-9]+)/");
m = p.matcher(u);
if (m.find()) {
return m.group(1);
}
} else if (u.contains("/news/")) {
p = Pattern.compile("/news/([0-9]+)/?");
m = p.matcher(u);
if (m.find()) {
return m.group(1);
}
}
throw new MalformedURLException(
"Expected natalie.mu URL formats: "
+ "http://natalie.mu/music/news/xxxxxx or http://natalie.mu/music/gallery/show/news_id/xxxxxx/image_id/yyyyyy"
+ " Got: " + u);
}
@Override
public String getDomain() {
return this.url.getHost();
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(this.url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toString(), null);
}
}
|
List<String> imageURLs = new ArrayList<>();
Pattern p; Matcher m;
//select all album thumbnails
for (Element span : page.select(".NA_articleGallery span")) {
if (!span.hasAttr("style")) {
continue;
}
String style = span.attr("style").trim();
p = Pattern.compile("background-image: url\\((.*list_thumb_inbox.*)\\);", Pattern.CASE_INSENSITIVE);
m = p.matcher(style);
if (m.find()) {
String imgUrl = m.group(1);
if (imgUrl.startsWith("//")) {
imgUrl = "http:" + imgUrl;
}
if (imgUrl.startsWith("/")) {
imgUrl = "http://" + this.url.getHost() + imgUrl;
}
//convert thumbnail url into fullsize url
imgUrl = imgUrl.replace("list_thumb_inbox","xlarge");
// Don't download the same URL twice
if (imageURLs.contains(imgUrl)) {
LOGGER.debug("Already attempted: " + imgUrl);
continue;
}
imageURLs.add(imgUrl);
if (isThisATest()) {
break;
}
}
if (isStopped()) {
break;
}
}
return imageURLs;
| 793
| 362
| 1,155
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/NewgroundsRipper.java
|
NewgroundsRipper
|
getURLsFromPage
|
class NewgroundsRipper extends AbstractHTMLRipper {
private String username = ""; // Name of artist
// Extensions supported by Newgrounds
private List<String> ALLOWED_EXTENSIONS = Arrays.asList("png", "gif", "jpeg", "jpg");
// Images are pulled 60 at a time, a new page request is needed when count == 60
private int pageNumber = 1;
private int count = 0;
public NewgroundsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "newgrounds";
}
@Override
protected String getDomain() {
return "newgrounds.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(.+).newgrounds.com/?.*");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
this.username = m.group(1);
return m.group(1);
}
throw new MalformedURLException("Expected newgrounds.com URL format: " +
"username.newgrounds.com/art - got " + url + " instead");
}
@Override
protected Document getFirstPage() throws IOException {
return Http.url("https://" + this.username + ".newgrounds.com/art").get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
if(this.count < 60) {
throw new IOException("No more pages");
}
this.count = 0; // New page found so reset count
return Http.url("https://" + this.username + ".newgrounds.com/art/page/" + this.pageNumber)
.header("X-Requested-With", "XMLHttpRequest").get(); // Send header to imitate scrolling
}
@Override
protected List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
@Override
protected void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> imageURLs = new ArrayList<>();
String documentHTMLString = page.toString().replaceAll(""", "");
String findStr = "newgrounds.com\\/art\\/view\\/" + this.username;
int lastIndex = 0;
// Index where findStr is found; each occasion contains the link to an image
ArrayList<Integer> indices = new ArrayList<>();
while(lastIndex != -1){
lastIndex = documentHTMLString.indexOf(findStr, lastIndex);
if(lastIndex != -1){
this.count ++;
lastIndex += findStr.length();
indices.add(lastIndex);
}
}
// Retrieve direct URL for image
for(int i = 0; i < indices.size(); i++){
String imageUrl = "https://art.ngfiles.com/images/";
String inLink = "https://www.newgrounds.com/art/view/" + this.username + "/";
String s;
if(i == indices.size() - 1){
s = documentHTMLString.substring(indices.get(i) + 2);
} else{
s = documentHTMLString.substring(indices.get(i) + 2, indices.get(i + 1));
}
s = s.replaceAll("\n", "").replaceAll("\t", "")
.replaceAll("\\\\", "");
Pattern p = Pattern.compile("(.*?)\" class.*/thumbnails/(.*?)/(.*?)\\.");
Matcher m = p.matcher(s);
if (m.lookingAt()) {
String testURL = m.group(3) + "_" + this.username + "_" + m.group(1);
// Open new document to get full sized image
try {
Document imagePage = Http.url(inLink + m.group(1)).get();
for(String extensions: this.ALLOWED_EXTENSIONS){
if(imagePage.toString().contains(testURL + "." + extensions)){
imageUrl += m.group(2) + "/" + m.group(3) + "_" + this.username + "_" + m.group(1) + "." + extensions;
imageURLs.add(imageUrl);
break;
}
}
} catch (IOException e) {
LOGGER.error("IO Error on trying to check extension: " + inLink + m.group(1));
}
}
}
this.pageNumber += 1;
return imageURLs;
| 574
| 644
| 1,218
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/NfsfwRipper.java
|
NfsfwRipper
|
getImagePageURLs
|
class NfsfwRipper extends AbstractHTMLRipper {
private static final String DOMAIN = "nfsfw.com",
HOST = "nfsfw";
private int index = 0;
private String currentDir = "";
private List<String> subalbumURLs = new ArrayList<>();
private Pattern subalbumURLPattern = Pattern.compile(
"https?://[wm.]*nfsfw.com/gallery/v/[^/]+/(.+)$"
);
// cached first page
private Document fstPage;
// threads pool for downloading images from image pages
private DownloadThreadPool nfsfwThreadPool;
public NfsfwRipper(URL url) throws IOException {
super(url);
nfsfwThreadPool = new DownloadThreadPool("NFSFW");
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
public String getHost() {
return HOST;
}
@Override
protected Document getFirstPage() throws IOException {
// cache the first page
this.fstPage = Http.url(url).get();
return fstPage;
}
@Override
public Document getNextPage(Document page) throws IOException {
String nextURL = null;
Elements a = page.select("a.next");
if (!a.isEmpty()){
// Get next page of current album
nextURL = "http://nfsfw.com" + a.first().attr("href");
} else if (!subalbumURLs.isEmpty()){
// Get next sub-album
nextURL = subalbumURLs.remove(0);
LOGGER.info("Detected subalbum URL at:" + nextURL);
Matcher m = subalbumURLPattern.matcher(nextURL);
if (m.matches()) {
// Set the new save directory and save images with a new index
this.currentDir = m.group(1);
this.index = 0;
} else {
LOGGER.error("Invalid sub-album URL: " + nextURL);
nextURL = null;
}
}
// Wait
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOGGER.error("Interrupted while waiting to load next page", e);
}
if (nextURL == null){
throw new IOException("No more pages");
} else {
return Http.url(nextURL).get();
}
}
@Override
protected List<String> getURLsFromPage(Document page) {
List<String> imagePageURLs = getImagePageURLs(page);
// Check if any sub-albums are present on this page
List<String> subalbumURLs = getSubalbumURLs(page);
this.subalbumURLs.addAll(subalbumURLs);
return imagePageURLs;
}
@Override
protected void downloadURL(URL url, int index) {
// if we are now downloading a sub-album, all images in it
// should be indexed starting from 0
if (!this.currentDir.equals("")){
index = ++this.index;
}
NfsfwImageThread t = new NfsfwImageThread(url, currentDir, index);
nfsfwThreadPool.addThread(t);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
// always start on the first page of an album
// (strip the options after the '?')
String u = url.toExternalForm();
if (u.contains("?")) {
u = u.substring(0, u.indexOf("?"));
return new URL(u);
} else {
return url;
}
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p; Matcher m;
p = Pattern.compile("https?://[wm.]*nfsfw.com/gallery/v/(.*)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
String group = m.group(1);
if (group.endsWith("/")) {
group = group.substring(0, group.length() - 1);
}
return group.replaceAll("/", "__");
}
throw new MalformedURLException(
"Expected nfsfw.com gallery format: "
+ "nfsfw.com/v/albumname"
+ " Got: " + url);
}
@Override
public DownloadThreadPool getThreadPool() {
return nfsfwThreadPool;
}
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
List<String> imageURLs = getImagePageURLs(fstPage);
List<String> subalbumURLs = getSubalbumURLs(fstPage);
return imageURLs.isEmpty() && !subalbumURLs.isEmpty();
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
return getSubalbumURLs(doc);
}
// helper methods
private List<String> getImagePageURLs(Document page){<FILL_FUNCTION_BODY>}
private List<String> getSubalbumURLs(Document page){
// Check if sub-albums are present on this page
List<String> subalbumURLs = new ArrayList<>();
for (Element suba : page.select("td.IMG > a")) {
String subURL = "http://nfsfw.com" + suba.attr("href");
subalbumURLs.add(subURL);
}
return subalbumURLs;
}
/**
* Helper class to find and download images found on "image" pages
*/
private class NfsfwImageThread extends Thread {
private URL url;
private String subdir;
private int index;
NfsfwImageThread(URL url, String subdir, int index) {
super();
this.url = url;
this.subdir = subdir;
this.index = index;
}
@Override
public void run() {
try {
Document doc = Http.url(this.url)
.referrer(this.url)
.get();
Elements images = doc.select(".gbBlock img");
if (images.isEmpty()) {
LOGGER.error("Failed to find image at " + this.url);
return;
}
String file = images.first().attr("src");
if (file.startsWith("/")) {
file = "http://nfsfw.com" + file;
}
addURLToDownload(new URL(file), getPrefix(index), this.subdir);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
}
}
}
|
// get image pages
// NOTE: It might be possible to get the (non-thumbnail) image URL
// without going to its page first as there seems to be a pattern
// between the thumb and actual image URLs, but that is outside the
// scope of the current issue being solved.
List<String> imagePageURLs = new ArrayList<>();
for (Element thumb : page.select("td.giItemCell > div > a")) {
String imagePage = "http://nfsfw.com" + thumb.attr("href");
imagePageURLs.add(imagePage);
}
return imagePageURLs;
| 1,826
| 157
| 1,983
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/NhentaiRipper.java
|
NhentaiRipper
|
getGID
|
class NhentaiRipper extends AbstractHTMLRipper {
private String albumTitle;
private Document firstPage;
// Thread pool for finding direct image links from "image" pages (html)
private DownloadThreadPool nhentaiThreadPool = new DownloadThreadPool("nhentai");
@Override
public boolean hasQueueSupport() {
return true;
}
@Override
public boolean pageContainsAlbums(URL url) {
Pattern pa = Pattern.compile("^https?://nhentai\\.net/tag/([a-zA-Z0-9_\\-]+)/?");
Matcher ma = pa.matcher(url.toExternalForm());
return ma.matches();
}
@Override
public List<String> getAlbumsToQueue(Document doc) {
List<String> urlsToAddToQueue = new ArrayList<>();
for (Element elem : doc.select("a.cover")) {
urlsToAddToQueue.add("https://" + getDomain() + elem.attr("href"));
}
return urlsToAddToQueue;
}
@Override
public DownloadThreadPool getThreadPool() {
return nhentaiThreadPool;
}
public NhentaiRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "nhentai.net";
}
@Override
public String getHost() {
return "nhentai";
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
if (firstPage == null) {
try {
firstPage = Http.url(url).get();
} catch (IOException e) {
e.printStackTrace();
}
}
String title = firstPage.select("#info > h1").text();
if (title == null) {
return getAlbumTitle(url);
}
return "nhentai" + title;
}
public List<String> getTags(Document doc) {
List<String> tags = new ArrayList<>();
for (Element tag : doc.select("a.tag")) {
String tagString = tag.attr("href").replaceAll("/tag/", "").replaceAll("/", "");
LOGGER.info("Found tag: " + tagString);
tags.add(tagString);
}
return tags;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
if (firstPage == null) {
firstPage = Http.url(url).get();
}
String blacklistedTag = RipUtils.checkTags(Utils.getConfigStringArray("nhentai.blacklist.tags"), getTags(firstPage));
if (blacklistedTag != null) {
sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_WARN, "Skipping " + url.toExternalForm() + " as it " +
"contains the blacklisted tag \"" + blacklistedTag + "\"");
return null;
}
return firstPage;
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> imageURLs = new ArrayList<>();
Elements thumbs = page.select("a.gallerythumb > img");
for (Element el : thumbs) {
imageURLs.add(el.attr("data-src").replaceAll("t\\.n", "i.n").replaceAll("t\\.", "."));
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), null);
}
}
|
// Ex: https://nhentai.net/g/159174/
Pattern p = Pattern.compile("^https?://nhentai\\.net/g/(\\d+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
// Return the text contained between () in the regex - 159174 in this case
return m.group(1);
}
throw new MalformedURLException("Expected nhentai.net URL format: " +
"nhentai.net/g/albumid - got " + url + " instead");
| 987
| 166
| 1,153
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/NudeGalsRipper.java
|
NudeGalsRipper
|
getGID
|
class NudeGalsRipper extends AbstractHTMLRipper {
// Current HTML document
private Document albumDoc = null;
public NudeGalsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "Nude-Gals";
}
@Override
public String getDomain() {
return "nude-gals.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
albumDoc = Http.url(url).get();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
Elements thumbs = doc.select("img.thumbnail");
for (Element thumb : thumbs) {
String link = thumb.attr("src").replaceAll("thumbs/th_", "");
String imgSrc = "http://nude-gals.com/" + link;
imageURLs.add(imgSrc);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
// Send referrer when downloading images
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), null);
}
}
|
Pattern p;
Matcher m;
p = Pattern.compile("^.*nude-gals\\.com/photoshoot\\.php\\?photoshoot_id=(\\d+)$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected nude-gals.com gallery format: "
+ "nude-gals.com/photoshoot.php?phtoshoot_id=####"
+ " Got: " + url);
| 392
| 160
| 552
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/OglafRipper.java
|
OglafRipper
|
getNextPage
|
class OglafRipper extends AbstractHTMLRipper {
public OglafRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "oglaf";
}
@Override
public String getDomain() {
return "oglaf.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("http://oglaf\\.com/([a-zA-Z1-9_-]*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected oglaf URL format: " +
"oglaf.com/NAME - got " + url + " instead");
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
return getDomain();
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("b > img#strip")) {
String imageSource = el.select("img").attr("src");
result.add(imageSource);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
if (doc.select("div#nav > a > div#nx").first() == null) {
throw new IOException("No more pages");
}
Element elem = doc.select("div#nav > a > div#nx").first().parent();
String nextPage = elem.attr("href");
// Some times this returns a empty string
// This for stops that
if (nextPage.equals("")) {
throw new IOException("No more pages");
}
else {
sleep(1000);
return Http.url("http://oglaf.com" + nextPage).get();
}
| 464
| 155
| 619
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PahealRipper.java
|
PahealRipper
|
getTerm
|
class PahealRipper extends AbstractHTMLRipper {
private static final Logger logger = Logger.getLogger(PahealRipper.class);
private static Map<String, String> cookies = null;
private static Pattern gidPattern = null;
private static Map<String, String> getCookies() {
if (cookies == null) {
cookies = new HashMap<>(1);
cookies.put("ui-tnc-agreed", "true");
}
return cookies;
}
public PahealRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "rule34.paheal.net";
}
@Override
public String getHost() {
return "paheal";
}
@Override
public Document getFirstPage() throws IOException {
return Http.url("http://rule34.paheal.net/post/list/" + getTerm(url) + "/1").cookies(getCookies()).get();
}
@Override
public Document getNextPage(Document page) throws IOException {
for (Element e : page.select("#paginator a")) {
if (e.text().toLowerCase().equals("next")) {
return Http.url(e.absUrl("href")).cookies(getCookies()).get();
}
}
return null;
}
@Override
public List<String> getURLsFromPage(Document page) {
Elements elements = page.select(".shm-thumb.thumb>a").not(".shm-thumb-link");
List<String> res = new ArrayList<>(elements.size());
for (Element e : elements) {
res.add(e.absUrl("href"));
}
return res;
}
@Override
public void downloadURL(URL url, int index) {
try {
String name = url.getPath();
String ext = ".png";
name = name.substring(name.lastIndexOf('/') + 1);
if (name.indexOf('.') >= 0) {
ext = name.substring(name.lastIndexOf('.'));
name = name.substring(0, name.length() - ext.length());
}
File outFile = new File(workingDir.getCanonicalPath()
+ File.separator
+ Utils.filesystemSafe(new URI(name).getPath())
+ ext);
addURLToDownload(url, outFile);
} catch (IOException | URISyntaxException ex) {
logger.error("Error while downloading URL " + url, ex);
}
}
private String getTerm(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
try {
return Utils.filesystemSafe(new URI(getTerm(url)).getPath());
} catch (URISyntaxException ex) {
logger.error(ex);
}
throw new MalformedURLException("Expected paheal.net URL format: rule34.paheal.net/post/list/searchterm - got " + url + " instead");
}
}
|
if (gidPattern == null) {
gidPattern = Pattern.compile("^https?://(www\\.)?rule34\\.paheal\\.net/post/list/([a-zA-Z0-9$_.+!*'(),%-]+)(/.*)?(#.*)?$");
}
Matcher m = gidPattern.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
throw new MalformedURLException("Expected paheal.net URL format: rule34.paheal.net/post/list/searchterm - got " + url + " instead");
| 825
| 171
| 996
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PhotobucketRipper.java
|
AlbumMetadata
|
getNextPage
|
class AlbumMetadata {
private final String baseURL;
private final String location;
private final int sortOrder;
// cookies for the current page of this album
private Map<String, String> cookies;
private Document currPage;
private int numPages;
private int pageIndex = 1;
private AlbumMetadata(JSONObject data) {
this.baseURL = data.getString("url");
this.location = data.getString("location")
.replace(" ", "_");
this.sortOrder = data.getInt("sortOrder");
}
private String getCurrPageURL(){
return baseURL + String.format("?sort=%d&page=%d",
sortOrder, pageIndex);
}
}
private final Pattern collDataPattern;
private final Pattern pbURLPattern;
// all albums including sub-albums to rip
private List<AlbumMetadata> albums;
// the album currently being ripped
private AlbumMetadata currAlbum;
// a new index per album downloaded
private int index = 0;
public PhotobucketRipper(URL url) throws IOException {
super(url);
this.collDataPattern = Pattern.compile(
"^.*collectionData: (\\{.*}).*$", Pattern.DOTALL
);
this.pbURLPattern = Pattern.compile(
"^https?://([a-zA-Z0-9]+)\\.photobucket\\.com/user/" +
"([a-zA-Z0-9_\\-]+)/library/([^?]*).*$"
);
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
public String getHost() {
return HOST;
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
LOGGER.info(url);
String u = url.toExternalForm();
if (u.contains("?")) {
// strip options from URL
u = u.substring(0, u.indexOf("?"));
}
if (!u.endsWith("/")) {
// append trailing slash
u = u + "/";
}
return new URL(u);
}
@Override
public String getGID(URL url) throws MalformedURLException {
Matcher m;
URL sanitized = sanitizeURL(url);
// http://s844.photobucket.com/user/SpazzySpizzy/library/Lady%20Gaga?sort=3&page=1
m = pbURLPattern.matcher(sanitized.toExternalForm());
if (m.matches()) {
// the username is not really a unique GID, because the same user
// can have multiple albums, but on the other hand, using HOST_GID
// as save directory means we can group ripped albums of the same
// user.
return m.group(2);
}
throw new MalformedURLException(
"Expected photobucket.com gallery formats: "
+ "http://x###.photobucket.com/username/library/..."
+ " Got: " + url);
}
// Page iteration
@Override
public Document getFirstPage() throws IOException {
if (this.currAlbum == null) {
this.albums = getAlbumMetadata(this.url.toExternalForm());
LOGGER.info("Detected " + albums.size() + " albums in total");
}
this.currAlbum = this.albums.remove(0);
// NOTE: Why not just get media count in the metadata json?
//
// Because that data might not reflect what the user sees on the page
// and can lead to iterating more pages than there actually are.
//
// An example:
// Metadata JSON -> AlbumStats: 146 images + 0 videos -> 146 items/7 pages
// http://s1255.photobucket.com/api/user/mimajki/album/Movie%20gifs/get?subAlbums=48&json=1
// Actual item count when looking at the album url: 131 items/6 pages
// http://s1255.photobucket.com/user/mimajki/library/Movie%20gifs?sort=6&page=1
Connection.Response resp = Http.url(currAlbum.getCurrPageURL()).response();
this.currAlbum.cookies = resp.cookies();
this.currAlbum.currPage = resp.parse();
JSONObject collectionData = getCollectionData(currAlbum.currPage);
int totalNumItems = collectionData.getInt("total");
this.currAlbum.numPages = (int) Math.ceil(
(double)totalNumItems / (double)ITEMS_PER_PAGE);
this.index = 0;
return currAlbum.currPage;
}
@Override
public Document getNextPage(Document page) throws IOException {<FILL_FUNCTION_BODY>
|
this.currAlbum.pageIndex++;
boolean endOfAlbum = currAlbum.pageIndex > currAlbum.numPages;
boolean noMoreSubalbums = albums.isEmpty();
if (endOfAlbum && noMoreSubalbums){
throw new IOException("No more pages");
}
try {
Thread.sleep(WAIT_BEFORE_NEXT_PAGE);
} catch (InterruptedException e) {
LOGGER.info("Interrupted while waiting before getting next page");
}
if (endOfAlbum){
LOGGER.info("Turning to next album " + albums.get(0).baseURL);
return getFirstPage();
} else {
LOGGER.info("Turning to page " + currAlbum.pageIndex +
" of album " + currAlbum.baseURL);
Connection.Response resp = Http.url(currAlbum.getCurrPageURL()).response();
currAlbum.cookies = resp.cookies();
currAlbum.currPage = resp.parse();
return currAlbum.currPage;
}
| 1,321
| 287
| 1,608
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PichunterRipper.java
|
PichunterRipper
|
getNextPage
|
class PichunterRipper extends AbstractHTMLRipper {
public PichunterRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "pichunter";
}
@Override
public String getDomain() {
return "pichunter.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.pichunter.com/(|tags|models|sites)/(\\S*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
p = Pattern.compile("https?://www.pichunter.com/(tags|models|sites)/(\\S*)/photos/\\d+/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
p = Pattern.compile("https?://www.pichunter.com/tags/all/(\\S*)/\\d+/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("https?://www.pichunter.com/gallery/\\d+/(\\S*)/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected pichunter URL format: " +
"pichunter.com/(tags|models|sites)/Name/ - got " + url + " instead");
}
private boolean isPhotoSet(URL url) {
Pattern p = Pattern.compile("https?://www.pichunter.com/gallery/\\d+/(\\S*)/?");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (!isPhotoSet(url)) {
for (Element el : doc.select("div.thumbtable > a.thumb > img")) {
result.add(el.attr("src").replaceAll("_i", "_o"));
}
} else {
for (Element el : doc.select("div.flex-images > figure > a.item > img")) {
result.add(el.attr("src").replaceAll("_i", "_o"));
}
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
// We use comic-nav-next to the find the next page
Element elem = doc.select("div.paperSpacings > ul > li.arrow").last();
if (elem != null) {
String nextPage = elem.select("a").attr("href");
// Some times this returns a empty string
// This for stops that
return Http.url("http://www.pichunter.com" + nextPage).get();
}
throw new IOException("No more pages");
| 809
| 122
| 931
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PicstatioRipper.java
|
PicstatioRipper
|
getFullSizedImageFromURL
|
class PicstatioRipper extends AbstractHTMLRipper {
public PicstatioRipper(URL url) throws IOException {
super(url);
}
private String getFullSizedImageFromURL(String fileName) {<FILL_FUNCTION_BODY>}
@Override
public String getHost() {
return "picstatio";
}
@Override
public String getDomain() {
return "picstatio.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.picstatio.com/([a-zA-Z1-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected picstatio URL format: " +
"www.picstatio.com//ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
if (doc.select("a.next_page") != null) {
return Http.url("https://www.picstatio.com" + doc.select("a.next_page").attr("href")).get();
}
throw new IOException("No more pages");
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element e : doc.select("img.img")) {
String imageName = e.parent().attr("href");
LOGGER.info(getFullSizedImageFromURL(imageName.split("/")[2]));
result.add(getFullSizedImageFromURL(imageName.split("/")[2]));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
try {
LOGGER.info("https://www.picstatio.com/wallpaper/" + fileName + "/download");
return Http.url("https://www.picstatio.com/wallpaper/" + fileName + "/download").get().select("p.text-center > span > a").attr("href");
} catch (IOException e) {
e.printStackTrace();
return null;
}
| 558
| 104
| 662
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PorncomixRipper.java
|
PorncomixRipper
|
getURLsFromPage
|
class PorncomixRipper extends AbstractHTMLRipper {
public PorncomixRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "porncomix";
}
@Override
public String getDomain() {
return "porncomix.info";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.porncomix.info/([a-zA-Z0-9_\\-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected proncomix URL format: " +
"porncomix.info/comic - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select("div.single-post > div.gallery > dl > dt > a > img")) {
String imageSource = el.attr("data-lazy-src");
// We remove the .md from images so we download the full size image
// not the thumbnail ones
imageSource = imageSource.replaceAll("-\\d\\d\\dx\\d\\d\\d", "");
result.add(imageSource);
}
return result;
| 356
| 133
| 489
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PornhubRipper.java
|
PornhubRipper
|
downloadURL
|
class PornhubRipper extends AbstractHTMLRipper {
// All sleep times are in milliseconds
private static final int IMAGE_SLEEP_TIME = 1000;
private static final String DOMAIN = "pornhub.com", HOST = "Pornhub";
// Thread pool for finding direct image links from "image" pages (html)
private DownloadThreadPool pornhubThreadPool = new DownloadThreadPool("pornhub");
public PornhubRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
protected Document getFirstPage() throws IOException {
return Http.url(url).referrer(url).get();
}
@Override
public Document getNextPage(Document page) throws IOException {
Elements nextPageLink = page.select("li.page_next > a");
if (nextPageLink.isEmpty()){
throw new IOException("No more pages");
} else {
URL nextURL = new URL(this.url, nextPageLink.first().attr("href"));
return Http.url(nextURL).get();
}
}
@Override
protected List<String> getURLsFromPage(Document page) {
List<String> pageURLs = new ArrayList<>();
// Find thumbnails
Elements thumbs = page.select(".photoBlockBox li");
// Iterate over thumbnail images on page
for (Element thumb : thumbs) {
String imagePage = thumb.select(".photoAlbumListBlock > a")
.first().attr("href");
String fullURL = "https://pornhub.com" + imagePage;
pageURLs.add(fullURL);
}
return pageURLs;
}
@Override
protected void downloadURL(URL url, int index) {<FILL_FUNCTION_BODY>}
public URL sanitizeURL(URL url) throws MalformedURLException {
// always start on the first page of an album
// (strip the options after the '?')
String u = url.toExternalForm();
if (u.contains("?")) {
u = u.substring(0, u.indexOf("?"));
return new URL(u);
} else {
return url;
}
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p;
Matcher m;
p = Pattern.compile("^.*pornhub\\.com/album/([0-9]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected pornhub.com album format: "
+ "http://www.pornhub.com/album/####"
+ " Got: " + url);
}
@Override
public DownloadThreadPool getThreadPool(){
return pornhubThreadPool;
}
public boolean canRip(URL url) {
return url.getHost().endsWith(DOMAIN) && url.getPath().startsWith("/album");
}
/**
* Helper class to find and download images found on "image" pages
*
* Handles case when site has IP-banned the user.
*/
private class PornhubImageThread extends Thread {
private URL url;
private int index;
PornhubImageThread(URL url, int index, File workingDir) {
super();
this.url = url;
this.index = index;
}
@Override
public void run() {
fetchImage();
}
private void fetchImage() {
try {
Document doc = Http.url(this.url)
.referrer(this.url)
.get();
// Find image
Elements images = doc.select("#photoImageSection img");
Element image = images.first();
String imgsrc = image.attr("src");
LOGGER.info("Found URL " + imgsrc + " via " + images.get(0));
// Provide prefix and let the AbstractRipper "guess" the filename
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
URL imgurl = new URL(url, imgsrc);
addURLToDownload(imgurl, prefix);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
}
}
}
|
PornhubImageThread t = new PornhubImageThread(url, index, this.workingDir);
pornhubThreadPool.addThread(t);
try {
Thread.sleep(IMAGE_SLEEP_TIME);
} catch (InterruptedException e) {
LOGGER.warn("Interrupted while waiting to load next image", e);
}
| 1,227
| 94
| 1,321
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PornpicsRipper.java
|
PornpicsRipper
|
getURLsFromPage
|
class PornpicsRipper extends AbstractHTMLRipper {
public PornpicsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "pornpics";
}
@Override
public String getDomain() {
return "pornpics.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.pornpics.com/galleries/([a-zA-Z0-9_-]*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected pornpics URL format: " +
"www.pornpics.com/galleries/ID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select("a.rel-link")) {
result.add(el.attr("href"));
}
return result;
| 360
| 53
| 413
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ReadcomicRipper.java
|
ReadcomicRipper
|
getURLsFromPage
|
class ReadcomicRipper extends ViewcomicRipper {
public ReadcomicRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "read-comic";
}
@Override
public String getDomain() {
return "read-comic.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://read-comic.com/([a-zA-Z1-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected view-comic URL format: " +
"read-comic.com/COMIC_NAME - got " + url + " instead");
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
}
|
List<String> result = new ArrayList<String>();
for (Element el : doc.select("div.pinbin-copy > a > img")) {
result.add(el.attr("src"));
}
return result;
| 278
| 60
| 338
|
<methods>public void <init>(java.net.URL) throws java.io.IOException,public void downloadURL(java.net.URL, int) ,public java.lang.String getAlbumTitle(java.net.URL) throws java.net.MalformedURLException,public java.lang.String getDomain() ,public Document getFirstPage() throws java.io.IOException,public java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public java.lang.String getHost() ,public List<java.lang.String> getURLsFromPage(Document) <variables>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/RedgifsRipper.java
|
RedgifsRipper
|
getNextPage
|
class RedgifsRipper extends AbstractHTMLRipper {
private static final String HOST = "redgifs.com";
private static final String HOST_2 = "gifdeliverynetwork.com";
String username = "";
String cursor = "";
String count = "100";
String searchText = "";
int searchCount = 150;
int searchStart = 0;
public RedgifsRipper(URL url) throws IOException {
super(new URL(url.toExternalForm().replace("thumbs.", "")));
}
@Override
public String getDomain() { return "redgifs.com"; }
@Override
public String getHost() {
return "redgifs";
}
@Override
public boolean canRip(URL url) {
return url.getHost().endsWith(HOST) || url.getHost().endsWith(HOST_2);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
String sUrl = url.toExternalForm();
sUrl = sUrl.replace("/gifs/detail", "");
sUrl = sUrl.replace("/amp", "");
sUrl = sUrl.replace("gifdeliverynetwork.com", "redgifs.com/watch");
return new URL(sUrl);
}
public Matcher isProfile() {
Pattern p = Pattern.compile("^https?://[wm.]*redgifs\\.com/users/([a-zA-Z0-9_-]+).*$");
return p.matcher(url.toExternalForm());
}
public Matcher isSearch() {
Pattern p = Pattern.compile("^https?://[wm.]*redgifs\\.com/gifs/browse/([a-zA-Z0-9_-]+).*$");
return p.matcher(url.toExternalForm());
}
public Matcher isSingleton() {
Pattern p = Pattern.compile("^https?://[wm.]*redgifs\\.com/watch/([a-zA-Z0-9_-]+).*$");
return p.matcher(url.toExternalForm());
}
@Override
public Document getFirstPage() throws IOException {
if (!isProfile().matches() && !isSearch().matches()) {
return Http.url(url).get();
} else if (isSearch().matches()) {
searchText = getGID(url).replace("-", " ");
return Http.url(
new URL("https://napi.redgifs.com/v1/gfycats/search?search_text=" + searchText + "&count=" + searchCount + "&start=" + searchStart*searchCount)).ignoreContentType().get();
} else {
username = getGID(url);
return Http.url(new URL("https://napi.redgifs.com/v1/users/" + username + "/gfycats?count=" + count))
.ignoreContentType().get();
}
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
public String getGID(URL url) throws MalformedURLException {
Matcher m = isProfile();
if (m.matches()) {
return m.group(1);
}
m = isSearch();
if (m.matches()) {
return m.group(1);
}
m = isSingleton();
if (m.matches()) {
return m.group(1).split("-")[0];
}
throw new MalformedURLException(
"Expected redgifs.com format: "
+ "redgifs.com/id or "
+ "thumbs.redgifs.com/id.gif"
+ " Got: " + url);
}
private String stripHTMLTags(String t) {
t = t.replaceAll("<html>\n" +
" <head></head>\n" +
" <body>", "");
t = t.replaceAll("</body>\n" +
"</html>", "");
t = t.replaceAll("\n", "");
t = t.replaceAll("=\"\"", "");
return t;
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (isProfile().matches() || isSearch().matches()) {
result = hasURLs(doc);
} else {
Elements videos = doc.select("script");
for (Element el : videos) {
String json = el.html();
if (json.startsWith("{")) {
JSONObject page = new JSONObject(json);
result.add(page.getJSONObject("video").getString("contentUrl"));
}
}
}
return result;
}
/**
* Helper method for retrieving URLs.
* @param doc Document of the URL page to look through
* @return List of URLs to download
*/
public List<String> hasURLs(Document doc) {
List<String> result = new ArrayList<>();
JSONObject page = new JSONObject(stripHTMLTags(doc.html()));
JSONArray content = page.getJSONArray("gfycats");
for (int i = 0; i < content.length(); i++) {
result.add(content.getJSONObject(i).getString("mp4Url"));
}
cursor = page.getString("cursor");
return result;
}
/**
* Helper method for retrieving video URLs.
* @param url URL to gfycat page
* @return URL to video
* @throws IOException
*/
public static String getVideoURL(URL url) throws IOException {
LOGGER.info("Retrieving " + url.toExternalForm());
//Sanitize the URL first
url = new URL(url.toExternalForm().replace("/gifs/detail", ""));
Document doc = Http.url(url).get();
Elements videos = doc.select("script");
for (Element el : videos) {
String json = el.html();
if (json.startsWith("{")) {
JSONObject page = new JSONObject(json);
return page.getJSONObject("video").getString("contentUrl");
}
}
throw new IOException();
}
}
|
if (isSearch().matches()) {
Document d = Http.url(
new URL("https://napi.redgifs.com/v1/gfycats/search?search_text=" + searchText
+ "&count=" + searchCount + "&start=" + searchCount*++searchStart))
.ignoreContentType().get();
return (hasURLs(d).isEmpty()) ? null : d;
} else {
if (cursor.equals("")) {
return null;
} else {
Document d = Http.url(new URL("https://napi.redgifs.com/v1/users/" + username + "/gfycats?count=" + count + "&cursor=" + cursor)).ignoreContentType().get();
return (hasURLs(d).isEmpty()) ? null : d;
}
}
| 1,685
| 213
| 1,898
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/Rule34Ripper.java
|
Rule34Ripper
|
getNextPage
|
class Rule34Ripper extends AbstractHTMLRipper {
public Rule34Ripper(URL url) throws IOException {
super(url);
}
private String apiUrl;
private int pageNumber = 0;
@Override
public String getHost() {
return "rule34";
}
@Override
public String getDomain() {
return "rule34.xxx";
}
@Override
public boolean canRip(URL url){
Pattern p = Pattern.compile("https?://rule34.xxx/index.php\\?page=post&s=list&tags=([\\S]+)");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://rule34.xxx/index.php\\?page=post&s=list&tags=([\\S]+)");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected rule34.xxx URL format: " +
"rule34.xxx/index.php?page=post&s=list&tags=TAG - got " + url + " instead");
}
public URL getAPIUrl() throws MalformedURLException {
URL urlToReturn = new URL("https://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags=" + getGID(url));
return urlToReturn;
}
@Override
public Document getFirstPage() throws IOException {
apiUrl = getAPIUrl().toExternalForm();
// "url" is an instance field of the superclass
return Http.url(getAPIUrl()).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("posts > post")) {
String imageSource = el.select("post").attr("file_url");
result.add(imageSource);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
if (doc.html().contains("Search error: API limited due to abuse")) {
throw new IOException("No more pages");
}
pageNumber += 1;
String nextPage = apiUrl + "&pid=" + pageNumber;
return Http.url(nextPage).get();
| 646
| 73
| 719
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/RulePornRipper.java
|
RulePornRipper
|
getGID
|
class RulePornRipper extends AbstractSingleFileRipper {
public RulePornRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "ruleporn";
}
@Override
public String getDomain() {
return "ruleporn.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
result.add(doc.select("source[type=video/mp4]").attr("src"));
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^https://.*ruleporn\\.com/(.*)/$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected ruleporn.com URL format: " + "ruleporn.com/NAME - got " + url + " instead");
| 260
| 108
| 368
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/SankakuComplexRipper.java
|
SankakuComplexRipper
|
getNextPage
|
class SankakuComplexRipper extends AbstractHTMLRipper {
private Document albumDoc = null;
private Map<String,String> cookies = new HashMap<>();
public SankakuComplexRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "sankakucomplex";
}
@Override
public String getDomain() {
return "sankakucomplex.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://([a-zA-Z0-9]+\\.)?sankakucomplex\\.com/.*tags=([^&]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
try {
return URLDecoder.decode(m.group(1) + "_" + m.group(2), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new MalformedURLException("Cannot decode tag name '" + m.group(1) + "'");
}
}
throw new MalformedURLException("Expected sankakucomplex.com URL format: " +
"idol.sankakucomplex.com?...&tags=something... - got " +
url + "instead");
}
public String getSubDomain(URL url){
Pattern p = Pattern.compile("^https?://([a-zA-Z0-9]+\\.)?sankakucomplex\\.com/.*tags=([^&]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
try {
return URLDecoder.decode(m.group(1), "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
return null;
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
Response resp = Http.url(url).response();
cookies.putAll(resp.cookies());
albumDoc = resp.parse();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
// Image URLs are basically thumbnail URLs with a different domain, a simple
// path replacement, and a ?xxxxxx post ID at the end (obtainable from the href)
for (Element thumbSpan : doc.select("div.content > div > span.thumb > a")) {
String postLink = thumbSpan.attr("href");
try {
String subDomain = getSubDomain(url);
String siteURL = "https://" + subDomain + "sankakucomplex.com";
// Get the page the full sized image is on
Document subPage = Http.url(siteURL + postLink).get();
LOGGER.info("Checking page " + siteURL + postLink);
imageURLs.add("https:" + subPage.select("div[id=stats] > ul > li > a[id=highres]").attr("href"));
} catch (IOException e) {
LOGGER.warn("Error while loading page " + postLink, e);
}
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
sleep(8000);
addURLToDownload(url, getPrefix(index));
}
@Override
public Document getNextPage(Document doc) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Element pagination = doc.select("div.pagination").first();
if (pagination.hasAttr("next-page-url")) {
String nextPage = pagination.attr("abs:next-page-url");
// Only logged in users can see past page 25
// Trying to rip page 26 will throw a no images found error
if (!nextPage.contains("page=26")) {
LOGGER.info("Getting next page: " + pagination.attr("abs:next-page-url"));
return Http.url(pagination.attr("abs:next-page-url")).cookies(cookies).get();
}
}
throw new IOException("No more pages");
| 941
| 175
| 1,116
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ShesFreakyRipper.java
|
ShesFreakyRipper
|
getGID
|
class ShesFreakyRipper extends AbstractHTMLRipper {
public ShesFreakyRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "shesfreaky";
}
@Override
public String getDomain() {
return "shesfreaky.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("a[data-lightbox=\"gallery\"]")) {
String image = thumb.attr("href");
imageURLs.add("https:" + image);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*shesfreaky\\.com/gallery/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected shesfreaky.com URL format: "
+ "shesfreaky.com/gallery/... - got " + url + "instead");
| 297
| 136
| 433
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/SinfestRipper.java
|
SinfestRipper
|
getURLsFromPage
|
class SinfestRipper extends AbstractHTMLRipper {
public SinfestRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "sinfest";
}
@Override
public String getDomain() {
return "sinfest.net";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://sinfest.net/view.php\\?date=([0-9-]*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected sinfest URL format: " +
"sinfest.net/view.php?date=XXXX-XX-XX/ - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
Element elem = doc.select("td.style5 > a > img").last();
LOGGER.info(elem.parent().attr("href"));
if (elem == null || elem.parent().attr("href").equals("view.php?date=")) {
throw new IOException("No more pages");
}
String nextPage = elem.parent().attr("href");
// Some times this returns a empty string
// This for stops that
if (nextPage.equals("")) {
return null;
}
else {
return Http.url("http://sinfest.net/" + nextPage).get();
}
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
Element elem = doc.select("tbody > tr > td > img").last();
result.add("http://sinfest.net/" + elem.attr("src"));
return result;
| 530
| 60
| 590
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/SmuttyRipper.java
|
SmuttyRipper
|
getGID
|
class SmuttyRipper extends AbstractHTMLRipper {
private static final String DOMAIN = "smutty.com",
HOST = "smutty";
public SmuttyRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "smutty";
}
@Override
public String getDomain() {
return "smutty.com";
}
@Override
public boolean canRip(URL url) {
return (url.getHost().endsWith(DOMAIN));
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> results = new ArrayList<>();
for (Element image : doc.select("a.l > img")) {
if (isStopped()) {
break;
}
String imageUrl = image.attr("src");
// Construct direct link to image based on thumbnail
StringBuilder sb = new StringBuilder();
String[] fields = imageUrl.split("/");
for (int i = 0; i < fields.length; i++) {
if (i == fields.length - 2 && fields[i].equals("m")) {
fields[i] = "b";
}
sb.append(fields[i]);
if (i < fields.length - 1) {
sb.append("/");
}
}
imageUrl = sb.toString();
results.add("http:" + imageUrl);
}
return results;
}
@Override
public Document getNextPage(Document doc) throws IOException {
Element elem = doc.select("a.next").first();
if (elem == null) {
throw new IOException("No more pages");
}
String nextPage = elem.attr("href");
// Some times this returns a empty string
// This for stops that
if (nextPage.equals("")) {
throw new IOException("No more pages");
}
else {
return Http.url("https://smutty.com" + nextPage).get();
}
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
}
|
Pattern p = Pattern.compile("^https?://smutty\\.com/h/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("^https?://[wm.]*smutty\\.com/search/\\?q=([a-zA-Z0-9\\-_%]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1).replace("%23", "");
}
p = Pattern.compile("^https?://smutty.com/user/([a-zA-Z0-9\\-_]+)/?$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected tag in URL (smutty.com/h/tag and not " + url);
| 675
| 287
| 962
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/SpankbangRipper.java
|
SpankbangRipper
|
getGID
|
class SpankbangRipper extends AbstractSingleFileRipper {
private static final String HOST = "spankbang";
public SpankbangRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "spankbang.com";
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
Elements videos = doc.select(".video-js > source");
if (videos.isEmpty()) {
LOGGER.error("Could not find Embed code at " + url);
return null;
}
result.add(videos.attr("src"));
return result;
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://.*spankbang\\.com/(.*)/video/.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^https?://.*spankbang\\.com/(.*)/video/(.*)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
throw new MalformedURLException(
"Expected spankbang format:"
+ "spankbang.com/####/video/"
+ " Got: " + url);
| 426
| 119
| 545
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/StaRipper.java
|
StaRipper
|
getURLsFromPage
|
class StaRipper extends AbstractHTMLRipper {
public StaRipper(URL url) throws IOException {
super(url);
}
private Map<String,String> cookies = new HashMap<>();
@Override
public String getHost() {
return "sta";
}
@Override
public String getDomain() {
return "sta.sh";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://sta.sh/([A-Za-z0-9]+)");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected sta.sh URL format: " +
"sta.sh/ALBUMID - got " + url + " instead");
}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
private boolean checkURL(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
private String getImageLinkFromDLLink(String url) {
try {
Connection.Response response = Jsoup.connect(url)
.userAgent(USER_AGENT)
.timeout(10000)
.cookies(cookies)
.followRedirects(false)
.execute();
String imageURL = response.header("Location");
LOGGER.info(imageURL);
return imageURL;
} catch (IOException e) {
LOGGER.info("Got error message " + e.getMessage() + " trying to download " + url);
return null;
}
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> result = new ArrayList<>();
for (Element el : doc.select("span > span > a.thumb")) {
String thumbPageURL = el.attr("href");
Document thumbPage = null;
if (checkURL(thumbPageURL)) {
try {
Connection.Response resp = Http.url(new URL(thumbPageURL)).response();
cookies.putAll(resp.cookies());
thumbPage = resp.parse();
} catch (MalformedURLException e) {
LOGGER.info(thumbPageURL + " is a malformed URL");
} catch (IOException e) {
LOGGER.info(e.getMessage());
}
String imageDownloadUrl = thumbPage.select("a.dev-page-download").attr("href");
if (imageDownloadUrl != null && !imageDownloadUrl.equals("")) {
result.add(getImageLinkFromDLLink(imageDownloadUrl));
}
}
}
return result;
| 558
| 243
| 801
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/TapasticRipper.java
|
TapasticRipper
|
downloadURL
|
class TapasticRipper extends AbstractHTMLRipper {
private List<TapasticEpisode> episodes= new ArrayList<>();
public TapasticRipper(URL url) throws IOException {
super(url);
}
@Override
public String getDomain() {
return "tapas.io";
}
@Override
public String getHost() {
return "tapas";
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> urls = new ArrayList<>();
String html = page.data();
if (!html.contains("episodeList : ")) {
LOGGER.error("No 'episodeList' found at " + this.url);
return urls;
}
String jsonString = Utils.between(html, "episodeList : ", ",\n").get(0);
JSONArray json = new JSONArray(jsonString);
for (int i = 0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
TapasticEpisode episode = new TapasticEpisode(i, obj.getInt("id"), obj.getString("title"));
episodes.add(episode);
urls.add("http://tapastic.com/episode/" + episode.id);
}
return urls;
}
@Override
public void downloadURL(URL url, int index) {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://tapas.io/series/([^/?]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "series_ " + m.group(1);
}
p = Pattern.compile("^https?://tapas.io/episode/([^/?]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return "ep_" + m.group(1);
}
throw new MalformedURLException("Expected tapastic.com URL format: "
+ "tapastic.com/[series|episode]/name - got " + url + " instead");
}
}
|
try {
Document doc = Http.url(url).get();
Elements images = doc.select("article.ep-contents img");
// Find maximum # of images for optimal filename indexing
int epiLog = (int) (Math.floor(Math.log10(episodes.size())) + 1),
imgLog = (int) (Math.floor(Math.log10(images.size() )) + 1);
for (int i = 0; i < images.size(); i++) {
String link = images.get(i).attr("src");
TapasticEpisode episode = episodes.get(index - 1);
// Build elaborate filename prefix
StringBuilder prefix = new StringBuilder();
prefix.append(String.format("ep%0" + epiLog + "d", index));
prefix.append(String.format("-%0" + imgLog + "dof%0" + imgLog + "d-", i + 1, images.size()));
prefix.append(episode.filename.replace(" ", "-"));
prefix.append("-");
addURLToDownload(new URL(link), prefix.toString());
if (isThisATest()) {
break;
}
}
} catch (IOException e) {
LOGGER.error("[!] Exception while downloading " + url, e);
}
| 629
| 333
| 962
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/TeenplanetRipper.java
|
TeenplanetRipper
|
getURLsFromPage
|
class TeenplanetRipper extends AbstractHTMLRipper {
private static final String DOMAIN = "teenplanet.org",
HOST = "teenplanet";
public TeenplanetRipper(URL url) throws IOException {
super(url);
}
@Override
protected String getDomain() {
return DOMAIN;
}
@Override
public String getHost() {
return HOST;
}
@Override
protected Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
protected List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
@Override
protected void downloadURL(URL url, int index) {
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
addURLToDownload(url, prefix);
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p; Matcher m;
p = Pattern.compile("^.*teenplanet.org/galleries/([a-zA-Z0-9\\-]+).html$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected teenplanet.org gallery format: "
+ "teenplanet.org/galleries/....html"
+ " Got: " + url);
}
}
|
List<String> imageURLs = new ArrayList<>();
for (Element thumb : page.select("#galleryImages > a > img")) {
if (!thumb.hasAttr("src")) {
continue;
}
String imageURL = thumb.attr("src");
imageURL = imageURL.replace(
"/thumbs/",
"/");
imageURLs.add(imageURL);
}
System.out.println("Found" + imageURLs.size() + " image urls");
return imageURLs;
| 416
| 134
| 550
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/TheyiffgalleryRipper.java
|
TheyiffgalleryRipper
|
getGID
|
class TheyiffgalleryRipper extends AbstractHTMLRipper {
public TheyiffgalleryRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "theyiffgallery";
}
@Override
public String getDomain() {
return "theyiffgallery.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
String nextPage = doc.select("span.navPrevNext > a").attr("href");
if (nextPage != null && !nextPage.isEmpty() && nextPage.contains("start-")) {
return Http.url("https://theyiffgallery.com/" + nextPage).get();
}
throw new IOException("No more pages");
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
for (Element el : doc.select("img.thumbnail")) {
String imageSource = el.attr("src");
imageSource = imageSource.replaceAll("_data/i", "");
imageSource = imageSource.replaceAll("-\\w\\w_\\w\\d+x\\d+", "");
result.add("https://theyiffgallery.com" + imageSource);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https?://theyiffgallery.com/index\\?/category/(\\d+)");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected theyiffgallery URL format: " +
"theyiffgallery.com/index?/category/#### - got " + url + " instead");
| 456
| 119
| 575
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/TsuminoRipper.java
|
TsuminoRipper
|
getPageUrls
|
class TsuminoRipper extends AbstractHTMLRipper {
private Map<String,String> cookies = new HashMap<>();
public TsuminoRipper(URL url) throws IOException {
super(url);
}
public List<String> getTags(Document doc) {
List<String> tags = new ArrayList<>();
LOGGER.info("Getting tags");
for (Element tag : doc.select("div#Tag > a")) {
LOGGER.info("Found tag " + tag.text());
tags.add(tag.text().toLowerCase());
}
return tags;
}
private JSONArray getPageUrls() {<FILL_FUNCTION_BODY>}
@Override
public String getHost() {
return "tsumino";
}
@Override
public String getDomain() {
return "tsumino.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https?://www.tsumino.com/Book/Info/([0-9]+)/([a-zA-Z0-9_-]*)/?");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1) + "_" + m.group(2);
}
p = Pattern.compile("https?://www.tsumino.com/Book/Info/([0-9]+)/?");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected tsumino URL format: " +
"tsumino.com/Book/Info/ID/TITLE - got " + url + " instead");
}
private String getAlbumID() {
Pattern p = Pattern.compile("https?://www.tsumino.com/Book/Info/([0-9]+)/\\S*");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
return null;
}
@Override
public Document getFirstPage() throws IOException {
Connection.Response resp = Http.url(url).response();
cookies.putAll(resp.cookies());
Document doc = resp.parse();
String blacklistedTag = RipUtils.checkTags(Utils.getConfigStringArray("tsumino.blacklist.tags"), getTags(doc));
if (blacklistedTag != null) {
sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_WARN, "Skipping " + url.toExternalForm() + " as it " +
"contains the blacklisted tag \"" + blacklistedTag + "\"");
return null;
}
return doc;
}
@Override
public List<String> getURLsFromPage(Document doc) {
JSONArray imageIds = getPageUrls();
List<String> result = new ArrayList<>();
for (int i = 0; i < imageIds.length(); i++) {
result.add("http://www.tsumino.com/Image/Object?name=" + URLEncoder.encode(imageIds.getString(i)));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
sleep(1000);
/*
There is no way to tell if an image returned from tsumino.com is a png to jpg. The content-type header is always
"image/jpeg" even when the image is a png. The file ext is not included in the url.
*/
addURLToDownload(url, getPrefix(index), "", null, null, null, null, true);
}
}
|
String postURL = "http://www.tsumino.com/Read/Load";
try {
// This sessionId will expire and need to be replaced
cookies.put("ASP.NET_SessionId","c4rbzccf0dvy3e0cloolmlkq");
Document doc = Jsoup.connect(postURL).data("q", getAlbumID()).userAgent(USER_AGENT).cookies(cookies).referrer("http://www.tsumino.com/Read/View/" + getAlbumID()).get();
String jsonInfo = doc.html().replaceAll("<html>","").replaceAll("<head></head>", "").replaceAll("<body>", "").replaceAll("</body>", "")
.replaceAll("</html>", "").replaceAll("\n", "");
JSONObject json = new JSONObject(jsonInfo);
return json.getJSONArray("reader_page_urls");
} catch (IOException e) {
LOGGER.info(e);
sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_ERRORED, "Unable to download album, please compete the captcha at http://www.tsumino.com/Read/Auth/"
+ getAlbumID() + " and try again");
return null;
}
| 969
| 324
| 1,293
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/TwodgalleriesRipper.java
|
TwodgalleriesRipper
|
login
|
class TwodgalleriesRipper extends AbstractHTMLRipper {
private int offset = 0;
private Map<String,String> cookies = new HashMap<>();
public TwodgalleriesRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "2dgalleries";
}
@Override
public String getDomain() {
return "2dgalleries.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p; Matcher m;
p = Pattern.compile("^.*2dgalleries.com/artist/([a-zA-Z0-9\\-]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected 2dgalleries.com album format: "
+ "2dgalleries.com/artist/..."
+ " Got: " + url);
}
private String getURL(String userid, int offset) {
return "http://en.2dgalleries.com/artist/" + userid
+ "?timespan=4"
+ "&order=1"
+ "&catid=2"
+ "&offset=" + offset
+ "&ajx=1&pager=1";
}
@Override
public Document getFirstPage() throws IOException {
try {
login();
} catch (IOException e) {
LOGGER.error("Failed to login", e);
}
String url = getURL(getGID(this.url), offset);
return Http.url(url)
.cookies(cookies)
.get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
offset += 24;
String url = getURL(getGID(this.url), offset);
sleep(500);
Document nextDoc = Http.url(url)
.cookies(cookies)
.get();
if (nextDoc.select("div.hcaption > img").isEmpty()) {
throw new IOException("No more images to retrieve");
}
return nextDoc;
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div.hcaption > img")) {
String image = thumb.attr("src");
image = image.replace("/200H/", "/");
if (image.startsWith("//")) {
image = "http:" + image;
} else if (image.startsWith("/")) {
image = "http://en.2dgalleries.com" + image;
}
imageURLs.add(image);
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
private void login() throws IOException {<FILL_FUNCTION_BODY>}
}
|
Response resp = Http.url(this.url).response();
cookies = resp.cookies();
String ctoken = resp.parse().select("form > input[name=ctoken]").first().attr("value");
Map<String,String> postdata = new HashMap<>();
postdata.put("user[login]", new String(Base64.decode("cmlwbWU=")));
postdata.put("user[password]", new String(Base64.decode("cmlwcGVy")));
postdata.put("rememberme", "1");
postdata.put("ctoken", ctoken);
resp = Http.url("http://en.2dgalleries.com/account/login")
.referrer("http://en.2dgalleries.com/")
.cookies(cookies)
.data(postdata)
.method(Method.POST)
.response();
cookies = resp.cookies();
| 812
| 242
| 1,054
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/VidbleRipper.java
|
VidbleRipper
|
getGID
|
class VidbleRipper extends AbstractHTMLRipper {
public VidbleRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "vidble";
}
@Override
public String getDomain() {
return "vidble.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
return getURLsFromPageStatic(doc);
}
private static List<String> getURLsFromPageStatic(Document doc) {
List<String> imageURLs = new ArrayList<>();
Elements els = doc.select("#ContentPlaceHolder1_divContent");
Elements imgs = els.select("img");
for (Element img : imgs) {
String src = img.absUrl("src");
src = src.replaceAll("_[a-zA-Z]{3,5}", "");
if (!src.equals("")) {
imageURLs.add(src);
}
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
public static List<URL> getURLsFromPage(URL url) throws IOException {
List<URL> urls = new ArrayList<>();
Document doc = Http.url(url).get();
for (String stringURL : getURLsFromPageStatic(doc)) {
urls.add(new URL(stringURL));
}
return urls;
}
}
|
Pattern p; Matcher m;
p = Pattern.compile("^.*vidble.com/album/([a-zA-Z0-9_\\-]+).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected vidble.com album format: "
+ "vidble.com/album/####"
+ " Got: " + url);
| 467
| 134
| 601
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ViewcomicRipper.java
|
ViewcomicRipper
|
getGID
|
class ViewcomicRipper extends AbstractHTMLRipper {
public ViewcomicRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "view-comic";
}
@Override
public String getDomain() {
return "view-comic.com";
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
String titleText = getFirstPage().select("title").first().text();
String title = titleText.replace("Viewcomic reading comics online for free", "");
title = title.replace("_", "");
title = title.replace("|", "");
title = title.replace("…", "");
title = title.replace(".", "");
return getHost() + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
// "url" is an instance field of the superclass
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element el : doc.select("div.separator > a > img")) {
result.add(el.attr("src"));
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("https?://view-comic.com/([a-zA-Z1-9_-]*)/?$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected view-comic URL format: " +
"view-comic.com/COMIC_NAME - got " + url + " instead");
| 486
| 122
| 608
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/WebtoonsRipper.java
|
WebtoonsRipper
|
getAlbumTitle
|
class WebtoonsRipper extends AbstractHTMLRipper {
private Map<String,String> cookies = new HashMap<String,String>();
public WebtoonsRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "webtoons";
}
@Override
public String getDomain() {
return "www.webtoons.com";
}
@Override
public boolean canRip(URL url) {
Pattern pat = Pattern.compile("https?://www.webtoons.com/[a-zA-Z-_]+/[a-zA-Z_-]+/([a-zA-Z0-9_-]*)/[a-zA-Z0-9_-]+/\\S*");
Matcher mat = pat.matcher(url.toExternalForm());
return mat.matches();
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern pat = Pattern.compile("https?://www.webtoons.com/[a-zA-Z]+/[a-zA-Z]+/([a-zA-Z0-9_-]*)/[a-zA-Z0-9_-]+/\\S*");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return mat.group(1);
}
throw new MalformedURLException("Expected URL format: http://www.webtoons.com/LANG/CAT/TITLE/VOL/, got: " + url);
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element elem : doc.select("div.viewer_img > img")) {
String origUrl = elem.attr("data-url");
String[] finalUrl = origUrl.split("\\?type");
result.add(finalUrl[0]);
}
return result;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
@Override
public Document getFirstPage() throws IOException {
Response resp = Http.url(url).response();
cookies = resp.cookies();
cookies.put("needCOPPA", "false");
cookies.put("needCCPA", "false");
cookies.put("needGDPR", "false");
return Http.url(url).cookies(cookies).get();
}
@Override
public Document getNextPage(Document doc) throws IOException {
// Find next page
String nextUrl = "";
Element elem = doc.select("a.pg_next").first();
nextUrl = elem.attr("href");
if (nextUrl.equals("") || nextUrl.equals("#")) {
throw new IOException("No more pages");
}
return Http.url(nextUrl).get();
}
}
|
Pattern pat = Pattern.compile("https?://www.webtoons.com/[a-zA-Z-_]+/[a-zA-Z_-]+/([a-zA-Z0-9_-]*)/[a-zA-Z0-9_-]+/\\S*");
Matcher mat = pat.matcher(url.toExternalForm());
if (mat.matches()) {
return getHost() + "_" + mat.group(1);
}
return super.getAlbumTitle(url);
| 813
| 139
| 952
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/XcartxRipper.java
|
XcartxRipper
|
getURLsFromPage
|
class XcartxRipper extends AbstractHTMLRipper {
private Map<String,String> cookies = new HashMap<>();
public XcartxRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "xcartx";
}
@Override
public String getDomain() {
return "xcartx.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://xcartx.com/([a-zA-Z0-9_\\-]+).html");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected URL format: http://xcartx.com/comic, got: " + url);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document page) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
@Override
public String getPrefix(int index) {
return String.format("%03d_", index);
}
}
|
List<String> imageURLs = new ArrayList<>();
Elements imageElements = page.select("div.f-desc img");
for (Element image : imageElements) {
String imageUrl = image.attr("data-src");
imageURLs.add("https://" + getDomain() + imageUrl);
}
return imageURLs;
| 387
| 90
| 477
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/XlecxRipper.java
|
XlecxRipper
|
getGID
|
class XlecxRipper extends XcartxRipper {
private Pattern p = Pattern.compile("^https?://xlecx.org/([a-zA-Z0-9_\\-]+).html");
public XlecxRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "xlecx";
}
@Override
public String getDomain() {
return "xlecx.org";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
}
|
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected URL format: http://xlecx.org/comic, got: " + url);
| 193
| 81
| 274
|
<methods>public void <init>(java.net.URL) throws java.io.IOException,public void downloadURL(java.net.URL, int) ,public java.lang.String getDomain() ,public Document getFirstPage() throws java.io.IOException,public java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public java.lang.String getHost() ,public java.lang.String getPrefix(int) ,public List<java.lang.String> getURLsFromPage(Document) <variables>private Map<java.lang.String,java.lang.String> cookies
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/XvideosRipper.java
|
XvideosRipper
|
getGID
|
class XvideosRipper extends AbstractSingleFileRipper {
private static final String HOST = "xvideos";
public XvideosRipper(URL url) throws IOException {
super(url);
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(this.url).get();
}
@Override
public String getHost() {
return HOST;
}
@Override
public String getDomain() {
return HOST + ".com";
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*xvideos\\.com/video[0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return true;
}
p = Pattern.compile("^https?://[wm.]*xvideos\\.com/profiles/[a-zA-Z0-9_-]+/photos/\\d+/[a-zA-Z0-9_-]+$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return true;
}
return false;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> results = new ArrayList<>();
Pattern p = Pattern.compile("^https?://[wm.]*xvideos\\.com/video([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
Elements scripts = doc.select("script");
for (Element e : scripts) {
if (e.html().contains("html5player.setVideoUrlHigh")) {
LOGGER.info("Found the right script");
String[] lines = e.html().split("\n");
for (String line : lines) {
if (line.contains("html5player.setVideoUrlHigh")) {
String videoURL = line.replaceAll("\t", "").replaceAll("html5player.setVideoUrlHigh\\(", "").replaceAll("\'", "").replaceAll("\\);", "");
results.add(videoURL);
}
}
}
}
} else {
for (Element e : doc.select("div.thumb > a")) {
results.add(e.attr("href"));
if (isThisATest()) {
break;
}
}
}
return results;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*xvideos\\.com/profiles/([a-zA-Z0-9_-]+)/photos/(\\d+)/([a-zA-Z0-9_-]+)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return getHost() + "_" + m.group(1) + "_" + m.group(3) + "_" + m.group(2);
} else {
return super.getAlbumTitle(url);
}
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*xvideos\\.com/video([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
p = Pattern.compile("^https?://[wm.]*xvideos\\.com/profiles/[a-zA-Z0-9_-]+/photos/(\\d+)/[a-zA-Z0-9_-]+$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected xvideo format:"
+ "xvideos.com/video####"
+ " Got: " + url);
| 906
| 222
| 1,128
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/YoupornRipper.java
|
YoupornRipper
|
getURLsFromPage
|
class YoupornRipper extends AbstractSingleFileRipper {
public YoupornRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "youporn";
}
@Override
public String getDomain() {
return "youporn.com";
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*youporn\\.com/watch/[0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(this.url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*youporn\\.com/watch/([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected youporn format:"
+ "youporn.com/watch/####"
+ " Got: " + url);
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> results = new ArrayList<>();
Elements videos = doc.select("video");
Element video = videos.get(0);
results.add(video.attr("src"));
return results;
| 427
| 56
| 483
|
<methods>public int getCompletionPercentage() ,public java.lang.String getStatusText() ,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public boolean useByteProgessBar() <variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/YuvutuRipper.java
|
YuvutuRipper
|
getURLsFromPage
|
class YuvutuRipper extends AbstractHTMLRipper {
private static final String DOMAIN = "yuvutu.com",
HOST = "yuvutu";
public YuvutuRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public String getDomain() {
return DOMAIN;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^http://www\\.yuvutu\\.com/modules\\.php\\?name=YuGallery&action=view&set_id=([0-9]+)$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^http://www\\.yuvutu\\.com/modules\\.php\\?name=YuGallery&action=view&set_id=([0-9]+)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected yuvutu.com URL format: " +
"yuvutu.com/modules.php?name=YuGallery&action=view&set_id=albumid - got " + url + "instead");
}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {<FILL_FUNCTION_BODY>}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
List<String> imageURLs = new ArrayList<>();
for (Element thumb : doc.select("div#galleria > a > img")) {
String image = thumb.attr("src");
imageURLs.add(image);
}
return imageURLs;
| 501
| 69
| 570
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ZizkiRipper.java
|
ZizkiRipper
|
getGID
|
class ZizkiRipper extends AbstractHTMLRipper {
private Document albumDoc = null;
private Map<String,String> cookies = new HashMap<>();
public ZizkiRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "zizki";
}
@Override
public String getDomain() {
return "zizki.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
Element titleElement = getFirstPage().select("h1.title").first();
String title = titleElement.text();
Element authorSpan = getFirstPage().select("span[class=creator]").first();
String author = authorSpan.select("a").first().text();
LOGGER.debug("Author: " + author);
return getHost() + "_" + author + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
Response resp = Http.url(url).response();
cookies.putAll(resp.cookies());
albumDoc = resp.parse();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> imageURLs = new ArrayList<>();
// Page contains images
LOGGER.info("Look for images.");
for (Element thumb : page.select("img")) {
if (super.isStopped()) break;
// Find thumbnail image source
String image = null;
String img_type = null;
String src = null;
if (thumb.hasAttr("typeof")) {
img_type = thumb.attr("typeof");
if (img_type.equals("foaf:Image")) {
LOGGER.debug("Found image with " + img_type);
if (thumb.parent() != null &&
thumb.parent().parent() != null &&
thumb.parent().parent().attr("class") != null &&
thumb.parent().parent().attr("class").equals("aimage-center")
)
{
src = thumb.attr("src");
LOGGER.debug("Found url with " + src);
if (!src.contains("zizki.com")) {
} else {
imageURLs.add(src.replace("/styles/medium/public/","/styles/large/public/"));
}
}
}
}
}
return imageURLs;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
@Override
public String getPrefix(int index) {
return String.format("%03d_", index);
}
}
|
Pattern p = Pattern.compile("^https?://(www\\.)?zizki\\.com/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (!m.matches()) {
throw new MalformedURLException("Expected URL format: http://www.zizki.com/author/albumname, got: " + url);
}
return m.group(m.groupCount());
| 826
| 126
| 952
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/tamindirmp3.java
|
tamindirmp3
|
getGID
|
class tamindirmp3 extends AbstractHTMLRipper {
public tamindirmp3(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return "tamindir";
}
@Override
public String getDomain() {
return "tamindir.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public Document getFirstPage() throws IOException {
return Http.url(url).get();
}
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> music = new ArrayList<>();
for (Element el : doc.select("mp3")) {
music.add(el.attr("src"));
}
return music;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
}
}
|
Pattern p = Pattern.compile("^https?://[server48.]*tamindir\\.com/files/([a-zA-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException("Expected tamindir.com URL format: " +
"tamindir.com/files/albumid - got " + url + "instead");
| 266
| 134
| 400
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean canRip(java.net.URL) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public int getCompletionPercentage() ,public int getCount() ,public abstract java.lang.String getHost() ,public Document getNextPage(Document) throws java.io.IOException,public java.lang.String getStatusText() ,public void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public boolean saveText(java.net.URL, java.lang.String, java.lang.String, int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private Map<java.net.URL,java.io.File> itemsCompleted,private Map<java.net.URL,java.lang.String> itemsErrored,private Map<java.net.URL,java.io.File> itemsPending
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/CliphunterRipper.java
|
CliphunterRipper
|
canRip
|
class CliphunterRipper extends VideoRipper {
private static final String HOST = "cliphunter";
private static final String decryptString="{'$':':','&':'.','(':'=','-':'-','_':'_','^':'&','a':'h','c':'c','b':'b','e':'v','d':'e','g':'f','f':'o','i':'d','m':'a','l':'n','n':'m','q':'t','p':'u','r':'s','w':'w','v':'p','y':'l','x':'r','z':'i','=':'/','?':'?'}";
private static final JSONObject decryptDict = new JSONObject(decryptString);
public CliphunterRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {<FILL_FUNCTION_BODY>}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*cliphunter\\.com/w/([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected cliphunter format:"
+ "cliphunter.com/w/####..."
+ " Got: " + url);
}
@Override
public void rip() throws IOException {
LOGGER.info("Retrieving " + this.url);
String html = Http.url(url).get().html();
String jsonString = html.substring(html.indexOf("var flashVars = {d: '") + 21);
jsonString = jsonString.substring(0, jsonString.indexOf("'"));
JSONObject json = new JSONObject(new String(Base64.decode(jsonString)));
JSONObject jsonURL = new JSONObject(new String(Base64.decode(json.getString("url"))));
String encryptedURL = jsonURL.getJSONObject("u").getString("l");
String vidURL = "";
for (char c : encryptedURL.toCharArray()) {
if (decryptDict.has(Character.toString(c))) {
vidURL += decryptDict.getString(Character.toString(c));
}
else {
vidURL += c;
}
}
addURLToDownload(new URL(vidURL), HOST + "_" + getGID(this.url));
waitForThreads();
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*cliphunter\\.com/w/[0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
| 727
| 66
| 793
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/MotherlessVideoRipper.java
|
MotherlessVideoRipper
|
getGID
|
class MotherlessVideoRipper extends VideoRipper {
private static final String HOST = "motherless";
public MotherlessVideoRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*motherless\\.com/[A-Z0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public void rip() throws IOException {
LOGGER.info(" Retrieving " + this.url);
String html = Http.url(this.url).get().toString();
if (html.contains("__fileurl = '")) {
LOGGER.error("WTF");
}
List<String> vidUrls = Utils.between(html, "__fileurl = '", "';");
if (vidUrls.isEmpty()) {
throw new IOException("Could not find video URL at " + url);
}
String vidUrl = vidUrls.get(0);
addURLToDownload(new URL(vidUrl), HOST + "_" + getGID(this.url));
waitForThreads();
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*motherless\\.com/([A-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected motherless format:"
+ "motherless.com/####"
+ " Got: " + url);
| 413
| 120
| 533
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/PornhubRipper.java
|
PornhubRipper
|
rip
|
class PornhubRipper extends VideoRipper {
private static final String HOST = "pornhub";
public PornhubRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*pornhub\\.com/view_video.php\\?viewkey=[a-z0-9]+$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*pornhub\\.com/view_video.php\\?viewkey=([a-z0-9]+)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected pornhub format:"
+ "pornhub.com/view_video.php?viewkey=####"
+ " Got: " + url);
}
@Override
public void rip() throws IOException {<FILL_FUNCTION_BODY>}
}
|
String vidUrl = "";
LOGGER.info(" Retrieving " + this.url.toExternalForm());
Document doc = Http.url(this.url).get();
String html = doc.body().html();
html = StringEscapeUtils.unescapeJavaScript(html);
html = html.substring(html.indexOf("var ra"));
html = html.substring(0, html.indexOf('\n'));
html = html.replaceAll("\\/\\*([\\S\\s]+?)\\*\\/", ""); // Delete JS comments from the String
String varName;
String varValue;
int nextEqual;
int nextSemicolonSpace;
HashMap<String, String> vars = new HashMap<>();
HashMap<String, String> qualityMap = new HashMap<>();
ArrayList<String> urlArray = new ArrayList<>();
for (int i = 0; i < 4; i++) { // Max. 4 loops for 240p, 480p, 720p, 1080p
// Put every of the (unsorted) variables with their corresponding values in a HashMap
while (html.startsWith("var ra")) {
nextEqual = html.indexOf('=');
nextSemicolonSpace = html.indexOf(';');
varName = html.substring(4,nextEqual);
varValue = html.substring(nextEqual + 1, nextSemicolonSpace);
// Remove """ and " + " from varValue
varValue = varValue.replaceAll("\"", "");
varValue = varValue.replaceAll(" \\+ ", "");
vars.put(varName, varValue);
html = html.substring(nextSemicolonSpace + 1);
}
// put every variable's name in an ArrayList
if (html.startsWith("var quality")) {
int next = 3;
nextEqual = html.indexOf('=');
urlArray.add(html.substring(12, nextEqual - 1)); // Get numeric value of the video's resolution to compare it later
html = html.substring(nextEqual + 1);
while (html.startsWith("ra")) {
nextSemicolonSpace = html.indexOf(' ');
if (nextSemicolonSpace > html.indexOf(';')) {
nextSemicolonSpace = html.indexOf(';');
next = 1;
}
varName = html.substring(0, nextSemicolonSpace);
urlArray.add(varName);
html = html.substring(nextSemicolonSpace + next);
}
}
// Put together vidURL by matching the variable's names with the corresponding value from the vars-Map
for (int k = 1; k < urlArray.size(); k++) {
varName = urlArray.get(k);
Iterator<Map.Entry<String, String>> iterator = vars.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (varName.equals(entry.getKey())) {
vidUrl = vidUrl + entry.getValue();
iterator.remove();
break;
}
}
}
qualityMap.put(urlArray.get(0), vidUrl);
vidUrl = ""; // Delete content of vidURL
urlArray.clear();
// Delete "flashvars" because it's not needed
if (html.startsWith("flashvars")) {
nextSemicolonSpace = html.indexOf(';');
html = html.substring(nextSemicolonSpace + 1);
}
}
// Get URL of highest quality version
int bestQuality = 0;
int currentQuality;
for (Map.Entry<String, String> entry : qualityMap.entrySet()) {
currentQuality = Integer.parseInt(entry.getKey());
if (currentQuality > bestQuality) {
bestQuality = currentQuality;
vidUrl = entry.getValue();
}
}
if (vidUrl.equals("")) {
throw new IOException("Unable to find encrypted video URL at " + this.url);
}
addURLToDownload(new URL(vidUrl), HOST + "_" + bestQuality + "p_" + getGID(this.url));
waitForThreads();
| 397
| 1,096
| 1,493
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/StickyXXXRipper.java
|
StickyXXXRipper
|
getGID
|
class StickyXXXRipper extends VideoRipper {
private static final String HOST = "stickyxxx";
public StickyXXXRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://.*stickyxxx\\.com(/)(.*)/$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public void rip() throws IOException {
LOGGER.info("Retrieving " + this.url);
Document doc = Http.url(url).get();
Elements videos = doc.select(".wp-video > video > source");
if (videos.isEmpty()) {
throw new IOException("Could not find Embed code at " + url);
}
String vidUrl = videos.attr("src");
addURLToDownload(new URL(vidUrl), HOST + "_" + getGID(this.url));
waitForThreads();
}
}
|
Pattern p = Pattern.compile("^https?://.*stickyxxx\\.com(/)(.*)/$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(2);
}
throw new MalformedURLException(
"Expected stickyxxx format:"
+ "stickyxxx.com/####"
+ " Got: " + url);
| 360
| 111
| 471
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/TwitchVideoRipper.java
|
TwitchVideoRipper
|
rip
|
class TwitchVideoRipper extends VideoRipper {
private static final String HOST = "twitch";
public TwitchVideoRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https://clips\\.twitch\\.tv/.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https://clips\\.twitch\\.tv/(.*)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(m.groupCount());
}
throw new MalformedURLException(
"Expected Twitch.tv format:"
+ "https://clips.twitch.tv/####"
+ " Got: " + url);
}
@Override
public void rip() throws IOException {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Retrieving " + this.url);
Document doc = Http.url(url).get();
//Get user friendly filename from page title
String title = doc.title();
Elements script = doc.select("script");
if (script.isEmpty()) {
throw new IOException("Could not find script code at " + url);
}
//Regex assumes highest quality source is listed first
Pattern p = Pattern.compile("\"source\":\"(.*?)\"");
for (Element element : script) {
Matcher m = p.matcher(element.data());
if (m.find()){
String vidUrl = m.group(1);
addURLToDownload(new URL(vidUrl), HOST + "_" + title);
}
}
waitForThreads();
| 389
| 234
| 623
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/ViddmeRipper.java
|
ViddmeRipper
|
getGID
|
class ViddmeRipper extends VideoRipper {
private static final String HOST = "vid";
public ViddmeRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*vid\\.me/[a-zA-Z0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>}
@Override
public void rip() throws IOException {
LOGGER.info(" Retrieving " + this.url.toExternalForm());
Document doc = Http.url(this.url).get();
Elements videos = doc.select("meta[name=twitter:player:stream]");
if (videos.isEmpty()) {
throw new IOException("Could not find twitter:player:stream at " + url);
}
String vidUrl = videos.first().attr("content");
vidUrl = vidUrl.replaceAll("&", "&");
addURLToDownload(new URL(vidUrl), HOST + "_" + getGID(this.url));
waitForThreads();
}
}
|
Pattern p = Pattern.compile("^https?://[wm.]*vid\\.me/([a-zA-Z0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected vid.me format:"
+ "vid.me/id"
+ " Got: " + url);
| 403
| 123
| 526
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/VidearnRipper.java
|
VidearnRipper
|
rip
|
class VidearnRipper extends VideoRipper {
private static final String HOST = "videarn";
public VidearnRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*videarn\\.com/[a-zA-Z0-9\\-]+/([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*videarn\\.com/[a-zA-Z0-9\\-]+/([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected videarn format:"
+ "videarn.com/.../####-..."
+ " Got: " + url);
}
@Override
public void rip() throws IOException {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Retrieving " + this.url);
Document doc = Http.url(url).get();
List<String> mp4s = Utils.between(doc.html(), "file:\"", "\"");
if (mp4s.isEmpty()) {
throw new IOException("Could not find files at " + url);
}
String vidUrl = mp4s.get(0);
addURLToDownload(new URL(vidUrl), HOST + "_" + getGID(this.url));
waitForThreads();
| 393
| 137
| 530
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/VkRipper.java
|
VkRipper
|
getVideoURLAtPage
|
class VkRipper extends VideoRipper {
private static final String HOST = "vk";
public VkRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^https?://[wm.]*vk\\.com/video[0-9]+.*$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://[wm.]*vk\\.com/video([0-9]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected vk video URL format:"
+ "vk.com/videos####"
+ " Got: " + url);
}
@Override
public void rip() throws IOException {
LOGGER.info(" Retrieving " + this.url);
String videoURL = getVideoURLAtPage(this.url.toExternalForm());
addURLToDownload(new URL(videoURL), HOST + "_" + getGID(this.url));
waitForThreads();
}
public static String getVideoURLAtPage(String url) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Document doc = Http.url(url)
.userAgent(USER_AGENT)
.get();
String html = doc.outerHtml();
String videoURL = null;
for (String quality : new String[] {"1080", "720", "480", "240"}) {
quality = "url" + quality + "\\\":\\\"";
if (html.contains(quality)) {
videoURL = html.substring(html.indexOf(quality) + quality.length());
videoURL = videoURL.substring(0, videoURL.indexOf("\""));
videoURL = videoURL.replace("\\", "");
break;
}
}
if (videoURL == null) {
throw new IOException("Could not find video URL at " + url);
}
return videoURL;
| 448
| 209
| 657
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/video/YuvutuRipper.java
|
YuvutuRipper
|
rip
|
class YuvutuRipper extends VideoRipper {
private static final String HOST = "yuvutu";
public YuvutuRipper(URL url) throws IOException {
super(url);
}
@Override
public String getHost() {
return HOST;
}
@Override
public boolean canRip(URL url) {
Pattern p = Pattern.compile("^http://www\\.yuvutu\\.com/video/[0-9]+/(.*)$");
Matcher m = p.matcher(url.toExternalForm());
return m.matches();
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^http://www\\.yuvutu\\.com/video/[0-9]+/(.*)$");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
return m.group(1);
}
throw new MalformedURLException(
"Expected yuvutu format:"
+ "yuvutu.com/video/####"
+ " Got: " + url);
}
@Override
public void rip() throws IOException {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Retrieving " + this.url);
Document doc = Http.url(url).get();
Element iframe = doc.select("iframe").first();
String iframeSrc = iframe.attr("src");
if (iframeSrc != null) {
doc = Http.url("http://www.yuvutu.com" + iframeSrc).get();
} else {
throw new IOException("Could not find iframe code at " + url);
}
Elements script = doc.select("script");
if (script.isEmpty()) {
throw new IOException("Could not find script code at " + url);
}
Pattern p = Pattern.compile("file: \"(.*?)\"");
for (Element element : script) {
Matcher m = p.matcher(element.data());
if (m.find()){
String vidUrl = m.group(1);
addURLToDownload(new URL(vidUrl), HOST + "_" + getGID(this.url));
}
}
waitForThreads();
| 369
| 276
| 645
|
<methods>public boolean addURLToDownload(java.net.URL, java.io.File) ,public boolean addURLToDownload(java.net.URL, java.io.File, java.lang.String, Map<java.lang.String,java.lang.String>, java.lang.Boolean) ,public void downloadCompleted(java.net.URL, java.io.File) ,public void downloadErrored(java.net.URL, java.lang.String) ,public void downloadExists(java.net.URL, java.io.File) ,public java.lang.String getAlbumTitle(java.net.URL) ,public int getCompletionPercentage() ,public abstract java.lang.String getGID(java.net.URL) throws java.net.MalformedURLException,public abstract java.lang.String getHost() ,public java.lang.String getStatusText() ,public abstract void rip() throws java.io.IOException,public java.net.URL sanitizeURL(java.net.URL) throws java.net.MalformedURLException,public void setBytesCompleted(int) ,public void setBytesTotal(int) ,public void setWorkingDir(java.net.URL) throws java.io.IOException<variables>private int bytesCompleted,private int bytesTotal
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/ClipboardUtils.java
|
ClipboardUtils
|
setClipboardAutoRip
|
class ClipboardUtils {
private static AutoripThread autoripThread = new AutoripThread();
public static void setClipboardAutoRip(boolean enabled) {<FILL_FUNCTION_BODY>}
public static boolean getClipboardAutoRip() {
return autoripThread.isRunning;
}
public static String getClipboardString() {
try {
return (String) Toolkit
.getDefaultToolkit()
.getSystemClipboard()
.getData(DataFlavor.stringFlavor);
} catch (IllegalStateException e) {
e.printStackTrace();
logger.error("Caught and recovered from IllegalStateException: " + e.getMessage());
} catch (HeadlessException | IOException | UnsupportedFlavorException e) {
e.printStackTrace();
}
return null;
}
}
|
if (enabled) {
autoripThread.kill();
autoripThread = new AutoripThread();
autoripThread.isRunning = true;
autoripThread.start();
} else {
autoripThread.kill();
}
| 219
| 65
| 284
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/ContextMenuMouseListener.java
|
ContextMenuMouseListener
|
mouseClicked
|
class ContextMenuMouseListener extends MouseAdapter {
private JPopupMenu popup = new JPopupMenu();
private Action cutAction;
private Action copyAction;
private Action pasteAction;
private Action undoAction;
private Action selectAllAction;
private JTextComponent textComponent;
private String savedString = "";
private Actions lastActionSelected;
private enum Actions { UNDO, CUT, COPY, PASTE, SELECT_ALL }
@SuppressWarnings("serial")
public ContextMenuMouseListener() {
undoAction = new AbstractAction("Undo") {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.setText("");
textComponent.replaceSelection(savedString);
lastActionSelected = Actions.UNDO;
}
};
popup.add(undoAction);
popup.addSeparator();
cutAction = new AbstractAction("Cut") {
@Override
public void actionPerformed(ActionEvent ae) {
lastActionSelected = Actions.CUT;
savedString = textComponent.getText();
textComponent.cut();
}
};
popup.add(cutAction);
copyAction = new AbstractAction("Copy") {
@Override
public void actionPerformed(ActionEvent ae) {
lastActionSelected = Actions.COPY;
textComponent.copy();
}
};
popup.add(copyAction);
pasteAction = new AbstractAction("Paste") {
@Override
public void actionPerformed(ActionEvent ae) {
lastActionSelected = Actions.PASTE;
savedString = textComponent.getText();
textComponent.paste();
}
};
popup.add(pasteAction);
popup.addSeparator();
selectAllAction = new AbstractAction("Select All") {
@Override
public void actionPerformed(ActionEvent ae) {
lastActionSelected = Actions.SELECT_ALL;
textComponent.selectAll();
}
};
popup.add(selectAllAction);
}
@Override
public void mouseClicked(MouseEvent e) {<FILL_FUNCTION_BODY>}
}
|
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JTextComponent)) {
return;
}
textComponent = (JTextComponent) e.getSource();
textComponent.requestFocus();
boolean enabled = textComponent.isEnabled();
boolean editable = textComponent.isEditable();
boolean nonempty = !(textComponent.getText() == null || textComponent.getText().equals(""));
boolean marked = textComponent.getSelectedText() != null;
boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);
undoAction.setEnabled(enabled && editable && (lastActionSelected == Actions.CUT || lastActionSelected == Actions.PASTE));
cutAction.setEnabled(enabled && editable && marked);
copyAction.setEnabled(enabled && marked);
pasteAction.setEnabled(enabled && editable && pasteAvailable);
selectAllAction.setEnabled(enabled && nonempty);
int nx = e.getX();
if (nx > 500) {
nx = nx - popup.getSize().width;
}
popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
}
| 575
| 350
| 925
|
<methods>public void mouseClicked(java.awt.event.MouseEvent) ,public void mouseDragged(java.awt.event.MouseEvent) ,public void mouseEntered(java.awt.event.MouseEvent) ,public void mouseExited(java.awt.event.MouseEvent) ,public void mouseMoved(java.awt.event.MouseEvent) ,public void mousePressed(java.awt.event.MouseEvent) ,public void mouseReleased(java.awt.event.MouseEvent) ,public void mouseWheelMoved(java.awt.event.MouseWheelEvent) <variables>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/History.java
|
History
|
fromFile
|
class History {
private final List<HistoryEntry> list;
private static final String[] COLUMNS = new String[] {
"URL",
"created",
"modified",
"#",
""
};
public History() {
this.list = new ArrayList<>();
}
public void add(HistoryEntry entry) {
list.add(entry);
}
public void remove(HistoryEntry entry) {
list.remove(entry);
}
public void remove(int index) {
list.remove(index);
}
public void clear() {
list.clear();
}
public HistoryEntry get(int index) {
return list.get(index);
}
public String getColumnName(int index) {
return COLUMNS[index];
}
public int getColumnCount() {
return COLUMNS.length;
}
public Object getValueAt(int row, int col) {
HistoryEntry entry = this.list.get(row);
switch (col) {
case 0:
return entry.url;
case 1:
return dateToHumanReadable(entry.startDate);
case 2:
return dateToHumanReadable(entry.modifiedDate);
case 3:
return entry.count;
case 4:
return entry.selected;
default:
return null;
}
}
private String dateToHumanReadable(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
return sdf.format(date);
}
public boolean containsURL(String url) {
for (HistoryEntry entry : this.list) {
if (entry.url.equals(url)) {
return true;
}
}
return false;
}
public HistoryEntry getEntryByURL(String url) {
for (HistoryEntry entry : this.list) {
if (entry.url.equals(url)) {
return entry;
}
}
throw new RuntimeException("Could not find URL " + url + " in History");
}
private void fromJSON(JSONArray jsonArray) {
JSONObject json;
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
list.add(new HistoryEntry().fromJSON(json));
}
}
public void fromFile(String filename) throws IOException {<FILL_FUNCTION_BODY>}
public void fromList(List<String> stringList) {
for (String item : stringList) {
HistoryEntry entry = new HistoryEntry();
entry.url = item;
list.add(entry);
}
}
private JSONArray toJSON() {
JSONArray jsonArray = new JSONArray();
for (HistoryEntry entry : list) {
jsonArray.put(entry.toJSON());
}
return jsonArray;
}
public List<HistoryEntry> toList() {
return list;
}
public boolean isEmpty() {
return list.isEmpty();
}
public void toFile(String filename) throws IOException {
try (OutputStream os = new FileOutputStream(filename)) {
IOUtils.write(toJSON().toString(2), os);
}
}
}
|
try (InputStream is = new FileInputStream(filename)) {
String jsonString = IOUtils.toString(is);
JSONArray jsonArray = new JSONArray(jsonString);
fromJSON(jsonArray);
} catch (JSONException e) {
throw new IOException("Failed to load JSON file " + filename + ": " + e.getMessage(), e);
}
| 845
| 90
| 935
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/HistoryEntry.java
|
HistoryEntry
|
fromJSON
|
class HistoryEntry {
public String url = "",
title = "",
dir = "";
public int count = 0;
public Date startDate = new Date(),
modifiedDate = new Date();
public boolean selected = false;
public HistoryEntry() {
}
public HistoryEntry fromJSON(JSONObject json) {<FILL_FUNCTION_BODY>}
public JSONObject toJSON() {
JSONObject json = new JSONObject();
json.put("url", this.url);
json.put("startDate", this.startDate.getTime());
json.put("modifiedDate", this.modifiedDate.getTime());
json.put("title", this.title);
json.put("count", this.count);
json.put("selected", this.selected);
return json;
}
@Override
public String toString() {
return this.url;
}
}
|
this.url = json.getString("url");
this.startDate = new Date(json.getLong("startDate"));
this.modifiedDate = new Date(json.getLong("modifiedDate"));
if (json.has("title")) {
this.title = json.getString("title");
}
if (json.has("count")) {
this.count = json.getInt("count");
}
if (json.has("dir")) {
this.dir = json.getString("dir");
}
if (json.has("selected")) {
this.selected = json.getBoolean("selected");
}
return this;
| 244
| 166
| 410
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/HistoryMenuMouseListener.java
|
HistoryMenuMouseListener
|
actionPerformed
|
class HistoryMenuMouseListener extends MouseAdapter {
private JPopupMenu popup = new JPopupMenu();
private JTable tableComponent;
@SuppressWarnings("serial")
public HistoryMenuMouseListener() {
Action checkAllAction = new AbstractAction(Utils.getLocalizedString("history.check.all")) {
@Override
public void actionPerformed(ActionEvent ae) {
for (int row = 0; row < tableComponent.getRowCount(); row++) {
tableComponent.setValueAt(true, row, 4);
}
}
};
popup.add(checkAllAction);
Action uncheckAllAction = new AbstractAction(Utils.getLocalizedString("history.check.none")) {
@Override
public void actionPerformed(ActionEvent ae) {
for (int row = 0; row < tableComponent.getRowCount(); row++) {
tableComponent.setValueAt(false, row, 4);
}
}
};
popup.add(uncheckAllAction);
popup.addSeparator();
Action checkSelected = new AbstractAction(Utils.getLocalizedString("history.check.selected")) {
@Override
public void actionPerformed(ActionEvent ae) {<FILL_FUNCTION_BODY>}
};
popup.add(checkSelected);
Action uncheckSelected = new AbstractAction(Utils.getLocalizedString("history.uncheck.selected")) {
@Override
public void actionPerformed(ActionEvent ae) {
for (int row : tableComponent.getSelectedRows()) {
tableComponent.setValueAt(false, row, 4);
}
}
};
popup.add(uncheckSelected);
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JTable)) {
return;
}
tableComponent = (JTable) e.getSource();
tableComponent.requestFocus();
int nx = e.getX();
if (nx > 500) {
nx = nx - popup.getSize().width;
}
popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
}
}
}
|
for (int row : tableComponent.getSelectedRows()) {
tableComponent.setValueAt(true, row, 4);
}
| 604
| 37
| 641
|
<methods>public void mouseClicked(java.awt.event.MouseEvent) ,public void mouseDragged(java.awt.event.MouseEvent) ,public void mouseEntered(java.awt.event.MouseEvent) ,public void mouseExited(java.awt.event.MouseEvent) ,public void mouseMoved(java.awt.event.MouseEvent) ,public void mousePressed(java.awt.event.MouseEvent) ,public void mouseReleased(java.awt.event.MouseEvent) ,public void mouseWheelMoved(java.awt.event.MouseWheelEvent) <variables>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/MainWindow.java
|
StatusEvent
|
handleEvent
|
class StatusEvent implements Runnable {
private final AbstractRipper ripper;
private final RipStatusMessage msg;
StatusEvent(AbstractRipper ripper, RipStatusMessage msg) {
this.ripper = ripper;
this.msg = msg;
}
public void run() {
handleEvent(this);
}
}
private synchronized void handleEvent(StatusEvent evt) {<FILL_FUNCTION_BODY>
|
if (ripper.isStopped()) {
return;
}
RipStatusMessage msg = evt.msg;
int completedPercent = evt.ripper.getCompletionPercentage();
statusProgress.setValue(completedPercent);
statusProgress.setVisible(true);
status(evt.ripper.getStatusText());
switch (msg.getStatus()) {
case LOADING_RESOURCE:
case DOWNLOAD_STARTED:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("Downloading " + msg.getObject(), Color.BLACK);
}
break;
case DOWNLOAD_COMPLETE:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("Downloaded " + msg.getObject(), Color.GREEN);
}
break;
case DOWNLOAD_COMPLETE_HISTORY:
if (LOGGER.isEnabledFor(Level.INFO)) {
appendLog("" + msg.getObject(), Color.GREEN);
}
break;
case DOWNLOAD_ERRORED:
if (LOGGER.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
break;
case DOWNLOAD_WARN:
if (LOGGER.isEnabledFor(Level.WARN)) {
appendLog((String) msg.getObject(), Color.ORANGE);
}
break;
case RIP_ERRORED:
if (LOGGER.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(false);
pack();
statusWithColor("Error: " + msg.getObject(), Color.RED);
break;
case RIP_COMPLETE:
RipStatusComplete rsc = (RipStatusComplete) msg.getObject();
String url = ripper.getURL().toExternalForm();
if (HISTORY.containsURL(url)) {
// TODO update "modifiedDate" of entry in HISTORY
HistoryEntry entry = HISTORY.getEntryByURL(url);
entry.count = rsc.count;
entry.modifiedDate = new Date();
} else {
HistoryEntry entry = new HistoryEntry();
entry.url = url;
entry.dir = rsc.getDir();
entry.count = rsc.count;
try {
entry.title = ripper.getAlbumTitle(ripper.getURL());
} catch (MalformedURLException e) {
}
HISTORY.add(entry);
historyTableModel.fireTableDataChanged();
}
if (configPlaySound.isSelected()) {
Utils.playSound("camera.wav");
}
saveHistory();
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(true);
File f = rsc.dir;
String prettyFile = Utils.shortenPath(f);
openButton.setText(Utils.getLocalizedString("open") + prettyFile);
mainFrame.setTitle("RipMe v" + UpdateUtils.getThisJarVersion());
try {
Image folderIcon = ImageIO.read(getClass().getClassLoader().getResource("folder.png"));
openButton.setIcon(new ImageIcon(folderIcon));
} catch (Exception e) {
}
/*
* content key %path% the path to the album folder %url% is the album url
*
*
*/
if (Utils.getConfigBoolean("enable.finish.command", false)) {
try {
String commandToRun = Utils.getConfigString("finish.command", "ls");
commandToRun = commandToRun.replaceAll("%url%", url);
commandToRun = commandToRun.replaceAll("%path%", f.getAbsolutePath());
LOGGER.info("RUnning command " + commandToRun);
// code from:
// https://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program
Process proc = Runtime.getRuntime().exec(commandToRun);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
LOGGER.info("Command output:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
LOGGER.info(s);
}
// read any errors from the attempted command
LOGGER.error("Command error:\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
LOGGER.error("Was unable to run command \"" + Utils.getConfigString("finish.command", "ls"));
LOGGER.error(e.getStackTrace());
}
}
appendLog("Rip complete, saved to " + f.getAbsolutePath(), Color.GREEN);
openButton.setActionCommand(f.toString());
openButton.addActionListener(event -> {
try {
Desktop.getDesktop().open(new File(event.getActionCommand()));
} catch (Exception e) {
LOGGER.error(e);
}
});
pack();
ripNextAlbum();
break;
case COMPLETED_BYTES:
// Update completed bytes
break;
case TOTAL_BYTES:
// Update total bytes
break;
case NO_ALBUM_OR_USER:
if (LOGGER.isEnabledFor(Level.ERROR)) {
appendLog((String) msg.getObject(), Color.RED);
}
stopButton.setEnabled(false);
statusProgress.setValue(0);
statusProgress.setVisible(false);
openButton.setVisible(false);
pack();
statusWithColor("Error: " + msg.getObject(), Color.RED);
break;
}
| 117
| 1,605
| 1,722
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/QueueMenuMouseListener.java
|
QueueMenuMouseListener
|
updateUI
|
class QueueMenuMouseListener extends MouseAdapter {
private JPopupMenu popup = new JPopupMenu();
private JList<Object> queueList;
private DefaultListModel<Object> queueListModel;
private Consumer<DefaultListModel<Object>> updateQueue;
public QueueMenuMouseListener(Consumer<DefaultListModel<Object>> updateQueue) {
this.updateQueue = updateQueue;
updateUI();
}
@SuppressWarnings("serial")
public void updateUI() {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JList)) {
return;
}
queueList = (JList<Object>) e.getSource();
queueListModel = (DefaultListModel<Object>) queueList.getModel();
queueList.requestFocus();
int nx = e.getX();
if (nx > 500) {
nx = nx - popup.getSize().width;
}
popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
}
}
}
|
popup.removeAll();
Action removeSelected = new AbstractAction(Utils.getLocalizedString("queue.remove.selected")) {
@Override
public void actionPerformed(ActionEvent ae) {
Object o = queueList.getSelectedValue();
while (o != null) {
queueListModel.removeElement(o);
o = queueList.getSelectedValue();
}
updateUI();
}
};
popup.add(removeSelected);
Action clearQueue = new AbstractAction(Utils.getLocalizedString("queue.remove.all")) {
@Override
public void actionPerformed(ActionEvent ae) {
if (JOptionPane.showConfirmDialog(null, Utils.getLocalizedString("queue.validation"), "RipMe",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
queueListModel.removeAllElements();
updateUI();
}
}
};
popup.add(clearQueue);
updateQueue.accept(queueListModel);
| 339
| 269
| 608
|
<methods>public void mouseClicked(java.awt.event.MouseEvent) ,public void mouseDragged(java.awt.event.MouseEvent) ,public void mouseEntered(java.awt.event.MouseEvent) ,public void mouseExited(java.awt.event.MouseEvent) ,public void mouseMoved(java.awt.event.MouseEvent) ,public void mousePressed(java.awt.event.MouseEvent) ,public void mouseReleased(java.awt.event.MouseEvent) ,public void mouseWheelMoved(java.awt.event.MouseWheelEvent) <variables>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ui/RipStatusComplete.java
|
RipStatusComplete
|
getDir
|
class RipStatusComplete {
File dir = null;
int count = 0;
public RipStatusComplete(File dir) {
this.dir = dir;
this.count = 1;
}
public RipStatusComplete(File dir, int count) {
this.dir = dir;
this.count = count;
}
public String getDir() {<FILL_FUNCTION_BODY>}
}
|
String result;
try {
result = this.dir.getCanonicalPath();
} catch (IOException e) {
result = this.dir.toString();
}
return result;
| 108
| 52
| 160
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/utils/Base64.java
|
Base64
|
decode
|
class Base64 {
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static int[] toInt = new int[128];
static {
for (int i = 0; i < ALPHABET.length; i++) {
toInt[ALPHABET[i]] = i;
}
}
private Base64() {
}
/**
* Translates the specified byte array into Base64 string.
*
* @param buf the byte array (not null)
* @return the translated Base64 string (not null)
*/
public static String encode(byte[] buf) {
int size = buf.length;
char[] ar = new char[((size + 2) / 3) * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = (i < size) ? buf[i++] : 0;
byte b2 = (i < size) ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
if (size % 3 == 1 || size % 3 == 2) {
ar[--a] = '=';
}
return new String(ar);
}
/**
* Translates the specified Base64 string into a byte array.
*
* @param s the Base64 string (not null)
* @return the byte array (not null)
*/
public static byte[] decode(String s) {<FILL_FUNCTION_BODY>}
}
|
int delta = s.endsWith("==") ? 2 : (s.endsWith("=") ? 1 : 0);
byte[] buffer = new byte[s.length() * 3 / 4 - delta];
int mask = 0xFF;
int index = 0;
for (int i = 0; i < s.length(); i += 4) {
int c0 = toInt[s.charAt(i)];
int c1 = toInt[s.charAt(i + 1)];
buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask);
if (index >= buffer.length) {
return buffer;
}
int c2 = toInt[s.charAt(i + 2)];
buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask);
if (index >= buffer.length) {
return buffer;
}
int c3 = toInt[s.charAt(i + 3)];
buffer[index++] = (byte) (((c2 << 6) | c3) & mask);
}
return buffer;
| 573
| 299
| 872
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/utils/Http.java
|
Http
|
cookiesForURL
|
class Http {
private static final int TIMEOUT = Utils.getConfigInteger("page.timeout", 5 * 1000);
private static final Logger logger = Logger.getLogger(Http.class);
private int retries;
private String url;
private Connection connection;
// Constructors
public Http(String url) {
this.url = url;
defaultSettings();
}
private Http(URL url) {
this.url = url.toExternalForm();
defaultSettings();
}
public static Http url(String url) {
return new Http(url);
}
public static Http url(URL url) {
return new Http(url);
}
private void defaultSettings() {
this.retries = Utils.getConfigInteger("download.retries", 1);
connection = Jsoup.connect(this.url);
connection.userAgent(AbstractRipper.USER_AGENT);
connection.method(Method.GET);
connection.timeout(TIMEOUT);
connection.maxBodySize(0);
// Extract cookies from config entry:
// Example config entry:
// cookies.reddit.com = reddit_session=<value>; other_cookie=<value>
connection.cookies(cookiesForURL(this.url));
}
private Map<String, String> cookiesForURL(String u) {<FILL_FUNCTION_BODY>}
// Setters
public Http timeout(int timeout) {
connection.timeout(timeout);
return this;
}
public Http ignoreContentType() {
connection.ignoreContentType(true);
return this;
}
public Http referrer(String ref) {
connection.referrer(ref);
return this;
}
public Http referrer(URL ref) {
return referrer(ref.toExternalForm());
}
public Http userAgent(String ua) {
connection.userAgent(ua);
return this;
}
public Http retries(int tries) {
this.retries = tries;
return this;
}
public Http header(String name, String value) {
connection.header(name, value);
return this;
}
public Http cookies(Map<String,String> cookies) {
connection.cookies(cookies);
return this;
}
public Http data(Map<String,String> data) {
connection.data(data);
return this;
}
public Http data(String name, String value) {
Map<String,String> data = new HashMap<>();
data.put(name, value);
return data(data);
}
public Http method(Method method) {
connection.method(method);
return this;
}
// Getters
public Connection connection() {
return connection;
}
public Document get() throws IOException {
connection.method(Method.GET);
return response().parse();
}
public Document post() throws IOException {
connection.method(Method.POST);
return response().parse();
}
public JSONObject getJSON() throws IOException {
ignoreContentType();
String jsonString = response().body();
return new JSONObject(jsonString);
}
public JSONArray getJSONArray() throws IOException {
ignoreContentType();
String jsonArray = response().body();
return new JSONArray(jsonArray);
}
public Response response() throws IOException {
Response response = null;
IOException lastException = null;
int retries = this.retries;
while (--retries >= 0) {
try {
response = connection.execute();
return response;
} catch (IOException e) {
// Warn users about possibly fixable permission error
if (e instanceof org.jsoup.HttpStatusException) {
HttpStatusException ex = (HttpStatusException)e;
// These status codes might indicate missing cookies
// 401 Unauthorized
// 403 Forbidden
int status = ex.getStatusCode();
if (status == 401 || status == 403) {
throw new IOException("Failed to load " + url + ": Status Code " + Integer.toString(status) + ". You might be able to circumvent this error by setting cookies for this domain" , e);
}
}
logger.warn("Error while loading " + url, e);
lastException = e;
}
}
throw new IOException("Failed to load " + url + " after " + this.retries + " attempts", lastException);
}
}
|
Map<String, String> cookiesParsed = new HashMap<>();
String cookieDomain = "";
try {
URL parsed = new URL(u);
String cookieStr = "";
String[] parts = parsed.getHost().split("\\.");
// if url is www.reddit.com, we should also use cookies from reddit.com;
// this rule is applied for all subdomains (for all rippers); e.g. also
// old.reddit.com, new.reddit.com
while (parts.length > 1) {
String domain = String.join(".", parts);
// Try to get cookies for this host from config
logger.info("Trying to load cookies from config for " + domain);
cookieStr = Utils.getConfigString("cookies." + domain, "");
if (!cookieStr.equals("")) {
cookieDomain = domain;
// we found something, start parsing
break;
}
parts = (String[]) ArrayUtils.remove(parts, 0);
}
if (!cookieStr.equals("")) {
cookiesParsed = RipUtils.getCookiesFromString(cookieStr.trim());
}
} catch (MalformedURLException e) {
logger.warn("Parsing url " + u + " while getting cookies", e);
}
if (cookiesParsed.size() > 0) {
logger.info("Cookies for " + cookieDomain + " have been added to this request");
}
return cookiesParsed;
| 1,164
| 391
| 1,555
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/utils/Proxy.java
|
Proxy
|
parseServer
|
class Proxy {
private Proxy() {
}
/**
* Parse the proxy server settings from string, using the format
* [user:password]@host[:port].
*
* @param fullproxy the string to parse
* @return HashMap containing proxy server, port, user and password
*/
private static Map<String, String> parseServer(String fullproxy) {<FILL_FUNCTION_BODY>}
/**
* Set a HTTP Proxy.
* WARNING: Authenticated HTTP Proxy won't work from jdk1.8.111 unless
* passing the flag -Djdk.http.auth.tunneling.disabledSchemes="" to java
* see https://stackoverflow.com/q/41505219
*
* @param fullproxy the proxy, using format [user:password]@host[:port]
*/
public static void setHTTPProxy(String fullproxy) {
Map<String, String> proxyServer = parseServer(fullproxy);
if (proxyServer.get("user") != null && proxyServer.get("password") != null) {
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
PasswordAuthentication p = new PasswordAuthentication(proxyServer.get("user"), proxyServer.get("password").toCharArray());
return p;
}
});
System.setProperty("http.proxyUser", proxyServer.get("user"));
System.setProperty("http.proxyPassword", proxyServer.get("password"));
System.setProperty("https.proxyUser", proxyServer.get("user"));
System.setProperty("https.proxyPassword", proxyServer.get("password"));
}
if (proxyServer.get("port") != null) {
System.setProperty("http.proxyPort", proxyServer.get("port"));
System.setProperty("https.proxyPort", proxyServer.get("port"));
}
System.setProperty("http.proxyHost", proxyServer.get("server"));
System.setProperty("https.proxyHost", proxyServer.get("server"));
}
/**
* Set a Socks Proxy Server (globally).
*
* @param fullsocks the socks server, using format [user:password]@host[:port]
*/
public static void setSocks(String fullsocks) {
Map<String, String> socksServer = parseServer(fullsocks);
if (socksServer.get("user") != null && socksServer.get("password") != null) {
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
PasswordAuthentication p = new PasswordAuthentication(socksServer.get("user"), socksServer.get("password").toCharArray());
return p;
}
});
System.setProperty("java.net.socks.username", socksServer.get("user"));
System.setProperty("java.net.socks.password", socksServer.get("password"));
}
if (socksServer.get("port") != null) {
System.setProperty("socksProxyPort", socksServer.get("port"));
}
System.setProperty("socksProxyHost", socksServer.get("server"));
}
}
|
Map<String, String> proxy = new HashMap<String, String>();
if (fullproxy.lastIndexOf("@") != -1) {
int sservli = fullproxy.lastIndexOf("@");
String userpw = fullproxy.substring(0, sservli);
String[] usersplit = userpw.split(":");
proxy.put("user", usersplit[0]);
proxy.put("password", usersplit[1]);
fullproxy = fullproxy.substring(sservli + 1);
}
String[] servsplit = fullproxy.split(":");
if (servsplit.length == 2) {
proxy.put("port", servsplit[1]);
}
proxy.put("server", servsplit[0]);
return proxy;
| 898
| 215
| 1,113
|
<no_super_class>
|
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/utils/UTF8Control.java
|
UTF8Control
|
newBundle
|
class UTF8Control extends ResourceBundle.Control {
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{<FILL_FUNCTION_BODY>}
}
|
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
| 71
| 241
| 312
|
<methods>public List<java.util.Locale> getCandidateLocales(java.lang.String, java.util.Locale) ,public static final java.util.ResourceBundle.Control getControl(List<java.lang.String>) ,public java.util.Locale getFallbackLocale(java.lang.String, java.util.Locale) ,public List<java.lang.String> getFormats(java.lang.String) ,public static final java.util.ResourceBundle.Control getNoFallbackControl(List<java.lang.String>) ,public long getTimeToLive(java.lang.String, java.util.Locale) ,public boolean needsReload(java.lang.String, java.util.Locale, java.lang.String, java.lang.ClassLoader, java.util.ResourceBundle, long) ,public java.util.ResourceBundle newBundle(java.lang.String, java.util.Locale, java.lang.String, java.lang.ClassLoader, boolean) throws java.lang.IllegalAccessException, java.lang.InstantiationException, java.io.IOException,public java.lang.String toBundleName(java.lang.String, java.util.Locale) ,public final java.lang.String toResourceName(java.lang.String, java.lang.String) <variables>static final boolean $assertionsDisabled,private static final java.util.ResourceBundle.Control.CandidateListCache CANDIDATES_CACHE,public static final List<java.lang.String> FORMAT_CLASS,public static final List<java.lang.String> FORMAT_DEFAULT,public static final List<java.lang.String> FORMAT_PROPERTIES,private static final java.util.ResourceBundle.Control INSTANCE,public static final long TTL_DONT_CACHE,public static final long TTL_NO_EXPIRATION_CONTROL
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/category/Category.java
|
Category
|
getDescription
|
class Category extends SalesManagerEntity<Long, Category> implements Auditable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "CATEGORY_ID", unique=true, nullable=false)
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CATEGORY_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Embedded
private AuditSection auditSection = new AuditSection();
@Valid
@OneToMany(mappedBy="category", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<CategoryDescription> descriptions = new HashSet<CategoryDescription>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
@ManyToOne
@JoinColumn(name = "PARENT_ID")
private Category parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private List<Category> categories = new ArrayList<Category>();
@Column(name = "CATEGORY_IMAGE", length=100)
private String categoryImage;
@Column(name = "SORT_ORDER")
private Integer sortOrder = 0;
@Column(name = "CATEGORY_STATUS")
private boolean categoryStatus;
@Column(name = "VISIBLE")
private boolean visible;
@Column(name = "DEPTH")
private Integer depth;
@Column(name = "LINEAGE")
private String lineage;
@Column(name="FEATURED")
private boolean featured;
@NotEmpty
@Column(name="CODE", length=100, nullable=false)
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Category() {
}
public Category(MerchantStore store) {
this.merchantStore = store;
this.id = 0L;
}
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public AuditSection getAuditSection() {
return auditSection;
}
@Override
public void setAuditSection(AuditSection auditSection) {
this.auditSection = auditSection;
}
public String getCategoryImage() {
return categoryImage;
}
public void setCategoryImage(String categoryImage) {
this.categoryImage = categoryImage;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public boolean isCategoryStatus() {
return categoryStatus;
}
public void setCategoryStatus(boolean categoryStatus) {
this.categoryStatus = categoryStatus;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
public String getLineage() {
return lineage;
}
public void setLineage(String lineage) {
this.lineage = lineage;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public CategoryDescription getDescription() {<FILL_FUNCTION_BODY>}
public boolean isFeatured() {
return featured;
}
public void setFeatured(boolean featured) {
this.featured = featured;
}
public Set<CategoryDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(Set<CategoryDescription> descriptions) {
this.descriptions = descriptions;
}
}
|
if(descriptions!=null && descriptions.size()>0) {
return descriptions.iterator().next();
}
return null;
| 1,273
| 41
| 1,314
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.catalog.category.Category) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductOption.java
|
ProductOption
|
getDescriptionsSettoList
|
class ProductOption extends SalesManagerEntity<Long, ProductOption> {
private static final long serialVersionUID = 1L;
@Id
@Column(name="PRODUCT_OPTION_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRODUCT_OPTION_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name="PRODUCT_OPTION_SORT_ORD")
private Integer productOptionSortOrder;
@Column(name="PRODUCT_OPTION_TYPE", length=10)
private String productOptionType;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "productOption")
private Set<ProductOptionDescription> descriptions = new HashSet<ProductOptionDescription>();
@Transient
private List<ProductOptionDescription> descriptionsList = new ArrayList<ProductOptionDescription>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
@Column(name="PRODUCT_OPTION_READ")
private boolean readOnly;
@NotEmpty
@Pattern(regexp="^[a-zA-Z0-9_]*$")
@Column(name="PRODUCT_OPTION_CODE")
private String code;
public ProductOption() {
}
public Integer getProductOptionSortOrder() {
return productOptionSortOrder;
}
public void setProductOptionSortOrder(Integer productOptionSortOrder) {
this.productOptionSortOrder = productOptionSortOrder;
}
public String getProductOptionType() {
return productOptionType;
}
public void setProductOptionType(String productOptionType) {
this.productOptionType = productOptionType;
}
public Set<ProductOptionDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(Set<ProductOptionDescription> descriptions) {
this.descriptions = descriptions;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public void setDescriptionsList(List<ProductOptionDescription> descriptionsList) {
this.descriptionsList = descriptionsList;
}
public List<ProductOptionDescription> getDescriptionsList() {
return descriptionsList;
}
public List<ProductOptionDescription> getDescriptionsSettoList() {<FILL_FUNCTION_BODY>}
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean isReadOnly() {
return readOnly;
}
}
|
if(descriptionsList==null || descriptionsList.size()==0) {
descriptionsList = new ArrayList<ProductOptionDescription>(this.getDescriptions());
}
return descriptionsList;
| 829
| 57
| 886
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.catalog.product.attribute.ProductOption) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductOptionValue.java
|
ProductOptionValue
|
getDescriptionsSettoList
|
class ProductOptionValue extends SalesManagerEntity<Long, ProductOptionValue> {
private static final long serialVersionUID = 1L;
@Id
@Column(name="PRODUCT_OPTION_VALUE_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRODUCT_OPT_VAL_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name="PRODUCT_OPT_VAL_SORT_ORD")
private Integer productOptionValueSortOrder;
@Column(name="PRODUCT_OPT_VAL_IMAGE")
private String productOptionValueImage;
@Column(name="PRODUCT_OPT_FOR_DISP")
private boolean productOptionDisplayOnly=false;
@NotEmpty
@Pattern(regexp="^[a-zA-Z0-9_]*$")
@Column(name="PRODUCT_OPTION_VAL_CODE")
private String code;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "productOptionValue")
private Set<ProductOptionValueDescription> descriptions = new HashSet<ProductOptionValueDescription>();
@Transient
private MultipartFile image = null;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
@Transient
private List<ProductOptionValueDescription> descriptionsList = new ArrayList<ProductOptionValueDescription>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
public ProductOptionValue() {
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Integer getProductOptionValueSortOrder() {
return productOptionValueSortOrder;
}
public void setProductOptionValueSortOrder(Integer productOptionValueSortOrder) {
this.productOptionValueSortOrder = productOptionValueSortOrder;
}
public String getProductOptionValueImage() {
return productOptionValueImage;
}
public void setProductOptionValueImage(String productOptionValueImage) {
this.productOptionValueImage = productOptionValueImage;
}
public Set<ProductOptionValueDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(Set<ProductOptionValueDescription> descriptions) {
this.descriptions = descriptions;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public void setDescriptionsList(List<ProductOptionValueDescription> descriptionsList) {
this.descriptionsList = descriptionsList;
}
public List<ProductOptionValueDescription> getDescriptionsList() {
return descriptionsList;
}
public List<ProductOptionValueDescription> getDescriptionsSettoList() {<FILL_FUNCTION_BODY>}
public boolean isProductOptionDisplayOnly() {
return productOptionDisplayOnly;
}
public void setProductOptionDisplayOnly(boolean productOptionDisplayOnly) {
this.productOptionDisplayOnly = productOptionDisplayOnly;
}
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
|
if(descriptionsList==null || descriptionsList.size()==0) {
descriptionsList = new ArrayList<ProductOptionValueDescription>(this.getDescriptions());
}
return descriptionsList;
| 926
| 57
| 983
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/availability/ProductAvailability.java
|
ProductAvailability
|
defaultPrice
|
class ProductAvailability extends SalesManagerEntity<Long, ProductAvailability> implements Auditable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Embedded
private AuditSection auditSection = new AuditSection();
@Id
@Column(name = "PRODUCT_AVAIL_ID", unique = true, nullable = false)
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRODUCT_AVAIL_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@JsonIgnore
@ManyToOne(targetEntity = Product.class)
@JoinColumn(name = "PRODUCT_ID", nullable = false)
private Product product;
/** Specific retailer store **/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MERCHANT_ID", nullable = true)
private MerchantStore merchantStore;
/**
* This describes the availability of a product variant
*/
@ManyToOne(targetEntity = ProductVariant.class)
@JoinColumn(name = "PRODUCT_VARIANT", nullable = true)
private ProductVariant productVariant;
@Pattern(regexp="^[a-zA-Z0-9_]*$")
@Column(name = "SKU", nullable = true)
private String sku;
@Embedded
private ProductDimensions dimensions;
@NotNull
@Column(name = "QUANTITY")
private Integer productQuantity = 0;
@Temporal(TemporalType.DATE)
@Column(name = "DATE_AVAILABLE")
private Date productDateAvailable;
@Column(name = "REGION")
private String region = SchemaConstant.ALL_REGIONS;
@Column(name = "REGION_VARIANT")
private String regionVariant;
@Column(name = "OWNER")
private String owner;
@Column(name = "STATUS")
private boolean productStatus = true; //can be used as flag for variant can be purchase or not
@Column(name = "FREE_SHIPPING")
private boolean productIsAlwaysFreeShipping;
@Column(name = "AVAILABLE")
private Boolean available;
@Column(name = "QUANTITY_ORD_MIN")
private Integer productQuantityOrderMin = 0;
@Column(name = "QUANTITY_ORD_MAX")
private Integer productQuantityOrderMax = 0;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "productAvailability", cascade = CascadeType.ALL)
private Set<ProductPrice> prices = new HashSet<ProductPrice>();
@Transient
public ProductPrice defaultPrice() {<FILL_FUNCTION_BODY>}
public ProductAvailability() {
}
public ProductAvailability(Product product, MerchantStore store) {
this.product = product;
this.merchantStore = store;
}
public Integer getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(Integer productQuantity) {
this.productQuantity = productQuantity;
}
public Date getProductDateAvailable() {
return CloneUtils.clone(productDateAvailable);
}
public void setProductDateAvailable(Date productDateAvailable) {
this.productDateAvailable = CloneUtils.clone(productDateAvailable);
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getRegionVariant() {
return regionVariant;
}
public void setRegionVariant(String regionVariant) {
this.regionVariant = regionVariant;
}
public boolean getProductStatus() {
return productStatus;
}
public void setProductStatus(boolean productStatus) {
this.productStatus = productStatus;
}
public boolean getProductIsAlwaysFreeShipping() {
return productIsAlwaysFreeShipping;
}
public void setProductIsAlwaysFreeShipping(boolean productIsAlwaysFreeShipping) {
this.productIsAlwaysFreeShipping = productIsAlwaysFreeShipping;
}
public Integer getProductQuantityOrderMin() {
return productQuantityOrderMin;
}
public void setProductQuantityOrderMin(Integer productQuantityOrderMin) {
this.productQuantityOrderMin = productQuantityOrderMin;
}
public Integer getProductQuantityOrderMax() {
return productQuantityOrderMax;
}
public void setProductQuantityOrderMax(Integer productQuantityOrderMax) {
this.productQuantityOrderMax = productQuantityOrderMax;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Set<ProductPrice> getPrices() {
return prices;
}
public void setPrices(Set<ProductPrice> prices) {
this.prices = prices;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Override
public AuditSection getAuditSection() {
return auditSection;
}
@Override
public void setAuditSection(AuditSection audit) {
this.auditSection = audit;
}
public Boolean getAvailable() {
return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public ProductDimensions getDimensions() {
return dimensions;
}
public void setDimensions(ProductDimensions dimensions) {
this.dimensions = dimensions;
}
public ProductVariant getProductVariant() {
return productVariant;
}
public void setProductVariant(ProductVariant productVariant) {
this.productVariant = productVariant;
}
}
|
for (ProductPrice price : prices) {
if (price.isDefaultPrice()) {
return price;
}
}
return new ProductPrice();
| 1,656
| 43
| 1,699
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/common/audit/AuditListener.java
|
AuditListener
|
onUpdate
|
class AuditListener {
@PrePersist
public void onSave(Object o) {
if (o instanceof Auditable) {
Auditable audit = (Auditable) o;
AuditSection auditSection = audit.getAuditSection();
auditSection.setDateModified(new Date());
if (auditSection.getDateCreated() == null) {
auditSection.setDateCreated(new Date());
}
audit.setAuditSection(auditSection);
}
}
@PreUpdate
public void onUpdate(Object o) {<FILL_FUNCTION_BODY>}
}
|
if (o instanceof Auditable) {
Auditable audit = (Auditable) o;
AuditSection auditSection = audit.getAuditSection();
auditSection.setDateModified(new Date());
if (auditSection.getDateCreated() == null) {
auditSection.setDateCreated(new Date());
}
audit.setAuditSection(auditSection);
}
| 159
| 104
| 263
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/common/audit/AuditSection.java
|
AuditSection
|
setModifiedBy
|
class AuditSection implements Serializable {
private static final long serialVersionUID = 1L;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "DATE_CREATED")
private Date dateCreated;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "DATE_MODIFIED")
private Date dateModified;
@Column(name = "UPDT_ID", length = 60)
private String modifiedBy;
public AuditSection() {}
public Date getDateCreated() {
return CloneUtils.clone(dateCreated);
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = CloneUtils.clone(dateCreated);
}
public Date getDateModified() {
return CloneUtils.clone(dateModified);
}
public void setDateModified(Date dateModified) {
this.dateModified = CloneUtils.clone(dateModified);
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {<FILL_FUNCTION_BODY>}
}
|
if(!StringUtils.isBlank(modifiedBy)) {//TODO
if(modifiedBy.length()>20) {
modifiedBy = modifiedBy.substring(0, 20);
}
}
this.modifiedBy = modifiedBy;
| 306
| 74
| 380
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/content/Content.java
|
Content
|
getDescription
|
class Content extends SalesManagerEntity<Long, Content> implements Serializable {
private static final long serialVersionUID = 1772757159185494620L;
@Id
@Column(name = "CONTENT_ID", unique=true, nullable=false)
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CONTENT_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Embedded
private AuditSection auditSection = new AuditSection();
@Valid
@OneToMany(mappedBy="content", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<ContentDescription> descriptions = new ArrayList<ContentDescription>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
@NotEmpty
@Column(name="CODE", length=100, nullable=false)
private String code;
@Column(name = "VISIBLE")
private boolean visible;
@Column(name = "LINK_TO_MENU")
private boolean linkToMenu;
@Column(name = "CONTENT_POSITION", length=10, nullable=true)
@Enumerated(value = EnumType.STRING)
private ContentPosition contentPosition;
//Used for grouping
//BOX, SECTION, PAGE
@Column(name = "CONTENT_TYPE", length=10, nullable=true)
@Enumerated(value = EnumType.STRING)
private ContentType contentType;
@Column(name = "SORT_ORDER")
private Integer sortOrder = 0;
//A page can contain one product listing
@Column(name = "PRODUCT_GROUP", nullable = true)
private String productGroup;
public String getProductGroup() {
return productGroup;
}
public void setProductGroup(String productGroup) {
this.productGroup = productGroup;
}
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public void setAuditSection(AuditSection auditSection) {
this.auditSection = auditSection;
}
public AuditSection getAuditSection() {
return auditSection;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public List<ContentDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(List<ContentDescription> descriptions) {
this.descriptions = descriptions;
}
public void setContentType(ContentType contentType) {
this.contentType = contentType;
}
public ContentType getContentType() {
return contentType;
}
public ContentDescription getDescription() {<FILL_FUNCTION_BODY>}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setContentPosition(ContentPosition contentPosition) {
this.contentPosition = contentPosition;
}
public ContentPosition getContentPosition() {
return contentPosition;
}
public boolean isLinkToMenu() {
return linkToMenu;
}
public void setLinkToMenu(boolean linkToMenu) {
this.linkToMenu = linkToMenu;
}
}
|
if(this.getDescriptions()!=null && this.getDescriptions().size()>0) {
return this.getDescriptions().get(0);
}
return null;
| 1,041
| 59
| 1,100
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.content.Content) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/customer/attribute/CustomerOption.java
|
CustomerOption
|
getDescriptionsSettoList
|
class CustomerOption extends SalesManagerEntity<Long, CustomerOption> {
private static final long serialVersionUID = -2019269055342226086L;
@Id
@Column(name="CUSTOMER_OPTION_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CUSTOMER_OPTION_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name="SORT_ORDER")
private Integer sortOrder = 0;
@Column(name="CUSTOMER_OPTION_TYPE", length=10)
private String customerOptionType;
@NotEmpty
@Pattern(regexp="^[a-zA-Z0-9_]*$")
@Column(name="CUSTOMER_OPT_CODE")
//@Index(name="CUST_OPT_CODE_IDX")
private String code;
@Column(name="CUSTOMER_OPT_ACTIVE")
private boolean active;
@Column(name="CUSTOMER_OPT_PUBLIC")
private boolean publicOption;
@Valid
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "customerOption")
private Set<CustomerOptionDescription> descriptions = new HashSet<CustomerOptionDescription>();
@Transient
private List<CustomerOptionDescription> descriptionsList = new ArrayList<CustomerOptionDescription>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
public CustomerOption() {
}
public Set<CustomerOptionDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(Set<CustomerOptionDescription> descriptions) {
this.descriptions = descriptions;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public void setDescriptionsList(List<CustomerOptionDescription> descriptionsList) {
this.descriptionsList = descriptionsList;
}
public List<CustomerOptionDescription> getDescriptionsList() {
return descriptionsList;
}
public List<CustomerOptionDescription> getDescriptionsSettoList() {<FILL_FUNCTION_BODY>}
public String getCustomerOptionType() {
return customerOptionType;
}
public void setCustomerOptionType(String customerOptionType) {
this.customerOptionType = customerOptionType;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isPublicOption() {
return publicOption;
}
public void setPublicOption(boolean publicOption) {
this.publicOption = publicOption;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getSortOrder() {
return sortOrder;
}
}
|
if(descriptionsList==null || descriptionsList.size()==0) {
descriptionsList = new ArrayList<CustomerOptionDescription>(this.getDescriptions());
}
return descriptionsList;
| 934
| 57
| 991
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.customer.attribute.CustomerOption) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/customer/attribute/CustomerOptionValue.java
|
CustomerOptionValue
|
getDescriptionsSettoList
|
class CustomerOptionValue extends SalesManagerEntity<Long, CustomerOptionValue> {
private static final long serialVersionUID = 3736085877929910891L;
@Id
@Column(name="CUSTOMER_OPTION_VALUE_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CUSTOMER_OPT_VAL_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name="SORT_ORDER")
private Integer sortOrder = 0;
@Column(name="CUSTOMER_OPT_VAL_IMAGE")
private String customerOptionValueImage;
@NotEmpty
@Pattern(regexp="^[a-zA-Z0-9_]*$")
@Column(name="CUSTOMER_OPT_VAL_CODE")
private String code;
@Valid
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "customerOptionValue")
private Set<CustomerOptionValueDescription> descriptions = new HashSet<CustomerOptionValueDescription>();
@Transient
private List<CustomerOptionValueDescription> descriptionsList = new ArrayList<CustomerOptionValueDescription>();
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=false)
private MerchantStore merchantStore;
public CustomerOptionValue() {
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Set<CustomerOptionValueDescription> getDescriptions() {
return descriptions;
}
public void setDescriptions(Set<CustomerOptionValueDescription> descriptions) {
this.descriptions = descriptions;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public void setDescriptionsList(List<CustomerOptionValueDescription> descriptionsList) {
this.descriptionsList = descriptionsList;
}
public List<CustomerOptionValueDescription> getDescriptionsList() {
return descriptionsList;
}
public List<CustomerOptionValueDescription> getDescriptionsSettoList() {<FILL_FUNCTION_BODY>}
//public void setImage(MultipartFile image) {
// this.image = image;
//}
//public MultipartFile getImage() {
// return image;
//}
public String getCustomerOptionValueImage() {
return customerOptionValueImage;
}
public void setCustomerOptionValueImage(String customerOptionValueImage) {
this.customerOptionValueImage = customerOptionValueImage;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getSortOrder() {
return sortOrder;
}
}
|
if(descriptionsList==null || descriptionsList.size()==0) {
descriptionsList = new ArrayList<CustomerOptionValueDescription>(this.getDescriptions());
}
return descriptionsList;
| 838
| 57
| 895
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.customer.attribute.CustomerOptionValue) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/customer/connection/UserConnectionPK.java
|
UserConnectionPK
|
equals
|
class UserConnectionPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String userId;
private String providerId;
private String providerUserId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getProviderId() {
return providerId;
}
public void setProviderId(String providerId) {
this.providerId = providerId;
}
public String getProviderUserId() {
return providerUserId;
}
public void setProviderUserId(String providerUserId) {
this.providerUserId = providerUserId;
}
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
public int hashCode() {
return getUserId().hashCode() + getProviderId().hashCode()
+ getProviderUserId().hashCode();
}
}
|
if (o instanceof UserConnectionPK) {
UserConnectionPK other = (UserConnectionPK) o;
return other.getProviderId().equals(getProviderId())
&& other.getProviderUserId().equals(getProviderUserId())
&& other.getUserId().equals(getUserId());
} else {
return false;
}
| 246
| 89
| 335
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/generic/SalesManagerEntity.java
|
SalesManagerEntity
|
compareTo
|
class SalesManagerEntity<K extends Serializable & Comparable<K>, E extends SalesManagerEntity<K, ?>>
implements Serializable, Comparable<E> {
private static final long serialVersionUID = -3988499137919577054L;
public static final Collator DEFAULT_STRING_COLLATOR = Collator.getInstance(Locale.FRENCH);
static {
DEFAULT_STRING_COLLATOR.setStrength(Collator.PRIMARY);
}
/**
* Retourne la valeur de l'identifiant unique.
*
* @return id
*/
public abstract K getId();
/**
* Définit la valeur de l'identifiant unique.
*
* @param id id
*/
public abstract void setId(K id);
/**
* Indique si l'objet a déjà été persisté ou non
*
* @return vrai si l'objet n'a pas encore été persisté
*/
public boolean isNew() {
return getId() == null;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object == this) {
return true;
}
// l'objet peut être proxyfié donc on utilise Hibernate.getClass() pour sortir la vraie classe
if (Hibernate.getClass(object) != Hibernate.getClass(this)) {
return false;
}
SalesManagerEntity<K, E> entity = (SalesManagerEntity<K, E>) object; // NOSONAR : traité au-dessus mais wrapper Hibernate
K id = getId();
if (id == null) {
return false;
}
return id.equals(entity.getId());
}
@Override
public int hashCode() {
int hash = 7;
K id = getId();
hash = 31 * hash + ((id == null) ? 0 : id.hashCode());
return hash;
}
public int compareTo(E o) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("entity.");
builder.append(Hibernate.getClass(this).getSimpleName());
builder.append("<");
builder.append(getId());
builder.append("-");
builder.append(super.toString());
builder.append(">");
return builder.toString();
}
}
|
if (this == o) {
return 0;
}
return this.getId().compareTo(o.getId());
| 705
| 35
| 740
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/payments/Transaction.java
|
Transaction
|
toJSONString
|
class Transaction extends SalesManagerEntity<Long, Transaction> implements Serializable, Auditable, JSONAware {
private static final Logger LOGGER = LoggerFactory.getLogger(Transaction.class);
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "TRANSACTION_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "TRANSACT_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Embedded
private AuditSection auditSection = new AuditSection();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="ORDER_ID", nullable=true)
private Order order;
@Column(name="AMOUNT")
private BigDecimal amount;
@Column(name="TRANSACTION_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date transactionDate;
@Column(name="TRANSACTION_TYPE")
@Enumerated(value = EnumType.STRING)
private TransactionType transactionType;
@Column(name="PAYMENT_TYPE")
@Enumerated(value = EnumType.STRING)
private PaymentType paymentType;
@Column(name="DETAILS")
@Type(type = "org.hibernate.type.TextType")
private String details;
@Transient
private Map<String,String> transactionDetails= new HashMap<String,String>();
@Override
public AuditSection getAuditSection() {
return this.auditSection;
}
@Override
public void setAuditSection(AuditSection audit) {
this.auditSection = audit;
}
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Date getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
}
public TransactionType getTransactionType() {
return transactionType;
}
public String getTransactionTypeName() {
return this.getTransactionType()!=null?this.getTransactionType().name():"";
}
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType;
}
public PaymentType getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentType paymentType) {
this.paymentType = paymentType;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public Map<String, String> getTransactionDetails() {
return transactionDetails;
}
public void setTransactionDetails(Map<String, String> transactionDetails) {
this.transactionDetails = transactionDetails;
}
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
}
|
if(this.getTransactionDetails()!=null && this.getTransactionDetails().size()>0) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this.getTransactionDetails());
} catch (Exception e) {
LOGGER.error("Cannot parse transactions map",e);
}
}
return null;
| 902
| 104
| 1,006
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.payments.Transaction) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/reference/currency/Currency.java
|
Currency
|
getCode
|
class Currency extends SalesManagerEntity<Long, Currency> implements Serializable {
private static final long serialVersionUID = -999926410367685145L;
@Id
@Column(name = "CURRENCY_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "CURRENCY_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Column(name = "CURRENCY_CURRENCY_CODE" ,nullable = false, unique = true)
private java.util.Currency currency;
@Column(name = "CURRENCY_SUPPORTED")
private Boolean supported = true;
@Column(name = "CURRENCY_CODE", unique = true)
private String code;
@Column(name = "CURRENCY_NAME", unique = true)
private String name;
public Currency() {
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public java.util.Currency getCurrency() {
return currency;
}
public void setCurrency(java.util.Currency currency) {
this.currency = currency;
this.code = currency.getCurrencyCode();
}
public Boolean getSupported() {
return supported;
}
public void setSupported(Boolean supported) {
this.supported = supported;
}
public String getCode() {<FILL_FUNCTION_BODY>}
public String getSymbol() {
return currency.getSymbol();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
if (currency.getCurrencyCode() != code) {
return currency.getCurrencyCode();
}
return code;
| 502
| 37
| 539
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.reference.currency.Currency) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Long getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Long) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/reference/language/Language.java
|
Language
|
equals
|
class Language extends SalesManagerEntity<Integer, Language> implements Auditable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "LANGUAGE_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "LANG_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Integer id;
@JsonIgnore
@Embedded
private AuditSection auditSection = new AuditSection();
@Column(name = "CODE", nullable = false)
private String code;
@JsonIgnore
@Column(name = "SORT_ORDER")
private Integer sortOrder;
@JsonIgnore
@OneToMany(mappedBy = "defaultLanguage", targetEntity = MerchantStore.class)
private List<MerchantStore> storesDefaultLanguage;
@JsonIgnore
@ManyToMany(mappedBy = "languages", targetEntity = MerchantStore.class, fetch = FetchType.LAZY)
private List<MerchantStore> stores = new ArrayList<MerchantStore>();
public Language() {}
public Language(String code) {
this.setCode(code);
}
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
@Override
public AuditSection getAuditSection() {
return auditSection;
}
@Override
public void setAuditSection(AuditSection auditSection) {
this.auditSection = auditSection;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (null == obj)
return false;
if (!(obj instanceof Language)) {
return false;
} else {
Language language = (Language) obj;
return (this.id == language.getId());
}
| 577
| 61
| 638
|
<methods>public non-sealed void <init>() ,public int compareTo(com.salesmanager.core.model.reference.language.Language) ,public boolean equals(java.lang.Object) ,public abstract java.lang.Integer getId() ,public int hashCode() ,public boolean isNew() ,public abstract void setId(java.lang.Integer) ,public java.lang.String toString() <variables>public static final java.text.Collator DEFAULT_STRING_COLLATOR,private static final long serialVersionUID
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/shipping/ShippingOption.java
|
ShippingOption
|
getOptionPrice
|
class ShippingOption implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(ShippingOption.class);
/**
*
*/
private static final long serialVersionUID = 1L;
private BigDecimal optionPrice;
private Long shippingQuoteOptionId;
private String optionName = null;
private String optionCode = null;
private String optionDeliveryDate = null;
private String optionShippingDate = null;
private String optionPriceText = null;
private String optionId = null;
private String description = null;
private String shippingModuleCode = null;
private String note = null;
private String estimatedNumberOfDays;
public BigDecimal getOptionPrice() {<FILL_FUNCTION_BODY>}
public void setOptionPrice(BigDecimal optionPrice) {
this.optionPrice = optionPrice;
}
public void setOptionCode(String optionCode) {
this.optionCode = optionCode;
}
public String getOptionCode() {
return optionCode;
}
public void setOptionName(String optionName) {
this.optionName = optionName;
}
public String getOptionName() {
return optionName;
}
public void setOptionPriceText(String optionPriceText) {
this.optionPriceText = optionPriceText;
}
public String getOptionPriceText() {
return optionPriceText;
}
public void setOptionId(String optionId) {
this.optionId = optionId;
}
public String getOptionId() {
return optionId;
}
public void setOptionDeliveryDate(String optionDeliveryDate) {
this.optionDeliveryDate = optionDeliveryDate;
}
public String getOptionDeliveryDate() {
return optionDeliveryDate;
}
public void setOptionShippingDate(String optionShippingDate) {
this.optionShippingDate = optionShippingDate;
}
public String getOptionShippingDate() {
return optionShippingDate;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setEstimatedNumberOfDays(String estimatedNumberOfDays) {
this.estimatedNumberOfDays = estimatedNumberOfDays;
}
public String getEstimatedNumberOfDays() {
return estimatedNumberOfDays;
}
public String getShippingModuleCode() {
return shippingModuleCode;
}
public void setShippingModuleCode(String shippingModuleCode) {
this.shippingModuleCode = shippingModuleCode;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Long getShippingQuoteOptionId() {
return shippingQuoteOptionId;
}
public void setShippingQuoteOptionId(Long shippingQuoteOptionId) {
this.shippingQuoteOptionId = shippingQuoteOptionId;
}
}
|
if(optionPrice == null && !StringUtils.isBlank(this.getOptionPriceText())) {//if price text only is available, try to parse it
try {
this.optionPrice = new BigDecimal(this.getOptionPriceText());
} catch(Exception e) {
LOGGER.error("Can't convert price text " + this.getOptionPriceText() + " to big decimal");
}
}
return optionPrice;
| 747
| 118
| 865
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/system/IntegrationConfiguration.java
|
IntegrationConfiguration
|
toJSONString
|
class IntegrationConfiguration implements JSONAware {
public final static String TEST_ENVIRONMENT = "TEST";
public final static String PRODUCTION_ENVIRONMENT = "PRODUCTION";
private String moduleCode;
private boolean active;
private boolean defaultSelected;
private Map<String, String> integrationKeys = new HashMap<String, String>();
private Map<String, List<String>> integrationOptions = new HashMap<String, List<String>>();
private String environment;
public String getModuleCode() {
return moduleCode;
}
@JsonProperty("moduleCode")
public void setModuleCode(String moduleCode) {
this.moduleCode = moduleCode;
}
public boolean isActive() {
return active;
}
@JsonProperty("active")
public void setActive(boolean active) {
this.active = active;
}
public Map<String, String> getIntegrationKeys() {
return integrationKeys;
}
@JsonProperty("integrationKeys")
public void setIntegrationKeys(Map<String, String> integrationKeys) {
this.integrationKeys = integrationKeys;
}
protected String getJsonInfo() {
StringBuilder returnString = new StringBuilder();
returnString.append("{");
returnString.append("\"moduleCode\"").append(":\"").append(this.getModuleCode()).append("\"");
returnString.append(",");
returnString.append("\"active\"").append(":").append(this.isActive());
returnString.append(",");
returnString.append("\"defaultSelected\"").append(":").append(this.isDefaultSelected());
returnString.append(",");
returnString.append("\"environment\"").append(":\"").append(this.getEnvironment()).append("\"");
return returnString.toString();
}
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
public void setEnvironment(String environment) {
this.environment = environment;
}
public String getEnvironment() {
return environment;
}
public Map<String, List<String>> getIntegrationOptions() {
return integrationOptions;
}
public void setIntegrationOptions(Map<String, List<String>> integrationOptions) {
this.integrationOptions = integrationOptions;
}
public boolean isDefaultSelected() {
return defaultSelected;
}
public void setDefaultSelected(boolean defaultSelected) {
this.defaultSelected = defaultSelected;
}
}
|
StringBuilder returnString = new StringBuilder();
returnString.append(getJsonInfo());
if (this.getIntegrationKeys().size() > 0) {
JSONObject data = new JSONObject();
Set<String> keys = this.getIntegrationKeys().keySet();
for (String key : keys) {
data.put(key, this.getIntegrationKeys().get(key));
}
String dataField = data.toJSONString();
returnString.append(",").append("\"integrationKeys\"").append(":");
returnString.append(dataField.toString());
}
if (this.getIntegrationOptions() != null && this.getIntegrationOptions().size() > 0) {
// JSONObject data = new JSONObject();
StringBuilder optionDataEntries = new StringBuilder();
Set<String> keys = this.getIntegrationOptions().keySet();
int countOptions = 0;
int keySize = 0;
for (String key : keys) {
List<String> values = this.getIntegrationOptions().get(key);
if (values != null) {
keySize++;
}
}
for (String key : keys) {
List<String> values = this.getIntegrationOptions().get(key);
if (values == null) {
continue;
}
StringBuilder optionsEntries = new StringBuilder();
StringBuilder dataEntries = new StringBuilder();
int count = 0;
for (String value : values) {
dataEntries.append("\"").append(value).append("\"");
if (count < values.size() - 1) {
dataEntries.append(",");
}
count++;
}
optionsEntries.append("[").append(dataEntries.toString()).append("]");
optionDataEntries.append("\"").append(key).append("\":").append(optionsEntries.toString());
if (countOptions < keySize - 1) {
optionDataEntries.append(",");
}
countOptions++;
}
String dataField = optionDataEntries.toString();
returnString.append(",").append("\"integrationOptions\"").append(":{");
returnString.append(dataField.toString());
returnString.append("}");
}
returnString.append("}");
return returnString.toString();
| 665
| 617
| 1,282
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/system/MerchantConfig.java
|
MerchantConfig
|
toJSONString
|
class MerchantConfig implements Serializable, JSONAware {
/**
* TODO
* Add a generic key value in order to allow the creation of configuration
* on the fly from the client application and read from a key value map
*/
private static final long serialVersionUID = 1L;
private boolean displayCustomerSection =false;
private boolean displayContactUs =false;
private boolean displayStoreAddress = false;
private boolean displayAddToCartOnFeaturedItems = false;
private boolean displayCustomerAgreement = false;
private boolean displayPagesMenu = true;
private boolean allowPurchaseItems = true;
private boolean displaySearchBox = true;
private boolean testMode = false;
private boolean debugMode = false;
/** Store default search json config **/
private Map<String,Boolean> useDefaultSearchConfig= new HashMap<String,Boolean>();//language code | true or false
private Map<String,String> defaultSearchConfigPath= new HashMap<String,String>();//language code | file path
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
public void setDisplayCustomerSection(boolean displayCustomerSection) {
this.displayCustomerSection = displayCustomerSection;
}
public boolean isDisplayCustomerSection() {
return displayCustomerSection;
}
public void setDisplayContactUs(boolean displayContactUs) {
this.displayContactUs = displayContactUs;
}
public boolean isDisplayContactUs() {
return displayContactUs;
}
public boolean isDisplayStoreAddress() {
return displayStoreAddress;
}
public void setDisplayStoreAddress(boolean displayStoreAddress) {
this.displayStoreAddress = displayStoreAddress;
}
public void setUseDefaultSearchConfig(Map<String,Boolean> useDefaultSearchConfig) {
this.useDefaultSearchConfig = useDefaultSearchConfig;
}
public Map<String,Boolean> getUseDefaultSearchConfig() {
return useDefaultSearchConfig;
}
public void setDefaultSearchConfigPath(Map<String,String> defaultSearchConfigPath) {
this.defaultSearchConfigPath = defaultSearchConfigPath;
}
public Map<String,String> getDefaultSearchConfigPath() {
return defaultSearchConfigPath;
}
public void setDisplayAddToCartOnFeaturedItems(
boolean displayAddToCartOnFeaturedItems) {
this.displayAddToCartOnFeaturedItems = displayAddToCartOnFeaturedItems;
}
public boolean isDisplayAddToCartOnFeaturedItems() {
return displayAddToCartOnFeaturedItems;
}
public boolean isDisplayCustomerAgreement() {
return displayCustomerAgreement;
}
public void setDisplayCustomerAgreement(boolean displayCustomerAgreement) {
this.displayCustomerAgreement = displayCustomerAgreement;
}
public boolean isAllowPurchaseItems() {
return allowPurchaseItems;
}
public void setAllowPurchaseItems(boolean allowPurchaseItems) {
this.allowPurchaseItems = allowPurchaseItems;
}
public boolean isDisplaySearchBox() {
return displaySearchBox;
}
public void setDisplaySearchBox(boolean displaySearchBox) {
this.displaySearchBox = displaySearchBox;
}
public boolean isTestMode() {
return testMode;
}
public void setTestMode(boolean testMode) {
this.testMode = testMode;
}
public boolean isDebugMode() {
return debugMode;
}
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
public boolean isDisplayPagesMenu() {
return displayPagesMenu;
}
public void setDisplayPagesMenu(boolean displayPagesMenu) {
this.displayPagesMenu = displayPagesMenu;
}
}
|
JSONObject data = new JSONObject();
data.put("displayCustomerSection", this.isDisplayCustomerSection());
data.put("displayContactUs", this.isDisplayContactUs());
data.put("displayStoreAddress", this.isDisplayStoreAddress());
data.put("displayAddToCartOnFeaturedItems", this.isDisplayAddToCartOnFeaturedItems());
data.put("displayPagesMenu", this.isDisplayPagesMenu());
data.put("displayCustomerAgreement", this.isDisplayCustomerAgreement());
data.put("allowPurchaseItems", this.isAllowPurchaseItems());
data.put("displaySearchBox", this.displaySearchBox);
data.put("testMode", this.isTestMode());
data.put("debugMode", this.isDebugMode());
if(useDefaultSearchConfig!=null) {
JSONObject obj = new JSONObject();
for(String key : useDefaultSearchConfig.keySet()) {
Boolean val = (Boolean)useDefaultSearchConfig.get(key);
if(val!=null) {
obj.put(key,val);
}
}
data.put("useDefaultSearchConfig", obj);
}
if(defaultSearchConfigPath!=null) {
JSONObject obj = new JSONObject();
for(String key : defaultSearchConfigPath.keySet()) {
String val = (String)defaultSearchConfigPath.get(key);
if(!StringUtils.isBlank(val)) {
obj.put(key, val);
}
}
data.put("defaultSearchConfigPath", obj);
}
return data.toJSONString();
| 914
| 427
| 1,341
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/model/tax/TaxConfiguration.java
|
TaxConfiguration
|
toJSONString
|
class TaxConfiguration implements JSONAware {
private TaxBasisCalculation taxBasisCalculation = TaxBasisCalculation.SHIPPINGADDRESS;
private boolean collectTaxIfDifferentProvinceOfStoreCountry = true;
private boolean collectTaxIfDifferentCountryOfStoreCountry = false;
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
public void setTaxBasisCalculation(TaxBasisCalculation taxBasisCalculation) {
this.taxBasisCalculation = taxBasisCalculation;
}
public TaxBasisCalculation getTaxBasisCalculation() {
return taxBasisCalculation;
}
public void setCollectTaxIfDifferentProvinceOfStoreCountry(
boolean collectTaxIfDifferentProvinceOfStoreCountry) {
this.collectTaxIfDifferentProvinceOfStoreCountry = collectTaxIfDifferentProvinceOfStoreCountry;
}
public boolean isCollectTaxIfDifferentProvinceOfStoreCountry() {
return collectTaxIfDifferentProvinceOfStoreCountry;
}
public void setCollectTaxIfDifferentCountryOfStoreCountry(
boolean collectTaxIfDifferentCountryOfStoreCountry) {
this.collectTaxIfDifferentCountryOfStoreCountry = collectTaxIfDifferentCountryOfStoreCountry;
}
public boolean isCollectTaxIfDifferentCountryOfStoreCountry() {
return collectTaxIfDifferentCountryOfStoreCountry;
}
}
|
JSONObject data = new JSONObject();
data.put("taxBasisCalculation", this.getTaxBasisCalculation().name());
return data.toJSONString();
| 356
| 49
| 405
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-model/src/main/java/com/salesmanager/core/utils/CloneUtils.java
|
CloneUtils
|
clone
|
class CloneUtils {
private CloneUtils() {};
public static Date clone(Date date) {<FILL_FUNCTION_BODY>}
}
|
if (date != null) {
return (Date) date.clone();
}
return null;
| 42
| 31
| 73
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-modules/src/main/java/com/salesmanager/core/modules/integration/shipping/model/CustomShippingQuoteWeightItem.java
|
CustomShippingQuoteWeightItem
|
toJSONString
|
class CustomShippingQuoteWeightItem extends CustomShippingQuoteItem implements JSONAware {
private int maximumWeight;
private String priceText;
public String getPriceText() {
return priceText;
}
public void setPriceText(String priceText) {
this.priceText = priceText;
}
public void setMaximumWeight(int maximumWeight) {
this.maximumWeight = maximumWeight;
}
public int getMaximumWeight() {
return maximumWeight;
}
@SuppressWarnings("unchecked")
public String toJSONString() {<FILL_FUNCTION_BODY>}
}
|
JSONObject data = new JSONObject();
data.put("price", super.getPrice());
data.put("maximumWeight", this.getMaximumWeight());
return data.toJSONString();
| 163
| 57
| 220
|
<methods>public non-sealed void <init>() ,public java.math.BigDecimal getPrice() ,public java.lang.String getPriceText() ,public void setPrice(java.math.BigDecimal) ,public void setPriceText(java.lang.String) <variables>private java.math.BigDecimal price,private java.lang.String priceText
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-modules/src/main/java/com/salesmanager/core/modules/integration/shipping/model/CustomShippingQuotesConfiguration.java
|
CustomShippingQuotesConfiguration
|
toJSONString
|
class CustomShippingQuotesConfiguration extends IntegrationConfiguration implements CustomIntegrationConfiguration, Serializable {
/**
*
*/
private String moduleCode;
private List<CustomShippingQuotesRegion> regions = new ArrayList<CustomShippingQuotesRegion>();
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public String toJSONString() {<FILL_FUNCTION_BODY>}
@Override
public String getModuleCode() {
return moduleCode;
}
@Override
public void setModuleCode(String moduleCode) {
this.moduleCode = moduleCode;
}
public void setRegions(List<CustomShippingQuotesRegion> regions) {
this.regions = regions;
}
public List<CustomShippingQuotesRegion> getRegions() {
return regions;
}
}
|
//JSONObject data = new JSONObject();
//data.put("active", super.isActive());
//data.put("moduleCode", this.getModuleCode());
StringBuilder returnString = new StringBuilder();
returnString.append("{");
returnString.append("\"moduleCode\"").append(":\"").append(this.getModuleCode()).append("\"");
returnString.append(",");
returnString.append("\"active\"").append(":").append(this.isActive());
if(regions!=null && regions.size()>0) {
returnString.append(",");
//org.json.simple.JSONArray array=new org.json.simple.JSONArray();
StringBuilder regionsList = new StringBuilder();
int countRegion = 0;
regionsList.append("[");
for(CustomShippingQuotesRegion region : regions) {
regionsList.append(region.toJSONString());
countRegion ++;
if(countRegion<regions.size()) {
regionsList.append(",");
}
}
regionsList.append("]");
returnString.append("\"regions\"").append(":").append(regionsList.toString());
}
//return data.toJSONString();
returnString.append("}");
return returnString.toString();
| 227
| 360
| 587
|
<methods>public non-sealed void <init>() ,public java.lang.String getEnvironment() ,public Map<java.lang.String,java.lang.String> getIntegrationKeys() ,public Map<java.lang.String,List<java.lang.String>> getIntegrationOptions() ,public java.lang.String getModuleCode() ,public boolean isActive() ,public boolean isDefaultSelected() ,public void setActive(boolean) ,public void setDefaultSelected(boolean) ,public void setEnvironment(java.lang.String) ,public void setIntegrationKeys(Map<java.lang.String,java.lang.String>) ,public void setIntegrationOptions(Map<java.lang.String,List<java.lang.String>>) ,public void setModuleCode(java.lang.String) ,public java.lang.String toJSONString() <variables>public static final java.lang.String PRODUCTION_ENVIRONMENT,public static final java.lang.String TEST_ENVIRONMENT,private boolean active,private boolean defaultSelected,private java.lang.String environment,private Map<java.lang.String,java.lang.String> integrationKeys,private Map<java.lang.String,List<java.lang.String>> integrationOptions,private java.lang.String moduleCode
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core-modules/src/main/java/com/salesmanager/core/modules/integration/shipping/model/CustomShippingQuotesRegion.java
|
CustomShippingQuotesRegion
|
toJSONString
|
class CustomShippingQuotesRegion implements JSONAware {
private String customRegionName;//a name given by the merchant for this custom region
private List<String> countries;//a list of country code for this region
private List<CustomShippingQuoteWeightItem> quoteItems;//price max weight
public void setQuoteItems(List<CustomShippingQuoteWeightItem> quoteItems) {
this.quoteItems = quoteItems;
}
public List<CustomShippingQuoteWeightItem> getQuoteItems() {
return quoteItems;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
public List<String> getCountries() {
return countries;
}
public void setCustomRegionName(String customRegionName) {
this.customRegionName = customRegionName;
}
public String getCustomRegionName() {
return customRegionName;
}
public String toJSONString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder returnString = new StringBuilder();
returnString.append("{");
returnString.append("\"customRegionName\"").append(":\"").append(this.getCustomRegionName()).append("\"");
if(countries!=null) {
returnString.append(",");
StringBuilder coutriesList = new StringBuilder();
int countCountry = 0;
coutriesList.append("[");
for(String country : countries) {
coutriesList.append("\"").append(country).append("\"");
countCountry ++;
if(countCountry<countries.size()) {
coutriesList.append(",");
}
}
coutriesList.append("]");
returnString.append("\"countries\"").append(":").append(coutriesList.toString());
}
if(quoteItems!=null) {
returnString.append(",");
StringBuilder quotesList = new StringBuilder();
int countQuotes = 0;
quotesList.append("[");
for(CustomShippingQuoteWeightItem quote : quoteItems) {
quotesList.append(quote.toJSONString());
countQuotes ++;
if(countQuotes<quoteItems.size()) {
quotesList.append(",");
}
}
quotesList.append("]");
returnString.append("\"quoteItems\"").append(":").append(quotesList.toString());
}
returnString.append("}");
return returnString.toString();
| 257
| 409
| 666
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/configuration/DataConfiguration.java
|
DataConfiguration
|
dataSource
|
class DataConfiguration {
/**
* Datasource
*/
@Value("${db.driverClass}")
private String driverClassName;
@Value("${db.jdbcUrl}")
private String url;
@Value("${db.user}")
private String user;
@Value("${db.password}")
private String password;
/**
* Other connection properties
*/
@Value("${hibernate.hbm2ddl.auto}")
private String hbm2ddl;
@Value("${hibernate.dialect}")
private String dialect;
@Value("${db.show.sql}")
private String showSql;
@Value("${db.preferredTestQuery}")
private String preferredTestQuery;
@Value("${db.schema}")
private String schema;
@Value("${db.preferredTestQuery}")
private String testQuery;
@Value("${db.minPoolSize}")
private int minPoolSize;
@Value("${db.maxPoolSize}")
private int maxPoolSize;
@Bean
public HikariDataSource dataSource() {<FILL_FUNCTION_BODY>}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.salesmanager.core.model");
factory.setJpaProperties(additionalProperties());
factory.setDataSource(dataSource());
return factory;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", hbm2ddl);
hibernateProperties.setProperty("hibernate.default_schema", schema);
hibernateProperties.setProperty("hibernate.dialect", dialect);
hibernateProperties.setProperty("hibernate.show_sql", showSql);
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "true");
hibernateProperties.setProperty("hibernate.cache.use_query_cache", "true");
hibernateProperties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
hibernateProperties.setProperty("hibernate.connection.CharSet", "utf8");
hibernateProperties.setProperty("hibernate.connection.characterEncoding", "utf8");
hibernateProperties.setProperty("hibernate.connection.useUnicode", "true");
hibernateProperties.setProperty("hibernate.id.new_generator_mappings", "false"); //unless you run on a new schema
hibernateProperties.setProperty("hibernate.generate_statistics", "false");
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
|
HikariDataSource dataSource = DataSourceBuilder.create().type(HikariDataSource.class)
.driverClassName(driverClassName)
.url(url)
.username(user)
.password(password)
.build();
/** Datasource config **/
dataSource.setIdleTimeout(minPoolSize);
dataSource.setMaximumPoolSize(maxPoolSize);
dataSource.setConnectionTestQuery(testQuery);
return dataSource;
| 900
| 133
| 1,033
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/configuration/DroolsBeanFactory.java
|
DroolsBeanFactory
|
getKieSession
|
class DroolsBeanFactory {
@Value("${config.shipping.rule.priceByDistance}")
private String priceByDistance;
@Value("${config.shipping.rule.shippingModuleDecision}")
private String shippingDecision;
private static final String RULES_PATH = "com/salesmanager/drools/rules/";
private KieServices kieServices = KieServices.Factory.get();
private KieFileSystem getKieFileSystem() throws IOException{
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
List<String> rules=Arrays.asList(priceByDistance,shippingDecision);
for(String rule:rules){
kieFileSystem.write(ResourceFactory.newClassPathResource(rule));
}
return kieFileSystem;
}
public KieContainer getKieContainer() throws IOException {
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
return kieServices.newKieContainer(kieModule.getReleaseId());
}
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
}
public KieSession getKieSession(){<FILL_FUNCTION_BODY>}
public KieSession getKieSession(Resource dt) {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem()
.write(dt);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem)
.buildAll();
KieRepository kieRepository = kieServices.getRepository();
ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);
return kieContainer.newKieSession();
}
/*
* Can be used for debugging
* Input excelFile example: com/baeldung/drools/rules/Discount.xls
*/
public String getDrlFromExcel(String excelFile) {
DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
configuration.setInputType(DecisionTableInputType.XLS);
Resource dt = ResourceFactory.newClassPathResource(excelFile, getClass());
DecisionTableProviderImpl decisionTableProvider = new DecisionTableProviderImpl();
return decisionTableProvider.loadFromResource(dt, null);
}
}
|
getKieRepository();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + priceByDistance));
kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + shippingDecision));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer.newKieSession();
| 696
| 174
| 870
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/configuration/ProcessorsConfiguration.java
|
ProcessorsConfiguration
|
orderTotalsPostProcessors
|
class ProcessorsConfiguration {
@Inject
private PromoCodeCalculatorModule promoCodeCalculatorModule;
/**
* Calculate processors
* @return
*/
@Bean
public List<OrderTotalPostProcessorModule> orderTotalsPostProcessors() {<FILL_FUNCTION_BODY>}
}
|
List<OrderTotalPostProcessorModule> processors = new ArrayList<OrderTotalPostProcessorModule>();
///processors.add(new com.salesmanager.core.business.modules.order.total.ManufacturerShippingCodeOrderTotalModuleImpl());
processors.add(promoCodeCalculatorModule);
return processors;
| 81
| 89
| 170
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/configuration/db/DbConfig.java
|
DbConfig
|
dbCredentials
|
class DbConfig {
@Inject Environment env;
@Bean
public DbCredentials dbCredentials() {<FILL_FUNCTION_BODY>}
}
|
DbCredentials dbCredentials = new DbCredentials();
dbCredentials.setUserName(env.getProperty("user"));
dbCredentials.setPassword(env.getProperty("password"));
return dbCredentials;
| 48
| 61
| 109
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/AsynchronousEventsConfiguration.java
|
AsynchronousEventsConfiguration
|
simpleApplicationEventMulticaster
|
class AsynchronousEventsConfiguration {
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {<FILL_FUNCTION_BODY>}
}
|
SimpleApplicationEventMulticaster eventMulticaster
= new SimpleApplicationEventMulticaster();
eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
return eventMulticaster;
| 56
| 58
| 114
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/cms/content/gcp/GCPStaticContentAssetsManagerImpl.java
|
GCPStaticContentAssetsManagerImpl
|
getFileNames
|
class GCPStaticContentAssetsManagerImpl implements ContentAssetsManager {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(GCPStaticContentAssetsManagerImpl.class);
@Autowired
@Qualifier("gcpAssetsManager")
private CMSManager cmsManager;
@Override
public OutputContentFile getFile(String merchantStoreCode, Optional<String> folderPath, FileContentType fileContentType, String contentName)
throws ServiceException {
try {
String bucketName = bucketName();
// Instantiates a client
Storage storage = StorageOptions.getDefaultInstance().getService();
Blob blob = storage.get(BlobId.of(bucketName, nodePath(merchantStoreCode, fileContentType) + contentName));
LOGGER.info("Content getFile");
return getOutputContentFile(blob.getContent(BlobSourceOption.generationMatch()));
} catch (Exception e) {
LOGGER.error("Error while getting file", e);
throw new ServiceException(e);
}
}
@Override
public List<String> getFileNames(String merchantStoreCode, Optional<String> folderPath, FileContentType fileContentType)
throws ServiceException {<FILL_FUNCTION_BODY>}
@Override
public List<OutputContentFile> getFiles(String merchantStoreCode, Optional<String> folderPath, FileContentType fileContentType)
throws ServiceException {
try {
List<String> fileNames = getFileNames(merchantStoreCode, folderPath, fileContentType);
List<OutputContentFile> files = new ArrayList<OutputContentFile>();
for (String fileName : fileNames) {
files.add(getFile(merchantStoreCode, folderPath, fileContentType, fileName));
}
LOGGER.info("Content get file names");
return files;
} catch (Exception e) {
LOGGER.error("Error while getting file names", e);
throw new ServiceException(e);
}
}
@Override
public void addFile(String merchantStoreCode, Optional<String> folderPath, InputContentFile inputStaticContentData) throws ServiceException {
try {
LOGGER.debug("Adding file " + inputStaticContentData.getFileName());
String bucketName = bucketName();
String nodePath = nodePath(merchantStoreCode, inputStaticContentData.getFileContentType());
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of(bucketName, nodePath + inputStaticContentData.getFileName());
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(inputStaticContentData.getFileContentType().name())
.build();
byte[] targetArray = new byte[inputStaticContentData.getFile().available()];
inputStaticContentData.getFile().read(targetArray);
storage.create(blobInfo, targetArray);
LOGGER.info("Content add file");
} catch (IOException e) {
LOGGER.error("Error while adding file", e);
throw new ServiceException(e);
}
}
@Override
public void addFiles(String merchantStoreCode, Optional<String> folderPath, List<InputContentFile> inputStaticContentDataList)
throws ServiceException {
if (CollectionUtils.isNotEmpty(inputStaticContentDataList)) {
for (InputContentFile inputFile : inputStaticContentDataList) {
this.addFile(merchantStoreCode, folderPath, inputFile);
}
}
}
@Override
public void removeFile(String merchantStoreCode, FileContentType staticContentType, String fileName, Optional<String> folderPath)
throws ServiceException {
try {
String bucketName = bucketName();
Storage storage = StorageOptions.getDefaultInstance().getService();
storage.delete(bucketName, nodePath(merchantStoreCode, staticContentType) + fileName);
LOGGER.info("Remove file");
} catch (final Exception e) {
LOGGER.error("Error while removing file", e);
throw new ServiceException(e);
}
}
@Override
public void removeFiles(String merchantStoreCode, Optional<String> folderPath) throws ServiceException {
try {
// get buckets
String bucketName = bucketName();
Storage storage = StorageOptions.getDefaultInstance().getService();
storage.delete(bucketName, nodePath(merchantStoreCode));
LOGGER.info("Remove folder");
} catch (final Exception e) {
LOGGER.error("Error while removing folder", e);
throw new ServiceException(e);
}
}
public CMSManager getCmsManager() {
return cmsManager;
}
public void setCmsManager(CMSManager cmsManager) {
this.cmsManager = cmsManager;
}
@Override
public void addFolder(String merchantStoreCode, String folderName, Optional<String> folderPath) throws ServiceException {
// TODO Auto-generated method stub
}
@Override
public void removeFolder(String merchantStoreCode, String folderName, Optional<String> folderPath) throws ServiceException {
// TODO Auto-generated method stub
}
@Override
public List<String> listFolders(String merchantStoreCode, Optional<String> folderPath) throws ServiceException {
// TODO Auto-generated method stub
return null;
}
}
|
try {
String bucketName = bucketName();
Storage storage = StorageOptions.getDefaultInstance().getService();
long bucketMetaGeneration = 42;
Bucket bucket = storage.get(bucketName, BucketGetOption.metagenerationMatch(bucketMetaGeneration));
Page<Blob> blobs = bucket.list(Storage.BlobListOption.prefix(nodePath(merchantStoreCode, fileContentType)),
Storage.BlobListOption.fields(BlobField.NAME));
List<String> fileNames = new ArrayList<String>();
for (Blob blob : blobs.iterateAll()) {
if (isInsideSubFolder(blob.getName()))
continue;
String mimetype = URLConnection.guessContentTypeFromName(blob.getName());
if (!StringUtils.isBlank(mimetype)) {
fileNames.add(getName(blob.getName()));
}
}
LOGGER.info("Content get file names");
return fileNames;
} catch (Exception e) {
LOGGER.error("Error while getting file names", e);
throw new ServiceException(e);
}
| 1,398
| 305
| 1,703
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/cms/impl/CacheManagerImpl.java
|
CacheManagerImpl
|
init
|
class CacheManagerImpl implements CacheManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheManagerImpl.class);
//private static final String LOCATION_PROPERTIES = "location";
protected String location = null;
@SuppressWarnings("rawtypes")
private TreeCache treeCache = null;
@SuppressWarnings("unchecked")
protected void init(String namedCache, String locationFolder) {<FILL_FUNCTION_BODY>}
public EmbeddedCacheManager getManager() {
return VendorCacheManager.getInstance().getManager();
}
@SuppressWarnings("rawtypes")
public TreeCache getTreeCache() {
return treeCache;
}
}
|
try {
this.location = locationFolder;
// manager = new DefaultCacheManager(repositoryFileName);
VendorCacheManager manager = VendorCacheManager.getInstance();
if (manager == null) {
LOGGER.error("CacheManager is null");
return;
}
TreeCacheFactory f = null;
/* @SuppressWarnings("rawtypes")
Cache c = manager.getManager().getCache(namedCache);
if(c != null) {
f = new TreeCacheFactory();
treeCache = f.createTreeCache(c);
//this.treeCache = (TreeCache)c;
return;
}*/
Configuration config = new ConfigurationBuilder()
.persistence().passivation(false)
.addSingleFileStore()
.segmented(false)
.location(location).async().enable()
.preload(false).shared(false)
.invocationBatching().enable()
.build();
manager.getManager().defineConfiguration(namedCache, config);
final Cache<String, String> cache = manager.getManager().getCache(namedCache);
f = new TreeCacheFactory();
treeCache = f.createTreeCache(cache);
cache.start();
LOGGER.debug("CMS started");
} catch (Exception e) {
LOGGER.error("Error while instantiating CmsImageFileManager", e);
} finally {
}
| 190
| 400
| 590
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/cms/impl/VendorCacheManager.java
|
VendorCacheManager
|
getInstance
|
class VendorCacheManager {
private static final Logger LOGGER = LoggerFactory.getLogger(VendorCacheManager.class);
private EmbeddedCacheManager manager = null;
private static VendorCacheManager vendorCacheManager = null;
private VendorCacheManager() {
try {
manager = new DefaultCacheManager();
} catch (Exception e) {
LOGGER.error("Cannot start manager " + e.toString());
}
}
public static VendorCacheManager getInstance() {<FILL_FUNCTION_BODY>}
public EmbeddedCacheManager getManager() {
return manager;
}
}
|
if (vendorCacheManager == null) {
vendorCacheManager = new VendorCacheManager();
}
return vendorCacheManager;
| 166
| 37
| 203
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/cms/product/local/CmsImageFileManagerImpl.java
|
CmsImageFileManagerImpl
|
removeProductImage
|
class CmsImageFileManagerImpl
implements ProductAssetsManager {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(CmsImageFileManagerImpl.class);
private static CmsImageFileManagerImpl fileManager = null;
private final static String ROOT_NAME = "";
private final static String SMALL = "SMALL";
private final static String LARGE = "LARGE";
private static final String ROOT_CONTAINER = "products";
private String rootName = ROOT_NAME;
private LocalCacheManagerImpl cacheManager;
@PostConstruct
void init() {
this.rootName = ((CMSManager) cacheManager).getRootName();
LOGGER.info("init " + getClass().getName() + " setting root" + this.rootName);
}
public static CmsImageFileManagerImpl getInstance() {
if (fileManager == null) {
fileManager = new CmsImageFileManagerImpl();
}
return fileManager;
}
private CmsImageFileManagerImpl() {
}
/**
* root/products/<merchant id>/<product id>/1.jpg
*/
@Override
public void addProductImage(ProductImage productImage, ImageContentFile contentImage)
throws ServiceException {
try {
// base path
String rootPath = this.buildRootPath();
Path confDir = Paths.get(rootPath);
this.createDirectoryIfNorExist(confDir);
// node path
StringBuilder nodePath = new StringBuilder();
nodePath.append(rootPath).append(productImage.getProduct().getMerchantStore().getCode());
Path merchantPath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(merchantPath);
// product path
nodePath.append(Constants.SLASH).append(productImage.getProduct().getSku())
.append(Constants.SLASH);
Path dirPath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(dirPath);
// small large
if (contentImage.getFileContentType().name().equals(FileContentType.PRODUCT.name())) {
nodePath.append(SMALL);
} else if (contentImage.getFileContentType().name()
.equals(FileContentType.PRODUCTLG.name())) {
nodePath.append(LARGE);
}
Path sizePath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(sizePath);
// file creation
nodePath.append(Constants.SLASH).append(contentImage.getFileName());
Path path = Paths.get(nodePath.toString());
InputStream isFile = contentImage.getFile();
Files.copy(isFile, path, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public OutputContentFile getProductImage(ProductImage productImage) throws ServiceException {
// the web server takes care of the images
return null;
}
public List<OutputContentFile> getImages(MerchantStore store, FileContentType imageContentType)
throws ServiceException {
// the web server takes care of the images
return null;
}
@Override
public List<OutputContentFile> getImages(Product product) throws ServiceException {
// the web server takes care of the images
return null;
}
@Override
public void removeImages(final String merchantStoreCode) throws ServiceException {
try {
StringBuilder merchantPath = new StringBuilder();
merchantPath.append(buildRootPath()).append(Constants.SLASH).append(merchantStoreCode);
Path path = Paths.get(merchantPath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public void removeProductImage(ProductImage productImage) throws ServiceException {<FILL_FUNCTION_BODY>}
@Override
public void removeProductImages(Product product) throws ServiceException {
try {
StringBuilder nodePath = new StringBuilder();
nodePath.append(buildRootPath()).append(Constants.SLASH)
.append(product.getMerchantStore().getCode()).append(Constants.SLASH)
.append(product.getSku());
Path path = Paths.get(nodePath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public List<OutputContentFile> getImages(final String merchantStoreCode,
FileContentType imageContentType) throws ServiceException {
// the web server taks care of the images
return null;
}
@Override
public OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName) throws ServiceException {
return getProductImage(merchantStoreCode, productCode, imageName,
ProductImageSize.SMALL.name());
}
@Override
public OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName, ProductImageSize size) throws ServiceException {
return getProductImage(merchantStoreCode, productCode, imageName, size.name());
}
private OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName, String size) throws ServiceException {
return null;
}
private String buildRootPath() {
return new StringBuilder().append(getRootName()).append(Constants.SLASH).append(ROOT_CONTAINER)
.append(Constants.SLASH).toString();
}
private void createDirectoryIfNorExist(Path path) throws IOException {
if (Files.notExists(path)) {
Files.createDirectory(path);
}
}
public void setRootName(String rootName) {
this.rootName = rootName;
}
public String getRootName() {
return rootName;
}
public LocalCacheManagerImpl getCacheManager() {
return cacheManager;
}
public void setCacheManager(LocalCacheManagerImpl cacheManager) {
this.cacheManager = cacheManager;
}
}
|
try {
StringBuilder nodePath = new StringBuilder();
nodePath.append(buildRootPath()).append(Constants.SLASH)
.append(productImage.getProduct().getMerchantStore().getCode()).append(Constants.SLASH)
.append(productImage.getProduct().getSku());
// delete small
StringBuilder smallPath = new StringBuilder(nodePath);
smallPath.append(Constants.SLASH).append(SMALL).append(Constants.SLASH)
.append(productImage.getProductImage());
Path path = Paths.get(smallPath.toString());
Files.deleteIfExists(path);
// delete large
StringBuilder largePath = new StringBuilder(nodePath);
largePath.append(Constants.SLASH).append(LARGE).append(Constants.SLASH)
.append(productImage.getProductImage());
path = Paths.get(largePath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
| 1,666
| 273
| 1,939
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/email/DefaultEmailSenderImpl.java
|
DefaultEmailSenderImpl
|
prepare
|
class DefaultEmailSenderImpl implements EmailModule {
@Inject
private Configuration freemarkerMailConfiguration;
@Inject
private JavaMailSender mailSender;
private static final String CHARSET = "UTF-8";
private EmailConfig emailConfig;
private final static String TEMPLATE_PATH = "templates/email";
@Override
public void send(Email email) throws Exception {
final String eml = email.getFrom();
final String from = email.getFromEmail();
final String to = email.getTo();
final String subject = email.getSubject();
final String tmpl = email.getTemplateName();
final Map<String, String> templateTokens = email.getTemplateTokens();
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException {<FILL_FUNCTION_BODY>}
};
mailSender.send(preparator);
}
public Configuration getFreemarkerMailConfiguration() {
return freemarkerMailConfiguration;
}
public void setFreemarkerMailConfiguration(Configuration freemarkerMailConfiguration) {
this.freemarkerMailConfiguration = freemarkerMailConfiguration;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public EmailConfig getEmailConfig() {
return emailConfig;
}
public void setEmailConfig(EmailConfig emailConfig) {
this.emailConfig = emailConfig;
}
}
|
JavaMailSenderImpl impl = (JavaMailSenderImpl) mailSender;
// if email configuration is present in Database, use the same
if (emailConfig != null) {
impl.setProtocol(emailConfig.getProtocol());
impl.setHost(emailConfig.getHost());
impl.setPort(Integer.parseInt(emailConfig.getPort()));
impl.setUsername(emailConfig.getUsername());
impl.setPassword(emailConfig.getPassword());
Properties prop = new Properties();
prop.put("mail.smtp.auth", emailConfig.isSmtpAuth());
prop.put("mail.smtp.starttls.enable", emailConfig.isStarttls());
impl.setJavaMailProperties(prop);
}
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
InternetAddress inetAddress = new InternetAddress();
inetAddress.setPersonal(eml);
inetAddress.setAddress(from);
mimeMessage.setFrom(inetAddress);
mimeMessage.setSubject(subject);
Multipart mp = new MimeMultipart("alternative");
// Create a "text" Multipart message
BodyPart textPart = new MimeBodyPart();
freemarkerMailConfiguration.setClassForTemplateLoading(DefaultEmailSenderImpl.class, "/");
Template textTemplate = freemarkerMailConfiguration.getTemplate(
new StringBuilder(TEMPLATE_PATH).append("/").append(tmpl).toString());
final StringWriter textWriter = new StringWriter();
try {
textTemplate.process(templateTokens, textWriter);
} catch (TemplateException e) {
throw new MailPreparationException("Can't generate text mail", e);
}
textPart.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {
public InputStream getInputStream() throws IOException {
// return new StringBufferInputStream(textWriter
// .toString());
return new ByteArrayInputStream(textWriter.toString().getBytes(CHARSET));
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Read-only data");
}
public String getContentType() {
return "text/plain";
}
public String getName() {
return "main";
}
}));
mp.addBodyPart(textPart);
// Create a "HTML" Multipart message
Multipart htmlContent = new MimeMultipart("related");
BodyPart htmlPage = new MimeBodyPart();
freemarkerMailConfiguration.setClassForTemplateLoading(DefaultEmailSenderImpl.class, "/");
Template htmlTemplate = freemarkerMailConfiguration.getTemplate(
new StringBuilder(TEMPLATE_PATH).append("/").append(tmpl).toString());
final StringWriter htmlWriter = new StringWriter();
try {
htmlTemplate.process(templateTokens, htmlWriter);
} catch (TemplateException e) {
throw new MailPreparationException("Can't generate HTML mail", e);
}
htmlPage.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {
public InputStream getInputStream() throws IOException {
// return new StringBufferInputStream(htmlWriter
// .toString());
return new ByteArrayInputStream(textWriter.toString().getBytes(CHARSET));
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Read-only data");
}
public String getContentType() {
return "text/html";
}
public String getName() {
return "main";
}
}));
htmlContent.addBodyPart(htmlPage);
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent);
mp.addBodyPart(htmlPart);
mimeMessage.setContent(mp);
// if(attachment!=null) {
// MimeMessageHelper messageHelper = new
// MimeMessageHelper(mimeMessage, true);
// messageHelper.addAttachment(attachmentFileName, attachment);
// }
| 439
| 1,033
| 1,472
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/email/EmailComponent.java
|
EmailComponent
|
send
|
class EmailComponent implements HtmlEmailSender {
@Value("${config.emailSender}")
private String emailSender;
@Inject
private EmailModule defaultEmailSender;
@Inject
private EmailModule sesEmailSender;
@Override
public void send(Email email) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void setEmailConfig(EmailConfig emailConfig) {
switch(emailSender)
{
case "default":
defaultEmailSender.setEmailConfig(emailConfig);
break;
case "ses":
sesEmailSender.setEmailConfig(emailConfig);
break;
default:
}
}
}
|
switch(emailSender)
{
case "default":
defaultEmailSender.send(email);
break;
case "ses":
sesEmailSender.send(email);
break;
default:
throw new Exception("No email implementation for " + emailSender);
}
| 200
| 89
| 289
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/email/EmailConfig.java
|
EmailConfig
|
toJSONString
|
class EmailConfig implements JSONAware {
private String host;
private String port;
private String protocol;
private String username;
private String password;
private boolean smtpAuth = false;
private boolean starttls = false;
private String emailTemplatesPath = null;
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
public boolean isSmtpAuth() {
return smtpAuth;
}
public void setSmtpAuth(boolean smtpAuth) {
this.smtpAuth = smtpAuth;
}
public boolean isStarttls() {
return starttls;
}
public void setStarttls(boolean starttls) {
this.starttls = starttls;
}
public void setEmailTemplatesPath(String emailTemplatesPath) {
this.emailTemplatesPath = emailTemplatesPath;
}
public String getEmailTemplatesPath() {
return emailTemplatesPath;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
JSONObject data = new JSONObject();
data.put("host", this.getHost());
data.put("port", this.getPort());
data.put("protocol", this.getProtocol());
data.put("username", this.getUsername());
data.put("smtpAuth", this.isSmtpAuth());
data.put("starttls", this.isStarttls());
data.put("password", this.getPassword());
return data.toJSONString();
| 457
| 131
| 588
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/email/SESEmailSenderImpl.java
|
SESEmailSenderImpl
|
prepareHtml
|
class SESEmailSenderImpl implements EmailModule {
@Inject
private Configuration freemarkerMailConfiguration;
@Value("${config.emailSender.region}")
private String region;
private final static String TEMPLATE_PATH = "templates/email";
// The configuration set to use for this email. If you do not want to use a
// configuration set, comment the following variable and the
// .withConfigurationSetName(CONFIGSET); argument below.
//static final String CONFIGSET = "ConfigSet";
// The email body for recipients with non-HTML email clients.
static final String TEXTBODY =
"This email was sent through Amazon SES " + "using the AWS SDK for Java.";
@Override
public void send(Email email) throws Exception {
//String eml = email.getFrom();
Validate.notNull(region,"AWS region is null");
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
// Replace US_WEST_2 with the AWS Region you're using for
// Amazon SES.
.withRegion(Regions.valueOf(region.toUpperCase())).build();
SendEmailRequest request = new SendEmailRequest()
.withDestination(new Destination().withToAddresses(email.getTo()))
.withMessage(new Message()
.withBody(new Body().withHtml(new Content().withCharset("UTF-8").withData(prepareHtml(email)))
.withText(new Content().withCharset("UTF-8").withData(TEXTBODY)))
.withSubject(new Content().withCharset("UTF-8").withData(email.getSubject())))
.withSource(email.getFromEmail());
// Comment or remove the next line if you are not using a
// configuration set
//.withConfigurationSetName(CONFIGSET);
client.sendEmail(request);
}
private String prepareHtml(Email email) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void setEmailConfig(EmailConfig emailConfig) {
// TODO Auto-generated method stub
}
}
|
freemarkerMailConfiguration.setClassForTemplateLoading(DefaultEmailSenderImpl.class, "/");
Template htmlTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH)
.append("/").append(email.getTemplateName()).toString());
final StringWriter htmlWriter = new StringWriter();
try {
htmlTemplate.process(email.getTemplateTokens(), htmlWriter);
} catch (TemplateException e) {
throw new MailPreparationException("Can't generate HTML mail", e);
}
return htmlWriter.toString();
| 546
| 148
| 694
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/integration/payment/impl/MoneyOrderPayment.java
|
MoneyOrderPayment
|
authorizeAndCapture
|
class MoneyOrderPayment implements PaymentModule {
@Override
public void validateModuleConfiguration(
IntegrationConfiguration integrationConfiguration,
MerchantStore store) throws IntegrationException {
List<String> errorFields = null;
Map<String,String> keys = integrationConfiguration.getIntegrationKeys();
//validate integrationKeys['address']
if(keys==null || StringUtils.isBlank(keys.get("address"))) {
errorFields = new ArrayList<String>();
errorFields.add("address");
}
if(errorFields!=null) {
IntegrationException ex = new IntegrationException(IntegrationException.ERROR_VALIDATION_SAVE);
ex.setErrorFields(errorFields);
throw ex;
}
}
@Override
public Transaction initTransaction(MerchantStore store, Customer customer,
BigDecimal amount, Payment payment,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
//NOT REQUIRED
return null;
}
@Override
public Transaction authorize(MerchantStore store, Customer customer,
List<ShoppingCartItem> items, BigDecimal amount, Payment payment,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
//NOT REQUIRED
return null;
}
/* @Override
public Transaction capture(MerchantStore store, Customer customer,
List<ShoppingCartItem> items, BigDecimal amount, Payment payment, Transaction transaction,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
//NOT REQUIRED
return null;
}*/
@Override
public Transaction authorizeAndCapture(MerchantStore store, Customer customer,
List<ShoppingCartItem> items, BigDecimal amount, Payment payment,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {<FILL_FUNCTION_BODY>}
@Override
public Transaction refund(boolean partial, MerchantStore store, Transaction transaction,
Order order, BigDecimal amount,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
throw new IntegrationException("Transaction not supported");
}
@Override
public Transaction capture(MerchantStore store, Customer customer,
Order order, Transaction capturableTransaction,
IntegrationConfiguration configuration, IntegrationModule module)
throws IntegrationException {
// TODO Auto-generated method stub
return null;
}
}
|
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setTransactionDate(new Date());
transaction.setTransactionType(TransactionType.AUTHORIZECAPTURE);
transaction.setPaymentType(PaymentType.MONEYORDER);
return transaction;
| 638
| 93
| 731
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/integration/shipping/impl/CustomShippingQuoteRules.java
|
CustomShippingQuoteRules
|
getShippingQuotes
|
class CustomShippingQuoteRules implements ShippingQuoteModule {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomShippingQuoteRules.class);
@Inject
private DroolsBeanFactory droolsBeanFactory;
public final static String MODULE_CODE = "customQuotesRules";
@Override
public void validateModuleConfiguration(
IntegrationConfiguration integrationConfiguration,
MerchantStore store) throws IntegrationException {
// Not used
}
@Override
public CustomIntegrationConfiguration getCustomModuleConfiguration(
MerchantStore store) throws IntegrationException {
// Not used
return null;
}
@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote quote,
List<PackageDetails> packages, BigDecimal orderTotal,
Delivery delivery, ShippingOrigin origin, MerchantStore store,
IntegrationConfiguration configuration, IntegrationModule module,
ShippingConfiguration shippingConfiguration, Locale locale)
throws IntegrationException {<FILL_FUNCTION_BODY>}
/* public StatelessKnowledgeSession getShippingPriceRule() {
return shippingPriceRule;
}
public void setShippingPriceRule(StatelessKnowledgeSession shippingPriceRule) {
this.shippingPriceRule = shippingPriceRule;
}
public KnowledgeBase getKbase() {
return kbase;
}
public void setKbase(KnowledgeBase kbase) {
this.kbase = kbase;
}*/
}
|
Validate.notNull(delivery, "Delivery cannot be null");
Validate.notNull(delivery.getCountry(), "Delivery.country cannot be null");
Validate.notNull(packages, "packages cannot be null");
Validate.notEmpty(packages, "packages cannot be empty");
//requires the postal code
if(StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
Double distance = null;
if(quote!=null) {
//look if distance has been calculated
if(quote.getQuoteInformations()!=null) {
if(quote.getQuoteInformations().containsKey(Constants.DISTANCE_KEY)) {
distance = (Double)quote.getQuoteInformations().get(Constants.DISTANCE_KEY);
}
}
}
//calculate volume (L x W x H)
Double volume = null;
Double weight = 0D;
Double size = null;
//calculate weight
for(PackageDetails pack : packages) {
weight = weight + pack.getShippingWeight();
Double tmpVolume = pack.getShippingHeight() * pack.getShippingLength() * pack.getShippingWidth();
if(volume == null || tmpVolume > volume) { //take the largest volume
volume = tmpVolume;
}
//largest size
List<Double> sizeList = new ArrayList<Double>();
sizeList.add(pack.getShippingHeight());
sizeList.add(pack.getShippingWidth());
sizeList.add(pack.getShippingLength());
Double maxSize = Collections.max(sizeList);
if(size==null || maxSize > size) {
size = maxSize;
}
}
//Build a ShippingInputParameters
ShippingInputParameters inputParameters = new ShippingInputParameters();
inputParameters.setWeight((long)weight.doubleValue());
inputParameters.setCountry(delivery.getCountry().getIsoCode());
inputParameters.setProvince("*");
inputParameters.setModuleName(module.getCode());
if(delivery.getZone() != null && delivery.getZone().getCode()!=null) {
inputParameters.setProvince(delivery.getZone().getCode());
}
if(distance!=null) {
double ddistance = distance;
long ldistance = (long)ddistance;
inputParameters.setDistance(ldistance);
}
if(volume!=null) {
inputParameters.setVolume((long)volume.doubleValue());
}
List<ShippingOption> options = quote.getShippingOptions();
if(options == null) {
options = new ArrayList<ShippingOption>();
quote.setShippingOptions(options);
}
LOGGER.debug("Setting input parameters " + inputParameters.toString());
KieSession kieSession=droolsBeanFactory.getKieSession(ResourceFactory.newClassPathResource("com/salesmanager/drools/rules/PriceByDistance.drl"));
DecisionResponse resp = new DecisionResponse();
kieSession.insert(inputParameters);
kieSession.setGlobal("decision",resp);
kieSession.fireAllRules();
//System.out.println(resp.getCustomPrice());
if(resp.getCustomPrice() != null) {
ShippingOption shippingOption = new ShippingOption();
shippingOption.setOptionPrice(new BigDecimal(resp.getCustomPrice()));
shippingOption.setShippingModuleCode(MODULE_CODE);
shippingOption.setOptionCode(MODULE_CODE);
shippingOption.setOptionId(MODULE_CODE);
options.add(shippingOption);
}
return options;
| 381
| 1,043
| 1,424
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/integration/shipping/impl/CustomWeightBasedShippingQuote.java
|
CustomWeightBasedShippingQuote
|
validateModuleConfiguration
|
class CustomWeightBasedShippingQuote implements ShippingQuoteModule {
public final static String MODULE_CODE = "weightBased";
private final static String CUSTOM_WEIGHT = "CUSTOM_WEIGHT";
@Inject
private MerchantConfigurationService merchantConfigurationService;
@Inject
private ProductPriceUtils productPriceUtils;
@Override
public void validateModuleConfiguration(
IntegrationConfiguration integrationConfiguration,
MerchantStore store) throws IntegrationException {<FILL_FUNCTION_BODY>}
@Override
public CustomIntegrationConfiguration getCustomModuleConfiguration(
MerchantStore store) throws IntegrationException {
try {
MerchantConfiguration configuration = merchantConfigurationService.getMerchantConfiguration(MODULE_CODE, store);
if(configuration!=null) {
String value = configuration.getValue();
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(value, CustomShippingQuotesConfiguration.class);
} catch(Exception e) {
throw new ServiceException("Cannot parse json string " + value);
}
} else {
CustomShippingQuotesConfiguration custom = new CustomShippingQuotesConfiguration();
custom.setModuleCode(MODULE_CODE);
return custom;
}
} catch (Exception e) {
throw new IntegrationException(e);
}
}
@Override
public List<ShippingOption> getShippingQuotes(
ShippingQuote shippingQuote,
List<PackageDetails> packages, BigDecimal orderTotal,
Delivery delivery, ShippingOrigin origin, MerchantStore store,
IntegrationConfiguration configuration, IntegrationModule module,
ShippingConfiguration shippingConfiguration, Locale locale)
throws IntegrationException {
if(StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
//get configuration
CustomShippingQuotesConfiguration customConfiguration = (CustomShippingQuotesConfiguration)this.getCustomModuleConfiguration(store);
List<CustomShippingQuotesRegion> regions = customConfiguration.getRegions();
ShippingBasisType shippingType = shippingConfiguration.getShippingBasisType();
ShippingOption shippingOption = null;
try {
for(CustomShippingQuotesRegion region : customConfiguration.getRegions()) {
for(String countryCode : region.getCountries()) {
if(countryCode.equals(delivery.getCountry().getIsoCode())) {
//determine shipping weight
double weight = 0;
for(PackageDetails packageDetail : packages) {
weight = weight + packageDetail.getShippingWeight();
}
//see the price associated with the width
List<CustomShippingQuoteWeightItem> quoteItems = region.getQuoteItems();
for(CustomShippingQuoteWeightItem quoteItem : quoteItems) {
if(weight<= quoteItem.getMaximumWeight()) {
shippingOption = new ShippingOption();
shippingOption.setOptionCode(new StringBuilder().append(CUSTOM_WEIGHT).toString());
shippingOption.setOptionId(new StringBuilder().append(CUSTOM_WEIGHT).append("_").append(region.getCustomRegionName()).toString());
shippingOption.setOptionPrice(quoteItem.getPrice());
shippingOption.setOptionPriceText(productPriceUtils.getStoreFormatedAmountWithCurrency(store, quoteItem.getPrice()));
break;
}
}
}
}
}
if(shippingOption!=null) {
List<ShippingOption> options = new ArrayList<ShippingOption>();
options.add(shippingOption);
return options;
}
return null;
} catch (Exception e) {
throw new IntegrationException(e);
}
}
}
|
//not used, it has its own controller with complex validators
| 1,021
| 23
| 1,044
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/integration/shipping/impl/PriceByDistanceShippingQuoteRules.java
|
PriceByDistanceShippingQuoteRules
|
getShippingQuotes
|
class PriceByDistanceShippingQuoteRules implements ShippingQuoteModule {
private static final Logger LOGGER = LoggerFactory.getLogger(PriceByDistanceShippingQuoteRules.class);
public final static String MODULE_CODE = "priceByDistance";
@Override
public void validateModuleConfiguration(
IntegrationConfiguration integrationConfiguration,
MerchantStore store) throws IntegrationException {
// Not used
}
@Override
public CustomIntegrationConfiguration getCustomModuleConfiguration(
MerchantStore store) throws IntegrationException {
// Not used
return null;
}
@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote quote,
List<PackageDetails> packages, BigDecimal orderTotal,
Delivery delivery, ShippingOrigin origin, MerchantStore store,
IntegrationConfiguration configuration, IntegrationModule module,
ShippingConfiguration shippingConfiguration, Locale locale)
throws IntegrationException {<FILL_FUNCTION_BODY>}
}
|
Validate.notNull(delivery, "Delivery cannot be null");
Validate.notNull(delivery.getCountry(), "Delivery.country cannot be null");
Validate.notNull(packages, "packages cannot be null");
Validate.notEmpty(packages, "packages cannot be empty");
//requires the postal code
if(StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
Double distance = null;
//look if distance has been calculated
if (Objects.nonNull(quote) && Objects.nonNull(quote.getQuoteInformations())) {
if (quote.getQuoteInformations().containsKey(Constants.DISTANCE_KEY)) {
distance = (Double) quote.getQuoteInformations().get(Constants.DISTANCE_KEY);
}
}
if(distance==null) {
return null;
}
//maximum distance TODO configure from admin
if(distance > 150D) {
return null;
}
List<ShippingOption> options = quote.getShippingOptions();
if(options == null) {
options = new ArrayList<>();
quote.setShippingOptions(options);
}
BigDecimal price = null;
if(distance<=20) {
price = new BigDecimal(2);//TODO from the admin
} else {
price = new BigDecimal(3);//TODO from the admin
}
BigDecimal total = new BigDecimal(distance).multiply(price);
if(distance < 1) { //minimum 1 unit
distance = 1D;
}
ShippingOption shippingOption = new ShippingOption();
shippingOption.setOptionPrice(total);
shippingOption.setShippingModuleCode(MODULE_CODE);
shippingOption.setOptionCode(MODULE_CODE);
shippingOption.setOptionId(MODULE_CODE);
options.add(shippingOption);
return options;
| 256
| 560
| 816
|
<no_super_class>
|
shopizer-ecommerce_shopizer
|
shopizer/sm-core/src/main/java/com/salesmanager/core/business/modules/integration/shipping/impl/ShippingDecisionPreProcessorImpl.java
|
ShippingDecisionPreProcessorImpl
|
prePostProcessShippingQuotes
|
class ShippingDecisionPreProcessorImpl implements ShippingQuotePrePostProcessModule {
private static final Logger LOGGER = LoggerFactory.getLogger(ShippingDecisionPreProcessorImpl.class);
private final static String MODULE_CODE = "shippingDecisionModule";
@Inject
private DroolsBeanFactory droolsBeanFactory;
//private StatelessKnowledgeSession shippingMethodDecision;
//private KnowledgeBase kbase;
//@Inject
//KieContainer kieShippingDecisionContainer;
@Override
public void prePostProcessShippingQuotes(
ShippingQuote quote,
List<PackageDetails> packages,
BigDecimal orderTotal,
Delivery delivery,
ShippingOrigin origin,
MerchantStore store,
IntegrationConfiguration globalShippingConfiguration,
IntegrationModule currentModule,
ShippingConfiguration shippingConfiguration,
List<IntegrationModule> allModules,
Locale locale)
throws IntegrationException {<FILL_FUNCTION_BODY>}
@Override
public String getModuleCode() {
return MODULE_CODE;
}
}
|
Validate.notNull(delivery, "Delivery cannot be null");
Validate.notNull(currentModule, "IntegrationModule cannot be null");
Validate.notNull(delivery.getCountry(), "Delivery.country cannot be null");
Validate.notNull(allModules, "List<IntegrationModule> cannot be null");
Validate.notNull(packages, "packages cannot be null");
Validate.notEmpty(packages, "packages cannot be empty");
Double distance = null;
if(quote!=null) {
//look if distance has been calculated
if(quote.getQuoteInformations()!=null) {
if(quote.getQuoteInformations().containsKey(Constants.DISTANCE_KEY)) {
distance = (Double)quote.getQuoteInformations().get(Constants.DISTANCE_KEY);
}
}
}
//calculate volume (L x W x H)
Double volume = null;
Double weight = 0D;
Double size = null;
//calculate weight, volume and largest size
for(PackageDetails pack : packages) {
weight = weight + pack.getShippingWeight();
Double tmpVolume = pack.getShippingHeight() * pack.getShippingLength() * pack.getShippingWidth();
if(volume == null || tmpVolume > volume) { //take the largest volume
volume = tmpVolume;
}
//largest size
List<Double> sizeList = new ArrayList<Double>();
sizeList.add(pack.getShippingHeight());
sizeList.add(pack.getShippingLength());
sizeList.add(pack.getShippingWidth());
Double maxSize = Collections.max(sizeList);
if(size==null || maxSize > size) {
size = maxSize;
}
}
//Build a ShippingInputParameters
ShippingInputParameters inputParameters = new ShippingInputParameters();
inputParameters.setWeight((long)weight.doubleValue());
inputParameters.setCountry(delivery.getCountry().getIsoCode());
if(delivery.getZone()!=null && delivery.getZone().getCode()!=null) {
inputParameters.setProvince(delivery.getZone().getCode());
} else {
inputParameters.setProvince(delivery.getState());
}
//inputParameters.setModuleName(currentModule.getCode());
if(size!=null) {
inputParameters.setSize((long)size.doubleValue());
}
if(distance!=null) {
double ddistance = distance;
long ldistance = (long)ddistance;
inputParameters.setDistance(ldistance);
}
if(volume!=null) {
inputParameters.setVolume((long)volume.doubleValue());
}
LOGGER.debug("Setting input parameters " + inputParameters.toString());
System.out.println(inputParameters.toString());
/**
* New code
*/
KieSession kieSession=droolsBeanFactory.getKieSession(ResourceFactory.newClassPathResource("com/salesmanager/drools/rules/ShippingDecision.drl"));
DecisionResponse resp = new DecisionResponse();
kieSession.insert(inputParameters);
kieSession.setGlobal("decision",resp);
kieSession.fireAllRules();
//System.out.println(resp.getModuleName());
inputParameters.setModuleName(resp.getModuleName());
LOGGER.debug("Using shipping nodule " + inputParameters.getModuleName());
if(!StringUtils.isBlank(inputParameters.getModuleName())) {
for(IntegrationModule toBeUsed : allModules) {
if(toBeUsed.getCode().equals(inputParameters.getModuleName())) {
quote.setCurrentShippingModule(toBeUsed);
break;
}
}
}
| 311
| 1,048
| 1,359
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.