repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/repositories/UserLatestEpisodesRepositoryTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Image;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | " {" +
" \"title\": \"Newest Episode from another podcast\"," +
" \"publishedDate\": \"2015-05-15T15:00:00.000Z\"," +
" \"description\": \"Another newest episode description\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_episode_image.png\"" +
" }," +
" \"enclosure\": {" +
" \"url\": \"http://example.com/another_newest_episode.mp3\"," +
" \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
"]")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserLatestEpisodesRepository(httpClient);
}
@Test
public void itReturnsTitleWhenGetLatestEpisodes() { | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/test/java/com/mypodcasts/repositories/UserLatestEpisodesRepositoryTest.java
import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Image;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
" {" +
" \"title\": \"Newest Episode from another podcast\"," +
" \"publishedDate\": \"2015-05-15T15:00:00.000Z\"," +
" \"description\": \"Another newest episode description\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_episode_image.png\"" +
" }," +
" \"enclosure\": {" +
" \"url\": \"http://example.com/another_newest_episode.mp3\"," +
" \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
"]")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserLatestEpisodesRepository(httpClient);
}
@Test
public void itReturnsTitleWhenGetLatestEpisodes() { | Episode episode = repository.getLatestEpisodes().get(firstPosition); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/repositories/UserLatestEpisodesRepositoryTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Image;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | Episode expectedEpisode = new Episode() {
@Override
public String getTitle() {
return "Newest Episode!";
}
};
assertThat(episode.getTitle(), is(expectedEpisode.getTitle()));
}
@Test
public void itReturnsAudioUrlWhenGetLatestEpisodes() {
Episode episode = repository.getLatestEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override
public String getAudioUrl() {
return "http://example.com/episode_audio.mp3";
}
};
assertThat(episode.getAudioUrl(), is(expectedEpisode.getAudioUrl()));
}
@Test
public void itReturnsImageUrlWhenGetLatestEpisodes() {
Episode episode = repository.getLatestEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/test/java/com/mypodcasts/repositories/UserLatestEpisodesRepositoryTest.java
import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Image;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
Episode expectedEpisode = new Episode() {
@Override
public String getTitle() {
return "Newest Episode!";
}
};
assertThat(episode.getTitle(), is(expectedEpisode.getTitle()));
}
@Test
public void itReturnsAudioUrlWhenGetLatestEpisodes() {
Episode episode = repository.getLatestEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override
public String getAudioUrl() {
return "http://example.com/episode_audio.mp3";
}
};
assertThat(episode.getAudioUrl(), is(expectedEpisode.getAudioUrl()));
}
@Test
public void itReturnsImageUrlWhenGetLatestEpisodes() {
Episode episode = repository.getLatestEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override | public Image getImage() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeListAdapterTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.List;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.robolectric.Robolectric.buildActivity; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeListAdapterTest {
Activity activity;
ViewGroup parent;
EpisodeViewInflater episodeViewInflater;
int firstPosition = 0;
@Before
public void setup() {
activity = buildActivity(Activity.class).create().get();
episodeViewInflater = new EpisodeViewInflater(
activity, mock(ImageLoader.class), mock(EpisodeDownloader.class)
);
parent = new ViewGroup(activity) {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
};
}
@Test
public void itReturnsEpisodesCount() { | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeListAdapterTest.java
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.List;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.robolectric.Robolectric.buildActivity;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeListAdapterTest {
Activity activity;
ViewGroup parent;
EpisodeViewInflater episodeViewInflater;
int firstPosition = 0;
@Before
public void setup() {
activity = buildActivity(Activity.class).create().get();
episodeViewInflater = new EpisodeViewInflater(
activity, mock(ImageLoader.class), mock(EpisodeDownloader.class)
);
parent = new ViewGroup(activity) {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
};
}
@Test
public void itReturnsEpisodesCount() { | List<Episode> episodes = asList(new Episode()); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeDownloader.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
| import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import javax.inject.Inject;
import static android.net.Uri.parse; | package com.mypodcasts.episodes;
public class EpisodeDownloader {
private final FileDownloadManager fileDownloadManager;
private final EpisodeFile episodeFile;
@Inject
public EpisodeDownloader(FileDownloadManager fileDownloadManager, EpisodeFile episodeFile) {
this.fileDownloadManager = fileDownloadManager;
this.episodeFile = episodeFile;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeDownloader.java
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import javax.inject.Inject;
import static android.net.Uri.parse;
package com.mypodcasts.episodes;
public class EpisodeDownloader {
private final FileDownloadManager fileDownloadManager;
private final EpisodeFile episodeFile;
@Inject
public EpisodeDownloader(FileDownloadManager fileDownloadManager, EpisodeFile episodeFile) {
this.fileDownloadManager = fileDownloadManager;
this.episodeFile = episodeFile;
}
| public void download(Episode episode) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java | // Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
// @ContentView(R.layout.base_layout)
// public class MyPodcastsActivity extends RoboActionBarActivity {
//
// @InjectView(R.id.tool_bar)
// private Toolbar toolbar;
//
// @InjectView(R.id.drawer_layout)
// private DrawerLayout drawerLayout;
//
// @InjectView(R.id.left_drawer)
// private ListView leftDrawer;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedsAsyncTask feedsAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setSupportActionBar(toolbar);
// setActionBarDrawerToggle(drawerLayout, toolbar);
//
// leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Feed feed = (Feed) leftDrawer.getAdapter().getItem(position);
// Intent intent = new Intent(view.getContext(), EpisodeFeedsActivity.class);
// intent.putExtra(Feed.class.toString(), feed);
//
// startActivity(intent);
// }
// });
//
// feedsAsyncTask = new FeedsAsyncTask(this);
//
// feedsAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedsAsyncTask.cancel();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
//
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// private void setActionBarDrawerToggle(DrawerLayout drawerLayout, Toolbar toolbar) {
// ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
// this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
//
// drawerLayout.setDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.syncState();
// }
//
// private class FeedsAsyncTask extends RetryableAsyncTask<Void, Void, List<Feed>> {
// public FeedsAsyncTask(Activity activity) {
// super(activity);
// }
//
// @Override
// protected List<Feed> doInBackground(Void... params) {
// return userFeedsRepository.getFeeds();
// }
//
// @Override
// protected void onPostExecute(List<Feed> feeds) {
// leftDrawer.setAdapter(new FeedsAdapter(feeds, getLayoutInflater()));
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.mypodcasts.MyPodcastsActivity;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import static java.lang.String.format; | package com.mypodcasts.episodes;
public class EpisodeFeedsActivity extends MyPodcastsActivity {
@Inject
private FragmentManager fragmentManager;
@Inject
private Bundle arguments;
@Inject
private EpisodeListFragment episodeListFragment;
@Inject
private ProgressDialog progressDialog;
@Inject | // Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
// @ContentView(R.layout.base_layout)
// public class MyPodcastsActivity extends RoboActionBarActivity {
//
// @InjectView(R.id.tool_bar)
// private Toolbar toolbar;
//
// @InjectView(R.id.drawer_layout)
// private DrawerLayout drawerLayout;
//
// @InjectView(R.id.left_drawer)
// private ListView leftDrawer;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedsAsyncTask feedsAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setSupportActionBar(toolbar);
// setActionBarDrawerToggle(drawerLayout, toolbar);
//
// leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Feed feed = (Feed) leftDrawer.getAdapter().getItem(position);
// Intent intent = new Intent(view.getContext(), EpisodeFeedsActivity.class);
// intent.putExtra(Feed.class.toString(), feed);
//
// startActivity(intent);
// }
// });
//
// feedsAsyncTask = new FeedsAsyncTask(this);
//
// feedsAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedsAsyncTask.cancel();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
//
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// private void setActionBarDrawerToggle(DrawerLayout drawerLayout, Toolbar toolbar) {
// ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
// this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
//
// drawerLayout.setDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.syncState();
// }
//
// private class FeedsAsyncTask extends RetryableAsyncTask<Void, Void, List<Feed>> {
// public FeedsAsyncTask(Activity activity) {
// super(activity);
// }
//
// @Override
// protected List<Feed> doInBackground(Void... params) {
// return userFeedsRepository.getFeeds();
// }
//
// @Override
// protected void onPostExecute(List<Feed> feeds) {
// leftDrawer.setAdapter(new FeedsAdapter(feeds, getLayoutInflater()));
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.mypodcasts.MyPodcastsActivity;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import static java.lang.String.format;
package com.mypodcasts.episodes;
public class EpisodeFeedsActivity extends MyPodcastsActivity {
@Inject
private FragmentManager fragmentManager;
@Inject
private Bundle arguments;
@Inject
private EpisodeListFragment episodeListFragment;
@Inject
private ProgressDialog progressDialog;
@Inject | private UserFeedsRepository userFeedsRepository; |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java | // Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
// @ContentView(R.layout.base_layout)
// public class MyPodcastsActivity extends RoboActionBarActivity {
//
// @InjectView(R.id.tool_bar)
// private Toolbar toolbar;
//
// @InjectView(R.id.drawer_layout)
// private DrawerLayout drawerLayout;
//
// @InjectView(R.id.left_drawer)
// private ListView leftDrawer;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedsAsyncTask feedsAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setSupportActionBar(toolbar);
// setActionBarDrawerToggle(drawerLayout, toolbar);
//
// leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Feed feed = (Feed) leftDrawer.getAdapter().getItem(position);
// Intent intent = new Intent(view.getContext(), EpisodeFeedsActivity.class);
// intent.putExtra(Feed.class.toString(), feed);
//
// startActivity(intent);
// }
// });
//
// feedsAsyncTask = new FeedsAsyncTask(this);
//
// feedsAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedsAsyncTask.cancel();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
//
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// private void setActionBarDrawerToggle(DrawerLayout drawerLayout, Toolbar toolbar) {
// ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
// this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
//
// drawerLayout.setDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.syncState();
// }
//
// private class FeedsAsyncTask extends RetryableAsyncTask<Void, Void, List<Feed>> {
// public FeedsAsyncTask(Activity activity) {
// super(activity);
// }
//
// @Override
// protected List<Feed> doInBackground(Void... params) {
// return userFeedsRepository.getFeeds();
// }
//
// @Override
// protected void onPostExecute(List<Feed> feeds) {
// leftDrawer.setAdapter(new FeedsAdapter(feeds, getLayoutInflater()));
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.mypodcasts.MyPodcastsActivity;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import static java.lang.String.format; | package com.mypodcasts.episodes;
public class EpisodeFeedsActivity extends MyPodcastsActivity {
@Inject
private FragmentManager fragmentManager;
@Inject
private Bundle arguments;
@Inject
private EpisodeListFragment episodeListFragment;
@Inject
private ProgressDialog progressDialog;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
| // Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
// @ContentView(R.layout.base_layout)
// public class MyPodcastsActivity extends RoboActionBarActivity {
//
// @InjectView(R.id.tool_bar)
// private Toolbar toolbar;
//
// @InjectView(R.id.drawer_layout)
// private DrawerLayout drawerLayout;
//
// @InjectView(R.id.left_drawer)
// private ListView leftDrawer;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedsAsyncTask feedsAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setSupportActionBar(toolbar);
// setActionBarDrawerToggle(drawerLayout, toolbar);
//
// leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Feed feed = (Feed) leftDrawer.getAdapter().getItem(position);
// Intent intent = new Intent(view.getContext(), EpisodeFeedsActivity.class);
// intent.putExtra(Feed.class.toString(), feed);
//
// startActivity(intent);
// }
// });
//
// feedsAsyncTask = new FeedsAsyncTask(this);
//
// feedsAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedsAsyncTask.cancel();
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
//
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// private void setActionBarDrawerToggle(DrawerLayout drawerLayout, Toolbar toolbar) {
// ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
// this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
//
// drawerLayout.setDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.syncState();
// }
//
// private class FeedsAsyncTask extends RetryableAsyncTask<Void, Void, List<Feed>> {
// public FeedsAsyncTask(Activity activity) {
// super(activity);
// }
//
// @Override
// protected List<Feed> doInBackground(Void... params) {
// return userFeedsRepository.getFeeds();
// }
//
// @Override
// protected void onPostExecute(List<Feed> feeds) {
// leftDrawer.setAdapter(new FeedsAdapter(feeds, getLayoutInflater()));
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.mypodcasts.MyPodcastsActivity;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import static java.lang.String.format;
package com.mypodcasts.episodes;
public class EpisodeFeedsActivity extends MyPodcastsActivity {
@Inject
private FragmentManager fragmentManager;
@Inject
private Bundle arguments;
@Inject
private EpisodeListFragment episodeListFragment;
@Inject
private ProgressDialog progressDialog;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
| Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString()); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/support/injection/MyPodcastsModule.java | // Path: app/src/main/java/com/mypodcasts/support/MyPodcastsImageCache.java
// public class MyPodcastsImageCache implements ImageLoader.ImageCache {
//
// private LruCache<String, Bitmap> imageCache;
// private static final int ONE_KB = 1024;
//
// public MyPodcastsImageCache() {
// final int cacheSize = onEigthOf(maxMemoryInKB());
//
// imageCache = new LruCache<String, Bitmap>(cacheSize) {
// @Override
// protected int sizeOf(String imageUrl, Bitmap image) {
// return imageSizeInKB(image);
// }
//
// private int imageSizeInKB(Bitmap image) {
// return image.getByteCount() / ONE_KB;
// }
// };
// }
//
// @Override
// public Bitmap getBitmap(String imageUrl) {
// return imageCache.get(imageUrl);
// }
//
// @Override
// public void putBitmap(String imageUrl, Bitmap image) {
// if(imageCache.get(imageUrl) == null) {
// imageCache.put(imageUrl, image);
// }
// }
//
// private int onEigthOf(int value) {
// return (value / 8);
// }
//
// private int maxMemoryInKB() {
// return (int) (Runtime.getRuntime().maxMemory() / ONE_KB);
// }
//
// }
| import android.app.Notification;
import android.app.ProgressDialog;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.mypodcasts.support.MyPodcastsImageCache;
import org.greenrobot.eventbus.EventBus;
import retrofit.RestAdapter; | package com.mypodcasts.support.injection;
public class MyPodcastsModule implements Module {
@Override
public void configure(Binder binder) {
binder.bind(RestAdapter.Builder.class).toProvider(RestAdapterBuilderProvider.class);
binder.bind(ProgressDialog.class).toProvider(ProgressDialogProvider.class);
binder.bind(Notification.Builder.class).toProvider(NotificationBuilderProvider.class);
binder.bind(EventBus.class).toProvider(EventBusProvider.class);
| // Path: app/src/main/java/com/mypodcasts/support/MyPodcastsImageCache.java
// public class MyPodcastsImageCache implements ImageLoader.ImageCache {
//
// private LruCache<String, Bitmap> imageCache;
// private static final int ONE_KB = 1024;
//
// public MyPodcastsImageCache() {
// final int cacheSize = onEigthOf(maxMemoryInKB());
//
// imageCache = new LruCache<String, Bitmap>(cacheSize) {
// @Override
// protected int sizeOf(String imageUrl, Bitmap image) {
// return imageSizeInKB(image);
// }
//
// private int imageSizeInKB(Bitmap image) {
// return image.getByteCount() / ONE_KB;
// }
// };
// }
//
// @Override
// public Bitmap getBitmap(String imageUrl) {
// return imageCache.get(imageUrl);
// }
//
// @Override
// public void putBitmap(String imageUrl, Bitmap image) {
// if(imageCache.get(imageUrl) == null) {
// imageCache.put(imageUrl, image);
// }
// }
//
// private int onEigthOf(int value) {
// return (value / 8);
// }
//
// private int maxMemoryInKB() {
// return (int) (Runtime.getRuntime().maxMemory() / ONE_KB);
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/support/injection/MyPodcastsModule.java
import android.app.Notification;
import android.app.ProgressDialog;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.mypodcasts.support.MyPodcastsImageCache;
import org.greenrobot.eventbus.EventBus;
import retrofit.RestAdapter;
package com.mypodcasts.support.injection;
public class MyPodcastsModule implements Module {
@Override
public void configure(Binder binder) {
binder.bind(RestAdapter.Builder.class).toProvider(RestAdapterBuilderProvider.class);
binder.bind(ProgressDialog.class).toProvider(ProgressDialogProvider.class);
binder.bind(Notification.Builder.class).toProvider(NotificationBuilderProvider.class);
binder.bind(EventBus.class).toProvider(EventBusProvider.class);
| binder.bind(ImageLoader.ImageCache.class).to(MyPodcastsImageCache.class).in(Scopes.SINGLETON); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | " \"publishedDate\": \"2015-05-15T15:00:00.000Z\"," +
" \"description\": \"Another newest episode description\"," +
" \"duration\": \"01:21:38\"," +
" \"image\": {" +
" \"url\": \"http://example.com/episode_image.png\"" +
" }," +
" \"audio\": {" +
" \"url\": \"http://example.com/another_newest_episode.mp3\"," +
" \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
" ]" +
"}")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserFeedsRepository(httpClient);
}
@Test
public void itReturnsFeedId() { | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java
import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
" \"publishedDate\": \"2015-05-15T15:00:00.000Z\"," +
" \"description\": \"Another newest episode description\"," +
" \"duration\": \"01:21:38\"," +
" \"image\": {" +
" \"url\": \"http://example.com/episode_image.png\"" +
" }," +
" \"audio\": {" +
" \"url\": \"http://example.com/another_newest_episode.mp3\"," +
" \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
" ]" +
"}")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserFeedsRepository(httpClient);
}
@Test
public void itReturnsFeedId() { | Feed feed = repository.getFeed(expectedId); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | " \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
" ]" +
"}")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserFeedsRepository(httpClient);
}
@Test
public void itReturnsFeedId() {
Feed feed = repository.getFeed(expectedId);
assertThat(feed.getId(), is(expectedId));
}
@Test
public void itReturnsTitleWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId); | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java
import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
" \"length\": \"52417026\"," +
" \"type\": \"audio/mpeg\"" +
" }," +
" \"podcast\": {" +
" \"title\": \"Another podcasts\"," +
" \"image\": {" +
" \"url\": \"http://example.com/another_feed_image.jpg\"" +
" }" +
" }" +
" }" +
" ]" +
"}")
)
);
when(resources.getString(R.string.base_url)).thenReturn("http://localhost:1111");
httpClient = new HttpClient(resources, new RestAdapter.Builder());
repository = new UserFeedsRepository(httpClient);
}
@Test
public void itReturnsFeedId() {
Feed feed = repository.getFeed(expectedId);
assertThat(feed.getId(), is(expectedId));
}
@Test
public void itReturnsTitleWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId); | Episode episode = feed.getEpisodes().get(firstPosition); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | public String getTitle() {
return "Newest Episode!";
}
};
assertThat(episode.getTitle(), is(expectedEpisode.getTitle()));
}
@Test
public void itReturnsAudioUrlWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId);
Episode episode = feed.getEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override
public String getAudioUrl() {
return "http://example.com/newest_episode.mp3";
}
};
assertThat(episode.getAudioUrl(), is(expectedEpisode.getAudioUrl()));
}
@Test
public void itReturnsImageUrlWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId);
Episode episode = feed.getEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/test/java/com/mypodcasts/repositories/UserFeedsRepositoryTest.java
import android.content.res.Resources;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.mypodcasts.R;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import com.mypodcasts.repositories.models.Image;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import retrofit.RestAdapter;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.is;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public String getTitle() {
return "Newest Episode!";
}
};
assertThat(episode.getTitle(), is(expectedEpisode.getTitle()));
}
@Test
public void itReturnsAudioUrlWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId);
Episode episode = feed.getEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override
public String getAudioUrl() {
return "http://example.com/newest_episode.mp3";
}
};
assertThat(episode.getAudioUrl(), is(expectedEpisode.getAudioUrl()));
}
@Test
public void itReturnsImageUrlWhenGetFeeds() {
Feed feed = repository.getFeed(expectedId);
Episode episode = feed.getEpisodes().get(firstPosition);
Episode expectedEpisode = new Episode() {
@Override | public Image getImage() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeDownloaderTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
| import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static android.net.Uri.parse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeDownloaderTest {
EpisodeDownloader episodeDownloader;
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeDownloaderTest.java
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static android.net.Uri.parse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeDownloaderTest {
EpisodeDownloader episodeDownloader;
| Episode episode; |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeDownloaderTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
| import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static android.net.Uri.parse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeDownloaderTest {
EpisodeDownloader episodeDownloader;
Episode episode;
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/FileDownloadManager.java
// public class FileDownloadManager {
// private final DownloadManager downloadManager;
//
// @Inject
// public FileDownloadManager(DownloadManager downloadManager) {
// this.downloadManager = downloadManager;
// }
//
// public long enqueue(Uri uri, String directory, String filePath) {
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setDestinationInExternalPublicDir(directory, filePath);
//
// return downloadManager.enqueue(request);
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeDownloaderTest.java
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.FileDownloadManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static android.net.Uri.parse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeDownloaderTest {
EpisodeDownloader episodeDownloader;
Episode episode;
| FileDownloadManager fileDownloadManagerMock= mock(FileDownloadManager.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
| // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java
import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
| UserFeedsRepository userFeedsMock = mock(UserFeedsRepository.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
UserFeedsRepository userFeedsMock = mock(UserFeedsRepository.class); | // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java
import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
UserFeedsRepository userFeedsMock = mock(UserFeedsRepository.class); | UserLatestEpisodesRepository userLatestEpisodesRepositoryMock = mock(UserLatestEpisodesRepository.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
UserFeedsRepository userFeedsMock = mock(UserFeedsRepository.class);
UserLatestEpisodesRepository userLatestEpisodesRepositoryMock = mock(UserLatestEpisodesRepository.class);
ProgressDialog progressDialogMock = mock(ProgressDialog.class);
| // Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
// public class UserLatestEpisodesRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserLatestEpisodesRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Episode> getLatestEpisodes() {
// return httpClient.getApi().getLatestEpisodes();
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/latestepisodes/LatestEpisodesActivityTest.java
import android.app.ProgressDialog;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.UserLatestEpisodesRepository;
import com.mypodcasts.repositories.models.Episode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.episodes.latestepisodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class LatestEpisodesActivityTest {
LatestEpisodesActivity activity;
UserFeedsRepository userFeedsMock = mock(UserFeedsRepository.class);
UserLatestEpisodesRepository userLatestEpisodesRepositoryMock = mock(UserLatestEpisodesRepository.class);
ProgressDialog progressDialogMock = mock(ProgressDialog.class);
| List<Episode> emptyList = Collections.<Episode>emptyList(); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerServiceTest.java | // Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.Service;
import android.content.Intent;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import org.greenrobot.eventbus.EventBus;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.robolectric.Robolectric.buildService;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerServiceTest { | // Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerServiceTest.java
import android.app.Service;
import android.content.Intent;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import org.greenrobot.eventbus.EventBus;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.robolectric.Robolectric.buildService;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerServiceTest { | Episode episode = new Episode(); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerServiceTest.java | // Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.app.Service;
import android.content.Intent;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import org.greenrobot.eventbus.EventBus;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.robolectric.Robolectric.buildService;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | private Service createService(Intent intent) {
return buildService(AudioPlayerService.class, intent)
.create()
.startCommand(0, 1)
.get();
}
private Intent buildIntent(Episode episode, String action) {
Intent intent = new Intent(application, AudioPlayerService.class);
intent.putExtra(Episode.class.toString(), episode);
intent.setAction(action);
return intent;
}
public class MyTestModule extends AbstractModule {
@Override
protected void configure() {
bind(AudioPlayer.class).toInstance(audioPlayerMock);
}
}
public class CustomBroadcastReceiver {
private boolean isMessageReceived;
public CustomBroadcastReceiver(EventBus eventBus) {
eventBus.register(this);
}
@Subscribe | // Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerServiceTest.java
import android.app.Service;
import android.content.Intent;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import org.greenrobot.eventbus.EventBus;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.robolectric.Robolectric.buildService;
import static org.robolectric.RuntimeEnvironment.application;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
private Service createService(Intent intent) {
return buildService(AudioPlayerService.class, intent)
.create()
.startCommand(0, 1)
.get();
}
private Intent buildIntent(Episode episode, String action) {
Intent intent = new Intent(application, AudioPlayerService.class);
intent.putExtra(Episode.class.toString(), episode);
intent.setAction(action);
return intent;
}
public class MyTestModule extends AbstractModule {
@Override
protected void configure() {
bind(AudioPlayer.class).toInstance(audioPlayerMock);
}
}
public class CustomBroadcastReceiver {
private boolean isMessageReceived;
public CustomBroadcastReceiver(EventBus eventBus) {
eventBus.register(this);
}
@Subscribe | public void onEvent(AudioStoppedEvent event) { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeCheckpointTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/test/java/com/mypodcasts/util/EpisodeHelper.java
// public static Episode anEpisode() {
// return new Episode() {
// @Override public String getTitle() {
// return "An awesome episode";
// }
//
// @Override public Feed getFeed() {
// return new Feed() {
// @Override
// public String getId() {
// return "crazy_id_123";
// }
// };
// }
// };
// }
| import android.content.SharedPreferences;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Random;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.util.EpisodeHelper.anEpisode;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.robolectric.RuntimeEnvironment.application; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeCheckpointTest {
EpisodeCheckpoint episodeCheckpoint;
@Before
public void setup() {
episodeCheckpoint = new EpisodeCheckpoint(application);
}
@Test
public void itStoresCurrentStateOfPlayingEpisode() {
int audioPosition = new Random().nextInt();
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
//
// Path: app/src/test/java/com/mypodcasts/util/EpisodeHelper.java
// public static Episode anEpisode() {
// return new Episode() {
// @Override public String getTitle() {
// return "An awesome episode";
// }
//
// @Override public Feed getFeed() {
// return new Feed() {
// @Override
// public String getId() {
// return "crazy_id_123";
// }
// };
// }
// };
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeCheckpointTest.java
import android.content.SharedPreferences;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Random;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.util.EpisodeHelper.anEpisode;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.robolectric.RuntimeEnvironment.application;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeCheckpointTest {
EpisodeCheckpoint episodeCheckpoint;
@Before
public void setup() {
episodeCheckpoint = new EpisodeCheckpoint(application);
}
@Test
public void itStoresCurrentStateOfPlayingEpisode() {
int audioPosition = new Random().nextInt();
| assertThat(episodeCheckpoint.markCheckpoint(anEpisode(), audioPosition), is(audioPosition)); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | package com.mypodcasts.player;
@ContentView(R.layout.audio_player)
public class AudioPlayerActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@Inject
private EventBus eventBus;
private AudioPlayer audioPlayer;
@Inject
private AudioPlayerController mediaController;
@Inject | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
package com.mypodcasts.player;
@ContentView(R.layout.audio_player)
public class AudioPlayerActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@Inject
private EventBus eventBus;
private AudioPlayer audioPlayer;
@Inject
private AudioPlayerController mediaController;
@Inject | private EpisodeCheckpoint episodeCheckpoint; |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | package com.mypodcasts.player;
@ContentView(R.layout.audio_player)
public class AudioPlayerActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@Inject
private EventBus eventBus;
private AudioPlayer audioPlayer;
@Inject
private AudioPlayerController mediaController;
@Inject
private EpisodeCheckpoint episodeCheckpoint;
@InjectView(R.id.episode_description)
private TextView episodeDescription;
| // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
package com.mypodcasts.player;
@ContentView(R.layout.audio_player)
public class AudioPlayerActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@Inject
private EventBus eventBus;
private AudioPlayer audioPlayer;
@Inject
private AudioPlayerController mediaController;
@Inject
private EpisodeCheckpoint episodeCheckpoint;
@InjectView(R.id.episode_description)
private TextView episodeDescription;
| private Episode episode; |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | protected void onPause() {
super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
protected void onPause() {
super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe | public void onEvent(AudioPlayingEvent event) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) { | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) { | Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]"); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) { | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
super.onPause();
mediaController.hide();
if (audioPlayer != null) {
setPlayerCurrentPosition(audioPlayer.getCurrentPosition());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return super.onTouchEvent(event);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) { | Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]"); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]");
audioPlayer = event.getAudioPlayer();
audioPlayer.seekTo(
episodeCheckpoint.getLastCheckpointPosition(episode, playerCurrentPosition)
);
mediaController.setMediaPlayer(audioPlayer);
mediaController.setAnchorView(findViewById(R.id.audio_view));
mediaController.show();
if (episode != null) {
episodeDescription.setText(fromHtml(episode.getDescription()));
}
}
@Subscribe | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(AudioPlayer.class.toString(), playerCurrentPosition);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]");
audioPlayer = event.getAudioPlayer();
audioPlayer.seekTo(
episodeCheckpoint.getLastCheckpointPosition(episode, playerCurrentPosition)
);
mediaController.setMediaPlayer(audioPlayer);
mediaController.setAnchorView(findViewById(R.id.audio_view));
mediaController.show();
if (episode != null) {
episodeDescription.setText(fromHtml(episode.getDescription()));
}
}
@Subscribe | public void onEvent(AudioStoppedEvent event) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG; | setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]");
audioPlayer = event.getAudioPlayer();
audioPlayer.seekTo(
episodeCheckpoint.getLastCheckpointPosition(episode, playerCurrentPosition)
);
mediaController.setMediaPlayer(audioPlayer);
mediaController.setAnchorView(findViewById(R.id.audio_view));
mediaController.show();
if (episode != null) {
episodeDescription.setText(fromHtml(episode.getDescription()));
}
}
@Subscribe
public void onEvent(AudioStoppedEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioStoppedEvent]");
finish();
}
private Episode playAudio() {
Intent intent = new Intent(AudioPlayerActivity.this, AudioPlayerService.class); | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public class Support {
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// }
//
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerService.java
// public static final String ACTION_PLAY = "com.mypodcasts.player.action.play";
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/player/AudioPlayerActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.Support;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import static android.text.Html.fromHtml;
import static com.mypodcasts.player.AudioPlayerService.ACTION_PLAY;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
setPlayerCurrentPosition(savedInstanceState.getInt(AudioPlayer.class.toString()));
}
@Subscribe
public void onEvent(AudioPlayingEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioPlayingEvent]");
audioPlayer = event.getAudioPlayer();
audioPlayer.seekTo(
episodeCheckpoint.getLastCheckpointPosition(episode, playerCurrentPosition)
);
mediaController.setMediaPlayer(audioPlayer);
mediaController.setAnchorView(findViewById(R.id.audio_view));
mediaController.show();
if (episode != null) {
episodeDescription.setText(fromHtml(episode.getDescription()));
}
}
@Subscribe
public void onEvent(AudioStoppedEvent event) {
Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerActivity][onEvent][AudioStoppedEvent]");
finish();
}
private Episode playAudio() {
Intent intent = new Intent(AudioPlayerActivity.this, AudioPlayerService.class); | intent.setAction(ACTION_PLAY); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/MyPodcastsActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView; | package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject | private UserFeedsRepository userFeedsRepository; |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/MyPodcastsActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView; | package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedsAsyncTask feedsAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(toolbar);
setActionBarDrawerToggle(drawerLayout, toolbar);
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedsAsyncTask feedsAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(toolbar);
setActionBarDrawerToggle(drawerLayout, toolbar);
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { | Feed feed = (Feed) leftDrawer.getAdapter().getItem(position); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/MyPodcastsActivity.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView; | package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedsAsyncTask feedsAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(toolbar);
setActionBarDrawerToggle(drawerLayout, toolbar);
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Feed feed = (Feed) leftDrawer.getAdapter().getItem(position); | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFeedsActivity.java
// public class EpisodeFeedsActivity extends MyPodcastsActivity {
//
// @Inject
// private FragmentManager fragmentManager;
//
// @Inject
// private Bundle arguments;
//
// @Inject
// private EpisodeListFragment episodeListFragment;
//
// @Inject
// private ProgressDialog progressDialog;
//
// @Inject
// private UserFeedsRepository userFeedsRepository;
// private FeedEpisodesAsyncTask feedEpisodesAsyncTask;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Feed feed = (Feed) getIntent().getSerializableExtra(Feed.class.toString());
//
// feedEpisodesAsyncTask = new FeedEpisodesAsyncTask(this, feed);
//
// feedEpisodesAsyncTask.execute();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
//
// feedEpisodesAsyncTask.cancel();
// }
//
// @Override
// protected void onDestroy() {
// dismissProgressDialog();
//
// super.onDestroy();
// }
//
// private void showProgressDialog(String feedTitle) {
// progressDialog.setIndeterminate(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// progressDialog.setMessage(format(
// getResources().getString(R.string.loading_feed_episodes), feedTitle
// ));
// }
//
// private void dismissProgressDialog() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.dismiss();
// }
// }
//
// class FeedEpisodesAsyncTask extends RetryableAsyncTask<Void, Void, Feed> {
// private final Activity activity;
// private final Feed feed;
//
// public FeedEpisodesAsyncTask(Activity activity, Feed feed) {
// super(activity);
//
// this.activity = activity;
// this.feed = feed;
// }
//
// @Override
// protected void onPreExecute() {
// showProgressDialog(feed.getTitle());
// }
//
// @Override
// protected Feed doInBackground(Void... params) {
// return userFeedsRepository.getFeed(feed.getId());
// }
//
// @Override
// protected void onPostExecute(Feed feed) {
// if (this.activity.isDestroyed()) return;
//
// dismissProgressDialog();
//
// arguments.putSerializable(
// EpisodeList.HEADER,
// new EpisodeListHeaderInfo(feed.getTitle(), feed.getImage())
// );
//
// arguments.putSerializable(
// EpisodeList.LIST,
// new EpisodeList(feed.getEpisodes())
// );
//
// episodeListFragment.setArguments(arguments);
//
// fragmentManager.beginTransaction()
// .replace(R.id.content_frame, episodeListFragment)
// .commitAllowingStateLoss();
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
// public class UserFeedsRepository {
//
// private final HttpClient httpClient;
//
// @Inject
// public UserFeedsRepository(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// public List<Feed> getFeeds() {
// return httpClient.getApi().getUserFeeds();
// }
//
// public Feed getFeed(String id) {
// return httpClient.getApi().getFeed(id);
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/MyPodcastsActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.mypodcasts.episodes.EpisodeFeedsActivity;
import com.mypodcasts.repositories.UserFeedsRepository;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
import retryable.asynctask.RetryableAsyncTask;
import roboguice.activity.RoboActionBarActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
package com.mypodcasts;
@ContentView(R.layout.base_layout)
public class MyPodcastsActivity extends RoboActionBarActivity {
@InjectView(R.id.tool_bar)
private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout;
@InjectView(R.id.left_drawer)
private ListView leftDrawer;
@Inject
private UserFeedsRepository userFeedsRepository;
private FeedsAsyncTask feedsAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(toolbar);
setActionBarDrawerToggle(drawerLayout, toolbar);
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Feed feed = (Feed) leftDrawer.getAdapter().getItem(position); | Intent intent = new Intent(view.getContext(), EpisodeFeedsActivity.class); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeListHeaderInfo.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
| import com.mypodcasts.repositories.models.Image;
import java.io.Serializable; | package com.mypodcasts.episodes;
public class EpisodeListHeaderInfo implements Serializable {
private String title;
private String imageUrl;
public EpisodeListHeaderInfo(String title, String imageUrl) {
this.title = title;
this.imageUrl = imageUrl;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Image.java
// public class Image implements Serializable {
// private String url;
//
// public String getUrl() {
// return url;
// }
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeListHeaderInfo.java
import com.mypodcasts.repositories.models.Image;
import java.io.Serializable;
package com.mypodcasts.episodes;
public class EpisodeListHeaderInfo implements Serializable {
private String title;
private String imageUrl;
public EpisodeListHeaderInfo(String title, String imageUrl) {
this.title = title;
this.imageUrl = imageUrl;
}
| public EpisodeListHeaderInfo(String title, Image image) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject; | package com.mypodcasts.repositories;
public class UserFeedsRepository {
private final HttpClient httpClient;
@Inject
public UserFeedsRepository(HttpClient httpClient) {
this.httpClient = httpClient;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/repositories/UserFeedsRepository.java
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import javax.inject.Inject;
package com.mypodcasts.repositories;
public class UserFeedsRepository {
private final HttpClient httpClient;
@Inject
public UserFeedsRepository(HttpClient httpClient) {
this.httpClient = httpClient;
}
| public List<Feed> getFeeds() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class); | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class); | EpisodeFile episodeFileMock = mock(EpisodeFile.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class);
EpisodeFile episodeFileMock = mock(EpisodeFile.class);
| // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class);
EpisodeFile episodeFileMock = mock(EpisodeFile.class);
| Episode episode = new Episode() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class);
EpisodeFile episodeFileMock = mock(EpisodeFile.class);
Episode episode = new Episode() {
@Override | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerTest {
AudioPlayer audioPlayer;
EventBus eventBus;
MediaPlayer mediaPlayerMock = mock(MediaPlayer.class);
EpisodeFile episodeFileMock = mock(EpisodeFile.class);
Episode episode = new Episode() {
@Override | public Audio getAudio() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | audioPlayer.release();
InOrder order = inOrder(mediaPlayerMock);
order.verify(mediaPlayerMock).reset();
order.verify(mediaPlayerMock).release();
}
@Test
public void itReturnsFalseIfMediaPlayerIsNotPlaying() {
when(mediaPlayerMock.isPlaying()).thenReturn(false);
assertThat(audioPlayer.isPlaying(), is(false));
}
@Test
public void itReturnsTrueIfMediaPlayerIsPlaying() {
when(mediaPlayerMock.isPlaying()).thenReturn(true);
assertThat(audioPlayer.isPlaying(), is(true));
}
public class CustomBroadcastReceiver {
private boolean isMessageReceived;
public CustomBroadcastReceiver(EventBus eventBus) {
eventBus.register(this);
}
@Subscribe | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
// public class EpisodeFile {
// private final ExternalPublicFileLookup externalPublicFileLookup;
//
// @Inject
// public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
// this.externalPublicFileLookup = externalPublicFileLookup;
// }
//
// public boolean exists(Episode episode) {
// return externalPublicFileLookup.exists(
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// public String getAudioFilePath(Episode episode) {
// if (exists(episode)) {
// return format(
// "%s/%s",
// getExternalStoragePublicDirectory(getPodcastsDirectory()),
// episode.getAudioFilePath()
// );
// }
//
// return episode.getAudioUrl();
// }
//
// public String getPodcastsDirectory() {
// return DIRECTORY_PODCASTS;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Audio.java
// public class Audio implements Serializable {
// private String url;
// private String length;
// private String type;
//
// public String getUrl() {
// return url;
// }
//
// public String getLength() {
// return length;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerTest.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.episodes.EpisodeFile;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.repositories.models.Audio;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
audioPlayer.release();
InOrder order = inOrder(mediaPlayerMock);
order.verify(mediaPlayerMock).reset();
order.verify(mediaPlayerMock).release();
}
@Test
public void itReturnsFalseIfMediaPlayerIsNotPlaying() {
when(mediaPlayerMock.isPlaying()).thenReturn(false);
assertThat(audioPlayer.isPlaying(), is(false));
}
@Test
public void itReturnsTrueIfMediaPlayerIsPlaying() {
when(mediaPlayerMock.isPlaying()).thenReturn(true);
assertThat(audioPlayer.isPlaying(), is(true));
}
public class CustomBroadcastReceiver {
private boolean isMessageReceived;
public CustomBroadcastReceiver(EventBus eventBus) {
eventBus.register(this);
}
@Subscribe | public void onEvent(AudioPlayingEvent event) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
| import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import javax.inject.Inject;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static java.lang.String.format; | package com.mypodcasts.episodes;
public class EpisodeFile {
private final ExternalPublicFileLookup externalPublicFileLookup;
@Inject
public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
this.externalPublicFileLookup = externalPublicFileLookup;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeFile.java
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import javax.inject.Inject;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static java.lang.String.format;
package com.mypodcasts.episodes;
public class EpisodeFile {
private final ExternalPublicFileLookup externalPublicFileLookup;
@Inject
public EpisodeFile(ExternalPublicFileLookup externalPublicFileLookup) {
this.externalPublicFileLookup = externalPublicFileLookup;
}
| public boolean exists(Episode episode) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/repositories/Api.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path; | package com.mypodcasts.repositories;
public interface Api {
@GET("/api/user/johndoe/latest_episodes") | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/repositories/Api.java
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path;
package com.mypodcasts.repositories;
public interface Api {
@GET("/api/user/johndoe/latest_episodes") | List<Episode> getLatestEpisodes(); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/repositories/Api.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
| import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path; | package com.mypodcasts.repositories;
public interface Api {
@GET("/api/user/johndoe/latest_episodes")
List<Episode> getLatestEpisodes();
@GET("/api/user/johndoe/feeds") | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Feed.java
// public class Feed implements Serializable {
// private String id;
// private String title;
// private Image image;
// private List<Episode> episodes;
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Image getImage() {
// return image;
// }
//
// public List<Episode> getEpisodes() {
// return episodes;
// }
//
// }
// Path: app/src/main/java/com/mypodcasts/repositories/Api.java
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.repositories.models.Feed;
import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path;
package com.mypodcasts.repositories;
public interface Api {
@GET("/api/user/johndoe/latest_episodes")
List<Episode> getLatestEpisodes();
@GET("/api/user/johndoe/feeds") | List<Feed> getUserFeeds(); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import com.mypodcasts.repositories.models.Episode;
import java.util.List;
import javax.inject.Inject; | package com.mypodcasts.repositories;
public class UserLatestEpisodesRepository {
private final HttpClient httpClient;
@Inject
public UserLatestEpisodesRepository(HttpClient httpClient) {
this.httpClient = httpClient;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/main/java/com/mypodcasts/repositories/UserLatestEpisodesRepository.java
import com.mypodcasts.repositories.models.Episode;
import java.util.List;
import javax.inject.Inject;
package com.mypodcasts.repositories;
public class UserLatestEpisodesRepository {
private final HttpClient httpClient;
@Inject
public UserLatestEpisodesRepository(HttpClient httpClient) {
this.httpClient = httpClient;
}
| public List<Episode> getLatestEpisodes() { |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerActivityTest {
| // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java
import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerActivityTest {
| Episode episode; |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerActivityTest {
Episode episode;
AudioPlayerService audioPlayerServiceMock = mock(AudioPlayerService.class);
AudioPlayer audioPlayerMock = mock(AudioPlayer.class); | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java
import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
package com.mypodcasts.player;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class AudioPlayerActivityTest {
Episode episode;
AudioPlayerService audioPlayerServiceMock = mock(AudioPlayerService.class);
AudioPlayer audioPlayerMock = mock(AudioPlayer.class); | EpisodeCheckpoint episodeCheckpointMock = mock(EpisodeCheckpoint.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; |
@Test
public void itRegistersItselfToEventBusOnStart() {
AudioPlayerActivity activity = buildActivity(AudioPlayerActivity.class).create().get();
verify(eventBusMock).register(activity);
}
@Test
public void itUnregistersItselfToEventBusOnStop() {
AudioPlayerActivity activity = buildActivity(AudioPlayerActivity.class).create().stop().get();
verify(eventBusMock).unregister(activity);
}
@Test
public void itStartsAudioServiceGivenAnEpisode() throws IOException {
AudioPlayerActivity activity = createActivity();
Intent intent = shadowOf(activity).peekNextStartedService();
assertThat(
AudioPlayerService.class.getCanonicalName(),
is(intent.getComponent().getClassName())
);
}
@Test
public void itShowsMediaControlWhenAudioStartToPlay() {
AudioPlayerActivity activity = createActivity();
| // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java
import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
@Test
public void itRegistersItselfToEventBusOnStart() {
AudioPlayerActivity activity = buildActivity(AudioPlayerActivity.class).create().get();
verify(eventBusMock).register(activity);
}
@Test
public void itUnregistersItselfToEventBusOnStop() {
AudioPlayerActivity activity = buildActivity(AudioPlayerActivity.class).create().stop().get();
verify(eventBusMock).unregister(activity);
}
@Test
public void itStartsAudioServiceGivenAnEpisode() throws IOException {
AudioPlayerActivity activity = createActivity();
Intent intent = shadowOf(activity).peekNextStartedService();
assertThat(
AudioPlayerService.class.getCanonicalName(),
is(intent.getComponent().getClassName())
);
}
@Test
public void itShowsMediaControlWhenAudioStartToPlay() {
AudioPlayerActivity activity = createActivity();
| activity.onEvent(new AudioPlayingEvent(audioPlayerMock)); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java | // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector; | return "<span>Awesome Episode</span>";
}
};
AudioPlayerActivity activity = createActivity();
activity.onEvent(new AudioPlayingEvent(audioPlayerMock));
TextView textView = (TextView) activity.findViewById(R.id.episode_description);
String description = valueOf(textView.getText());
assertThat(description, is("Awesome Episode"));
}
@Test
public void itSetsToEmptyDescriptionWhenEpisodeIsNull() {
episode = null;
AudioPlayerActivity activity = createActivity();
activity.onEvent(new AudioPlayingEvent(audioPlayerMock));
TextView textView = (TextView) activity.findViewById(R.id.episode_description);
String description = valueOf(textView.getText());
assertThat(description, is(""));
}
@Test
public void itFinishesActivityOnAudioPlayerStoppedEvent() {
AudioPlayerActivity activity = createActivity();
| // Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
// public class EpisodeCheckpoint {
// public static final String STATE = EpisodeCheckpoint.class.toString();
// private final Context context;
//
// @Inject
// public EpisodeCheckpoint(Context context) {
// this.context = context;
// }
//
// public int markCheckpoint(Episode episode, int currentPosition) {
// SharedPreferences.Editor editor = getSharedPreferences().edit();
//
// Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode);
//
// editor.putInt(episodeKey(episode), currentPosition).apply();
//
// return currentPosition;
// }
//
// public int getLastCheckpointPosition(Episode episode, int defaultPosition) {
// SharedPreferences sharedPreferences = getSharedPreferences();
//
// return sharedPreferences.getInt(episodeKey(episode), defaultPosition);
// }
//
// private SharedPreferences getSharedPreferences() {
// return context.getSharedPreferences(STATE, MODE_PRIVATE);
// }
//
// private String episodeKey(Episode episode) {
// return format(
// "podcast_%s#episode_%s",
// episode.getFeed().getId(),
// replaceFromSpaceToUnderscore(episode.getTitle())
// );
// }
//
// private String replaceFromSpaceToUnderscore(String value) {
// return value.toLowerCase().replace(" ", "_");
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioPlayingEvent.java
// public class AudioPlayingEvent {
// private final AudioPlayer audioPlayer;
//
// public AudioPlayingEvent(AudioPlayer audioPlayer) {
// this.audioPlayer = audioPlayer;
// }
//
// public AudioPlayer getAudioPlayer() {
// return audioPlayer;
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/player/events/AudioStoppedEvent.java
// public class AudioStoppedEvent {}
//
// Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/test/java/com/mypodcasts/player/AudioPlayerActivityTest.java
import android.content.Intent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.google.inject.AbstractModule;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.episodes.EpisodeCheckpoint;
import com.mypodcasts.player.events.AudioPlayingEvent;
import com.mypodcasts.player.events.AudioStoppedEvent;
import com.mypodcasts.repositories.models.Episode;
import org.greenrobot.eventbus.EventBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.Random;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.RuntimeEnvironment.application;
import static org.robolectric.Shadows.shadowOf;
import static roboguice.RoboGuice.Util.reset;
import static roboguice.RoboGuice.overrideApplicationInjector;
return "<span>Awesome Episode</span>";
}
};
AudioPlayerActivity activity = createActivity();
activity.onEvent(new AudioPlayingEvent(audioPlayerMock));
TextView textView = (TextView) activity.findViewById(R.id.episode_description);
String description = valueOf(textView.getText());
assertThat(description, is("Awesome Episode"));
}
@Test
public void itSetsToEmptyDescriptionWhenEpisodeIsNull() {
episode = null;
AudioPlayerActivity activity = createActivity();
activity.onEvent(new AudioPlayingEvent(audioPlayerMock));
TextView textView = (TextView) activity.findViewById(R.id.episode_description);
String description = valueOf(textView.getText());
assertThat(description, is(""));
}
@Test
public void itFinishesActivityOnAudioPlayerStoppedEvent() {
AudioPlayerActivity activity = createActivity();
| activity.onEvent(new AudioStoppedEvent()); |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeList.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
| import com.mypodcasts.repositories.models.Episode;
import java.io.Serializable;
import java.util.List;
import static java.util.Collections.emptyList; | package com.mypodcasts.episodes;
public class EpisodeList implements Serializable {
public static final String HEADER = "EpisodeList#header";
public static final String LIST = "EpisodeList#list";
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeList.java
import com.mypodcasts.repositories.models.Episode;
import java.io.Serializable;
import java.util.List;
import static java.util.Collections.emptyList;
package com.mypodcasts.episodes;
public class EpisodeList implements Serializable {
public static final String HEADER = "EpisodeList#header";
public static final String LIST = "EpisodeList#list";
| private final List<Episode> episodes; |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.mypodcasts.repositories.models.Episode;
import javax.inject.Inject;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
import static java.lang.String.format; | package com.mypodcasts.episodes;
public class EpisodeCheckpoint {
public static final String STATE = EpisodeCheckpoint.class.toString();
private final Context context;
@Inject
public EpisodeCheckpoint(Context context) {
this.context = context;
}
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.mypodcasts.repositories.models.Episode;
import javax.inject.Inject;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
import static java.lang.String.format;
package com.mypodcasts.episodes;
public class EpisodeCheckpoint {
public static final String STATE = EpisodeCheckpoint.class.toString();
private final Context context;
@Inject
public EpisodeCheckpoint(Context context) {
this.context = context;
}
| public int markCheckpoint(Episode episode, int currentPosition) { |
alabeduarte/mypodcasts-android | app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.mypodcasts.repositories.models.Episode;
import javax.inject.Inject;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
import static java.lang.String.format; | package com.mypodcasts.episodes;
public class EpisodeCheckpoint {
public static final String STATE = EpisodeCheckpoint.class.toString();
private final Context context;
@Inject
public EpisodeCheckpoint(Context context) {
this.context = context;
}
public int markCheckpoint(Episode episode, int currentPosition) {
SharedPreferences.Editor editor = getSharedPreferences().edit();
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/Support.java
// public static final String MYPODCASTS_TAG = "[mypodcasts-android]";
// Path: app/src/main/java/com/mypodcasts/episodes/EpisodeCheckpoint.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.mypodcasts.repositories.models.Episode;
import javax.inject.Inject;
import static android.content.Context.MODE_PRIVATE;
import static com.mypodcasts.support.Support.MYPODCASTS_TAG;
import static java.lang.String.format;
package com.mypodcasts.episodes;
public class EpisodeCheckpoint {
public static final String STATE = EpisodeCheckpoint.class.toString();
private final Context context;
@Inject
public EpisodeCheckpoint(Context context) {
this.context = context;
}
public int markCheckpoint(Episode episode, int currentPosition) {
SharedPreferences.Editor editor = getSharedPreferences().edit();
| Log.i(MYPODCASTS_TAG, "Mark playing episode checkpoint: " + episode); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeFileTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
| import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.File;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeFileTest {
EpisodeFile episodeFile;
| // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeFileTest.java
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.File;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeFileTest {
EpisodeFile episodeFile;
| ExternalPublicFileLookup externalPublicFileLookupMock = mock(ExternalPublicFileLookup.class); |
alabeduarte/mypodcasts-android | app/src/test/java/com/mypodcasts/episodes/EpisodeFileTest.java | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
| import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.File;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeFileTest {
EpisodeFile episodeFile;
ExternalPublicFileLookup externalPublicFileLookupMock = mock(ExternalPublicFileLookup.class); | // Path: app/src/main/java/com/mypodcasts/repositories/models/Episode.java
// public class Episode implements Serializable {
//
// private String title;
// private String publishedDate;
// private String description;
// private String duration;
// private Audio audio;
// private Feed podcast;
// private Image image;
//
// public Image getImage() {
// return image;
// }
//
// public String getTitle() {
// return title;
// }
//
// public Date getPublishedDate() {
// if (publishedDate == null) { return null; }
//
// return dateTimeParser().parseDateTime(publishedDate).toDate();
// }
//
// public String getDescription() {
// return description == null ? "" : description;
// }
//
// public String getDuration() {
// return duration;
// }
//
// public Feed getFeed() {
// if (podcast == null) { return new Feed(); }
//
// return podcast;
// }
//
// public String getAudioFilePath() {
// return getFeed().getId() + "/" + getTitle() + ".mp3";
// }
//
// public String getAudioUrl() {
// return getAudio().getUrl();
// }
//
// public String getAudioLength() {
// return getAudio().getLength();
// }
//
// protected Audio getAudio() {
// if (audio == null) { return new EmptyAudio(); }
//
// return audio;
// }
//
// @Override
// public String toString() {
// return format(
// "{ \"title\": %s, " +
// "\"audioFilePath\": %s, " +
// "\"feed\": { \"id\": %s, \"title\": %s } " +
// "}",
// getTitle(),
// getAudioFilePath(),
// getFeed().getId(),
// getFeed().getTitle()
// );
// }
//
// private class EmptyAudio extends Audio {
// @Override
// public String getUrl() {
// return "";
// }
//
// @Override
// public String getLength() {
// return "0";
// }
// }
// }
//
// Path: app/src/main/java/com/mypodcasts/support/ExternalPublicFileLookup.java
// public class ExternalPublicFileLookup {
// public boolean exists(File directory, String filePath) {
// return new File(directory, filePath).exists();
// }
// }
// Path: app/src/test/java/com/mypodcasts/episodes/EpisodeFileTest.java
import com.mypodcasts.BuildConfig;
import com.mypodcasts.repositories.models.Episode;
import com.mypodcasts.support.ExternalPublicFileLookup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.File;
import static android.os.Environment.DIRECTORY_PODCASTS;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mypodcasts.episodes;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeFileTest {
EpisodeFile episodeFile;
ExternalPublicFileLookup externalPublicFileLookupMock = mock(ExternalPublicFileLookup.class); | Episode episode; |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/world/InstantMine.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
| import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.client.CPacketPlayerDigging.Action;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.world;
public class InstantMine extends Mod{
public InstantMine(String name, Category category) {
super(name, category);
}
public static boolean ncp = false;
@Override
public void onUpdate() {
BlockPos var1 = mc.objectMouseOver.getBlockPos();
if (mc.theWorld.getBlockState(var1).getMaterial() == Material.air)
return;
if (mc.playerController.isHittingBlock)
if (ncp
&& mc.gameSettings.keyBindAttack.isKeyDown()) | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
// Path: com/lunix/cheata/mod/mods/world/InstantMine.java
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.client.CPacketPlayerDigging.Action;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.world;
public class InstantMine extends Mod{
public InstantMine(String name, Category category) {
super(name, category);
}
public static boolean ncp = false;
@Override
public void onUpdate() {
BlockPos var1 = mc.objectMouseOver.getBlockPos();
if (mc.theWorld.getBlockState(var1).getMaterial() == Material.air)
return;
if (mc.playerController.isHittingBlock)
if (ncp
&& mc.gameSettings.keyBindAttack.isKeyDown()) | PacketUtils.sendPacket(new CPacketPlayerDigging(Action.STOP_DESTROY_BLOCK, |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/Mod.java | // Path: com/lunix/cheata/Client.java
// public class Client {
//
// private static String name = "Cheata";
// private static double ver = 1.21;
// private static String auth = "LUNiX";
// private static int color = 0x75ffb825;
// private static int colorDarker = 0xffb82500;
//
// private static ModManager modManager;
// private static FileManager fileManager;
// private static ModValueManager valueManager;
// private static FunctionMethods funcMethods;
// private static GuiManager guiManager;
// private static Class classs;
// private static GuiManagerDisplayScreen gui;
//
// private static boolean isInGame;
//
// public static void load(){
// Display.setTitle(name + " - " + ver);
//
// Client.getFileManager().setup();
// Client.getModManager().setup();
// Client.getValueManager().setup();
//
// ModEnabled.loadMods();
// ModSettings.loadMods();
//
// Runtime.getRuntime().addShutdownHook(new Thread()
// {
// @Override
// public void run()
// {
// Client.getFileManager().saveMods();
// Client.getFileManager().saveModSettigs();
// }
// });
// }
//
// public static GuiManager getGuiManager(){
// if(guiManager == null){
// guiManager = new GuiManager();
// guiManager.setTheme(new SimpleTheme());
// guiManager.setup();
// guiManager.update();
// }
// return guiManager;
// }
//
// public static GuiManagerDisplayScreen getGui(){
// if(gui == null){
// gui = new GuiManagerDisplayScreen(getGuiManager());
// }
// return gui;
// }
//
// public static String getName() {
// return name;
// }
//
// public static double getVer() {
// return ver;
// }
//
// public static String getAuth() {
// return auth;
// }
//
// public static ModManager getModManager() {
// return modManager;
// }
//
// public static FunctionMethods getFunctionMethods() {
// return funcMethods;
// }
//
// public static FileManager getFileManager(){
// return fileManager;
// }
//
// public static ModValueManager getValueManager(){
// return valueManager;
// }
//
// public static boolean isInGame() {
// return isInGame;
// }
//
// public static void setInGame(boolean isInGame) {
// Client.isInGame = isInGame;
// }
//
// public static int getColor() {
// return color;
// }
//
// public static int getColorDarker() {
// return colorDarker;
// }
//
// private static Class getClasss(){
// return classs;
// }
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
| import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import com.lunix.cheata.Client;
import com.lunix.cheata.utils.Category; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod;
public class Mod {
protected static Minecraft mc = Minecraft.getMinecraft();
private String name;
private int bind;
private int bindMask; | // Path: com/lunix/cheata/Client.java
// public class Client {
//
// private static String name = "Cheata";
// private static double ver = 1.21;
// private static String auth = "LUNiX";
// private static int color = 0x75ffb825;
// private static int colorDarker = 0xffb82500;
//
// private static ModManager modManager;
// private static FileManager fileManager;
// private static ModValueManager valueManager;
// private static FunctionMethods funcMethods;
// private static GuiManager guiManager;
// private static Class classs;
// private static GuiManagerDisplayScreen gui;
//
// private static boolean isInGame;
//
// public static void load(){
// Display.setTitle(name + " - " + ver);
//
// Client.getFileManager().setup();
// Client.getModManager().setup();
// Client.getValueManager().setup();
//
// ModEnabled.loadMods();
// ModSettings.loadMods();
//
// Runtime.getRuntime().addShutdownHook(new Thread()
// {
// @Override
// public void run()
// {
// Client.getFileManager().saveMods();
// Client.getFileManager().saveModSettigs();
// }
// });
// }
//
// public static GuiManager getGuiManager(){
// if(guiManager == null){
// guiManager = new GuiManager();
// guiManager.setTheme(new SimpleTheme());
// guiManager.setup();
// guiManager.update();
// }
// return guiManager;
// }
//
// public static GuiManagerDisplayScreen getGui(){
// if(gui == null){
// gui = new GuiManagerDisplayScreen(getGuiManager());
// }
// return gui;
// }
//
// public static String getName() {
// return name;
// }
//
// public static double getVer() {
// return ver;
// }
//
// public static String getAuth() {
// return auth;
// }
//
// public static ModManager getModManager() {
// return modManager;
// }
//
// public static FunctionMethods getFunctionMethods() {
// return funcMethods;
// }
//
// public static FileManager getFileManager(){
// return fileManager;
// }
//
// public static ModValueManager getValueManager(){
// return valueManager;
// }
//
// public static boolean isInGame() {
// return isInGame;
// }
//
// public static void setInGame(boolean isInGame) {
// Client.isInGame = isInGame;
// }
//
// public static int getColor() {
// return color;
// }
//
// public static int getColorDarker() {
// return colorDarker;
// }
//
// private static Class getClasss(){
// return classs;
// }
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
// Path: com/lunix/cheata/mod/Mod.java
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import com.lunix.cheata.Client;
import com.lunix.cheata.utils.Category;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod;
public class Mod {
protected static Minecraft mc = Minecraft.getMinecraft();
private String name;
private int bind;
private int bindMask; | private Category category; |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/Mod.java | // Path: com/lunix/cheata/Client.java
// public class Client {
//
// private static String name = "Cheata";
// private static double ver = 1.21;
// private static String auth = "LUNiX";
// private static int color = 0x75ffb825;
// private static int colorDarker = 0xffb82500;
//
// private static ModManager modManager;
// private static FileManager fileManager;
// private static ModValueManager valueManager;
// private static FunctionMethods funcMethods;
// private static GuiManager guiManager;
// private static Class classs;
// private static GuiManagerDisplayScreen gui;
//
// private static boolean isInGame;
//
// public static void load(){
// Display.setTitle(name + " - " + ver);
//
// Client.getFileManager().setup();
// Client.getModManager().setup();
// Client.getValueManager().setup();
//
// ModEnabled.loadMods();
// ModSettings.loadMods();
//
// Runtime.getRuntime().addShutdownHook(new Thread()
// {
// @Override
// public void run()
// {
// Client.getFileManager().saveMods();
// Client.getFileManager().saveModSettigs();
// }
// });
// }
//
// public static GuiManager getGuiManager(){
// if(guiManager == null){
// guiManager = new GuiManager();
// guiManager.setTheme(new SimpleTheme());
// guiManager.setup();
// guiManager.update();
// }
// return guiManager;
// }
//
// public static GuiManagerDisplayScreen getGui(){
// if(gui == null){
// gui = new GuiManagerDisplayScreen(getGuiManager());
// }
// return gui;
// }
//
// public static String getName() {
// return name;
// }
//
// public static double getVer() {
// return ver;
// }
//
// public static String getAuth() {
// return auth;
// }
//
// public static ModManager getModManager() {
// return modManager;
// }
//
// public static FunctionMethods getFunctionMethods() {
// return funcMethods;
// }
//
// public static FileManager getFileManager(){
// return fileManager;
// }
//
// public static ModValueManager getValueManager(){
// return valueManager;
// }
//
// public static boolean isInGame() {
// return isInGame;
// }
//
// public static void setInGame(boolean isInGame) {
// Client.isInGame = isInGame;
// }
//
// public static int getColor() {
// return color;
// }
//
// public static int getColorDarker() {
// return colorDarker;
// }
//
// private static Class getClasss(){
// return classs;
// }
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
| import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import com.lunix.cheata.Client;
import com.lunix.cheata.utils.Category; |
public void setBindMask(int bindMask) {
if(!this.hasBindMask){
this.hasBindMask = true;
}
this.bindMask = bindMask;
}
public void removeBindMask(int bindMask) {
this.hasBindMask = false;
bindMask = 0;
}
public String getName() {
return name;
}
public Category getCategory() {
return category;
}
public int getColor() {
return color;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean state){ | // Path: com/lunix/cheata/Client.java
// public class Client {
//
// private static String name = "Cheata";
// private static double ver = 1.21;
// private static String auth = "LUNiX";
// private static int color = 0x75ffb825;
// private static int colorDarker = 0xffb82500;
//
// private static ModManager modManager;
// private static FileManager fileManager;
// private static ModValueManager valueManager;
// private static FunctionMethods funcMethods;
// private static GuiManager guiManager;
// private static Class classs;
// private static GuiManagerDisplayScreen gui;
//
// private static boolean isInGame;
//
// public static void load(){
// Display.setTitle(name + " - " + ver);
//
// Client.getFileManager().setup();
// Client.getModManager().setup();
// Client.getValueManager().setup();
//
// ModEnabled.loadMods();
// ModSettings.loadMods();
//
// Runtime.getRuntime().addShutdownHook(new Thread()
// {
// @Override
// public void run()
// {
// Client.getFileManager().saveMods();
// Client.getFileManager().saveModSettigs();
// }
// });
// }
//
// public static GuiManager getGuiManager(){
// if(guiManager == null){
// guiManager = new GuiManager();
// guiManager.setTheme(new SimpleTheme());
// guiManager.setup();
// guiManager.update();
// }
// return guiManager;
// }
//
// public static GuiManagerDisplayScreen getGui(){
// if(gui == null){
// gui = new GuiManagerDisplayScreen(getGuiManager());
// }
// return gui;
// }
//
// public static String getName() {
// return name;
// }
//
// public static double getVer() {
// return ver;
// }
//
// public static String getAuth() {
// return auth;
// }
//
// public static ModManager getModManager() {
// return modManager;
// }
//
// public static FunctionMethods getFunctionMethods() {
// return funcMethods;
// }
//
// public static FileManager getFileManager(){
// return fileManager;
// }
//
// public static ModValueManager getValueManager(){
// return valueManager;
// }
//
// public static boolean isInGame() {
// return isInGame;
// }
//
// public static void setInGame(boolean isInGame) {
// Client.isInGame = isInGame;
// }
//
// public static int getColor() {
// return color;
// }
//
// public static int getColorDarker() {
// return colorDarker;
// }
//
// private static Class getClasss(){
// return classs;
// }
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
// Path: com/lunix/cheata/mod/Mod.java
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import com.lunix.cheata.Client;
import com.lunix.cheata.utils.Category;
public void setBindMask(int bindMask) {
if(!this.hasBindMask){
this.hasBindMask = true;
}
this.bindMask = bindMask;
}
public void removeBindMask(int bindMask) {
this.hasBindMask = false;
bindMask = 0;
}
public String getName() {
return name;
}
public Category getCategory() {
return category;
}
public int getColor() {
return color;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean state){ | if(Client.isInGame()) |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/combat/ChestStealer.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
| import net.minecraft.inventory.ClickType;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.Slot;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.combat;
public class ChestStealer extends Mod{
public ChestStealer(String name, Category category) {
super(name, category);
}
| // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
// Path: com/lunix/cheata/mod/mods/combat/ChestStealer.java
import net.minecraft.inventory.ClickType;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.Slot;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.combat;
public class ChestStealer extends Mod{
public ChestStealer(String name, Category category) {
super(name, category);
}
| Timer timer = new Timer(); |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/misc/SkinDerp.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
| import java.util.Random;
import net.minecraft.entity.player.EnumPlayerModelParts;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class SkinDerp extends Mod{
public SkinDerp(String name, Category category) {
super(name, category);
}
| // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
// Path: com/lunix/cheata/mod/mods/misc/SkinDerp.java
import java.util.Random;
import net.minecraft.entity.player.EnumPlayerModelParts;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class SkinDerp extends Mod{
public SkinDerp(String name, Category category) {
super(name, category);
}
| Timer timer = new Timer(); |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/misc/AutoFish.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
| import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class AutoFish extends Mod{
public AutoFish(String name, Category category) {
super(name, category);
}
private boolean isFishing = false; | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/Timer.java
// public class Timer {
// public static short convert(float perSecond) {
// return (short) (1000 / perSecond);
// }
//
// public static long getCurrentTime() {
// return System.nanoTime() / 1000000;
// }
//
// private long previousTime;
//
// public Timer() {
// previousTime = -1L;
// }
//
// public long get() {
// return previousTime;
// }
//
// public boolean check(float milliseconds) {
// return Timer.getCurrentTime() - previousTime >= milliseconds;
// }
//
// public void reset() {
// previousTime = Timer.getCurrentTime();
// }
// }
// Path: com/lunix/cheata/mod/mods/misc/AutoFish.java
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.Timer;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class AutoFish extends Mod{
public AutoFish(String name, Category category) {
super(name, category);
}
private boolean isFishing = false; | private Timer timer = new Timer(); |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/ModManager.java | // Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
| import java.util.ArrayList;
import java.util.Collections;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
import com.lunix.cheata.mod.mods.combat.*;
import com.lunix.cheata.mod.mods.misc.*;
import com.lunix.cheata.mod.mods.movement.*;
import com.lunix.cheata.mod.mods.player.*;
import com.lunix.cheata.mod.mods.world.*;
import com.lunix.cheata.utils.Category; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod;
public class ModManager {
public static ArrayList<Mod> mods = new ArrayList<Mod>();
public static void setup(){
/*
* Misc
*/ | // Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
// Path: com/lunix/cheata/mod/ModManager.java
import java.util.ArrayList;
import java.util.Collections;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
import com.lunix.cheata.mod.mods.combat.*;
import com.lunix.cheata.mod.mods.misc.*;
import com.lunix.cheata.mod.mods.movement.*;
import com.lunix.cheata.mod.mods.player.*;
import com.lunix.cheata.mod.mods.world.*;
import com.lunix.cheata.utils.Category;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod;
public class ModManager {
public static ArrayList<Mod> mods = new ArrayList<Mod>();
public static void setup(){
/*
* Misc
*/ | mods.add(new AntiFire("Anti-Fire", Category.MISC)); |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/misc/AntiFire.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
| import net.minecraft.network.play.client.CPacketPlayer;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class AntiFire extends Mod{
public AntiFire(String name, Category category) {
super(name, category);
}
@Override
public void onUpdate() {
if(!mc.thePlayer.capabilities.isCreativeMode){
if(mc.thePlayer.isBurning() && mc.thePlayer.onGround){ | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
// Path: com/lunix/cheata/mod/mods/misc/AntiFire.java
import net.minecraft.network.play.client.CPacketPlayer;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.misc;
public class AntiFire extends Mod{
public AntiFire(String name, Category category) {
super(name, category);
}
@Override
public void onUpdate() {
if(!mc.thePlayer.capabilities.isCreativeMode){
if(mc.thePlayer.isBurning() && mc.thePlayer.onGround){ | PacketUtils.sendPacket(new CPacketPlayer()); |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/player/FullBright.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
| import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.player;
public class FullBright extends Mod {
private float startBright;
private float fullBright = 1000000000;
| // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
// Path: com/lunix/cheata/mod/mods/player/FullBright.java
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.player;
public class FullBright extends Mod {
private float startBright;
private float fullBright = 1000000000;
| public FullBright(String name, int bind, Category category) { |
CheataClient/CheataClientSrc | com/lunix/cheata/mod/mods/movement/NoFall.java | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
| import net.minecraft.network.play.client.CPacketPlayer;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils; | /*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.movement;
public class NoFall extends Mod{
public NoFall(String name, Category category) {
super(name, category);
}
@Override
public void onUpdate() {
if(mc.thePlayer.fallDistance != 0){ | // Path: com/lunix/cheata/mod/Mod.java
// public class Mod {
//
// protected static Minecraft mc = Minecraft.getMinecraft();
//
// private String name;
// private int bind;
// private int bindMask;
// private Category category;
// private int color;
// private boolean isEnabled;
// public boolean hasBind;
// public boolean hasBindMask;
//
// public Mod(String name, Category category){
// this.name = name;
// this.category = category;
// this.hasBind = false;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, Category category){
// this.name = name;
// this.bind = bind;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = false;
// }
//
// public Mod(String name, int bind, int bindMask, Category category){
// this.name = name;
// this.bind = bind;
// this.bindMask = bindMask;
// this.category = category;
// this.hasBind = true;
// this.hasBindMask = true;
// }
//
// public int getBind() {
// return bind;
// }
//
// public int getBindMask() {
// return bindMask;
// }
//
// public void setBind(int bind){
// if(!this.hasBind){
// this.hasBind = true;
// }
// this.bind = bind;
// }
//
// public void setBindMask(int bindMask) {
// if(!this.hasBindMask){
// this.hasBindMask = true;
// }
// this.bindMask = bindMask;
// }
//
// public void removeBindMask(int bindMask) {
// this.hasBindMask = false;
// bindMask = 0;
// }
//
// public String getName() {
// return name;
// }
//
// public Category getCategory() {
// return category;
// }
//
// public int getColor() {
// return color;
// }
//
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setEnabled(boolean state){
// if(Client.isInGame())
// onToggle();
// if(state){
// if(Client.isInGame())
// onEnable();
// this.isEnabled = true;
// }else{
// if(Client.isInGame())
// onDisable();
// this.isEnabled = false;
// }
// }
//
// public void toggle(){
// setEnabled(!this.isEnabled());
// }
//
// public void onEnable(){}
// public void onDisable(){}
// public void onToggle(){}
// public void onUpdate(){}
// public void onRender(){}
// public void onClickLeft(){}
// public void onClickRight(){}
//
// public boolean isCategory(Category isCategory) {
// if(isCategory == category)
// return true;
// return false;
// }
//
// }
//
// Path: com/lunix/cheata/utils/Category.java
// public enum Category {
// COMBAT, WORLD, PLAYER, MISC, MOVEMENT, NONE
// }
//
// Path: com/lunix/cheata/utils/packet/PacketUtils.java
// public class PacketUtils {
//
// public static void sendPacket(Packet packetIn) {
// Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(packetIn);
// }
// public static NetworkManager getNetworkManager(){
// return NetworkPacket.networkManager;
// }
// }
// Path: com/lunix/cheata/mod/mods/movement/NoFall.java
import net.minecraft.network.play.client.CPacketPlayer;
import com.lunix.cheata.mod.Mod;
import com.lunix.cheata.utils.Category;
import com.lunix.cheata.utils.packet.PacketUtils;
/*
* Copyright © 2015 - 2017 Lunix and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.lunix.cheata.mod.mods.movement;
public class NoFall extends Mod{
public NoFall(String name, Category category) {
super(name, category);
}
@Override
public void onUpdate() {
if(mc.thePlayer.fallDistance != 0){ | PacketUtils.sendPacket(new CPacketPlayer(true)); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
| import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id"); | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
// Path: src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id"); | final PrepareSpecRequest prepareSpecRequest = new PrepareSpecRequest(); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
| import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id");
final PrepareSpecRequest prepareSpecRequest = new PrepareSpecRequest();
if (request.content() == null) {
throw new ElasticsearchException("prepare spec request must have a body");
}
prepareSpecRequest.source(new String(BytesReference.toBytes(request.content()), Charset.defaultCharset()));
if (id != null) {
prepareSpecRequest.id(id);
}
return channel -> { | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
// Path: src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id");
final PrepareSpecRequest prepareSpecRequest = new PrepareSpecRequest();
if (request.content() == null) {
throw new ElasticsearchException("prepare spec request must have a body");
}
prepareSpecRequest.source(new String(BytesReference.toBytes(request.content()), Charset.defaultCharset()));
if (id != null) {
prepareSpecRequest.id(id);
}
return channel -> { | client.execute(PrepareSpecAction.INSTANCE, prepareSpecRequest, new RestBuilderListener<PrepareSpecResponse>(channel) { |
brwe/es-token-plugin | src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
| import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id");
final PrepareSpecRequest prepareSpecRequest = new PrepareSpecRequest();
if (request.content() == null) {
throw new ElasticsearchException("prepare spec request must have a body");
}
prepareSpecRequest.source(new String(BytesReference.toBytes(request.content()), Charset.defaultCharset()));
if (id != null) {
prepareSpecRequest.id(id);
}
return channel -> { | // Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecAction.java
// public class PrepareSpecAction extends Action<PrepareSpecRequest, PrepareSpecResponse, PrepareSpecRequestBuilder> {
//
// public static final PrepareSpecAction INSTANCE = new PrepareSpecAction();
// public static final String NAME = "indices:data/create/spec";
//
// private PrepareSpecAction() {
// super(NAME);
// }
//
// @Override
// public PrepareSpecResponse newResponse() {
// return new PrepareSpecResponse();
// }
//
// @Override
// public PrepareSpecRequestBuilder newRequestBuilder(ElasticsearchClient client) {
// return new PrepareSpecRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecRequest.java
// public class PrepareSpecRequest extends ActionRequest<PrepareSpecRequest> {
//
// private String source;
// private String id;
//
// public PrepareSpecRequest() {
//
// }
// public PrepareSpecRequest(String source) {
// this.source = source;
//
// }
//
// @Override
// public ActionRequestValidationException validate() {
// ActionRequestValidationException validationException = null;
// if (source == null) {
// validationException = ValidateActions.addValidationError("prepare_spec needs a source", validationException);
// }
// return validationException;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// source = in.readString();
// id = in.readOptionalString();
//
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(source);
// out.writeOptionalString(id);
// }
//
//
// public PrepareSpecRequest source(String source) {
// this.source = source;
// return this;
// }
//
// public String source() {
// return source;
// }
//
// public void id(String id) {
// this.id = id;
// }
//
// public String id() {
// return id;
// }
// }
//
// Path: src/main/java/org/elasticsearch/action/preparespec/PrepareSpecResponse.java
// public class PrepareSpecResponse extends ActionResponse implements ToXContent {
//
// private BytesReference spec;
// private Map<String, Object> specAsMap;
// private int length;
//
// public PrepareSpecResponse() {
//
// }
//
// public PrepareSpecResponse(BytesReference spec, int length) {
// this.spec = spec;
// this.length = length;
// }
// public BytesReference getSpec() {
// return spec;
// }
//
// public Map<String, Object> getSpecAsMap() {
// if (specAsMap == null) {
// specAsMap = Collections.unmodifiableMap(XContentHelper.convertToMap(spec, true).v2());
// }
// return specAsMap;
// }
//
// public int getLength() {
// return length;
// }
//
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// builder.rawField(Fields.SPEC, spec);
// builder.field(Fields.LENGTH, length);
// return builder;
// }
//
// static final class Fields {
// static final String SPEC = "spec";
// static final String LENGTH = "length";
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// spec = in.readBytesReference();
// length = in.readInt();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeBytesReference(spec);
// out.writeInt(length);
// }
// }
// Path: src/main/java/org/elasticsearch/rest/action/preparespec/RestPrepareSpecAction.java
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.preparespec.PrepareSpecAction;
import org.elasticsearch.action.preparespec.PrepareSpecRequest;
import org.elasticsearch.action.preparespec.PrepareSpecResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.preparespec;
/**
*
*/
public class RestPrepareSpecAction extends BaseRestHandler {
@Inject
public RestPrepareSpecAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "/_prepare_spec", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String id = request.param("id");
final PrepareSpecRequest prepareSpecRequest = new PrepareSpecRequest();
if (request.content() == null) {
throw new ElasticsearchException("prepare spec request must have a body");
}
prepareSpecRequest.source(new String(BytesReference.toBytes(request.content()), Charset.defaultCharset()));
if (id != null) {
prepareSpecRequest.id(id);
}
return channel -> { | client.execute(PrepareSpecAction.INSTANCE, prepareSpecRequest, new RestBuilderListener<PrepareSpecResponse>(channel) { |
brwe/es-token-plugin | src/test/java/org/elasticsearch/search/fetch/analyzedtext/AnalyzedTextFetchIT.java | // Path: src/main/java/org/elasticsearch/plugin/TokenPlugin.java
// public class TokenPlugin extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin, IngestPlugin {
//
// private final Settings settings;
// private final boolean transportClientMode;
// private final IngestAnalysisService ingestAnalysisService;
//
// public TokenPlugin(Settings settings) {
// this.settings = settings;
// this.transportClientMode = TransportClient.CLIENT_TYPE.equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey()));
// ingestAnalysisService = new IngestAnalysisService(settings);
// }
//
// @Override
// public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool,
// ResourceWatcherService resourceWatcherService, ScriptService scriptService,
// SearchRequestParsers searchRequestParsers) {
// ModelTrainers modelTrainers = new ModelTrainers(Arrays.asList(new NaiveBayesModelTrainer()));
// TrainingService trainingService = new TrainingService(settings, clusterService, client, modelTrainers, searchRequestParsers);
//
// final ClusterSettings clusterSettings = clusterService.getClusterSettings();
// Setting<Settings> ingestAnalysisGroupSetting = ingestAnalysisService.getIngestAnalysisGroupSetting();
// clusterSettings.addSettingsUpdateConsumer(ingestAnalysisGroupSetting, ingestAnalysisService::setAnalysisSettings);
// ingestAnalysisService.setAnalysisSettings(ingestAnalysisGroupSetting.get(settings));
//
// return Arrays.asList(trainingService, ingestAnalysisService);
// }
//
// @Override
// public ScriptEngineService getScriptEngineService(Settings settings) {
// return new PMMLModelScriptEngineService(settings);
// }
//
// @Override
// public List<NativeScriptFactory> getNativeScripts() {
// return Collections.singletonList(new VectorScriptFactory());
// }
//
// @Override
// public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// return Arrays.asList(
// new ActionHandler<>(AllTermsAction.INSTANCE, TransportAllTermsAction.class, TransportAllTermsShardAction.class),
// new ActionHandler<>(PrepareSpecAction.INSTANCE, TransportPrepareSpecAction.class),
// new ActionHandler<>(TrainModelAction.INSTANCE, TransportTrainModelAction.class)
// );
// }
//
// @Override
// public List<Class<? extends RestHandler>> getRestHandlers() {
// return Arrays.asList(
// RestAllTermsAction.class,
// RestPrepareSpecAction.class,
// RestStoreModelAction.class,
// RestTrainModelAction.class
// );
// }
//
// @Override
// public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) {
// return Arrays.asList(
// new TermVectorsFetchSubPhase(),
// new AnalyzedTextFetchSubPhase()
// );
// }
//
// @Override
// public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
// ingestAnalysisService.setAnalysisRegistry(parameters.analysisRegistry);
// return Collections.singletonMap(AnalyzerProcessor.TYPE, new AnalyzerProcessor.Factory(ingestAnalysisService));
// }
//
// @Override
// public List<Setting<?>> getSettings() {
// return Collections.singletonList(ingestAnalysisService.getIngestAnalysisGroupSetting());
// }
//
// @Override
// public List<SearchExtSpec<?>> getSearchExts() {
// return Arrays.asList(
// new SearchExtSpec<>(TermVectorsFetchSubPhase.NAME, TermVectorsFetchBuilder::new, TermVectorsFetchParser.INSTANCE),
// new SearchExtSpec<>(AnalyzedTextFetchSubPhase.NAME, AnalyzedTextFetchBuilder::new, AnalyzedTextFetchParser.INSTANCE)
// );
// }
// }
| import java.util.List;
import static org.elasticsearch.client.Requests.indexRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.plugin.TokenPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESIntegTestCase;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.fetch.analyzedtext;
public class AnalyzedTextFetchIT extends ESIntegTestCase {
protected Collection<Class<? extends Plugin>> transportClientPlugins() { | // Path: src/main/java/org/elasticsearch/plugin/TokenPlugin.java
// public class TokenPlugin extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin, IngestPlugin {
//
// private final Settings settings;
// private final boolean transportClientMode;
// private final IngestAnalysisService ingestAnalysisService;
//
// public TokenPlugin(Settings settings) {
// this.settings = settings;
// this.transportClientMode = TransportClient.CLIENT_TYPE.equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey()));
// ingestAnalysisService = new IngestAnalysisService(settings);
// }
//
// @Override
// public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool,
// ResourceWatcherService resourceWatcherService, ScriptService scriptService,
// SearchRequestParsers searchRequestParsers) {
// ModelTrainers modelTrainers = new ModelTrainers(Arrays.asList(new NaiveBayesModelTrainer()));
// TrainingService trainingService = new TrainingService(settings, clusterService, client, modelTrainers, searchRequestParsers);
//
// final ClusterSettings clusterSettings = clusterService.getClusterSettings();
// Setting<Settings> ingestAnalysisGroupSetting = ingestAnalysisService.getIngestAnalysisGroupSetting();
// clusterSettings.addSettingsUpdateConsumer(ingestAnalysisGroupSetting, ingestAnalysisService::setAnalysisSettings);
// ingestAnalysisService.setAnalysisSettings(ingestAnalysisGroupSetting.get(settings));
//
// return Arrays.asList(trainingService, ingestAnalysisService);
// }
//
// @Override
// public ScriptEngineService getScriptEngineService(Settings settings) {
// return new PMMLModelScriptEngineService(settings);
// }
//
// @Override
// public List<NativeScriptFactory> getNativeScripts() {
// return Collections.singletonList(new VectorScriptFactory());
// }
//
// @Override
// public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// return Arrays.asList(
// new ActionHandler<>(AllTermsAction.INSTANCE, TransportAllTermsAction.class, TransportAllTermsShardAction.class),
// new ActionHandler<>(PrepareSpecAction.INSTANCE, TransportPrepareSpecAction.class),
// new ActionHandler<>(TrainModelAction.INSTANCE, TransportTrainModelAction.class)
// );
// }
//
// @Override
// public List<Class<? extends RestHandler>> getRestHandlers() {
// return Arrays.asList(
// RestAllTermsAction.class,
// RestPrepareSpecAction.class,
// RestStoreModelAction.class,
// RestTrainModelAction.class
// );
// }
//
// @Override
// public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) {
// return Arrays.asList(
// new TermVectorsFetchSubPhase(),
// new AnalyzedTextFetchSubPhase()
// );
// }
//
// @Override
// public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
// ingestAnalysisService.setAnalysisRegistry(parameters.analysisRegistry);
// return Collections.singletonMap(AnalyzerProcessor.TYPE, new AnalyzerProcessor.Factory(ingestAnalysisService));
// }
//
// @Override
// public List<Setting<?>> getSettings() {
// return Collections.singletonList(ingestAnalysisService.getIngestAnalysisGroupSetting());
// }
//
// @Override
// public List<SearchExtSpec<?>> getSearchExts() {
// return Arrays.asList(
// new SearchExtSpec<>(TermVectorsFetchSubPhase.NAME, TermVectorsFetchBuilder::new, TermVectorsFetchParser.INSTANCE),
// new SearchExtSpec<>(AnalyzedTextFetchSubPhase.NAME, AnalyzedTextFetchBuilder::new, AnalyzedTextFetchParser.INSTANCE)
// );
// }
// }
// Path: src/test/java/org/elasticsearch/search/fetch/analyzedtext/AnalyzedTextFetchIT.java
import java.util.List;
import static org.elasticsearch.client.Requests.indexRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.plugin.TokenPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESIntegTestCase;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.fetch.analyzedtext;
public class AnalyzedTextFetchIT extends ESIntegTestCase {
protected Collection<Class<? extends Plugin>> transportClientPlugins() { | return Collections.singletonList(TokenPlugin.class); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java | // Path: src/main/java/org/elasticsearch/ml/models/EsModelEvaluator.java
// public abstract class EsModelEvaluator<Input extends ModelInput, Output> {
//
// public abstract Map<String, Object> evaluateDebug(Input modelInput);
// public abstract Output evaluate(Input modelInput);
// }
| import org.elasticsearch.ml.models.EsModelEvaluator; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.modelinput;
/**
*
*/
public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
private final ModelInputEvaluator<Input> vectorRangesToVector;
| // Path: src/main/java/org/elasticsearch/ml/models/EsModelEvaluator.java
// public abstract class EsModelEvaluator<Input extends ModelInput, Output> {
//
// public abstract Map<String, Object> evaluateDebug(Input modelInput);
// public abstract Output evaluate(Input modelInput);
// }
// Path: src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java
import org.elasticsearch.ml.models.EsModelEvaluator;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.modelinput;
/**
*
*/
public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
private final ModelInputEvaluator<Input> vectorRangesToVector;
| private final EsModelEvaluator<Input, Output> model; |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/training/ModelTrainers.java | // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
| import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.training;
/**
* Collection of all available model trainers
*/
public class ModelTrainers {
private final Map<String, ModelTrainer> modelTrainers;
public ModelTrainers(List<ModelTrainer> modelTrainers) {
Map<String, ModelTrainer> modelParserMap = new HashMap<>();
for (ModelTrainer trainer : modelTrainers) {
ModelTrainer prev = modelParserMap.put(trainer.modelType(), trainer);
if (prev != null) {
throw new IllegalStateException("Added more than one trainer for model type [" + trainer.modelType() + "]");
}
}
this.modelTrainers = Collections.unmodifiableMap(modelParserMap);
}
| // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
// Path: src/main/java/org/elasticsearch/ml/training/ModelTrainers.java
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.training;
/**
* Collection of all available model trainers
*/
public class ModelTrainers {
private final Map<String, ModelTrainer> modelTrainers;
public ModelTrainers(List<ModelTrainer> modelTrainers) {
Map<String, ModelTrainer> modelParserMap = new HashMap<>();
for (ModelTrainer trainer : modelTrainers) {
ModelTrainer prev = modelParserMap.put(trainer.modelType(), trainer);
if (prev != null) {
throw new IllegalStateException("Added more than one trainer for model type [" + trainer.modelType() + "]");
}
}
this.modelTrainers = Collections.unmodifiableMap(modelParserMap);
}
| public TrainingSession createTrainingSession(MappingMetaData mappingMetaData, String modelType, Settings settings, |
brwe/es-token-plugin | src/main/java/org/elasticsearch/search/fetch/termvectors/TermVectorsFetchSubPhase.java | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.termvectors.TermVectorsRequest;
import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.termvectors.TermVectorsService;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHitField;
import org.elasticsearch.search.internal.SearchContext; | public void hitExecute(SearchContext context, HitContext hitContext) {
TermVectorsFetchBuilder fetchSubPhaseBuilder = (TermVectorsFetchBuilder)context.getSearchExt(NAME);
if (fetchSubPhaseBuilder == null) {
return;
}
if (hitContext.hit().fieldsOrNull() == null) {
hitContext.hit().fields(new HashMap<String, SearchHitField>());
}
SearchHitField hitField = hitContext.hit().fields().get(NAME);
if (hitField == null) {
hitField = new InternalSearchHitField(NAME, new ArrayList<>(1));
hitContext.hit().fields().put(NAME, hitField);
}
TermVectorsRequest request = fetchSubPhaseBuilder.getRequest();
request.id(hitContext.hit().id());
request.type(hitContext.hit().type());
request.index(context.indexShard().shardId().getIndexName());
TermVectorsResponse termVector = TermVectorsService.getTermVectors(context.indexShard(), request);
XContentBuilder builder;
try {
builder = jsonBuilder();
builder.startObject();
termVector.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
} catch (IOException e) {
throw new ElasticsearchException("could not build term vector respoonse", e);
}
try { | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
// Path: src/main/java/org/elasticsearch/search/fetch/termvectors/TermVectorsFetchSubPhase.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.termvectors.TermVectorsRequest;
import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.termvectors.TermVectorsService;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHitField;
import org.elasticsearch.search.internal.SearchContext;
public void hitExecute(SearchContext context, HitContext hitContext) {
TermVectorsFetchBuilder fetchSubPhaseBuilder = (TermVectorsFetchBuilder)context.getSearchExt(NAME);
if (fetchSubPhaseBuilder == null) {
return;
}
if (hitContext.hit().fieldsOrNull() == null) {
hitContext.hit().fields(new HashMap<String, SearchHitField>());
}
SearchHitField hitField = hitContext.hit().fields().get(NAME);
if (hitField == null) {
hitField = new InternalSearchHitField(NAME, new ArrayList<>(1));
hitContext.hit().fields().put(NAME, hitField);
}
TermVectorsRequest request = fetchSubPhaseBuilder.getRequest();
request.id(hitContext.hit().id());
request.type(hitContext.hit().type());
request.index(context.indexShard().shardId().getIndexName());
TermVectorsResponse termVector = TermVectorsService.getTermVectors(context.indexShard(), request);
XContentBuilder builder;
try {
builder = jsonBuilder();
builder.startObject();
termVector.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
} catch (IOException e) {
throw new ElasticsearchException("could not build term vector respoonse", e);
}
try { | Map<String, Object> termVectorAsMap = SharedMethods.getSourceAsMap(builder.string()); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/rest/action/trainmodel/RestTrainModelAction.java | // Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelRequestBuilder.java
// public class TrainModelRequestBuilder extends ActionRequestBuilder<TrainModelRequest, TrainModelResponse,
// TrainModelRequestBuilder> {
//
// public TrainModelRequestBuilder(ElasticsearchClient client) {
// super(client, TrainModelAction.INSTANCE, new TrainModelRequest());
// }
//
// public TrainModelRequestBuilder source(BytesReference source) throws IOException {
// request.source(source);
// return this;
// }
//
// @Override
// public void execute(ActionListener<TrainModelResponse> listener) {
// client.execute(TrainModelAction.INSTANCE, request, listener);
// }
//
// public TrainModelRequestBuilder setModelId(String id) {
// request.setModelId(id);
// return this;
// }
//
// public TrainModelRequestBuilder setModelType(String modelType) {
// request.setModelType(modelType);
// return this;
// }
//
// public TrainModelRequestBuilder addFields(ModelInputField ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (ModelInputField modelInputField : inputFields) {
// newFields.add(modelInputField);
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder addFields(String ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (String modelInputField : inputFields) {
// newFields.add(new ModelInputField(modelInputField));
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(ModelTargetField targetField) {
// request.setTargetField(targetField);
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(String targetField) {
// request.setTargetField(new ModelTargetField(targetField));
// return this;
// }
//
// public TrainModelRequestBuilder setSettings(Settings settings) {
// request.setModelSettings(settings);
// return this;
// }
//
// public TrainModelRequestBuilder setTrainingSet(DataSet dataSet) {
// request.setTrainingSet(dataSet);
// return this;
// }
//
// public TrainModelRequestBuilder setTestingSet(DataSet dataSet) {
// request.setTestingSet(dataSet);
// return this;
// }
//
// }
//
// Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelResponse.java
// public class TrainModelResponse extends ActionResponse implements ToXContent {
//
// @Nullable
// private String id;
//
// @Nullable
// private String model;
//
// public TrainModelResponse() {
//
// }
//
// public String getId() {
// return id;
// }
//
//
// public String getModel() {
// return model;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setModel(String model) {
// this.model = model;
// }
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// if (id != null) {
// builder.field("id", id);
// }
// if (model != null) {
// builder.field("model", model);
// }
// return builder;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// id = in.readOptionalString();
// model = in.readOptionalString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeOptionalString(id);
// out.writeOptionalString(model);
// }
// }
| import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import org.elasticsearch.action.trainmodel.TrainModelRequestBuilder;
import org.elasticsearch.action.trainmodel.TrainModelResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.trainmodel;
/**
*
*/
public class RestTrainModelAction extends BaseRestHandler {
@Inject
public RestTrainModelAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "_train_model", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { | // Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelRequestBuilder.java
// public class TrainModelRequestBuilder extends ActionRequestBuilder<TrainModelRequest, TrainModelResponse,
// TrainModelRequestBuilder> {
//
// public TrainModelRequestBuilder(ElasticsearchClient client) {
// super(client, TrainModelAction.INSTANCE, new TrainModelRequest());
// }
//
// public TrainModelRequestBuilder source(BytesReference source) throws IOException {
// request.source(source);
// return this;
// }
//
// @Override
// public void execute(ActionListener<TrainModelResponse> listener) {
// client.execute(TrainModelAction.INSTANCE, request, listener);
// }
//
// public TrainModelRequestBuilder setModelId(String id) {
// request.setModelId(id);
// return this;
// }
//
// public TrainModelRequestBuilder setModelType(String modelType) {
// request.setModelType(modelType);
// return this;
// }
//
// public TrainModelRequestBuilder addFields(ModelInputField ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (ModelInputField modelInputField : inputFields) {
// newFields.add(modelInputField);
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder addFields(String ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (String modelInputField : inputFields) {
// newFields.add(new ModelInputField(modelInputField));
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(ModelTargetField targetField) {
// request.setTargetField(targetField);
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(String targetField) {
// request.setTargetField(new ModelTargetField(targetField));
// return this;
// }
//
// public TrainModelRequestBuilder setSettings(Settings settings) {
// request.setModelSettings(settings);
// return this;
// }
//
// public TrainModelRequestBuilder setTrainingSet(DataSet dataSet) {
// request.setTrainingSet(dataSet);
// return this;
// }
//
// public TrainModelRequestBuilder setTestingSet(DataSet dataSet) {
// request.setTestingSet(dataSet);
// return this;
// }
//
// }
//
// Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelResponse.java
// public class TrainModelResponse extends ActionResponse implements ToXContent {
//
// @Nullable
// private String id;
//
// @Nullable
// private String model;
//
// public TrainModelResponse() {
//
// }
//
// public String getId() {
// return id;
// }
//
//
// public String getModel() {
// return model;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setModel(String model) {
// this.model = model;
// }
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// if (id != null) {
// builder.field("id", id);
// }
// if (model != null) {
// builder.field("model", model);
// }
// return builder;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// id = in.readOptionalString();
// model = in.readOptionalString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeOptionalString(id);
// out.writeOptionalString(model);
// }
// }
// Path: src/main/java/org/elasticsearch/rest/action/trainmodel/RestTrainModelAction.java
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import org.elasticsearch.action.trainmodel.TrainModelRequestBuilder;
import org.elasticsearch.action.trainmodel.TrainModelResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.trainmodel;
/**
*
*/
public class RestTrainModelAction extends BaseRestHandler {
@Inject
public RestTrainModelAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "_train_model", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { | TrainModelRequestBuilder trainModelRequestBuilder = new TrainModelRequestBuilder(client); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/rest/action/trainmodel/RestTrainModelAction.java | // Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelRequestBuilder.java
// public class TrainModelRequestBuilder extends ActionRequestBuilder<TrainModelRequest, TrainModelResponse,
// TrainModelRequestBuilder> {
//
// public TrainModelRequestBuilder(ElasticsearchClient client) {
// super(client, TrainModelAction.INSTANCE, new TrainModelRequest());
// }
//
// public TrainModelRequestBuilder source(BytesReference source) throws IOException {
// request.source(source);
// return this;
// }
//
// @Override
// public void execute(ActionListener<TrainModelResponse> listener) {
// client.execute(TrainModelAction.INSTANCE, request, listener);
// }
//
// public TrainModelRequestBuilder setModelId(String id) {
// request.setModelId(id);
// return this;
// }
//
// public TrainModelRequestBuilder setModelType(String modelType) {
// request.setModelType(modelType);
// return this;
// }
//
// public TrainModelRequestBuilder addFields(ModelInputField ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (ModelInputField modelInputField : inputFields) {
// newFields.add(modelInputField);
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder addFields(String ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (String modelInputField : inputFields) {
// newFields.add(new ModelInputField(modelInputField));
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(ModelTargetField targetField) {
// request.setTargetField(targetField);
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(String targetField) {
// request.setTargetField(new ModelTargetField(targetField));
// return this;
// }
//
// public TrainModelRequestBuilder setSettings(Settings settings) {
// request.setModelSettings(settings);
// return this;
// }
//
// public TrainModelRequestBuilder setTrainingSet(DataSet dataSet) {
// request.setTrainingSet(dataSet);
// return this;
// }
//
// public TrainModelRequestBuilder setTestingSet(DataSet dataSet) {
// request.setTestingSet(dataSet);
// return this;
// }
//
// }
//
// Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelResponse.java
// public class TrainModelResponse extends ActionResponse implements ToXContent {
//
// @Nullable
// private String id;
//
// @Nullable
// private String model;
//
// public TrainModelResponse() {
//
// }
//
// public String getId() {
// return id;
// }
//
//
// public String getModel() {
// return model;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setModel(String model) {
// this.model = model;
// }
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// if (id != null) {
// builder.field("id", id);
// }
// if (model != null) {
// builder.field("model", model);
// }
// return builder;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// id = in.readOptionalString();
// model = in.readOptionalString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeOptionalString(id);
// out.writeOptionalString(model);
// }
// }
| import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import org.elasticsearch.action.trainmodel.TrainModelRequestBuilder;
import org.elasticsearch.action.trainmodel.TrainModelResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.trainmodel;
/**
*
*/
public class RestTrainModelAction extends BaseRestHandler {
@Inject
public RestTrainModelAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "_train_model", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
TrainModelRequestBuilder trainModelRequestBuilder = new TrainModelRequestBuilder(client);
trainModelRequestBuilder.setModelId(request.param("id"));
try {
trainModelRequestBuilder.source(request.content());
} catch (IOException ex) {
throw new IllegalArgumentException(ex);
}
return channel -> { | // Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelRequestBuilder.java
// public class TrainModelRequestBuilder extends ActionRequestBuilder<TrainModelRequest, TrainModelResponse,
// TrainModelRequestBuilder> {
//
// public TrainModelRequestBuilder(ElasticsearchClient client) {
// super(client, TrainModelAction.INSTANCE, new TrainModelRequest());
// }
//
// public TrainModelRequestBuilder source(BytesReference source) throws IOException {
// request.source(source);
// return this;
// }
//
// @Override
// public void execute(ActionListener<TrainModelResponse> listener) {
// client.execute(TrainModelAction.INSTANCE, request, listener);
// }
//
// public TrainModelRequestBuilder setModelId(String id) {
// request.setModelId(id);
// return this;
// }
//
// public TrainModelRequestBuilder setModelType(String modelType) {
// request.setModelType(modelType);
// return this;
// }
//
// public TrainModelRequestBuilder addFields(ModelInputField ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (ModelInputField modelInputField : inputFields) {
// newFields.add(modelInputField);
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder addFields(String ... inputFields) {
// List<ModelInputField> newFields = new ArrayList<>();
// if (request.getFields() == null) {
// newFields.addAll(request.getFields());
// }
// for (String modelInputField : inputFields) {
// newFields.add(new ModelInputField(modelInputField));
// }
// request.setFields(Collections.unmodifiableList(newFields));
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(ModelTargetField targetField) {
// request.setTargetField(targetField);
// return this;
// }
//
// public TrainModelRequestBuilder setTargetField(String targetField) {
// request.setTargetField(new ModelTargetField(targetField));
// return this;
// }
//
// public TrainModelRequestBuilder setSettings(Settings settings) {
// request.setModelSettings(settings);
// return this;
// }
//
// public TrainModelRequestBuilder setTrainingSet(DataSet dataSet) {
// request.setTrainingSet(dataSet);
// return this;
// }
//
// public TrainModelRequestBuilder setTestingSet(DataSet dataSet) {
// request.setTestingSet(dataSet);
// return this;
// }
//
// }
//
// Path: src/main/java/org/elasticsearch/action/trainmodel/TrainModelResponse.java
// public class TrainModelResponse extends ActionResponse implements ToXContent {
//
// @Nullable
// private String id;
//
// @Nullable
// private String model;
//
// public TrainModelResponse() {
//
// }
//
// public String getId() {
// return id;
// }
//
//
// public String getModel() {
// return model;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public void setModel(String model) {
// this.model = model;
// }
//
// @Override
// public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// if (id != null) {
// builder.field("id", id);
// }
// if (model != null) {
// builder.field("model", model);
// }
// return builder;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// id = in.readOptionalString();
// model = in.readOptionalString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeOptionalString(id);
// out.writeOptionalString(model);
// }
// }
// Path: src/main/java/org/elasticsearch/rest/action/trainmodel/RestTrainModelAction.java
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import org.elasticsearch.action.trainmodel.TrainModelRequestBuilder;
import org.elasticsearch.action.trainmodel.TrainModelResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.trainmodel;
/**
*
*/
public class RestTrainModelAction extends BaseRestHandler {
@Inject
public RestTrainModelAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, "_train_model", this);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
TrainModelRequestBuilder trainModelRequestBuilder = new TrainModelRequestBuilder(client);
trainModelRequestBuilder.setModelId(request.param("id"));
try {
trainModelRequestBuilder.source(request.content());
} catch (IOException ex) {
throw new IllegalArgumentException(ex);
}
return channel -> { | trainModelRequestBuilder.execute(new RestBuilderListener<TrainModelResponse>(channel) { |
brwe/es-token-plugin | src/main/java/org/elasticsearch/search/fetch/analyzedtext/AnalyzedTextFetchParser.java | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
| import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchExtParser;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.fetch.analyzedtext;
public class AnalyzedTextFetchParser implements SearchExtParser<AnalyzedTextFetchBuilder> {
public static final AnalyzedTextFetchParser INSTANCE = new AnalyzedTextFetchParser();
private AnalyzedTextFetchParser() {
}
@Override
public AnalyzedTextFetchBuilder fromXContent(XContentParser parser) throws IOException {
XContentBuilder newBuilder = jsonBuilder();
newBuilder.copyCurrentStructure(parser); | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
// Path: src/main/java/org/elasticsearch/search/fetch/analyzedtext/AnalyzedTextFetchParser.java
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchExtParser;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.fetch.analyzedtext;
public class AnalyzedTextFetchParser implements SearchExtParser<AnalyzedTextFetchBuilder> {
public static final AnalyzedTextFetchParser INSTANCE = new AnalyzedTextFetchParser();
private AnalyzedTextFetchParser() {
}
@Override
public AnalyzedTextFetchBuilder fromXContent(XContentParser parser) throws IOException {
XContentBuilder newBuilder = jsonBuilder();
newBuilder.copyCurrentStructure(parser); | Map<String, Object> requestAsMap = SharedMethods.getSourceAsMap(newBuilder.string()); |
brwe/es-token-plugin | src/test/java/org/elasticsearch/action/allterms/AllTermsIT.java | // Path: src/main/java/org/elasticsearch/plugin/TokenPlugin.java
// public class TokenPlugin extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin, IngestPlugin {
//
// private final Settings settings;
// private final boolean transportClientMode;
// private final IngestAnalysisService ingestAnalysisService;
//
// public TokenPlugin(Settings settings) {
// this.settings = settings;
// this.transportClientMode = TransportClient.CLIENT_TYPE.equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey()));
// ingestAnalysisService = new IngestAnalysisService(settings);
// }
//
// @Override
// public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool,
// ResourceWatcherService resourceWatcherService, ScriptService scriptService,
// SearchRequestParsers searchRequestParsers) {
// ModelTrainers modelTrainers = new ModelTrainers(Arrays.asList(new NaiveBayesModelTrainer()));
// TrainingService trainingService = new TrainingService(settings, clusterService, client, modelTrainers, searchRequestParsers);
//
// final ClusterSettings clusterSettings = clusterService.getClusterSettings();
// Setting<Settings> ingestAnalysisGroupSetting = ingestAnalysisService.getIngestAnalysisGroupSetting();
// clusterSettings.addSettingsUpdateConsumer(ingestAnalysisGroupSetting, ingestAnalysisService::setAnalysisSettings);
// ingestAnalysisService.setAnalysisSettings(ingestAnalysisGroupSetting.get(settings));
//
// return Arrays.asList(trainingService, ingestAnalysisService);
// }
//
// @Override
// public ScriptEngineService getScriptEngineService(Settings settings) {
// return new PMMLModelScriptEngineService(settings);
// }
//
// @Override
// public List<NativeScriptFactory> getNativeScripts() {
// return Collections.singletonList(new VectorScriptFactory());
// }
//
// @Override
// public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// return Arrays.asList(
// new ActionHandler<>(AllTermsAction.INSTANCE, TransportAllTermsAction.class, TransportAllTermsShardAction.class),
// new ActionHandler<>(PrepareSpecAction.INSTANCE, TransportPrepareSpecAction.class),
// new ActionHandler<>(TrainModelAction.INSTANCE, TransportTrainModelAction.class)
// );
// }
//
// @Override
// public List<Class<? extends RestHandler>> getRestHandlers() {
// return Arrays.asList(
// RestAllTermsAction.class,
// RestPrepareSpecAction.class,
// RestStoreModelAction.class,
// RestTrainModelAction.class
// );
// }
//
// @Override
// public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) {
// return Arrays.asList(
// new TermVectorsFetchSubPhase(),
// new AnalyzedTextFetchSubPhase()
// );
// }
//
// @Override
// public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
// ingestAnalysisService.setAnalysisRegistry(parameters.analysisRegistry);
// return Collections.singletonMap(AnalyzerProcessor.TYPE, new AnalyzerProcessor.Factory(ingestAnalysisService));
// }
//
// @Override
// public List<Setting<?>> getSettings() {
// return Collections.singletonList(ingestAnalysisService.getIngestAnalysisGroupSetting());
// }
//
// @Override
// public List<SearchExtSpec<?>> getSearchExts() {
// return Arrays.asList(
// new SearchExtSpec<>(TermVectorsFetchSubPhase.NAME, TermVectorsFetchBuilder::new, TermVectorsFetchParser.INSTANCE),
// new SearchExtSpec<>(AnalyzedTextFetchSubPhase.NAME, AnalyzedTextFetchBuilder::new, AnalyzedTextFetchParser.INSTANCE)
// );
// }
// }
| import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugin.TokenPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.allterms;
/**
*
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, transportClientRatio = 0)
public class AllTermsIT extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() { | // Path: src/main/java/org/elasticsearch/plugin/TokenPlugin.java
// public class TokenPlugin extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin, IngestPlugin {
//
// private final Settings settings;
// private final boolean transportClientMode;
// private final IngestAnalysisService ingestAnalysisService;
//
// public TokenPlugin(Settings settings) {
// this.settings = settings;
// this.transportClientMode = TransportClient.CLIENT_TYPE.equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey()));
// ingestAnalysisService = new IngestAnalysisService(settings);
// }
//
// @Override
// public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool,
// ResourceWatcherService resourceWatcherService, ScriptService scriptService,
// SearchRequestParsers searchRequestParsers) {
// ModelTrainers modelTrainers = new ModelTrainers(Arrays.asList(new NaiveBayesModelTrainer()));
// TrainingService trainingService = new TrainingService(settings, clusterService, client, modelTrainers, searchRequestParsers);
//
// final ClusterSettings clusterSettings = clusterService.getClusterSettings();
// Setting<Settings> ingestAnalysisGroupSetting = ingestAnalysisService.getIngestAnalysisGroupSetting();
// clusterSettings.addSettingsUpdateConsumer(ingestAnalysisGroupSetting, ingestAnalysisService::setAnalysisSettings);
// ingestAnalysisService.setAnalysisSettings(ingestAnalysisGroupSetting.get(settings));
//
// return Arrays.asList(trainingService, ingestAnalysisService);
// }
//
// @Override
// public ScriptEngineService getScriptEngineService(Settings settings) {
// return new PMMLModelScriptEngineService(settings);
// }
//
// @Override
// public List<NativeScriptFactory> getNativeScripts() {
// return Collections.singletonList(new VectorScriptFactory());
// }
//
// @Override
// public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// return Arrays.asList(
// new ActionHandler<>(AllTermsAction.INSTANCE, TransportAllTermsAction.class, TransportAllTermsShardAction.class),
// new ActionHandler<>(PrepareSpecAction.INSTANCE, TransportPrepareSpecAction.class),
// new ActionHandler<>(TrainModelAction.INSTANCE, TransportTrainModelAction.class)
// );
// }
//
// @Override
// public List<Class<? extends RestHandler>> getRestHandlers() {
// return Arrays.asList(
// RestAllTermsAction.class,
// RestPrepareSpecAction.class,
// RestStoreModelAction.class,
// RestTrainModelAction.class
// );
// }
//
// @Override
// public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) {
// return Arrays.asList(
// new TermVectorsFetchSubPhase(),
// new AnalyzedTextFetchSubPhase()
// );
// }
//
// @Override
// public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
// ingestAnalysisService.setAnalysisRegistry(parameters.analysisRegistry);
// return Collections.singletonMap(AnalyzerProcessor.TYPE, new AnalyzerProcessor.Factory(ingestAnalysisService));
// }
//
// @Override
// public List<Setting<?>> getSettings() {
// return Collections.singletonList(ingestAnalysisService.getIngestAnalysisGroupSetting());
// }
//
// @Override
// public List<SearchExtSpec<?>> getSearchExts() {
// return Arrays.asList(
// new SearchExtSpec<>(TermVectorsFetchSubPhase.NAME, TermVectorsFetchBuilder::new, TermVectorsFetchParser.INSTANCE),
// new SearchExtSpec<>(AnalyzedTextFetchSubPhase.NAME, AnalyzedTextFetchBuilder::new, AnalyzedTextFetchParser.INSTANCE)
// );
// }
// }
// Path: src/test/java/org/elasticsearch/action/allterms/AllTermsIT.java
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugin.TokenPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.allterms;
/**
*
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, transportClientRatio = 0)
public class AllTermsIT extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() { | return Collections.singletonList(TokenPlugin.class); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/action/preparespec/TransportPrepareSpecAction.java | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
| import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchExtRegistry;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; | this.client = client;
this.queryRegistry = queryRegistry;
this.aggParsers = searchRequestParsers.aggParsers;
this.suggesters = searchRequestParsers.suggesters;
this.searchExtRegistry = searchExtRegistry;
this.parseFieldMatcher = new ParseFieldMatcher(settings);
}
@Override
protected void doExecute(final PrepareSpecRequest request, final ActionListener<PrepareSpecResponse> listener) {
Tuple<Boolean, List<FieldSpecRequest>> fieldSpecRequests = null;
try {
fieldSpecRequests = parseFieldSpecRequests(queryRegistry, aggParsers, suggesters, searchExtRegistry, parseFieldMatcher,
request.source());
} catch (IOException e) {
listener.onFailure(e);
}
final FieldSpecActionListener fieldSpecActionListener = new FieldSpecActionListener(fieldSpecRequests.v2().size(), listener,
fieldSpecRequests.v1());
for (final FieldSpecRequest fieldSpecRequest : fieldSpecRequests.v2()) {
fieldSpecRequest.process(fieldSpecActionListener, client);
}
}
static Tuple<Boolean, List<FieldSpecRequest>> parseFieldSpecRequests(IndicesQueriesRegistry queryRegistry, AggregatorParsers aggParsers,
Suggesters suggesters, SearchExtRegistry searchExtRegistry,
ParseFieldMatcher parseFieldMatcher,
String source) throws IOException {
List<FieldSpecRequest> fieldSpecRequests = new ArrayList<>(); | // Path: src/main/java/org/elasticsearch/script/SharedMethods.java
// public class SharedMethods {
//
// public static Map<String, Object> getSourceAsMap(String source) throws IOException {
// XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(source);
// return parser.mapOrdered();
// }
//
// }
// Path: src/main/java/org/elasticsearch/action/preparespec/TransportPrepareSpecAction.java
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.SharedMethods;
import org.elasticsearch.search.SearchExtRegistry;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.aggregations.AggregatorParsers;
import org.elasticsearch.search.suggest.Suggesters;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
this.client = client;
this.queryRegistry = queryRegistry;
this.aggParsers = searchRequestParsers.aggParsers;
this.suggesters = searchRequestParsers.suggesters;
this.searchExtRegistry = searchExtRegistry;
this.parseFieldMatcher = new ParseFieldMatcher(settings);
}
@Override
protected void doExecute(final PrepareSpecRequest request, final ActionListener<PrepareSpecResponse> listener) {
Tuple<Boolean, List<FieldSpecRequest>> fieldSpecRequests = null;
try {
fieldSpecRequests = parseFieldSpecRequests(queryRegistry, aggParsers, suggesters, searchExtRegistry, parseFieldMatcher,
request.source());
} catch (IOException e) {
listener.onFailure(e);
}
final FieldSpecActionListener fieldSpecActionListener = new FieldSpecActionListener(fieldSpecRequests.v2().size(), listener,
fieldSpecRequests.v1());
for (final FieldSpecRequest fieldSpecRequest : fieldSpecRequests.v2()) {
fieldSpecRequest.process(fieldSpecActionListener, client);
}
}
static Tuple<Boolean, List<FieldSpecRequest>> parseFieldSpecRequests(IndicesQueriesRegistry queryRegistry, AggregatorParsers aggParsers,
Suggesters suggesters, SearchExtRegistry searchExtRegistry,
ParseFieldMatcher parseFieldMatcher,
String source) throws IOException {
List<FieldSpecRequest> fieldSpecRequests = new ArrayList<>(); | Map<String, Object> parsedSource = SharedMethods.getSourceAsMap(source); |
brwe/es-token-plugin | src/test/java/org/elasticsearch/action/allterms/AllTermsTests.java | // Path: src/main/java/org/elasticsearch/action/allterms/TransportAllTermsShardAction.java
// protected static List<TermsEnum> getTermsEnums(AllTermsShardRequest request, List<LeafReaderContext> leaves) {
// List<TermsEnum> termIters = new ArrayList<>();
// try {
// for (LeafReaderContext reader : leaves) {
// termIters.add(reader.reader().terms(request.field()).iterator());
// }
// } catch (IOException e) {
// }
// return termIters;
// }
| import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.NoMergeScheduler;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.test.ESTestCase;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.action.allterms.TransportAllTermsShardAction.getTermsEnums;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.core.IsEqual.equalTo; | public void testFindSmallestTermFromNotExistentTerm() throws IOException {
SmallestTermAndExhausted smallestTermAndExhausted = getSmallestTermAndExhausted("foo");
BytesRef smallestTerm = smallestTermAndExhausted.getSmallestTerm();
int[] exhausted = smallestTermAndExhausted.getExhausted();
assertThat(smallestTerm.utf8ToString(), equalTo("forget"));
int i = -1;
int numExhausted = 0;
for (TermsEnum termsEnum : smallestTermAndExhausted.getTermsIters()) {
i++;
if (exhausted[i] == 1) {
numExhausted++;
} else {
assertThat(termsEnum.term().utf8ToString().compareTo("foo"), greaterThanOrEqualTo(0));
}
}
assertThat(numExhausted, equalTo(2));
}
public void testFindSmallestAllExhausted() throws IOException {
SmallestTermAndExhausted smallestTermAndExhausted = getSmallestTermAndExhausted("zonk");
BytesRef smallestTerm = smallestTermAndExhausted.getSmallestTerm();
int[] exhausted = smallestTermAndExhausted.getExhausted();
assertThat(smallestTerm, equalTo(null));
for (int i = 0; i < 4; i++) {
assertThat(exhausted[i], equalTo(1));
}
}
private SmallestTermAndExhausted getSmallestTermAndExhausted(String from) throws IOException {
AllTermsShardRequest request = new AllTermsShardRequest(new AllTermsRequest(), "index", 0, "field", 1, from, 0); | // Path: src/main/java/org/elasticsearch/action/allterms/TransportAllTermsShardAction.java
// protected static List<TermsEnum> getTermsEnums(AllTermsShardRequest request, List<LeafReaderContext> leaves) {
// List<TermsEnum> termIters = new ArrayList<>();
// try {
// for (LeafReaderContext reader : leaves) {
// termIters.add(reader.reader().terms(request.field()).iterator());
// }
// } catch (IOException e) {
// }
// return termIters;
// }
// Path: src/test/java/org/elasticsearch/action/allterms/AllTermsTests.java
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.NoMergeScheduler;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.test.ESTestCase;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.action.allterms.TransportAllTermsShardAction.getTermsEnums;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.core.IsEqual.equalTo;
public void testFindSmallestTermFromNotExistentTerm() throws IOException {
SmallestTermAndExhausted smallestTermAndExhausted = getSmallestTermAndExhausted("foo");
BytesRef smallestTerm = smallestTermAndExhausted.getSmallestTerm();
int[] exhausted = smallestTermAndExhausted.getExhausted();
assertThat(smallestTerm.utf8ToString(), equalTo("forget"));
int i = -1;
int numExhausted = 0;
for (TermsEnum termsEnum : smallestTermAndExhausted.getTermsIters()) {
i++;
if (exhausted[i] == 1) {
numExhausted++;
} else {
assertThat(termsEnum.term().utf8ToString().compareTo("foo"), greaterThanOrEqualTo(0));
}
}
assertThat(numExhausted, equalTo(2));
}
public void testFindSmallestAllExhausted() throws IOException {
SmallestTermAndExhausted smallestTermAndExhausted = getSmallestTermAndExhausted("zonk");
BytesRef smallestTerm = smallestTermAndExhausted.getSmallestTerm();
int[] exhausted = smallestTermAndExhausted.getExhausted();
assertThat(smallestTerm, equalTo(null));
for (int i = 0; i < 4; i++) {
assertThat(exhausted[i], equalTo(1));
}
}
private SmallestTermAndExhausted getSmallestTermAndExhausted(String from) throws IOException {
AllTermsShardRequest request = new AllTermsShardRequest(new AllTermsRequest(), "index", 0, "field", 1, from, 0); | List<TermsEnum> termIters = getTermsEnums(request, reader.leaves()); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/models/EsLogisticRegressionModel.java | // Path: src/main/java/org/elasticsearch/ml/modelinput/VectorModelInput.java
// public abstract class VectorModelInput implements ModelInput {
//
// public abstract int getSize();
//
// public abstract double getValue(int i);
//
// public abstract int getIndex(int i);
//
// }
| import java.util.Map;
import org.elasticsearch.ml.modelinput.VectorModelInput;
import java.util.HashMap; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.models;
public class EsLogisticRegressionModel extends EsRegressionModelEvaluator {
public EsLogisticRegressionModel(double[] coefficients,
double intercept, String[] classes) {
super(coefficients, intercept, classes);
}
@Override | // Path: src/main/java/org/elasticsearch/ml/modelinput/VectorModelInput.java
// public abstract class VectorModelInput implements ModelInput {
//
// public abstract int getSize();
//
// public abstract double getValue(int i);
//
// public abstract int getIndex(int i);
//
// }
// Path: src/main/java/org/elasticsearch/ml/models/EsLogisticRegressionModel.java
import java.util.Map;
import org.elasticsearch.ml.modelinput.VectorModelInput;
import java.util.HashMap;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.models;
public class EsLogisticRegressionModel extends EsRegressionModelEvaluator {
public EsLogisticRegressionModel(double[] coefficients,
double intercept, String[] classes) {
super(coefficients, intercept, classes);
}
@Override | public Map<String, Object> evaluateDebug(VectorModelInput modelInput) { |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/training/TrainingService.java | // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
| import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasOrIndex;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import org.elasticsearch.search.SearchRequestParsers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional; |
public TrainingService(Settings settings, ClusterService clusterService, Client client, ModelTrainers modelTrainers,
SearchRequestParsers searchRequestParsers) {
super(settings);
this.clusterService = clusterService;
this.modelTrainers = modelTrainers;
this.client = client;
this.searchRequestParsers = searchRequestParsers;
this.parseFieldMatcher = new ParseFieldMatcher(settings);
}
public void train(String modelType, Settings modelSettings, String index, String type, Map<String, Object> query,
List<ModelInputField> fields, ModelTargetField outputField, ActionListener<String> listener) {
try {
MetaData metaData = clusterService.state().getMetaData();
AliasOrIndex aliasOrIndex = metaData.getAliasAndIndexLookup().get(index);
if (aliasOrIndex == null) {
throw new IndexNotFoundException("the training index [" + index + "] not found");
}
if (aliasOrIndex.getIndices().size() != 1) {
throw new IllegalArgumentException("can only train on a single index");
}
IndexMetaData indexMetaData = aliasOrIndex.getIndices().get(0);
MappingMetaData mappingMetaData = indexMetaData.mapping(type);
if (mappingMetaData == null) {
throw new ResourceNotFoundException("the training type [" + type + "] not found");
}
Optional<QueryBuilder> queryBuilder = query.isEmpty() ? Optional.empty() : parseQuery(query);
| // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
// Path: src/main/java/org/elasticsearch/ml/training/TrainingService.java
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasOrIndex;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import org.elasticsearch.search.SearchRequestParsers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public TrainingService(Settings settings, ClusterService clusterService, Client client, ModelTrainers modelTrainers,
SearchRequestParsers searchRequestParsers) {
super(settings);
this.clusterService = clusterService;
this.modelTrainers = modelTrainers;
this.client = client;
this.searchRequestParsers = searchRequestParsers;
this.parseFieldMatcher = new ParseFieldMatcher(settings);
}
public void train(String modelType, Settings modelSettings, String index, String type, Map<String, Object> query,
List<ModelInputField> fields, ModelTargetField outputField, ActionListener<String> listener) {
try {
MetaData metaData = clusterService.state().getMetaData();
AliasOrIndex aliasOrIndex = metaData.getAliasAndIndexLookup().get(index);
if (aliasOrIndex == null) {
throw new IndexNotFoundException("the training index [" + index + "] not found");
}
if (aliasOrIndex.getIndices().size() != 1) {
throw new IllegalArgumentException("can only train on a single index");
}
IndexMetaData indexMetaData = aliasOrIndex.getIndices().get(0);
MappingMetaData mappingMetaData = indexMetaData.mapping(type);
if (mappingMetaData == null) {
throw new ResourceNotFoundException("the training type [" + type + "] not found");
}
Optional<QueryBuilder> queryBuilder = query.isEmpty() ? Optional.empty() : parseQuery(query);
| TrainingSession trainingSession = |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/factories/ModelFactories.java | // Path: src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java
// public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
// private final ModelInputEvaluator<Input> vectorRangesToVector;
//
// private final EsModelEvaluator<Input, Output> model;
//
// public ModelAndModelInputEvaluator(ModelInputEvaluator<Input> vectorRangesToVector, EsModelEvaluator<Input, Output> model) {
// this.vectorRangesToVector = vectorRangesToVector;
// this.model = model;
// }
//
// public ModelInputEvaluator<Input> getVectorRangesToVector() {
// return vectorRangesToVector;
// }
//
// public EsModelEvaluator<Input, Output> getModel() {
// return model;
// }
// }
//
// Path: src/main/java/org/elasticsearch/ml/modelinput/ModelInput.java
// public interface ModelInput {
//
// }
| import org.dmg.pmml.Model;
import org.dmg.pmml.PMML;
import org.elasticsearch.ml.modelinput.ModelAndModelInputEvaluator;
import org.elasticsearch.ml.modelinput.ModelInput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.factories;
/**
*
*/
public class ModelFactories {
private final Map<Class<? extends Model>, ModelFactory<? extends ModelInput, ?, ? extends Model>> modelFactories;
public static ModelFactories createDefaultModelFactories() {
List<ModelFactory<? extends ModelInput, ?, ? extends Model>> parsers = new ArrayList<>();
parsers.add(new GeneralizedLinearRegressionModelFactory());
parsers.add(new NaiveBayesModelFactory());
parsers.add(new TreeModelFactory());
parsers.add(new RegressionModelFactory());
return new ModelFactories(parsers);
}
public ModelFactories(List<ModelFactory<? extends ModelInput, ?, ? extends Model>> modelFactories) {
Map<Class<? extends Model>, ModelFactory<? extends ModelInput, ?, ? extends Model>> modelParserMap = new HashMap<>();
for (ModelFactory<? extends ModelInput, ?, ? extends Model> modelFactory : modelFactories) {
@SuppressWarnings("unchecked") ModelFactory<? extends ModelInput, ?, ? extends Model> prev =
modelParserMap.put(modelFactory.getSupportedClass(), modelFactory);
if (prev != null) {
throw new IllegalStateException("Added more than one factories for class " + modelFactory.getSupportedClass());
}
}
this.modelFactories = Collections.unmodifiableMap(modelParserMap);
}
@SuppressWarnings("unchecked") | // Path: src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java
// public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
// private final ModelInputEvaluator<Input> vectorRangesToVector;
//
// private final EsModelEvaluator<Input, Output> model;
//
// public ModelAndModelInputEvaluator(ModelInputEvaluator<Input> vectorRangesToVector, EsModelEvaluator<Input, Output> model) {
// this.vectorRangesToVector = vectorRangesToVector;
// this.model = model;
// }
//
// public ModelInputEvaluator<Input> getVectorRangesToVector() {
// return vectorRangesToVector;
// }
//
// public EsModelEvaluator<Input, Output> getModel() {
// return model;
// }
// }
//
// Path: src/main/java/org/elasticsearch/ml/modelinput/ModelInput.java
// public interface ModelInput {
//
// }
// Path: src/main/java/org/elasticsearch/ml/factories/ModelFactories.java
import org.dmg.pmml.Model;
import org.dmg.pmml.PMML;
import org.elasticsearch.ml.modelinput.ModelAndModelInputEvaluator;
import org.elasticsearch.ml.modelinput.ModelInput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.factories;
/**
*
*/
public class ModelFactories {
private final Map<Class<? extends Model>, ModelFactory<? extends ModelInput, ?, ? extends Model>> modelFactories;
public static ModelFactories createDefaultModelFactories() {
List<ModelFactory<? extends ModelInput, ?, ? extends Model>> parsers = new ArrayList<>();
parsers.add(new GeneralizedLinearRegressionModelFactory());
parsers.add(new NaiveBayesModelFactory());
parsers.add(new TreeModelFactory());
parsers.add(new RegressionModelFactory());
return new ModelFactories(parsers);
}
public ModelFactories(List<ModelFactory<? extends ModelInput, ?, ? extends Model>> modelFactories) {
Map<Class<? extends Model>, ModelFactory<? extends ModelInput, ?, ? extends Model>> modelParserMap = new HashMap<>();
for (ModelFactory<? extends ModelInput, ?, ? extends Model> modelFactory : modelFactories) {
@SuppressWarnings("unchecked") ModelFactory<? extends ModelInput, ?, ? extends Model> prev =
modelParserMap.put(modelFactory.getSupportedClass(), modelFactory);
if (prev != null) {
throw new IllegalStateException("Added more than one factories for class " + modelFactory.getSupportedClass());
}
}
this.modelFactories = Collections.unmodifiableMap(modelParserMap);
}
@SuppressWarnings("unchecked") | public <Input extends ModelInput, Output> ModelAndModelInputEvaluator<Input, Output> buildFromPMML(PMML pmml, int modelNum) { |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/factories/ModelFactory.java | // Path: src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java
// public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
// private final ModelInputEvaluator<Input> vectorRangesToVector;
//
// private final EsModelEvaluator<Input, Output> model;
//
// public ModelAndModelInputEvaluator(ModelInputEvaluator<Input> vectorRangesToVector, EsModelEvaluator<Input, Output> model) {
// this.vectorRangesToVector = vectorRangesToVector;
// this.model = model;
// }
//
// public ModelInputEvaluator<Input> getVectorRangesToVector() {
// return vectorRangesToVector;
// }
//
// public EsModelEvaluator<Input, Output> getModel() {
// return model;
// }
// }
//
// Path: src/main/java/org/elasticsearch/ml/modelinput/ModelInput.java
// public interface ModelInput {
//
// }
| import org.elasticsearch.ml.modelinput.ModelInput;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.TransformationDictionary;
import org.elasticsearch.ml.modelinput.ModelAndModelInputEvaluator; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.factories;
/**
*
*/
public abstract class ModelFactory<Input extends ModelInput, Output, Model extends org.dmg.pmml.Model> {
protected ModelFactory(Class<Model> supportedClass) {
this.supportedClass = supportedClass;
}
private final Class<Model> supportedClass;
public Class<Model> getSupportedClass() {
return supportedClass;
}
| // Path: src/main/java/org/elasticsearch/ml/modelinput/ModelAndModelInputEvaluator.java
// public class ModelAndModelInputEvaluator<Input extends ModelInput, Output> {
// private final ModelInputEvaluator<Input> vectorRangesToVector;
//
// private final EsModelEvaluator<Input, Output> model;
//
// public ModelAndModelInputEvaluator(ModelInputEvaluator<Input> vectorRangesToVector, EsModelEvaluator<Input, Output> model) {
// this.vectorRangesToVector = vectorRangesToVector;
// this.model = model;
// }
//
// public ModelInputEvaluator<Input> getVectorRangesToVector() {
// return vectorRangesToVector;
// }
//
// public EsModelEvaluator<Input, Output> getModel() {
// return model;
// }
// }
//
// Path: src/main/java/org/elasticsearch/ml/modelinput/ModelInput.java
// public interface ModelInput {
//
// }
// Path: src/main/java/org/elasticsearch/ml/factories/ModelFactory.java
import org.elasticsearch.ml.modelinput.ModelInput;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.TransformationDictionary;
import org.elasticsearch.ml.modelinput.ModelAndModelInputEvaluator;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.factories;
/**
*
*/
public abstract class ModelFactory<Input extends ModelInput, Output, Model extends org.dmg.pmml.Model> {
protected ModelFactory(Class<Model> supportedClass) {
this.supportedClass = supportedClass;
}
private final Class<Model> supportedClass;
public Class<Model> getSupportedClass() {
return supportedClass;
}
| public abstract ModelAndModelInputEvaluator<Input, Output> buildFromPMML(Model model, DataDictionary dataDictionary, |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ingest/AnalyzerProcessor.java | // Path: src/main/java/org/elasticsearch/ingest/IngestAnalysisService.java
// public static class AnalysisServiceHolder implements Releasable {
// private final AtomicInteger userCount = new AtomicInteger(1);
// private final AnalysisService analysisService;
//
// public AnalysisServiceHolder(AnalysisService analysisService) {
// this.analysisService = analysisService;
// }
//
// public void acquire() {
// userCount.incrementAndGet();
// }
//
// public void release() {
// if (userCount.decrementAndGet() == 0) {
// analysisService.close();
// }
// }
//
// public boolean hasAnalyzer(String analyzerName) {
// return analysisService.analyzer(analyzerName) != null;
// }
//
// public TokenStream tokenStream(String analyzerName, String fieldName, String text) {
// Analyzer analyzer = analysisService.analyzer(analyzerName);
// if (analyzer == null) {
// throw new IllegalArgumentException("unknown analyzer [" + analyzerName + "]");
// }
// return analyzer.tokenStream(fieldName, text);
// }
//
// @Override
// public void close() {
// release();
// }
// }
| import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ingest.IngestAnalysisService.AnalysisServiceHolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; |
String getTargetField() {
return targetField;
}
String getAnalyzer() {
return analyzer;
}
@Override
public void execute(IngestDocument document) {
Object oldVal = document.getFieldValue(field, Object.class);
if (oldVal == null) {
throw new IllegalArgumentException("field [" + field + "] is null, cannot be analyzed.");
}
List<String> tokenList = new ArrayList<>();
if (oldVal instanceof String) {
analyze(tokenList, (String) oldVal);
} else if (oldVal instanceof ArrayList) {
for (Object obj : (ArrayList) oldVal) {
analyze(tokenList, obj.toString());
}
} else {
throw new IllegalArgumentException("field [" + field + "] has type [" + oldVal.getClass().getName() +
"] and cannot be analyzed");
}
document.setFieldValue(targetField, tokenList);
}
private void analyze(List<String> tokenList, String val) { | // Path: src/main/java/org/elasticsearch/ingest/IngestAnalysisService.java
// public static class AnalysisServiceHolder implements Releasable {
// private final AtomicInteger userCount = new AtomicInteger(1);
// private final AnalysisService analysisService;
//
// public AnalysisServiceHolder(AnalysisService analysisService) {
// this.analysisService = analysisService;
// }
//
// public void acquire() {
// userCount.incrementAndGet();
// }
//
// public void release() {
// if (userCount.decrementAndGet() == 0) {
// analysisService.close();
// }
// }
//
// public boolean hasAnalyzer(String analyzerName) {
// return analysisService.analyzer(analyzerName) != null;
// }
//
// public TokenStream tokenStream(String analyzerName, String fieldName, String text) {
// Analyzer analyzer = analysisService.analyzer(analyzerName);
// if (analyzer == null) {
// throw new IllegalArgumentException("unknown analyzer [" + analyzerName + "]");
// }
// return analyzer.tokenStream(fieldName, text);
// }
//
// @Override
// public void close() {
// release();
// }
// }
// Path: src/main/java/org/elasticsearch/ingest/AnalyzerProcessor.java
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ingest.IngestAnalysisService.AnalysisServiceHolder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
String getTargetField() {
return targetField;
}
String getAnalyzer() {
return analyzer;
}
@Override
public void execute(IngestDocument document) {
Object oldVal = document.getFieldValue(field, Object.class);
if (oldVal == null) {
throw new IllegalArgumentException("field [" + field + "] is null, cannot be analyzed.");
}
List<String> tokenList = new ArrayList<>();
if (oldVal instanceof String) {
analyze(tokenList, (String) oldVal);
} else if (oldVal instanceof ArrayList) {
for (Object obj : (ArrayList) oldVal) {
analyze(tokenList, obj.toString());
}
} else {
throw new IllegalArgumentException("field [" + field + "] has type [" + oldVal.getClass().getName() +
"] and cannot be analyzed");
}
document.setFieldValue(targetField, tokenList);
}
private void analyze(List<String> tokenList, String val) { | AnalysisServiceHolder analysisServiceHolder = ingestAnalysisService.acquireAnalysisServiceHolder(); |
brwe/es-token-plugin | src/main/java/org/elasticsearch/ml/models/EsLinearSVMModel.java | // Path: src/main/java/org/elasticsearch/ml/modelinput/VectorModelInput.java
// public abstract class VectorModelInput implements ModelInput {
//
// public abstract int getSize();
//
// public abstract double getValue(int i);
//
// public abstract int getIndex(int i);
//
// }
| import java.util.Map;
import org.elasticsearch.ml.modelinput.VectorModelInput;
import java.util.HashMap; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.models;
public class EsLinearSVMModel extends EsRegressionModelEvaluator {
public EsLinearSVMModel(double[] coefficients,
double intercept, String[] classes) {
super(coefficients, intercept, classes);
}
protected Map<String, Object> prepareResult(double val) {
String classValue = val > 0 ? classes[0] : classes[1];
Map<String, Object> result = new HashMap<>();
result.put("class", classValue);
return result;
}
@Override | // Path: src/main/java/org/elasticsearch/ml/modelinput/VectorModelInput.java
// public abstract class VectorModelInput implements ModelInput {
//
// public abstract int getSize();
//
// public abstract double getValue(int i);
//
// public abstract int getIndex(int i);
//
// }
// Path: src/main/java/org/elasticsearch/ml/models/EsLinearSVMModel.java
import java.util.Map;
import org.elasticsearch.ml.modelinput.VectorModelInput;
import java.util.HashMap;
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.ml.models;
public class EsLinearSVMModel extends EsRegressionModelEvaluator {
public EsLinearSVMModel(double[] coefficients,
double intercept, String[] classes) {
super(coefficients, intercept, classes);
}
protected Map<String, Object> prepareResult(double val) {
String classValue = val > 0 ? classes[0] : classes[1];
Map<String, Object> result = new HashMap<>();
result.put("class", classValue);
return result;
}
@Override | public Map<String, Object> evaluateDebug(VectorModelInput modelInput) { |
brwe/es-token-plugin | src/test/java/org/elasticsearch/ml/training/TrainingServiceTests.java | // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
| import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import org.elasticsearch.plugins.SearchPlugin.QuerySpec;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matcher;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | .putMapping(mappingMetaData)
.putAlias(AliasMetaData.builder("just_me_alias"))
.putAlias(AliasMetaData.builder("other_and_me_alias"))
.settings(MINIMAL_INDEX_SETTINGS);
IndexMetaData.Builder otherIndexMetaData = IndexMetaData.builder("other_index")
.putMapping(mappingMetaData)
.putAlias(AliasMetaData.builder("other_and_me_alias"))
.settings(MINIMAL_INDEX_SETTINGS);
MetaData.Builder metaData = MetaData.builder().put(indexMetaData).put(otherIndexMetaData);
when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("test")).metaData(metaData).build());
AggregationBuilder aggregationBuilder = mock(AggregationBuilder.class);
SearchRequestBuilder searchRequestBuilder = mockSearchRequestBuilder.apply(aggregationBuilder);
Client client = mock(Client.class);
when(client.prepareSearch()).thenReturn(searchRequestBuilder);
when(client.prepareSearch()).thenReturn(searchRequestBuilder);
SearchResponse searchResponse = mock(SearchResponse.class);
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked") ActionListener<SearchResponse> listener =
(ActionListener<SearchResponse>) invocationOnMock.getArguments()[0];
listener.onResponse(searchResponse);
return null;
}).when(searchRequestBuilder).execute(any());
ModelTrainer modelTrainer = mock(ModelTrainer.class);
when(modelTrainer.modelType()).thenReturn("mock");
ModelTrainers modelTrainers = new ModelTrainers(Collections.singletonList(modelTrainer)); | // Path: src/main/java/org/elasticsearch/ml/training/ModelTrainer.java
// interface TrainingSession {
// AggregationBuilder trainingRequest();
// String model(SearchResponse response);
// }
// Path: src/test/java/org/elasticsearch/ml/training/TrainingServiceTests.java
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.ml.training.ModelTrainer.TrainingSession;
import org.elasticsearch.plugins.SearchPlugin.QuerySpec;
import org.elasticsearch.search.SearchRequestParsers;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matcher;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
.putMapping(mappingMetaData)
.putAlias(AliasMetaData.builder("just_me_alias"))
.putAlias(AliasMetaData.builder("other_and_me_alias"))
.settings(MINIMAL_INDEX_SETTINGS);
IndexMetaData.Builder otherIndexMetaData = IndexMetaData.builder("other_index")
.putMapping(mappingMetaData)
.putAlias(AliasMetaData.builder("other_and_me_alias"))
.settings(MINIMAL_INDEX_SETTINGS);
MetaData.Builder metaData = MetaData.builder().put(indexMetaData).put(otherIndexMetaData);
when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("test")).metaData(metaData).build());
AggregationBuilder aggregationBuilder = mock(AggregationBuilder.class);
SearchRequestBuilder searchRequestBuilder = mockSearchRequestBuilder.apply(aggregationBuilder);
Client client = mock(Client.class);
when(client.prepareSearch()).thenReturn(searchRequestBuilder);
when(client.prepareSearch()).thenReturn(searchRequestBuilder);
SearchResponse searchResponse = mock(SearchResponse.class);
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked") ActionListener<SearchResponse> listener =
(ActionListener<SearchResponse>) invocationOnMock.getArguments()[0];
listener.onResponse(searchResponse);
return null;
}).when(searchRequestBuilder).execute(any());
ModelTrainer modelTrainer = mock(ModelTrainer.class);
when(modelTrainer.modelType()).thenReturn("mock");
ModelTrainers modelTrainers = new ModelTrainers(Collections.singletonList(modelTrainer)); | TrainingSession trainingSession = mock(TrainingSession.class); |
feedzai/fos-core | fos-server/src/test/java/com/feedzai/fos/server/remote/impl/RemoteClassifierScorerTest.java | // Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
| import java.util.ArrayList;
import java.util.UUID;
import com.feedzai.fos.api.Scorer;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.modules.junit4.PowerMockRunner; | /*
* $#
* FOS Server
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.impl;
/**
* @author Marco Jorge ([email protected])
*/
@RunWith(PowerMockRunner.class)
public class RemoteClassifierScorerTest {
@Mock | // Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
// Path: fos-server/src/test/java/com/feedzai/fos/server/remote/impl/RemoteClassifierScorerTest.java
import java.util.ArrayList;
import java.util.UUID;
import com.feedzai.fos.api.Scorer;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
/*
* $#
* FOS Server
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.impl;
/**
* @author Marco Jorge ([email protected])
*/
@RunWith(PowerMockRunner.class)
public class RemoteClassifierScorerTest {
@Mock | private Scorer innerScorer; |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/server/remote/api/FOSScorerAdapter.java | // Path: fos-api/src/main/java/com/feedzai/fos/api/FOSException.java
// public class FOSException extends Exception {
// public FOSException(String message) {
// super(message);
// }
//
// /**
// * Create an exception with a nested throwable and customized message
// * @param message exception message
// * @param t nested throable
// */
// public FOSException(String message, Throwable t) {
// super(message, t);
// }
//
// /**
// * Create an exception with a nested throwable. Throwable message used as exception message
// * @param e
// */
//
// public FOSException(Throwable e) {
// super(e.getMessage(), e);
// }
// }
//
// Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
| import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.Scorer;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.UUID; | /*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.api;
/**
* FOS Scorer local adapter.
*
* @author Miguel Duarte ([email protected])
* @since 13.1.0
*/
public class FOSScorerAdapter implements Scorer {
private final RemoteScorer scorer;
public FOSScorerAdapter(RemoteScorer scorer) {
this.scorer = scorer;
}
@Override | // Path: fos-api/src/main/java/com/feedzai/fos/api/FOSException.java
// public class FOSException extends Exception {
// public FOSException(String message) {
// super(message);
// }
//
// /**
// * Create an exception with a nested throwable and customized message
// * @param message exception message
// * @param t nested throable
// */
// public FOSException(String message, Throwable t) {
// super(message, t);
// }
//
// /**
// * Create an exception with a nested throwable. Throwable message used as exception message
// * @param e
// */
//
// public FOSException(Throwable e) {
// super(e.getMessage(), e);
// }
// }
//
// Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
// Path: fos-api/src/main/java/com/feedzai/fos/server/remote/api/FOSScorerAdapter.java
import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.Scorer;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.api;
/**
* FOS Scorer local adapter.
*
* @author Miguel Duarte ([email protected])
* @since 13.1.0
*/
public class FOSScorerAdapter implements Scorer {
private final RemoteScorer scorer;
public FOSScorerAdapter(RemoteScorer scorer) {
this.scorer = scorer;
}
@Override | public List<double[]> score(List<UUID> uuids, Object[] objects) throws FOSException { |
feedzai/fos-core | fos-server/src/main/java/com/feedzai/fos/server/remote/impl/RemoteScorer.java | // Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
| import com.feedzai.fos.api.Scorer;
import com.feedzai.fos.common.validation.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.rmi.RemoteException;
import java.util.List;
import java.util.UUID; | /*
* $#
* FOS Server
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.impl;
/**
* Remote scorer that encapsulates an underlying @{Scorer}.
* <p/>
* Encapsulates the underlying implementation exceptions in RemoteExceptions.
*
* @author Marco Jorge ([email protected])
*/
public class RemoteScorer implements com.feedzai.fos.server.remote.api.RemoteScorer {
private static Logger logger = LoggerFactory.getLogger(RemoteScorer.class);
| // Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
// Path: fos-server/src/main/java/com/feedzai/fos/server/remote/impl/RemoteScorer.java
import com.feedzai.fos.api.Scorer;
import com.feedzai.fos.common.validation.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.rmi.RemoteException;
import java.util.List;
import java.util.UUID;
/*
* $#
* FOS Server
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.impl;
/**
* Remote scorer that encapsulates an underlying @{Scorer}.
* <p/>
* Encapsulates the underlying implementation exceptions in RemoteExceptions.
*
* @author Marco Jorge ([email protected])
*/
public class RemoteScorer implements com.feedzai.fos.server.remote.api.RemoteScorer {
private static Logger logger = LoggerFactory.getLogger(RemoteScorer.class);
| private Scorer scorer; |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/api/KryoScorer.java | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
/**
* This class implements the internal Kryo scoring backend
*/
private static class RemoteConnection implements Scorer {
/*
* Buffer size in bytes to be used for Kryo i/o.
* It should be noted that (beyond reasonable values)
* this does not impose any limits to the size of objects to be read/written
* if the internal buffer is exausted/underflows, kryo will flush or read
* more data from the associated inputstream.
*
*/
public static final int BUFFER_SIZE = 1024; // bytes
final Socket s; // socket that represents client connection
InputStream is;
OutputStream os;
Kryo kryo;
Input input;
Output output;
RemoteConnection(String host, int port) throws IOException {
s = new Socket(host, port);
// Disable naggle Algorithm to decrease latency
s.setTcpNoDelay(true);
is = s.getInputStream();
os = s.getOutputStream();
kryo = new Kryo(); | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
// Path: fos-api/src/main/java/com/feedzai/fos/api/KryoScorer.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
/**
* This class implements the internal Kryo scoring backend
*/
private static class RemoteConnection implements Scorer {
/*
* Buffer size in bytes to be used for Kryo i/o.
* It should be noted that (beyond reasonable values)
* this does not impose any limits to the size of objects to be read/written
* if the internal buffer is exausted/underflows, kryo will flush or read
* more data from the associated inputstream.
*
*/
public static final int BUFFER_SIZE = 1024; // bytes
final Socket s; // socket that represents client connection
InputStream is;
OutputStream os;
Kryo kryo;
Input input;
Output output;
RemoteConnection(String host, int port) throws IOException {
s = new Socket(host, port);
// Disable naggle Algorithm to decrease latency
s.setTcpNoDelay(true);
is = s.getInputStream();
os = s.getOutputStream();
kryo = new Kryo(); | kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer()); |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/api/KryoScorer.java | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | * more data from the associated inputstream.
*
*/
public static final int BUFFER_SIZE = 1024; // bytes
final Socket s; // socket that represents client connection
InputStream is;
OutputStream os;
Kryo kryo;
Input input;
Output output;
RemoteConnection(String host, int port) throws IOException {
s = new Socket(host, port);
// Disable naggle Algorithm to decrease latency
s.setTcpNoDelay(true);
is = s.getInputStream();
os = s.getOutputStream();
kryo = new Kryo();
kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer());
input = new Input(BUFFER_SIZE);
output = new Output(BUFFER_SIZE);
input.setInputStream(is);
output.setOutputStream(os);
}
@Override
public List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
try { | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
// Path: fos-api/src/main/java/com/feedzai/fos/api/KryoScorer.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* more data from the associated inputstream.
*
*/
public static final int BUFFER_SIZE = 1024; // bytes
final Socket s; // socket that represents client connection
InputStream is;
OutputStream os;
Kryo kryo;
Input input;
Output output;
RemoteConnection(String host, int port) throws IOException {
s = new Socket(host, port);
// Disable naggle Algorithm to decrease latency
s.setTcpNoDelay(true);
is = s.getInputStream();
os = s.getOutputStream();
kryo = new Kryo();
kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer());
input = new Input(BUFFER_SIZE);
output = new Output(BUFFER_SIZE);
input.setInputStream(is);
output.setOutputStream(os);
}
@Override
public List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
try { | ScoringRequestEnvelope envelope = new ScoringRequestEnvelope(modelIds, scorable); |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/api/KryoScoringEndpoint.java | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
| import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; | /*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.api;
/**
* This class should be used to perform scoring requests
* to a remote FOS instance that suports kryo end points.
* <p/>
* It listens on a socket input stream for Kryo serialized {@link ScoringRequestEnvelope}
* objects, extracts them and forwards them to the local scorer.
* <p/>
* The scoring result is then Kryo encoded on the socket output stream.
*
* @author Miguel Duarte ([email protected])
* @since 1.0.6
*/
public class KryoScoringEndpoint implements Runnable {
/**
* The logger instance for the endpoint.
*/
private final static Logger logger = LoggerFactory.getLogger(KryoScoringEndpoint.class);
/**
* The buffer size for Kryo buffers.
*/
public static final int BUFFER_SIZE = 1024;
/**
* The client socket to read from and write to with Kryo serializer.
*/
Socket client;
/**
* The {@link com.feedzai.fos.api.Scorer} to use for scoring messages.
*/
Scorer scorer;
/**
* Flag to define if the
*/
private volatile boolean running = true;
/**
* Creates a new instance of the {@link com.feedzai.fos.api.KryoScoringEndpoint} class.
*
* @param client The socket to use during communication.
* @param scorer The scorer to score the messages that arrive in the socket.
* @throws IOException When a problem occurs in the socket communication channels.
*/
public KryoScoringEndpoint(Socket client, Scorer scorer) throws IOException {
this.client = client;
this.scorer = scorer;
}
@Override
public void run() {
Kryo kryo = new Kryo(); | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
// Path: fos-api/src/main/java/com/feedzai/fos/api/KryoScoringEndpoint.java
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
/*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.api;
/**
* This class should be used to perform scoring requests
* to a remote FOS instance that suports kryo end points.
* <p/>
* It listens on a socket input stream for Kryo serialized {@link ScoringRequestEnvelope}
* objects, extracts them and forwards them to the local scorer.
* <p/>
* The scoring result is then Kryo encoded on the socket output stream.
*
* @author Miguel Duarte ([email protected])
* @since 1.0.6
*/
public class KryoScoringEndpoint implements Runnable {
/**
* The logger instance for the endpoint.
*/
private final static Logger logger = LoggerFactory.getLogger(KryoScoringEndpoint.class);
/**
* The buffer size for Kryo buffers.
*/
public static final int BUFFER_SIZE = 1024;
/**
* The client socket to read from and write to with Kryo serializer.
*/
Socket client;
/**
* The {@link com.feedzai.fos.api.Scorer} to use for scoring messages.
*/
Scorer scorer;
/**
* Flag to define if the
*/
private volatile boolean running = true;
/**
* Creates a new instance of the {@link com.feedzai.fos.api.KryoScoringEndpoint} class.
*
* @param client The socket to use during communication.
* @param scorer The scorer to score the messages that arrive in the socket.
* @throws IOException When a problem occurs in the socket communication channels.
*/
public KryoScoringEndpoint(Socket client, Scorer scorer) throws IOException {
this.client = client;
this.scorer = scorer;
}
@Override
public void run() {
Kryo kryo = new Kryo(); | kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer()); |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/api/KryoScoringEndpoint.java | // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
| import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; | /*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.api;
/**
* This class should be used to perform scoring requests
* to a remote FOS instance that suports kryo end points.
* <p/>
* It listens on a socket input stream for Kryo serialized {@link ScoringRequestEnvelope}
* objects, extracts them and forwards them to the local scorer.
* <p/>
* The scoring result is then Kryo encoded on the socket output stream.
*
* @author Miguel Duarte ([email protected])
* @since 1.0.6
*/
public class KryoScoringEndpoint implements Runnable {
/**
* The logger instance for the endpoint.
*/
private final static Logger logger = LoggerFactory.getLogger(KryoScoringEndpoint.class);
/**
* The buffer size for Kryo buffers.
*/
public static final int BUFFER_SIZE = 1024;
/**
* The client socket to read from and write to with Kryo serializer.
*/
Socket client;
/**
* The {@link com.feedzai.fos.api.Scorer} to use for scoring messages.
*/
Scorer scorer;
/**
* Flag to define if the
*/
private volatile boolean running = true;
/**
* Creates a new instance of the {@link com.feedzai.fos.api.KryoScoringEndpoint} class.
*
* @param client The socket to use during communication.
* @param scorer The scorer to score the messages that arrive in the socket.
* @throws IOException When a problem occurs in the socket communication channels.
*/
public KryoScoringEndpoint(Socket client, Scorer scorer) throws IOException {
this.client = client;
this.scorer = scorer;
}
@Override
public void run() {
Kryo kryo = new Kryo();
kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer());
// workaround for java.util.Arrays$ArrayList missing default constructor
kryo.register(Arrays.asList().getClass(), new CollectionSerializer() {
protected Collection create(Kryo kryo, Input input, Class<Collection> type) {
return new ArrayList();
}
});
Input input = new Input(BUFFER_SIZE);
Output output = new Output(BUFFER_SIZE);
| // Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/CustomUUIDSerializer.java
// public class CustomUUIDSerializer extends Serializer<UUID> {
//
// @Override
// public void write(Kryo kryo, Output output, UUID uuid) {
// output.writeLong(uuid.getMostSignificantBits(), false);
// output.writeLong(uuid.getLeastSignificantBits(), false);
// }
//
// @Override
// public UUID read(Kryo kryo, Input input, Class<UUID> uuidClass) {
// return new UUID(input.readLong(false),
// input.readLong(false));
// }
// }
//
// Path: fos-common/src/main/java/com/feedzai/fos/common/kryo/ScoringRequestEnvelope.java
// public class ScoringRequestEnvelope {
// /**
// * List of classifier uuid to score
// */
// List<UUID> uuids;
//
// /**
// * Instance to score
// */
// Object[] instance;
//
// /**
// * Empty constructor to allow kryo to create new instances
// */
// public ScoringRequestEnvelope() {
// }
//
// /**
// * Sets the list of UUIDs to score
// * @param uuids list of uuids to score
// */
// public void setUuids(List<UUID> uuids) {
// this.uuids = uuids;
// }
//
// /**
// * Sets the instance to score
// * @param instance instance to score
// */
// public void setInstance(Object[] instance) {
// this.instance = instance;
// }
//
// /**
// * Creates a new scoring envelope
// *
// * @param uuids List of classifier uuid to score
// * @param instance instance to score
// */
// public ScoringRequestEnvelope(List<UUID> uuids,
// Object[] instance) {
// this.uuids = uuids;
// this.instance = instance;
// }
//
// /**
// * Returns the list of UUID to score
// * @return list of UUID to score
// */
// public List<UUID> getUUIDs() {
// return uuids;
// }
//
// /**
// * Returns the instance to score
// * @return the instance to score
// */
// public Object[] getInstance() {
// return instance;
// }
// }
// Path: fos-api/src/main/java/com/feedzai/fos/api/KryoScoringEndpoint.java
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.feedzai.fos.common.kryo.CustomUUIDSerializer;
import com.feedzai.fos.common.kryo.ScoringRequestEnvelope;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
/*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.api;
/**
* This class should be used to perform scoring requests
* to a remote FOS instance that suports kryo end points.
* <p/>
* It listens on a socket input stream for Kryo serialized {@link ScoringRequestEnvelope}
* objects, extracts them and forwards them to the local scorer.
* <p/>
* The scoring result is then Kryo encoded on the socket output stream.
*
* @author Miguel Duarte ([email protected])
* @since 1.0.6
*/
public class KryoScoringEndpoint implements Runnable {
/**
* The logger instance for the endpoint.
*/
private final static Logger logger = LoggerFactory.getLogger(KryoScoringEndpoint.class);
/**
* The buffer size for Kryo buffers.
*/
public static final int BUFFER_SIZE = 1024;
/**
* The client socket to read from and write to with Kryo serializer.
*/
Socket client;
/**
* The {@link com.feedzai.fos.api.Scorer} to use for scoring messages.
*/
Scorer scorer;
/**
* Flag to define if the
*/
private volatile boolean running = true;
/**
* Creates a new instance of the {@link com.feedzai.fos.api.KryoScoringEndpoint} class.
*
* @param client The socket to use during communication.
* @param scorer The scorer to score the messages that arrive in the socket.
* @throws IOException When a problem occurs in the socket communication channels.
*/
public KryoScoringEndpoint(Socket client, Scorer scorer) throws IOException {
this.client = client;
this.scorer = scorer;
}
@Override
public void run() {
Kryo kryo = new Kryo();
kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer());
// workaround for java.util.Arrays$ArrayList missing default constructor
kryo.register(Arrays.asList().getClass(), new CollectionSerializer() {
protected Collection create(Kryo kryo, Input input, Class<Collection> type) {
return new ArrayList();
}
});
Input input = new Input(BUFFER_SIZE);
Output output = new Output(BUFFER_SIZE);
| ScoringRequestEnvelope request = null; |
feedzai/fos-core | fos-impl-dummy/src/main/java/com/feedzai/fos/impl/dummy/DummyScorer.java | // Path: fos-api/src/main/java/com/feedzai/fos/api/FOSException.java
// public class FOSException extends Exception {
// public FOSException(String message) {
// super(message);
// }
//
// /**
// * Create an exception with a nested throwable and customized message
// * @param message exception message
// * @param t nested throable
// */
// public FOSException(String message, Throwable t) {
// super(message, t);
// }
//
// /**
// * Create an exception with a nested throwable. Throwable message used as exception message
// * @param e
// */
//
// public FOSException(Throwable e) {
// super(e.getMessage(), e);
// }
// }
//
// Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
| import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.Scorer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections; | try {
logger.trace("modelIds='{}', scorable='{}'", mapper.writeValueAsString(modelIds), mapper.writeValueAsString(scorable));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return Collections.EMPTY_LIST;
}
@Override
public List<double[]> score(UUID modelId, List<Object[]> scorables) {
try {
logger.trace("modelId='{}', scorable='{}'", mapper.writeValueAsString(modelId), mapper.writeValueAsString(scorables));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return Collections.EMPTY_LIST;
}
@Override
public double[] score(UUID modelId, Object[] scorable) {
try {
logger.trace("modelId='{}', scorable='{}'", mapper.writeValueAsString(modelId), mapper.writeValueAsString(scorable));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return new double[0];
}
@Override | // Path: fos-api/src/main/java/com/feedzai/fos/api/FOSException.java
// public class FOSException extends Exception {
// public FOSException(String message) {
// super(message);
// }
//
// /**
// * Create an exception with a nested throwable and customized message
// * @param message exception message
// * @param t nested throable
// */
// public FOSException(String message, Throwable t) {
// super(message, t);
// }
//
// /**
// * Create an exception with a nested throwable. Throwable message used as exception message
// * @param e
// */
//
// public FOSException(Throwable e) {
// super(e.getMessage(), e);
// }
// }
//
// Path: fos-api/src/main/java/com/feedzai/fos/api/Scorer.java
// public interface Scorer {
// /**
// * Score the <code>scorable</code> against the given <code>modelIds</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).
// *
// * @param modelIds the list of models to score
// * @param scorable the instance data to score
// * @return a list of scores double[] where each list position contains the score for each classifier
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (UUID modelId : modelIds) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score all <code>scorables against</code> the given <code>modelId</code>.
// * <p/> The score must be between 0 and 1.
// * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).
// *
// * @param modelId the id of the model
// * @param scorables an array of instances to score
// * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {
// ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();
//
// for (Object[] scorable : scorables) {
// resultsBuilder.add(score(modelId, scorable));
// }
//
// return resultsBuilder.build();
// }
//
// /**
// * Score a single <code>scorable</code> against the given <code>modelId</code>.
// *
// * <p/> The score must be between 0 and 1.
// *
// * @param modelId the id of the model
// * @param scorable the instance to score
// * @return the scores
// * @throws FOSException when scoring was not possible
// */
// @NotNull
// double[] score(UUID modelId, Object[] scorable) throws FOSException;
//
// /**
// * Frees any resources allocated to this scorer.
// *
// * @throws FOSException when closing resources was not possible
// */
// void close() throws FOSException;
// }
// Path: fos-impl-dummy/src/main/java/com/feedzai/fos/impl/dummy/DummyScorer.java
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.Scorer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
try {
logger.trace("modelIds='{}', scorable='{}'", mapper.writeValueAsString(modelIds), mapper.writeValueAsString(scorable));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return Collections.EMPTY_LIST;
}
@Override
public List<double[]> score(UUID modelId, List<Object[]> scorables) {
try {
logger.trace("modelId='{}', scorable='{}'", mapper.writeValueAsString(modelId), mapper.writeValueAsString(scorables));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return Collections.EMPTY_LIST;
}
@Override
public double[] score(UUID modelId, Object[] scorable) {
try {
logger.trace("modelId='{}', scorable='{}'", mapper.writeValueAsString(modelId), mapper.writeValueAsString(scorable));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return new double[0];
}
@Override | public void close() throws FOSException { |
StnetixDevTeam/ariADDna | keystore-service/src/main/java/com/stnetix/ariaddna/keystore/utils/CertFactory.java | // Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/exceptions/KeyStoreException.java
// public class KeyStoreException extends AriaddnaException {
// public KeyStoreException(Throwable cause) {
// super(cause);
// }
//
// public KeyStoreException(String traceMessage) {
// super(traceMessage);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage) {
// super(traceMessage, errorMessage);
// }
//
// public KeyStoreException(String traceMessage, Throwable cause) {
// super(traceMessage, cause);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage, Throwable cause) {
// super(traceMessage, errorMessage, cause);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.util.Date;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import com.stnetix.ariaddna.commonutils.dto.CertificateDTO;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.keystore.exceptions.KeyStoreException; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.keystore.utils;
/**
* Created by alexkotov on 20.04.17.
*/
public class CertFactory {
public CertFactory(IPersistHelper persistHelper) {
this.persistHelper = persistHelper;
}
private IPersistHelper persistHelper;
private static final AriaddnaLogger LOGGER;
private static final Date FROM;
private static final Date TO;
private static final int DAYS;
private static final String CRYPTO_ALGORITHM_RSA;
private static final String CRYPTO_ALGORITHM_SHA1RSA;
private static final int CERTIFICATE_SIZE;
private static final String SUBJECT_CN;
private static final String SUBJECT_L_C;
static {
LOGGER = AriaddnaLogger.getLogger(CertFactory.class);
FROM = new Date(System.currentTimeMillis());
DAYS = 365 * 10;
TO = new Date(System.currentTimeMillis() + 86400000L * DAYS);
CRYPTO_ALGORITHM_RSA = "RSA";
CRYPTO_ALGORITHM_SHA1RSA = "SHA1withRSA";
CERTIFICATE_SIZE = 1024;
SUBJECT_CN = "CN=";
SUBJECT_L_C = "L=Russia, C=RU";
}
| // Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/exceptions/KeyStoreException.java
// public class KeyStoreException extends AriaddnaException {
// public KeyStoreException(Throwable cause) {
// super(cause);
// }
//
// public KeyStoreException(String traceMessage) {
// super(traceMessage);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage) {
// super(traceMessage, errorMessage);
// }
//
// public KeyStoreException(String traceMessage, Throwable cause) {
// super(traceMessage, cause);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage, Throwable cause) {
// super(traceMessage, errorMessage, cause);
// }
// }
// Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/utils/CertFactory.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.util.Date;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import com.stnetix.ariaddna.commonutils.dto.CertificateDTO;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.keystore.exceptions.KeyStoreException;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.keystore.utils;
/**
* Created by alexkotov on 20.04.17.
*/
public class CertFactory {
public CertFactory(IPersistHelper persistHelper) {
this.persistHelper = persistHelper;
}
private IPersistHelper persistHelper;
private static final AriaddnaLogger LOGGER;
private static final Date FROM;
private static final Date TO;
private static final int DAYS;
private static final String CRYPTO_ALGORITHM_RSA;
private static final String CRYPTO_ALGORITHM_SHA1RSA;
private static final int CERTIFICATE_SIZE;
private static final String SUBJECT_CN;
private static final String SUBJECT_L_C;
static {
LOGGER = AriaddnaLogger.getLogger(CertFactory.class);
FROM = new Date(System.currentTimeMillis());
DAYS = 365 * 10;
TO = new Date(System.currentTimeMillis() + 86400000L * DAYS);
CRYPTO_ALGORITHM_RSA = "RSA";
CRYPTO_ALGORITHM_SHA1RSA = "SHA1withRSA";
CERTIFICATE_SIZE = 1024;
SUBJECT_CN = "CN=";
SUBJECT_L_C = "L=Russia, C=RU";
}
| public File getNewCertificate(String alias) throws KeyStoreException { |
StnetixDevTeam/ariADDna | block_manipulation_service/src/test/java/com/stnetix/ariaddna/blockmanipulation/service/BlockManipulationServiceImplTest.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.blockmanipulation.exception.BlockDoesNotExistException;
import com.stnetix.ariaddna.blockmanipulation.exception.MetafileIsFolderException;
import com.stnetix.ariaddna.commonutils.dto.vufs.FileType;
import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.vufs.bo.Metafile; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.blockmanipulation.service;
public class BlockManipulationServiceImplTest {
private Metafile metafile;
private IBlockManipulationService blockManipulationService;
@Before
public void setUp() throws Exception { | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
// Path: block_manipulation_service/src/test/java/com/stnetix/ariaddna/blockmanipulation/service/BlockManipulationServiceImplTest.java
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.blockmanipulation.exception.BlockDoesNotExistException;
import com.stnetix.ariaddna.blockmanipulation.exception.MetafileIsFolderException;
import com.stnetix.ariaddna.commonutils.dto.vufs.FileType;
import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.vufs.bo.Metafile;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.blockmanipulation.service;
public class BlockManipulationServiceImplTest {
private Metafile metafile;
private IBlockManipulationService blockManipulationService;
@Before
public void setUp() throws Exception { | metafile = new Metafile(MavenUtil.getCurrentVersion(), UUID.randomUUID().toString(), null); |
StnetixDevTeam/ariADDna | allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/AllocateServiceImplTest.java | // Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java
// public class VufsServiceStub implements IVufsService {
//
// @Override
// public Metafile createEmptyMetafile() {
// return null;
// }
//
// @Override
// public Metafile getMetafileByUuid(String fileUuid)
// throws MetafileDoesNotExistException {
// return null;
// }
//
// @Override
// public Metafile addBlockByUuidToMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public Metafile removeBlockByUuidFromMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public boolean addMetafileToMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public Set<String> getAllocationByBlockUuid(String blockUuid)
// throws BlockNotExistInMetatableException {
// Set<String> allocationSet = new HashSet<>();
// for (int i = 0; i < 3; i++) {
// allocationSet.add(UUID.randomUUID().toString());
// }
// return allocationSet;
// }
//
// @Override
// public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
//
// }
//
// @Override
// public boolean addMetafileAsChildToParent(Metafile childMetafile,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromParent(String childMetafileUuid,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public AllocationStrategy getAllocationStrategyByMetafileUuid(String metafileUuid)
// throws MetafileDoesNotExistException {
// return AllocationStrategy.HA;
// }
//
// @Override
// public void setAllocationStrategyByMetafileUuid(String metafileUuid,
// AllocationStrategy allocationStrategy) throws MetafileDoesNotExistException {
//
// }
// }
//
// Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
| import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.rps.service.IResourcePolicyService;
import com.stnetix.ariaddna.vufs.bo.Block;
import com.stnetix.ariaddna.vufs.service.IVufsService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.allocateservice.exception.AllocateServiceException;
import com.stnetix.ariaddna.allocateservice.exception.AvailableSpaceNotExistException;
import com.stnetix.ariaddna.allocateservice.exception.BlockDoesNotExistInMetafileException;
import com.stnetix.ariaddna.allocateservice.service.AllocateServiceImpl;
import com.stnetix.ariaddna.allocateservice.stub.ResoucePolicyServiceStub;
import com.stnetix.ariaddna.allocateservice.stub.VufsServiceStub; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.allocateservice;
public class AllocateServiceImplTest {
private AllocateServiceImpl service;
@Before
public void setUp() throws Exception {
IResourcePolicyService rpService = new ResoucePolicyServiceStub(); | // Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java
// public class VufsServiceStub implements IVufsService {
//
// @Override
// public Metafile createEmptyMetafile() {
// return null;
// }
//
// @Override
// public Metafile getMetafileByUuid(String fileUuid)
// throws MetafileDoesNotExistException {
// return null;
// }
//
// @Override
// public Metafile addBlockByUuidToMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public Metafile removeBlockByUuidFromMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public boolean addMetafileToMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public Set<String> getAllocationByBlockUuid(String blockUuid)
// throws BlockNotExistInMetatableException {
// Set<String> allocationSet = new HashSet<>();
// for (int i = 0; i < 3; i++) {
// allocationSet.add(UUID.randomUUID().toString());
// }
// return allocationSet;
// }
//
// @Override
// public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
//
// }
//
// @Override
// public boolean addMetafileAsChildToParent(Metafile childMetafile,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromParent(String childMetafileUuid,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public AllocationStrategy getAllocationStrategyByMetafileUuid(String metafileUuid)
// throws MetafileDoesNotExistException {
// return AllocationStrategy.HA;
// }
//
// @Override
// public void setAllocationStrategyByMetafileUuid(String metafileUuid,
// AllocationStrategy allocationStrategy) throws MetafileDoesNotExistException {
//
// }
// }
//
// Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
// Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/AllocateServiceImplTest.java
import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.rps.service.IResourcePolicyService;
import com.stnetix.ariaddna.vufs.bo.Block;
import com.stnetix.ariaddna.vufs.service.IVufsService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.allocateservice.exception.AllocateServiceException;
import com.stnetix.ariaddna.allocateservice.exception.AvailableSpaceNotExistException;
import com.stnetix.ariaddna.allocateservice.exception.BlockDoesNotExistInMetafileException;
import com.stnetix.ariaddna.allocateservice.service.AllocateServiceImpl;
import com.stnetix.ariaddna.allocateservice.stub.ResoucePolicyServiceStub;
import com.stnetix.ariaddna.allocateservice.stub.VufsServiceStub;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.allocateservice;
public class AllocateServiceImplTest {
private AllocateServiceImpl service;
@Before
public void setUp() throws Exception {
IResourcePolicyService rpService = new ResoucePolicyServiceStub(); | IVufsService vufsService = new VufsServiceStub(); |
StnetixDevTeam/ariADDna | allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/AllocateServiceImplTest.java | // Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java
// public class VufsServiceStub implements IVufsService {
//
// @Override
// public Metafile createEmptyMetafile() {
// return null;
// }
//
// @Override
// public Metafile getMetafileByUuid(String fileUuid)
// throws MetafileDoesNotExistException {
// return null;
// }
//
// @Override
// public Metafile addBlockByUuidToMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public Metafile removeBlockByUuidFromMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public boolean addMetafileToMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public Set<String> getAllocationByBlockUuid(String blockUuid)
// throws BlockNotExistInMetatableException {
// Set<String> allocationSet = new HashSet<>();
// for (int i = 0; i < 3; i++) {
// allocationSet.add(UUID.randomUUID().toString());
// }
// return allocationSet;
// }
//
// @Override
// public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
//
// }
//
// @Override
// public boolean addMetafileAsChildToParent(Metafile childMetafile,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromParent(String childMetafileUuid,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public AllocationStrategy getAllocationStrategyByMetafileUuid(String metafileUuid)
// throws MetafileDoesNotExistException {
// return AllocationStrategy.HA;
// }
//
// @Override
// public void setAllocationStrategyByMetafileUuid(String metafileUuid,
// AllocationStrategy allocationStrategy) throws MetafileDoesNotExistException {
//
// }
// }
//
// Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
| import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.rps.service.IResourcePolicyService;
import com.stnetix.ariaddna.vufs.bo.Block;
import com.stnetix.ariaddna.vufs.service.IVufsService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.allocateservice.exception.AllocateServiceException;
import com.stnetix.ariaddna.allocateservice.exception.AvailableSpaceNotExistException;
import com.stnetix.ariaddna.allocateservice.exception.BlockDoesNotExistInMetafileException;
import com.stnetix.ariaddna.allocateservice.service.AllocateServiceImpl;
import com.stnetix.ariaddna.allocateservice.stub.ResoucePolicyServiceStub;
import com.stnetix.ariaddna.allocateservice.stub.VufsServiceStub; | public void getLocationForNewBlockThrowException()
throws AvailableSpaceNotExistException, BlockDoesNotExistInMetafileException {
Block block = getNewBlockBySize(6000000L);
//here throw exception
Set<String> newLocation = service.getLocationForNewBlock(block);
}
@Test
public void getLocationForExistBlockByUuid() throws AllocateServiceException {
Set<String> locations = service
.getLocationForExistBlockByUuid(UUID.randomUUID().toString());
assertNotNull(locations);
assertEquals(3, locations.size());
}
@Test
public void setLocationForBlock() throws BlockDoesNotExistInMetafileException {
Set<String> allocationSet = new HashSet<>();
for (int i = 0; i < 3; i++) {
allocationSet.add(UUID.randomUUID().toString());
}
service.setLocationForBlock(allocationSet, UUID.randomUUID().toString());
}
private Block getNewBlockBySize(Long size) {
byte[] payload = new byte[Math.toIntExact(size)];
for (int i = 0; i < size; i++) {
payload[i] = (byte) (i % 127);
} | // Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java
// public class VufsServiceStub implements IVufsService {
//
// @Override
// public Metafile createEmptyMetafile() {
// return null;
// }
//
// @Override
// public Metafile getMetafileByUuid(String fileUuid)
// throws MetafileDoesNotExistException {
// return null;
// }
//
// @Override
// public Metafile addBlockByUuidToMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public Metafile removeBlockByUuidFromMetafile(String blockUuid, Metafile metafile) {
// return null;
// }
//
// @Override
// public boolean addMetafileToMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromMetatable(Metafile metafile) {
// return false;
// }
//
// @Override
// public Set<String> getAllocationByBlockUuid(String blockUuid)
// throws BlockNotExistInMetatableException {
// Set<String> allocationSet = new HashSet<>();
// for (int i = 0; i < 3; i++) {
// allocationSet.add(UUID.randomUUID().toString());
// }
// return allocationSet;
// }
//
// @Override
// public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
//
// }
//
// @Override
// public boolean addMetafileAsChildToParent(Metafile childMetafile,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public boolean removeMetafileFromParent(String childMetafileUuid,
// String parentMetafileUuid) {
// return false;
// }
//
// @Override
// public AllocationStrategy getAllocationStrategyByMetafileUuid(String metafileUuid)
// throws MetafileDoesNotExistException {
// return AllocationStrategy.HA;
// }
//
// @Override
// public void setAllocationStrategyByMetafileUuid(String metafileUuid,
// AllocationStrategy allocationStrategy) throws MetafileDoesNotExistException {
//
// }
// }
//
// Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/mavenutil/MavenUtil.java
// public class MavenUtil {
//
// private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(MavenUtil.class);
//
// private MavenUtil() {
// }
//
// public static String getCurrentVersion() {
// Model model = null;
// try {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// if ((new File("pom.xml")).exists()) {
// model = reader.read(new FileReader("pom.xml"));
// } else {
// model = reader.read(new InputStreamReader(MavenUtil.class.getResourceAsStream(
// "/META-INF/maven/com.stnetix.ariaddna/common-utils/pom.xml")));
// }
//
// } catch (IOException e) {
// LOGGER.error("Can't read Pom.xml file. Exception message is: ", e.getMessage());
// } catch (XmlPullParserException e) {
// LOGGER.error("Can't parse Pom.xml file. Exception message is: ", e.getMessage());
// }
// return model != null ? model.getParent().getVersion() : "0.0.0";
// }
// }
// Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/AllocateServiceImplTest.java
import com.stnetix.ariaddna.commonutils.mavenutil.MavenUtil;
import com.stnetix.ariaddna.rps.service.IResourcePolicyService;
import com.stnetix.ariaddna.vufs.bo.Block;
import com.stnetix.ariaddna.vufs.service.IVufsService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.allocateservice.exception.AllocateServiceException;
import com.stnetix.ariaddna.allocateservice.exception.AvailableSpaceNotExistException;
import com.stnetix.ariaddna.allocateservice.exception.BlockDoesNotExistInMetafileException;
import com.stnetix.ariaddna.allocateservice.service.AllocateServiceImpl;
import com.stnetix.ariaddna.allocateservice.stub.ResoucePolicyServiceStub;
import com.stnetix.ariaddna.allocateservice.stub.VufsServiceStub;
public void getLocationForNewBlockThrowException()
throws AvailableSpaceNotExistException, BlockDoesNotExistInMetafileException {
Block block = getNewBlockBySize(6000000L);
//here throw exception
Set<String> newLocation = service.getLocationForNewBlock(block);
}
@Test
public void getLocationForExistBlockByUuid() throws AllocateServiceException {
Set<String> locations = service
.getLocationForExistBlockByUuid(UUID.randomUUID().toString());
assertNotNull(locations);
assertEquals(3, locations.size());
}
@Test
public void setLocationForBlock() throws BlockDoesNotExistInMetafileException {
Set<String> allocationSet = new HashSet<>();
for (int i = 0; i < 3; i++) {
allocationSet.add(UUID.randomUUID().toString());
}
service.setLocationForBlock(allocationSet, UUID.randomUUID().toString());
}
private Block getNewBlockBySize(Long size) {
byte[] payload = new byte[Math.toIntExact(size)];
for (int i = 0; i < size; i++) {
payload[i] = (byte) (i % 127);
} | return new Block(MavenUtil.getCurrentVersion(), 0L, UUID.randomUUID().toString(), |
StnetixDevTeam/ariADDna | storage-service/src/test/java/com/stnetix/ariaddna/persistence/transformers/CloudCredentialsTransformerTest.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/CloudCredentialsDTO.java
// public class CloudCredentialsDTO {
//
// public CloudCredentialsDTO() {
// this.uuid = UUID.randomUUID().toString();
// }
//
// public CloudCredentialsDTO(String clientId, String clientSecret) {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// private Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// private String uuid;
//
// public String getUuid() {
// return uuid;
// }
//
// public void setUuid(String uuid) {
// this.uuid = uuid;
// }
//
// private String clientId;
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// private String clientSecret;
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public void setClientSecret(String clientSecret) {
// this.clientSecret = clientSecret;
// }
// }
| import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import com.stnetix.ariaddna.commonutils.dto.CloudCredentialsDTO;
import com.stnetix.ariaddna.persistence.entities.CloudCredentials; | /*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.transformers;
public class CloudCredentialsTransformerTest {
CloudCredentialsTransformer transformer = Mappers.getMapper(CloudCredentialsTransformer.class);
@Test
public void cloudCredentialsEntityToDTO() {
CloudCredentials cloudCredentials = new CloudCredentials();
cloudCredentials.setId(423L);
cloudCredentials.setClientId(UUID.randomUUID().toString());
cloudCredentials.setClientSecret(UUID.randomUUID().toString());
| // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/CloudCredentialsDTO.java
// public class CloudCredentialsDTO {
//
// public CloudCredentialsDTO() {
// this.uuid = UUID.randomUUID().toString();
// }
//
// public CloudCredentialsDTO(String clientId, String clientSecret) {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// private Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// private String uuid;
//
// public String getUuid() {
// return uuid;
// }
//
// public void setUuid(String uuid) {
// this.uuid = uuid;
// }
//
// private String clientId;
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// private String clientSecret;
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public void setClientSecret(String clientSecret) {
// this.clientSecret = clientSecret;
// }
// }
// Path: storage-service/src/test/java/com/stnetix/ariaddna/persistence/transformers/CloudCredentialsTransformerTest.java
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import com.stnetix.ariaddna.commonutils.dto.CloudCredentialsDTO;
import com.stnetix.ariaddna.persistence.entities.CloudCredentials;
/*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.transformers;
public class CloudCredentialsTransformerTest {
CloudCredentialsTransformer transformer = Mappers.getMapper(CloudCredentialsTransformer.class);
@Test
public void cloudCredentialsEntityToDTO() {
CloudCredentials cloudCredentials = new CloudCredentials();
cloudCredentials.setId(423L);
cloudCredentials.setClientId(UUID.randomUUID().toString());
cloudCredentials.setClientSecret(UUID.randomUUID().toString());
| CloudCredentialsDTO cloudCredentialsDTO = transformer |
StnetixDevTeam/ariADDna | keystore-service/src/main/java/com/stnetix/ariaddna/keystore/utils/KeyFactory.java | // Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/exceptions/KeyStoreException.java
// public class KeyStoreException extends AriaddnaException {
// public KeyStoreException(Throwable cause) {
// super(cause);
// }
//
// public KeyStoreException(String traceMessage) {
// super(traceMessage);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage) {
// super(traceMessage, errorMessage);
// }
//
// public KeyStoreException(String traceMessage, Throwable cause) {
// super(traceMessage, cause);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage, Throwable cause) {
// super(traceMessage, errorMessage, cause);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import sun.security.x509.X509CertImpl;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.keystore.exceptions.KeyStoreException; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.keystore.utils;
/**
* Created by alexkotov on 20.04.17.
*/
public class KeyFactory {
public KeyFactory(IPersistHelper persistHelper, CertFactory certFactory) {
this.persistHelper = persistHelper;
this.certFactory = certFactory;
pass = this.persistHelper.getPassword();
}
private IPersistHelper persistHelper;
private CertFactory certFactory;
private static final String KEYSTORE_PATH;
private char[] pass;
private static final AriaddnaLogger LOGGER;
private static final String KEYSTORE_FORMAT;
static {
KEYSTORE_PATH = "ariaddna.keystore";
LOGGER = AriaddnaLogger.getLogger(KeyFactory.class);
KEYSTORE_FORMAT = "JKS";
}
| // Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/exceptions/KeyStoreException.java
// public class KeyStoreException extends AriaddnaException {
// public KeyStoreException(Throwable cause) {
// super(cause);
// }
//
// public KeyStoreException(String traceMessage) {
// super(traceMessage);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage) {
// super(traceMessage, errorMessage);
// }
//
// public KeyStoreException(String traceMessage, Throwable cause) {
// super(traceMessage, cause);
// }
//
// public KeyStoreException(String traceMessage, String errorMessage, Throwable cause) {
// super(traceMessage, errorMessage, cause);
// }
// }
// Path: keystore-service/src/main/java/com/stnetix/ariaddna/keystore/utils/KeyFactory.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import sun.security.x509.X509CertImpl;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.keystore.exceptions.KeyStoreException;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.keystore.utils;
/**
* Created by alexkotov on 20.04.17.
*/
public class KeyFactory {
public KeyFactory(IPersistHelper persistHelper, CertFactory certFactory) {
this.persistHelper = persistHelper;
this.certFactory = certFactory;
pass = this.persistHelper.getPassword();
}
private IPersistHelper persistHelper;
private CertFactory certFactory;
private static final String KEYSTORE_PATH;
private char[] pass;
private static final AriaddnaLogger LOGGER;
private static final String KEYSTORE_FORMAT;
static {
KEYSTORE_PATH = "ariaddna.keystore";
LOGGER = AriaddnaLogger.getLogger(KeyFactory.class);
KEYSTORE_FORMAT = "JKS";
}
| public File getNewKeyStore() throws KeyStoreException { |
StnetixDevTeam/ariADDna | allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
| import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.service.IVufsService; | }
@Override
public Set<String> getAllocationByBlockUuid(String blockUuid)
throws BlockNotExistInMetatableException {
Set<String> allocationSet = new HashSet<>();
for (int i = 0; i < 3; i++) {
allocationSet.add(UUID.randomUUID().toString());
}
return allocationSet;
}
@Override
public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
}
@Override
public boolean addMetafileAsChildToParent(Metafile childMetafile,
String parentMetafileUuid) {
return false;
}
@Override
public boolean removeMetafileFromParent(String childMetafileUuid,
String parentMetafileUuid) {
return false;
}
@Override | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
// Path: allocate-service/src/test/java/com/stnetix/ariaddna/allocateservice/stub/VufsServiceStub.java
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.service.IVufsService;
}
@Override
public Set<String> getAllocationByBlockUuid(String blockUuid)
throws BlockNotExistInMetatableException {
Set<String> allocationSet = new HashSet<>();
for (int i = 0; i < 3; i++) {
allocationSet.add(UUID.randomUUID().toString());
}
return allocationSet;
}
@Override
public void setAllocationForBlockByUuid(String blockUuid, Set<String> allocationSet) {
}
@Override
public boolean addMetafileAsChildToParent(Metafile childMetafile,
String parentMetafileUuid) {
return false;
}
@Override
public boolean removeMetafileFromParent(String childMetafileUuid,
String parentMetafileUuid) {
return false;
}
@Override | public AllocationStrategy getAllocationStrategyByMetafileUuid(String metafileUuid) |
StnetixDevTeam/ariADDna | block_manipulation_service/src/main/java/com/stnetix/ariaddna/blockmanipulation/BlockGenerate.java | // Path: local-storage-manager/src/main/java/com/stnetix/ariaddna/localstoragemanager/localservice/LocalService.java
// public interface LocalService {
// File getLocalFileByUuid(String fileUuid);
// Map<String,String> getFileAttributes(String fileUuid);
//
// }
| import com.stnetix.ariaddna.vufs.bo.Metafile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.stnetix.ariaddna.commonutils.datetime.DateTime;
import com.stnetix.ariaddna.commonutils.settings.Settings;
import com.stnetix.ariaddna.commonutils.xmlparser.XmlParser;
import com.stnetix.ariaddna.commonutils.xmlparser.exception.XmlParserException;
import com.stnetix.ariaddna.commonutils.xmlparser.handlers.BlockManipulationSettingHandler;
import com.stnetix.ariaddna.localstoragemanager.localservice.LocalService;
import com.stnetix.ariaddna.vufs.bo.Block; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.blockmanipulation;
/**
* Created by LugovoyAV on 15.02.2018.
*/
@Service
public class BlockGenerate {
private final int defaultBlockSize = 5242880;
private int blockSize;
| // Path: local-storage-manager/src/main/java/com/stnetix/ariaddna/localstoragemanager/localservice/LocalService.java
// public interface LocalService {
// File getLocalFileByUuid(String fileUuid);
// Map<String,String> getFileAttributes(String fileUuid);
//
// }
// Path: block_manipulation_service/src/main/java/com/stnetix/ariaddna/blockmanipulation/BlockGenerate.java
import com.stnetix.ariaddna.vufs.bo.Metafile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.stnetix.ariaddna.commonutils.datetime.DateTime;
import com.stnetix.ariaddna.commonutils.settings.Settings;
import com.stnetix.ariaddna.commonutils.xmlparser.XmlParser;
import com.stnetix.ariaddna.commonutils.xmlparser.exception.XmlParserException;
import com.stnetix.ariaddna.commonutils.xmlparser.handlers.BlockManipulationSettingHandler;
import com.stnetix.ariaddna.localstoragemanager.localservice.LocalService;
import com.stnetix.ariaddna.vufs.bo.Block;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.blockmanipulation;
/**
* Created by LugovoyAV on 15.02.2018.
*/
@Service
public class BlockGenerate {
private final int defaultBlockSize = 5242880;
private int blockSize;
| private LocalService localService; |
StnetixDevTeam/ariADDna | vufs/src/test/java/com/stnetix/ariaddna/vufs/service/VufsServiceImplTest.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
//
// Path: user-service/src/main/java/com/stnetix/ariaddna/userservice/IProfile.java
// public interface IProfile {
//
// Set<MetatableDTO> getMetatables();
//
// MetatableDTO getCurrentMasterTable();
//
// CloudAvailableSpace getCloudAvailableSpace();
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.userservice.IProfile;
import com.stnetix.ariaddna.vufs.MetatablePersisteceServiceStub;
import com.stnetix.ariaddna.vufs.ProfileStub;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.transformers.MetafileTransformer;
import com.stnetix.ariaddna.vufs.transformers.MetatableTransformer; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.vufs.service;
public class VufsServiceImplTest {
private IVufsService vufsService;
@Before
public void initial() {
MetafileTransformer metafileTransformer = new MetafileTransformer();
MetatableTransformer transformer = new MetatableTransformer();
transformer.setMetafileTransformer(metafileTransformer); | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
//
// Path: user-service/src/main/java/com/stnetix/ariaddna/userservice/IProfile.java
// public interface IProfile {
//
// Set<MetatableDTO> getMetatables();
//
// MetatableDTO getCurrentMasterTable();
//
// CloudAvailableSpace getCloudAvailableSpace();
// }
// Path: vufs/src/test/java/com/stnetix/ariaddna/vufs/service/VufsServiceImplTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.userservice.IProfile;
import com.stnetix.ariaddna.vufs.MetatablePersisteceServiceStub;
import com.stnetix.ariaddna.vufs.ProfileStub;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.transformers.MetafileTransformer;
import com.stnetix.ariaddna.vufs.transformers.MetatableTransformer;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.vufs.service;
public class VufsServiceImplTest {
private IVufsService vufsService;
@Before
public void initial() {
MetafileTransformer metafileTransformer = new MetafileTransformer();
MetatableTransformer transformer = new MetatableTransformer();
transformer.setMetafileTransformer(metafileTransformer); | IProfile profile = new ProfileStub(); |
StnetixDevTeam/ariADDna | vufs/src/test/java/com/stnetix/ariaddna/vufs/service/VufsServiceImplTest.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
//
// Path: user-service/src/main/java/com/stnetix/ariaddna/userservice/IProfile.java
// public interface IProfile {
//
// Set<MetatableDTO> getMetatables();
//
// MetatableDTO getCurrentMasterTable();
//
// CloudAvailableSpace getCloudAvailableSpace();
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.userservice.IProfile;
import com.stnetix.ariaddna.vufs.MetatablePersisteceServiceStub;
import com.stnetix.ariaddna.vufs.ProfileStub;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.transformers.MetafileTransformer;
import com.stnetix.ariaddna.vufs.transformers.MetatableTransformer; | /*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.vufs.service;
public class VufsServiceImplTest {
private IVufsService vufsService;
@Before
public void initial() {
MetafileTransformer metafileTransformer = new MetafileTransformer();
MetatableTransformer transformer = new MetatableTransformer();
transformer.setMetafileTransformer(metafileTransformer);
IProfile profile = new ProfileStub();
IMetatableService persistService = new MetatablePersisteceServiceStub();
vufsService = new VufsServiceImpl(profile, transformer, persistService);
}
@Test
public void createEmptyMetafile() {
Metafile emptyMetafile = vufsService.createEmptyMetafile();
assertNotNull(emptyMetafile);
assertNotNull(emptyMetafile.getFileUuid());
assertNotNull(emptyMetafile.getVersion());
}
@Test
public void getMetafileByUuid() throws MetafileDoesNotExistException {
Metafile newMetafile = vufsService.createEmptyMetafile(); | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/vufs/AllocationStrategy.java
// public enum AllocationStrategy {
//
// /** Each file has one copy*/
// UNION {
// @Override
// public String toString() {
// return "UNION";
// }
// },
// /** Each file has 2 or more copy*/
// MIRROR {
// @Override
// public String toString() {
// return "MIRROR";
// }
// },
// /** Each file has 3 or more copy*/
// HA {
// @Override
// public String toString() {
// return "HA";
// }
// }
// }
//
// Path: user-service/src/main/java/com/stnetix/ariaddna/userservice/IProfile.java
// public interface IProfile {
//
// Set<MetatableDTO> getMetatables();
//
// MetatableDTO getCurrentMasterTable();
//
// CloudAvailableSpace getCloudAvailableSpace();
// }
// Path: vufs/src/test/java/com/stnetix/ariaddna/vufs/service/VufsServiceImplTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.stnetix.ariaddna.commonutils.dto.vufs.AllocationStrategy;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.userservice.IProfile;
import com.stnetix.ariaddna.vufs.MetatablePersisteceServiceStub;
import com.stnetix.ariaddna.vufs.ProfileStub;
import com.stnetix.ariaddna.vufs.bo.Metafile;
import com.stnetix.ariaddna.vufs.exception.BlockNotExistInMetatableException;
import com.stnetix.ariaddna.vufs.exception.MetafileDoesNotExistException;
import com.stnetix.ariaddna.vufs.transformers.MetafileTransformer;
import com.stnetix.ariaddna.vufs.transformers.MetatableTransformer;
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.vufs.service;
public class VufsServiceImplTest {
private IVufsService vufsService;
@Before
public void initial() {
MetafileTransformer metafileTransformer = new MetafileTransformer();
MetatableTransformer transformer = new MetatableTransformer();
transformer.setMetafileTransformer(metafileTransformer);
IProfile profile = new ProfileStub();
IMetatableService persistService = new MetatablePersisteceServiceStub();
vufsService = new VufsServiceImpl(profile, transformer, persistService);
}
@Test
public void createEmptyMetafile() {
Metafile emptyMetafile = vufsService.createEmptyMetafile();
assertNotNull(emptyMetafile);
assertNotNull(emptyMetafile.getFileUuid());
assertNotNull(emptyMetafile.getVersion());
}
@Test
public void getMetafileByUuid() throws MetafileDoesNotExistException {
Metafile newMetafile = vufsService.createEmptyMetafile(); | newMetafile.setAllocationStrategy(AllocationStrategy.HA); |
StnetixDevTeam/ariADDna | storage-service/src/main/java/com/stnetix/ariaddna/persistence/transformers/UserTransformer.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/UserDTO.java
// public class UserDTO implements Serializable {
// private UUID uuid;
//
// private String nickname;
//
// public UUID getUuid() {
// return uuid;
// }
//
// public void setUuid(UUID uuid) {
// this.uuid = uuid;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
// }
| import com.stnetix.ariaddna.commonutils.dto.UserDTO;
import com.stnetix.ariaddna.persistence.entities.UserEntity;
import org.mapstruct.Mapper; | /*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.transformers;
/**
* Created by alexkotov on 13.09.17.
*/
@Mapper
public interface UserTransformer { | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/UserDTO.java
// public class UserDTO implements Serializable {
// private UUID uuid;
//
// private String nickname;
//
// public UUID getUuid() {
// return uuid;
// }
//
// public void setUuid(UUID uuid) {
// this.uuid = uuid;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
// }
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/transformers/UserTransformer.java
import com.stnetix.ariaddna.commonutils.dto.UserDTO;
import com.stnetix.ariaddna.persistence.entities.UserEntity;
import org.mapstruct.Mapper;
/*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.transformers;
/**
* Created by alexkotov on 13.09.17.
*/
@Mapper
public interface UserTransformer { | UserEntity userDTOToEntity(UserDTO userDTO); |
StnetixDevTeam/ariADDna | storage-service/src/test/java/com/stnetix/ariaddna/persistence/services/CloudCredentialsServiceImplTest.java | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/CloudCredentialsDTO.java
// public class CloudCredentialsDTO {
//
// public CloudCredentialsDTO() {
// this.uuid = UUID.randomUUID().toString();
// }
//
// public CloudCredentialsDTO(String clientId, String clientSecret) {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// private Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// private String uuid;
//
// public String getUuid() {
// return uuid;
// }
//
// public void setUuid(String uuid) {
// this.uuid = uuid;
// }
//
// private String clientId;
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// private String clientSecret;
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public void setClientSecret(String clientSecret) {
// this.clientSecret = clientSecret;
// }
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/utils/AppConfiguration.java
// @SpringBootApplication
// @EntityScan("com.stnetix.ariaddna.persistence.entities")
// @Import(JPAConfiguration.class)
// public class AppConfiguration {
//
// private static AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(AppConfiguration.class);
//
// @PersistenceContext
// @Qualifier(value = "entityManager")
// private EntityManager em;
//
// @Bean
// public ICertificateService certificateServiceImpl() {
// return new CertificateServiceImpl();
// }
//
// @Bean
// public IKeyStorePasswordService keyStorePasswordServiceImpl() {
// return new KeyStorePasswordServiceImpl();
// }
//
// @Bean
// public RepositoryFactorySupport repositoryFactorySupport() {
// LOGGER.info("In bean repositoryFactorySupport() entity manager is : {}", em.toString());
// return new JpaRepositoryFactory(em);
// }
//
// @Bean CertificateRepository certificateRepository() {
// return repositoryFactorySupport().getRepository(CertificateRepository.class);
// }
//
// @Bean
// public KeyStorePasswordRepository keyStorePasswordRepository() {
// return repositoryFactorySupport().getRepository(KeyStorePasswordRepository.class);
// }
//
// @Bean
// public AccessTokenRepository accessTokenRepository() {
// return repositoryFactorySupport().getRepository(AccessTokenRepository.class);
// }
//
// @Bean
// public AccessTokenServiceImpl accessTokenServiceImpl() {
// return new AccessTokenServiceImpl();
// }
//
// @Bean
// public CloudCredentialsRepository cloudCredentialsRepository() {
// return repositoryFactorySupport().getRepository(CloudCredentialsRepository.class);
// }
//
// @Bean
// public CloudCredentialsServiceImpl cloudCredentialsServiceImpl() {
// return new CloudCredentialsServiceImpl();
// }
//
// @Bean
// public IMetatableService metatableService() {
// return new MetatableServiceImpl();
// }
//
// }
| import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.stnetix.ariaddna.commonutils.dto.CloudCredentialsDTO;
import com.stnetix.ariaddna.persistence.utils.AppConfiguration; | /*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.services;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AppConfiguration.class)
//Transactional mark this test to rollback all changes after test
@Transactional
public class CloudCredentialsServiceImplTest {
@Autowired
private ICloudCredentialsService cloudCredentialsService;
@Test
public void saveCloudCredentials() { | // Path: common-utils/src/main/java/com/stnetix/ariaddna/commonutils/dto/CloudCredentialsDTO.java
// public class CloudCredentialsDTO {
//
// public CloudCredentialsDTO() {
// this.uuid = UUID.randomUUID().toString();
// }
//
// public CloudCredentialsDTO(String clientId, String clientSecret) {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// private Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// private String uuid;
//
// public String getUuid() {
// return uuid;
// }
//
// public void setUuid(String uuid) {
// this.uuid = uuid;
// }
//
// private String clientId;
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// private String clientSecret;
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public void setClientSecret(String clientSecret) {
// this.clientSecret = clientSecret;
// }
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/utils/AppConfiguration.java
// @SpringBootApplication
// @EntityScan("com.stnetix.ariaddna.persistence.entities")
// @Import(JPAConfiguration.class)
// public class AppConfiguration {
//
// private static AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(AppConfiguration.class);
//
// @PersistenceContext
// @Qualifier(value = "entityManager")
// private EntityManager em;
//
// @Bean
// public ICertificateService certificateServiceImpl() {
// return new CertificateServiceImpl();
// }
//
// @Bean
// public IKeyStorePasswordService keyStorePasswordServiceImpl() {
// return new KeyStorePasswordServiceImpl();
// }
//
// @Bean
// public RepositoryFactorySupport repositoryFactorySupport() {
// LOGGER.info("In bean repositoryFactorySupport() entity manager is : {}", em.toString());
// return new JpaRepositoryFactory(em);
// }
//
// @Bean CertificateRepository certificateRepository() {
// return repositoryFactorySupport().getRepository(CertificateRepository.class);
// }
//
// @Bean
// public KeyStorePasswordRepository keyStorePasswordRepository() {
// return repositoryFactorySupport().getRepository(KeyStorePasswordRepository.class);
// }
//
// @Bean
// public AccessTokenRepository accessTokenRepository() {
// return repositoryFactorySupport().getRepository(AccessTokenRepository.class);
// }
//
// @Bean
// public AccessTokenServiceImpl accessTokenServiceImpl() {
// return new AccessTokenServiceImpl();
// }
//
// @Bean
// public CloudCredentialsRepository cloudCredentialsRepository() {
// return repositoryFactorySupport().getRepository(CloudCredentialsRepository.class);
// }
//
// @Bean
// public CloudCredentialsServiceImpl cloudCredentialsServiceImpl() {
// return new CloudCredentialsServiceImpl();
// }
//
// @Bean
// public IMetatableService metatableService() {
// return new MetatableServiceImpl();
// }
//
// }
// Path: storage-service/src/test/java/com/stnetix/ariaddna/persistence/services/CloudCredentialsServiceImplTest.java
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.stnetix.ariaddna.commonutils.dto.CloudCredentialsDTO;
import com.stnetix.ariaddna.persistence.utils.AppConfiguration;
/*
* Copyright (c) 2017 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.persistence.services;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AppConfiguration.class)
//Transactional mark this test to rollback all changes after test
@Transactional
public class CloudCredentialsServiceImplTest {
@Autowired
private ICloudCredentialsService cloudCredentialsService;
@Test
public void saveCloudCredentials() { | CloudCredentialsDTO cloudCredentialsDTO = new CloudCredentialsDTO(); |
StnetixDevTeam/ariADDna | storage-service/src/main/java/com/stnetix/ariaddna/persistence/utils/AppConfiguration.java | // Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/repositories/CloudCredentialsRepository.java
// @Transactional(readOnly = true)
// public interface CloudCredentialsRepository extends CrudRepository<CloudCredentials, Long> {
//
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/services/CertificateServiceImpl.java
// @Repository
// @Transactional(readOnly = true)
// public class CertificateServiceImpl implements ICertificateService {
//
// private CertificateTransformer tranformer;
// @Autowired
// private CertificateRepository repository;
//
// public CertificateServiceImpl() {
// tranformer = Mappers.getMapper(CertificateTransformer.class);
// }
//
// @Override
// @Transactional
// public CertificateDTO save(CertificateDTO certificateDTO) {
// Certificate certificate = tranformer.certificateDTOToEntity(certificateDTO);
// return tranformer.certificateEntityToDTO(repository.save(certificate));
// }
//
// @Override
// public void remove(CertificateDTO certificateDTO) {
// Certificate certificate = tranformer.certificateDTOToEntity(certificateDTO);
// repository.delete(certificate);
// }
//
// @Override
// public List<CertificateDTO> getActiveCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.getActiveCertificates().stream().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
//
// @Override
// public List<CertificateDTO> getDisableCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.getDisableCertificates().stream().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
//
// @Override
// public List<CertificateDTO> getAllCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.findAll().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/services/KeyStorePasswordServiceImpl.java
// @Repository
// @Transactional
// public class KeyStorePasswordServiceImpl implements IKeyStorePasswordService {
//
// private KeyStorePasswordTransformer transformer;
// @Autowired
// private KeyStorePasswordRepository repository;
//
// public KeyStorePasswordServiceImpl() {
// transformer = Mappers.getMapper(KeyStorePasswordTransformer.class);
// }
//
// @Override
// public KeyStorePasswordDTO save(KeyStorePasswordDTO passwordDTO) {
// List<KeyStorePasswordDTO> keyStorePasswordDTOs = getAllPasswords();
// if (keyStorePasswordDTOs.size() > 0) {
// return keyStorePasswordDTOs.get(0);
// }
// KeyStorePassword password = transformer.keyStorePasswordDTOToEntity(passwordDTO);
// return transformer.keyStorePasswordEntityToDTO(repository.save(password));
// }
//
// @Override
// public KeyStorePasswordDTO getPassword() {
// List<KeyStorePasswordDTO> keyStorePasswordDTOList = getAllPasswords();
// if (keyStorePasswordDTOList.size() == 0) {
// KeyStorePasswordDTO newKeyStorePasswordDTO = new KeyStorePasswordDTO(
// UUID.randomUUID().toString());
// return save(newKeyStorePasswordDTO);
// }
// return keyStorePasswordDTOList.get(0);
// }
//
// private List<KeyStorePasswordDTO> getAllPasswords() {
// List<KeyStorePasswordDTO> keyStorePasswordDTOList = new ArrayList<>();
// repository.findAll().forEach(keyStorePassword -> keyStorePasswordDTOList
// .add(transformer.keyStorePasswordEntityToDTO(keyStorePassword)));
// return keyStorePasswordDTOList;
// }
// }
| import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.persistence.repositories.AccessTokenRepository;
import com.stnetix.ariaddna.persistence.repositories.CertificateRepository;
import com.stnetix.ariaddna.persistence.repositories.CloudCredentialsRepository;
import com.stnetix.ariaddna.persistence.repositories.KeyStorePasswordRepository;
import com.stnetix.ariaddna.persistence.services.AccessTokenServiceImpl;
import com.stnetix.ariaddna.persistence.services.CertificateServiceImpl;
import com.stnetix.ariaddna.persistence.services.CloudCredentialsServiceImpl;
import com.stnetix.ariaddna.persistence.services.ICertificateService;
import com.stnetix.ariaddna.persistence.services.IKeyStorePasswordService;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.persistence.services.KeyStorePasswordServiceImpl;
import com.stnetix.ariaddna.persistence.services.MetatableServiceImpl; | public IKeyStorePasswordService keyStorePasswordServiceImpl() {
return new KeyStorePasswordServiceImpl();
}
@Bean
public RepositoryFactorySupport repositoryFactorySupport() {
LOGGER.info("In bean repositoryFactorySupport() entity manager is : {}", em.toString());
return new JpaRepositoryFactory(em);
}
@Bean CertificateRepository certificateRepository() {
return repositoryFactorySupport().getRepository(CertificateRepository.class);
}
@Bean
public KeyStorePasswordRepository keyStorePasswordRepository() {
return repositoryFactorySupport().getRepository(KeyStorePasswordRepository.class);
}
@Bean
public AccessTokenRepository accessTokenRepository() {
return repositoryFactorySupport().getRepository(AccessTokenRepository.class);
}
@Bean
public AccessTokenServiceImpl accessTokenServiceImpl() {
return new AccessTokenServiceImpl();
}
@Bean | // Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/repositories/CloudCredentialsRepository.java
// @Transactional(readOnly = true)
// public interface CloudCredentialsRepository extends CrudRepository<CloudCredentials, Long> {
//
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/services/CertificateServiceImpl.java
// @Repository
// @Transactional(readOnly = true)
// public class CertificateServiceImpl implements ICertificateService {
//
// private CertificateTransformer tranformer;
// @Autowired
// private CertificateRepository repository;
//
// public CertificateServiceImpl() {
// tranformer = Mappers.getMapper(CertificateTransformer.class);
// }
//
// @Override
// @Transactional
// public CertificateDTO save(CertificateDTO certificateDTO) {
// Certificate certificate = tranformer.certificateDTOToEntity(certificateDTO);
// return tranformer.certificateEntityToDTO(repository.save(certificate));
// }
//
// @Override
// public void remove(CertificateDTO certificateDTO) {
// Certificate certificate = tranformer.certificateDTOToEntity(certificateDTO);
// repository.delete(certificate);
// }
//
// @Override
// public List<CertificateDTO> getActiveCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.getActiveCertificates().stream().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
//
// @Override
// public List<CertificateDTO> getDisableCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.getDisableCertificates().stream().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
//
// @Override
// public List<CertificateDTO> getAllCertificates() {
// List<CertificateDTO> certificateDTOList = new ArrayList<>();
// repository.findAll().forEach(certificate -> certificateDTOList
// .add(tranformer.certificateEntityToDTO(certificate)));
// return certificateDTOList;
// }
// }
//
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/services/KeyStorePasswordServiceImpl.java
// @Repository
// @Transactional
// public class KeyStorePasswordServiceImpl implements IKeyStorePasswordService {
//
// private KeyStorePasswordTransformer transformer;
// @Autowired
// private KeyStorePasswordRepository repository;
//
// public KeyStorePasswordServiceImpl() {
// transformer = Mappers.getMapper(KeyStorePasswordTransformer.class);
// }
//
// @Override
// public KeyStorePasswordDTO save(KeyStorePasswordDTO passwordDTO) {
// List<KeyStorePasswordDTO> keyStorePasswordDTOs = getAllPasswords();
// if (keyStorePasswordDTOs.size() > 0) {
// return keyStorePasswordDTOs.get(0);
// }
// KeyStorePassword password = transformer.keyStorePasswordDTOToEntity(passwordDTO);
// return transformer.keyStorePasswordEntityToDTO(repository.save(password));
// }
//
// @Override
// public KeyStorePasswordDTO getPassword() {
// List<KeyStorePasswordDTO> keyStorePasswordDTOList = getAllPasswords();
// if (keyStorePasswordDTOList.size() == 0) {
// KeyStorePasswordDTO newKeyStorePasswordDTO = new KeyStorePasswordDTO(
// UUID.randomUUID().toString());
// return save(newKeyStorePasswordDTO);
// }
// return keyStorePasswordDTOList.get(0);
// }
//
// private List<KeyStorePasswordDTO> getAllPasswords() {
// List<KeyStorePasswordDTO> keyStorePasswordDTOList = new ArrayList<>();
// repository.findAll().forEach(keyStorePassword -> keyStorePasswordDTOList
// .add(transformer.keyStorePasswordEntityToDTO(keyStorePassword)));
// return keyStorePasswordDTOList;
// }
// }
// Path: storage-service/src/main/java/com/stnetix/ariaddna/persistence/utils/AppConfiguration.java
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import com.stnetix.ariaddna.commonutils.logger.AriaddnaLogger;
import com.stnetix.ariaddna.persistence.repositories.AccessTokenRepository;
import com.stnetix.ariaddna.persistence.repositories.CertificateRepository;
import com.stnetix.ariaddna.persistence.repositories.CloudCredentialsRepository;
import com.stnetix.ariaddna.persistence.repositories.KeyStorePasswordRepository;
import com.stnetix.ariaddna.persistence.services.AccessTokenServiceImpl;
import com.stnetix.ariaddna.persistence.services.CertificateServiceImpl;
import com.stnetix.ariaddna.persistence.services.CloudCredentialsServiceImpl;
import com.stnetix.ariaddna.persistence.services.ICertificateService;
import com.stnetix.ariaddna.persistence.services.IKeyStorePasswordService;
import com.stnetix.ariaddna.persistence.services.IMetatableService;
import com.stnetix.ariaddna.persistence.services.KeyStorePasswordServiceImpl;
import com.stnetix.ariaddna.persistence.services.MetatableServiceImpl;
public IKeyStorePasswordService keyStorePasswordServiceImpl() {
return new KeyStorePasswordServiceImpl();
}
@Bean
public RepositoryFactorySupport repositoryFactorySupport() {
LOGGER.info("In bean repositoryFactorySupport() entity manager is : {}", em.toString());
return new JpaRepositoryFactory(em);
}
@Bean CertificateRepository certificateRepository() {
return repositoryFactorySupport().getRepository(CertificateRepository.class);
}
@Bean
public KeyStorePasswordRepository keyStorePasswordRepository() {
return repositoryFactorySupport().getRepository(KeyStorePasswordRepository.class);
}
@Bean
public AccessTokenRepository accessTokenRepository() {
return repositoryFactorySupport().getRepository(AccessTokenRepository.class);
}
@Bean
public AccessTokenServiceImpl accessTokenServiceImpl() {
return new AccessTokenServiceImpl();
}
@Bean | public CloudCredentialsRepository cloudCredentialsRepository() { |
dinosaurwithakatana/hacker-news-android | app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutViewModel.java | // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java
// public class BaseViewModel {
// public void onAttachToView() {
// }
//
// public void onDetachFromView() {
// }
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java
// public class AboutLicense {
// public final int nameResId;
// public final int licenseResId;
//
// public AboutLicense(int nameResId, int license) {
// this.nameResId = nameResId;
// this.licenseResId = license;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import io.dwak.holohackernews.app.R;
import io.dwak.holohackernews.app.base.BaseViewModel;
import io.dwak.holohackernews.app.models.AboutLicense; | package io.dwak.holohackernews.app.ui.about;
public class AboutViewModel extends BaseViewModel{
public AboutViewModel() {
}
| // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java
// public class BaseViewModel {
// public void onAttachToView() {
// }
//
// public void onDetachFromView() {
// }
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java
// public class AboutLicense {
// public final int nameResId;
// public final int licenseResId;
//
// public AboutLicense(int nameResId, int license) {
// this.nameResId = nameResId;
// this.licenseResId = license;
// }
// }
// Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutViewModel.java
import java.util.ArrayList;
import java.util.List;
import io.dwak.holohackernews.app.R;
import io.dwak.holohackernews.app.base.BaseViewModel;
import io.dwak.holohackernews.app.models.AboutLicense;
package io.dwak.holohackernews.app.ui.about;
public class AboutViewModel extends BaseViewModel{
public AboutViewModel() {
}
| public List<AboutLicense> getLicenses(){ |
dinosaurwithakatana/hacker-news-android | app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java | // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java
// @Component(modules = {AppModule.class})
// public interface AppComponent {
// void inject(Application application);
//
// @Named(AppModule.CACHE_MANAGER)
// CacheManager getCacheManager();
//
// @Named(AppModule.RESOURCES)
// Resources getResources();
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java
// @Module
// public class AppModule {
// public static final String CACHE_MANAGER = "cacheManager";
// public static final String RESOURCES = "resources";
// Application mApplication;
//
// public AppModule(Application application) {
// mApplication = application;
// }
//
// @Provides
// @Named("context")
// Context providesApplication() {
// return mApplication;
// }
//
//
// @Provides
// @Named(RESOURCES)
// Resources providesResources() {
// return mApplication.getResources();
// }
//
// @Provides
// @Named("gson")
// Gson providesGson() {
// return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter())
// .create();
// }
//
// @Provides
// @Singleton
// @Named("loganSquare")
// LoganSquareConvertor providesLoganSquare(){
// return new LoganSquareConvertor();
// }
//
// @Provides
// @Named("retrofit-loglevel")
// RestAdapter.LogLevel providesLogLevel(){
// if(BuildConfig.DEBUG) {
// return RestAdapter.LogLevel.FULL;
// }
// else {
// return RestAdapter.LogLevel.NONE;
// }
// }
//
// @Provides
// @Named(CACHE_MANAGER)
// CacheManager providesCacheManager(@Named("context")Context context,
// @Named("gson") Gson gson){
// return CacheManager.getInstance(context, gson);
// }
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java
// public class LocalDataManager {
// public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER";
// public static final String OPEN_COUNT = "OPEN_COUNT";
// private static LocalDataManager sInstance;
// @Inject SharedPreferences mPreferences;
//
// private LocalDataManager(@NonNull Context context) {
// DaggerSharedPreferencesComponent.builder()
// .appComponent(HackerNewsApplication.getAppComponent())
// .appModule(HackerNewsApplication.getAppModule())
// .build()
// .inject(this);
// mPreferences.edit().commit();
// }
//
// public static void initialize(@NonNull Context context) {
// if (sInstance == null) {
// sInstance = new LocalDataManager(context);
// }
// else {
// throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!");
// }
// }
//
// public static LocalDataManager getInstance() {
// return sInstance;
// }
//
// public boolean isReturningUser() {
// return getBoolean(PREF_RETURNING_USER);
// }
//
// public void setReturningUser(boolean isFirstRun) {
// set(PREF_RETURNING_USER, isFirstRun);
// }
//
// public int getOpenCount(){
// return getInt(OPEN_COUNT);
// }
//
// public void addOpenCount(){
// int openCount = getOpenCount();
// set(OPEN_COUNT, ++openCount);
// }
//
// private void set(String key, int i) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putInt(key, i);
// editor.apply();
// }
//
// private int getInt(String key){
// return mPreferences.getInt(key, 0);
// }
// private boolean getBoolean(String key) {
// return mPreferences.getBoolean(key, false);
// }
//
// @Nullable
// private String getString(String key) {
// return mPreferences.getString(key, null);
// }
//
// private void set(@NonNull String key, boolean value) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// private void set(@NonNull String key, String value) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private void remove(@NonNull String key) {
// mPreferences.edit().remove(key).apply();
// }
// }
| import android.content.Context;
import com.bugsnag.android.Bugsnag;
import com.facebook.stetho.Stetho;
import com.orm.SugarApp;
import io.dwak.holohackernews.app.dagger.component.AppComponent;
import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent;
import io.dwak.holohackernews.app.dagger.module.AppModule;
import io.dwak.holohackernews.app.preferences.LocalDataManager; | package io.dwak.holohackernews.app;
public class HackerNewsApplication extends SugarApp {
private static boolean mDebug = BuildConfig.DEBUG;
private static HackerNewsApplication sInstance;
private Context mContext; | // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java
// @Component(modules = {AppModule.class})
// public interface AppComponent {
// void inject(Application application);
//
// @Named(AppModule.CACHE_MANAGER)
// CacheManager getCacheManager();
//
// @Named(AppModule.RESOURCES)
// Resources getResources();
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java
// @Module
// public class AppModule {
// public static final String CACHE_MANAGER = "cacheManager";
// public static final String RESOURCES = "resources";
// Application mApplication;
//
// public AppModule(Application application) {
// mApplication = application;
// }
//
// @Provides
// @Named("context")
// Context providesApplication() {
// return mApplication;
// }
//
//
// @Provides
// @Named(RESOURCES)
// Resources providesResources() {
// return mApplication.getResources();
// }
//
// @Provides
// @Named("gson")
// Gson providesGson() {
// return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter())
// .create();
// }
//
// @Provides
// @Singleton
// @Named("loganSquare")
// LoganSquareConvertor providesLoganSquare(){
// return new LoganSquareConvertor();
// }
//
// @Provides
// @Named("retrofit-loglevel")
// RestAdapter.LogLevel providesLogLevel(){
// if(BuildConfig.DEBUG) {
// return RestAdapter.LogLevel.FULL;
// }
// else {
// return RestAdapter.LogLevel.NONE;
// }
// }
//
// @Provides
// @Named(CACHE_MANAGER)
// CacheManager providesCacheManager(@Named("context")Context context,
// @Named("gson") Gson gson){
// return CacheManager.getInstance(context, gson);
// }
// }
//
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java
// public class LocalDataManager {
// public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER";
// public static final String OPEN_COUNT = "OPEN_COUNT";
// private static LocalDataManager sInstance;
// @Inject SharedPreferences mPreferences;
//
// private LocalDataManager(@NonNull Context context) {
// DaggerSharedPreferencesComponent.builder()
// .appComponent(HackerNewsApplication.getAppComponent())
// .appModule(HackerNewsApplication.getAppModule())
// .build()
// .inject(this);
// mPreferences.edit().commit();
// }
//
// public static void initialize(@NonNull Context context) {
// if (sInstance == null) {
// sInstance = new LocalDataManager(context);
// }
// else {
// throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!");
// }
// }
//
// public static LocalDataManager getInstance() {
// return sInstance;
// }
//
// public boolean isReturningUser() {
// return getBoolean(PREF_RETURNING_USER);
// }
//
// public void setReturningUser(boolean isFirstRun) {
// set(PREF_RETURNING_USER, isFirstRun);
// }
//
// public int getOpenCount(){
// return getInt(OPEN_COUNT);
// }
//
// public void addOpenCount(){
// int openCount = getOpenCount();
// set(OPEN_COUNT, ++openCount);
// }
//
// private void set(String key, int i) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putInt(key, i);
// editor.apply();
// }
//
// private int getInt(String key){
// return mPreferences.getInt(key, 0);
// }
// private boolean getBoolean(String key) {
// return mPreferences.getBoolean(key, false);
// }
//
// @Nullable
// private String getString(String key) {
// return mPreferences.getString(key, null);
// }
//
// private void set(@NonNull String key, boolean value) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// private void set(@NonNull String key, String value) {
// SharedPreferences.Editor editor = mPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private void remove(@NonNull String key) {
// mPreferences.edit().remove(key).apply();
// }
// }
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java
import android.content.Context;
import com.bugsnag.android.Bugsnag;
import com.facebook.stetho.Stetho;
import com.orm.SugarApp;
import io.dwak.holohackernews.app.dagger.component.AppComponent;
import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent;
import io.dwak.holohackernews.app.dagger.module.AppModule;
import io.dwak.holohackernews.app.preferences.LocalDataManager;
package io.dwak.holohackernews.app;
public class HackerNewsApplication extends SugarApp {
private static boolean mDebug = BuildConfig.DEBUG;
private static HackerNewsApplication sInstance;
private Context mContext; | private static AppComponent sAppComponent; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.