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
Doctoror/ParticlesDrawable
opengl/src/main/java/com/doctoror/particlesdrawable/opengl/chooser/MultisamplingConfigChooser.java
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/PotCalculator.java // public final class PotCalculator { // // private PotCalculator() { // // } // // public static boolean isPowerOfTwo(final int number) { // return number > 0 && ((number & (number - 1)) == 0); // } // // public static int findNextOrReturnIfPowerOfTwo(int n) { // if (n <= 0) { // return 1; // } // if (isPowerOfTwo(n)) { // return n; // } // n--; // n |= n >> 1; // n |= n >> 2; // n |= n >> 4; // n |= n >> 8; // n |= n >> 16; // n++; // return n; // } // }
import com.doctoror.particlesdrawable.opengl.util.PotCalculator; import javax.microedition.khronos.egl.EGL10; import androidx.annotation.Nullable;
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.chooser; final class MultisamplingConfigChooser extends BaseConfigChooser { MultisamplingConfigChooser( final int samples, @Nullable final EGLConfigChooserCallback callback) { super("MultisamplingConfigChooser", makeConfigSpec(samples), callback); } private static int[] makeConfigSpec(final int samples) { if (samples <= 1) { throw new IllegalArgumentException("samples must be > 1"); }
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/PotCalculator.java // public final class PotCalculator { // // private PotCalculator() { // // } // // public static boolean isPowerOfTwo(final int number) { // return number > 0 && ((number & (number - 1)) == 0); // } // // public static int findNextOrReturnIfPowerOfTwo(int n) { // if (n <= 0) { // return 1; // } // if (isPowerOfTwo(n)) { // return n; // } // n--; // n |= n >> 1; // n |= n >> 2; // n |= n >> 4; // n |= n >> 8; // n |= n >> 16; // n++; // return n; // } // } // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/chooser/MultisamplingConfigChooser.java import com.doctoror.particlesdrawable.opengl.util.PotCalculator; import javax.microedition.khronos.egl.EGL10; import androidx.annotation.Nullable; /* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.chooser; final class MultisamplingConfigChooser extends BaseConfigChooser { MultisamplingConfigChooser( final int samples, @Nullable final EGLConfigChooserCallback callback) { super("MultisamplingConfigChooser", makeConfigSpec(samples), callback); } private static int[] makeConfigSpec(final int samples) { if (samples <= 1) { throw new IllegalArgumentException("samples must be > 1"); }
if (!PotCalculator.isPowerOfTwo(samples)) {
Doctoror/ParticlesDrawable
opengl/src/main/java/com/doctoror/particlesdrawable/opengl/renderer/GlSceneRendererBackground.java
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java // @KeepAsApi // public final class GLErrorChecker { // // private static boolean shouldThrowOnGlError = true; // private static boolean shouldCheckGlError = true; // // public static void setShouldCheckGlError(final boolean shouldCheckGlError) { // GLErrorChecker.shouldCheckGlError = shouldCheckGlError; // } // // public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { // GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; // } // // public static void checkGlError(@NonNull final String tag) { // if (shouldCheckGlError) { // final int error = GLES20.glGetError(); // if (error != GLES20.GL_NO_ERROR) { // if (shouldThrowOnGlError) { // throw new GlException(error, tag); // } else { // Log.e("GLErrorChecker", "GLError" + Integer.toString(error) + ", tag = " + tag); // } // } // } // } // } // // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/ShaderLoader.java // public final class ShaderLoader { // // private ShaderLoader() {} // // public static int loadShader(final int type, @NonNull final String shaderCode) { // final int shader = GLES20.glCreateShader(type); // // GLES20.glShaderSource(shader, shaderCode); // GLES20.glCompileShader(shader); // // return shader; // } // }
import android.graphics.Bitmap; import android.opengl.GLES20; import android.opengl.GLUtils; import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker; import com.doctoror.particlesdrawable.opengl.util.ShaderLoader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import androidx.annotation.NonNull; import androidx.annotation.Nullable;
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.renderer; final class GlSceneRendererBackground { private static final String VERTEX_SHADER_CODE = "uniform mat4 uMVPMatrix;" + "attribute vec4 vPosition;" + "attribute vec2 aTexCoord;" + "varying vec2 vTexCoord;" + "void main() {" + " gl_Position = uMVPMatrix * vPosition;" + " vTexCoord = aTexCoord;" + "}"; private static final String FRAGMENT_SHADER_CODE = "precision mediump float;" + "varying vec2 vTexCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTexCoord);" + "}"; private static final int BYTES_PER_SHORT = 2; private static final int COORDINATES_PER_VERTEX = 2; private volatile boolean backgroundCoordinatesDirty; private ShortBuffer backgroundCoordinates; private ByteBuffer backgroundTextureCoordinates; private short width; private short height; private int program; private int textureId; private boolean hasTexture; void init(final int textureId) { this.textureId = textureId;
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java // @KeepAsApi // public final class GLErrorChecker { // // private static boolean shouldThrowOnGlError = true; // private static boolean shouldCheckGlError = true; // // public static void setShouldCheckGlError(final boolean shouldCheckGlError) { // GLErrorChecker.shouldCheckGlError = shouldCheckGlError; // } // // public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { // GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; // } // // public static void checkGlError(@NonNull final String tag) { // if (shouldCheckGlError) { // final int error = GLES20.glGetError(); // if (error != GLES20.GL_NO_ERROR) { // if (shouldThrowOnGlError) { // throw new GlException(error, tag); // } else { // Log.e("GLErrorChecker", "GLError" + Integer.toString(error) + ", tag = " + tag); // } // } // } // } // } // // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/ShaderLoader.java // public final class ShaderLoader { // // private ShaderLoader() {} // // public static int loadShader(final int type, @NonNull final String shaderCode) { // final int shader = GLES20.glCreateShader(type); // // GLES20.glShaderSource(shader, shaderCode); // GLES20.glCompileShader(shader); // // return shader; // } // } // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/renderer/GlSceneRendererBackground.java import android.graphics.Bitmap; import android.opengl.GLES20; import android.opengl.GLUtils; import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker; import com.doctoror.particlesdrawable.opengl.util.ShaderLoader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particlesdrawable.opengl.renderer; final class GlSceneRendererBackground { private static final String VERTEX_SHADER_CODE = "uniform mat4 uMVPMatrix;" + "attribute vec4 vPosition;" + "attribute vec2 aTexCoord;" + "varying vec2 vTexCoord;" + "void main() {" + " gl_Position = uMVPMatrix * vPosition;" + " vTexCoord = aTexCoord;" + "}"; private static final String FRAGMENT_SHADER_CODE = "precision mediump float;" + "varying vec2 vTexCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTexCoord);" + "}"; private static final int BYTES_PER_SHORT = 2; private static final int COORDINATES_PER_VERTEX = 2; private volatile boolean backgroundCoordinatesDirty; private ShortBuffer backgroundCoordinates; private ByteBuffer backgroundTextureCoordinates; private short width; private short height; private int program; private int textureId; private boolean hasTexture; void init(final int textureId) { this.textureId = textureId;
final int vertexShader = ShaderLoader.loadShader(
Doctoror/ParticlesDrawable
opengl/src/main/java/com/doctoror/particlesdrawable/opengl/renderer/GlSceneRendererBackground.java
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java // @KeepAsApi // public final class GLErrorChecker { // // private static boolean shouldThrowOnGlError = true; // private static boolean shouldCheckGlError = true; // // public static void setShouldCheckGlError(final boolean shouldCheckGlError) { // GLErrorChecker.shouldCheckGlError = shouldCheckGlError; // } // // public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { // GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; // } // // public static void checkGlError(@NonNull final String tag) { // if (shouldCheckGlError) { // final int error = GLES20.glGetError(); // if (error != GLES20.GL_NO_ERROR) { // if (shouldThrowOnGlError) { // throw new GlException(error, tag); // } else { // Log.e("GLErrorChecker", "GLError" + Integer.toString(error) + ", tag = " + tag); // } // } // } // } // } // // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/ShaderLoader.java // public final class ShaderLoader { // // private ShaderLoader() {} // // public static int loadShader(final int type, @NonNull final String shaderCode) { // final int shader = GLES20.glCreateShader(type); // // GLES20.glShaderSource(shader, shaderCode); // GLES20.glCompileShader(shader); // // return shader; // } // }
import android.graphics.Bitmap; import android.opengl.GLES20; import android.opengl.GLUtils; import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker; import com.doctoror.particlesdrawable.opengl.util.ShaderLoader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import androidx.annotation.NonNull; import androidx.annotation.Nullable;
private static final String FRAGMENT_SHADER_CODE = "precision mediump float;" + "varying vec2 vTexCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTexCoord);" + "}"; private static final int BYTES_PER_SHORT = 2; private static final int COORDINATES_PER_VERTEX = 2; private volatile boolean backgroundCoordinatesDirty; private ShortBuffer backgroundCoordinates; private ByteBuffer backgroundTextureCoordinates; private short width; private short height; private int program; private int textureId; private boolean hasTexture; void init(final int textureId) { this.textureId = textureId; final int vertexShader = ShaderLoader.loadShader( GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_CODE);
// Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/GLErrorChecker.java // @KeepAsApi // public final class GLErrorChecker { // // private static boolean shouldThrowOnGlError = true; // private static boolean shouldCheckGlError = true; // // public static void setShouldCheckGlError(final boolean shouldCheckGlError) { // GLErrorChecker.shouldCheckGlError = shouldCheckGlError; // } // // public static void setShouldThrowOnGlError(final boolean shouldThrowOnGlError) { // GLErrorChecker.shouldThrowOnGlError = shouldThrowOnGlError; // } // // public static void checkGlError(@NonNull final String tag) { // if (shouldCheckGlError) { // final int error = GLES20.glGetError(); // if (error != GLES20.GL_NO_ERROR) { // if (shouldThrowOnGlError) { // throw new GlException(error, tag); // } else { // Log.e("GLErrorChecker", "GLError" + Integer.toString(error) + ", tag = " + tag); // } // } // } // } // } // // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/util/ShaderLoader.java // public final class ShaderLoader { // // private ShaderLoader() {} // // public static int loadShader(final int type, @NonNull final String shaderCode) { // final int shader = GLES20.glCreateShader(type); // // GLES20.glShaderSource(shader, shaderCode); // GLES20.glCompileShader(shader); // // return shader; // } // } // Path: opengl/src/main/java/com/doctoror/particlesdrawable/opengl/renderer/GlSceneRendererBackground.java import android.graphics.Bitmap; import android.opengl.GLES20; import android.opengl.GLUtils; import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker; import com.doctoror.particlesdrawable.opengl.util.ShaderLoader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import androidx.annotation.NonNull; import androidx.annotation.Nullable; private static final String FRAGMENT_SHADER_CODE = "precision mediump float;" + "varying vec2 vTexCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTexCoord);" + "}"; private static final int BYTES_PER_SHORT = 2; private static final int COORDINATES_PER_VERTEX = 2; private volatile boolean backgroundCoordinatesDirty; private ShortBuffer backgroundCoordinates; private ByteBuffer backgroundTextureCoordinates; private short width; private short height; private int program; private int textureId; private boolean hasTexture; void init(final int textureId) { this.textureId = textureId; final int vertexShader = ShaderLoader.loadShader( GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_CODE);
GLErrorChecker.checkGlError("background glCompileShader vertex");
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/activity/BaseActivity.java
// Path: app/src/main/java/org/indywidualni/centrumfm/util/Miscellany.java // public abstract class Miscellany { // // public static int dpToPx(int dp) { // final float scale = MyApplication.getContextOfApplication().getResources() // .getDisplayMetrics().density; // return (int) (dp * scale + 0.5f); // } // // public static String readFromAssets(String filename) { // String result = ""; // try { // result = convertStreamToString(MyApplication.getContextOfApplication() // .getAssets().open(filename)); // } catch (IOException e) { // e.printStackTrace(); // } // return result; // } // // private static String convertStreamToString(java.io.InputStream is) { // java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // public static String convertMillisToHuman(long total) { // total /= 1000; // int minutes = (int) (total % 3600) / 60; // int seconds = (int) total % 60; // return minutes + ":" + (seconds < 10 ? "0" + seconds : seconds); // } // // public static String constructDateQueryForDay(boolean dayStart) { // DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // Date today = Calendar.getInstance(TimeZone.getTimeZone("Europe/Warsaw")).getTime(); // String reportDate = df.format(today); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static String constructDateQueryForDay(boolean dayStart, // int year, int month, int day) { // @SuppressLint("DefaultLocale") String reportDate = year + "-" + // String.format("%02d", month + 1) + "-" + String.format("%02d", day); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static void addFavouriteSongFromRds(Context context, List<Rds> rds) { // String error = context.getString(R.string.cannot_favourite_song); // if (rds == null) // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // else { // Rds now = rds.get(0); // if (!now.getTitle().isEmpty() && !now.getArtist().isEmpty()) { // Song song = new Song(); // song.setTitle(now.getTitle()); // song.setArtist(now.getArtist()); // song.setDuration(now.getTotal()); // AsyncWrapper.insertFavouriteSong(song); // String message = "\u2605 " + now.getArtist() + " – " + now.getTitle(); // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } else // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // } // } // // public static String formatSubtitleSave(Context context, String subtitle) { // return subtitle == null ? null : context.getString(R.string.songs_given_day, // subtitle.substring(0, 10)); // } // // public static String formatSubtitleRead(Context context, String subtitle) { // return subtitle == null ? context.getString(R.string.songs_current_day) : subtitle; // } // // // get some information about the device (needed for e-mail signature) // public static String getDeviceInfo(Activity activity) { // StringBuilder sb = new StringBuilder(); // // try { // PackageInfo pInfo = activity.getPackageManager().getPackageInfo( // activity.getPackageName(), PackageManager.GET_META_DATA); // sb.append("\nApp Package Name: ").append(activity.getPackageName()); // sb.append("\nApp Version Name: ").append(pInfo.versionName); // sb.append("\nApp Version Code: ").append(pInfo.versionCode); // } catch (PackageManager.NameNotFoundException ex) { // Log.e("Misc: getDeviceInfo", "" + ex.getMessage()); // } // // sb.append("\nOS Version: ").append(System.getProperty("os.version")).append(" (") // .append(android.os.Build.VERSION.RELEASE).append(")"); // sb.append("\nOS API Level: ").append(android.os.Build.VERSION.SDK_INT); // sb.append("\nDevice: ").append(android.os.Build.DEVICE); // sb.append("\nModel: ").append(android.os.Build.MODEL); // sb.append("\nManufacturer: ").append(android.os.Build.MANUFACTURER); // // DisplayMetrics metrics = new DisplayMetrics(); // activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); // // sb.append("\nScreen: ").append(metrics.heightPixels).append(" x ") // .append(metrics.widthPixels); // sb.append("\nLocale: ").append(Locale.getDefault().toString()); // // return sb.toString(); // } // // }
import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import org.indywidualni.centrumfm.R; import org.indywidualni.centrumfm.util.Miscellany; import butterknife.BindView;
package org.indywidualni.centrumfm.activity; public abstract class BaseActivity extends AppCompatActivity { @BindView(R.id.toolbar) Toolbar toolbar; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_base, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.email_me: Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.author_email_address), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + ": " + getString(R.string.email_author));
// Path: app/src/main/java/org/indywidualni/centrumfm/util/Miscellany.java // public abstract class Miscellany { // // public static int dpToPx(int dp) { // final float scale = MyApplication.getContextOfApplication().getResources() // .getDisplayMetrics().density; // return (int) (dp * scale + 0.5f); // } // // public static String readFromAssets(String filename) { // String result = ""; // try { // result = convertStreamToString(MyApplication.getContextOfApplication() // .getAssets().open(filename)); // } catch (IOException e) { // e.printStackTrace(); // } // return result; // } // // private static String convertStreamToString(java.io.InputStream is) { // java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // public static String convertMillisToHuman(long total) { // total /= 1000; // int minutes = (int) (total % 3600) / 60; // int seconds = (int) total % 60; // return minutes + ":" + (seconds < 10 ? "0" + seconds : seconds); // } // // public static String constructDateQueryForDay(boolean dayStart) { // DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // Date today = Calendar.getInstance(TimeZone.getTimeZone("Europe/Warsaw")).getTime(); // String reportDate = df.format(today); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static String constructDateQueryForDay(boolean dayStart, // int year, int month, int day) { // @SuppressLint("DefaultLocale") String reportDate = year + "-" + // String.format("%02d", month + 1) + "-" + String.format("%02d", day); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static void addFavouriteSongFromRds(Context context, List<Rds> rds) { // String error = context.getString(R.string.cannot_favourite_song); // if (rds == null) // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // else { // Rds now = rds.get(0); // if (!now.getTitle().isEmpty() && !now.getArtist().isEmpty()) { // Song song = new Song(); // song.setTitle(now.getTitle()); // song.setArtist(now.getArtist()); // song.setDuration(now.getTotal()); // AsyncWrapper.insertFavouriteSong(song); // String message = "\u2605 " + now.getArtist() + " – " + now.getTitle(); // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } else // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // } // } // // public static String formatSubtitleSave(Context context, String subtitle) { // return subtitle == null ? null : context.getString(R.string.songs_given_day, // subtitle.substring(0, 10)); // } // // public static String formatSubtitleRead(Context context, String subtitle) { // return subtitle == null ? context.getString(R.string.songs_current_day) : subtitle; // } // // // get some information about the device (needed for e-mail signature) // public static String getDeviceInfo(Activity activity) { // StringBuilder sb = new StringBuilder(); // // try { // PackageInfo pInfo = activity.getPackageManager().getPackageInfo( // activity.getPackageName(), PackageManager.GET_META_DATA); // sb.append("\nApp Package Name: ").append(activity.getPackageName()); // sb.append("\nApp Version Name: ").append(pInfo.versionName); // sb.append("\nApp Version Code: ").append(pInfo.versionCode); // } catch (PackageManager.NameNotFoundException ex) { // Log.e("Misc: getDeviceInfo", "" + ex.getMessage()); // } // // sb.append("\nOS Version: ").append(System.getProperty("os.version")).append(" (") // .append(android.os.Build.VERSION.RELEASE).append(")"); // sb.append("\nOS API Level: ").append(android.os.Build.VERSION.SDK_INT); // sb.append("\nDevice: ").append(android.os.Build.DEVICE); // sb.append("\nModel: ").append(android.os.Build.MODEL); // sb.append("\nManufacturer: ").append(android.os.Build.MANUFACTURER); // // DisplayMetrics metrics = new DisplayMetrics(); // activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); // // sb.append("\nScreen: ").append(metrics.heightPixels).append(" x ") // .append(metrics.widthPixels); // sb.append("\nLocale: ").append(Locale.getDefault().toString()); // // return sb.toString(); // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/activity/BaseActivity.java import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import org.indywidualni.centrumfm.R; import org.indywidualni.centrumfm.util.Miscellany; import butterknife.BindView; package org.indywidualni.centrumfm.activity; public abstract class BaseActivity extends AppCompatActivity { @BindView(R.id.toolbar) Toolbar toolbar; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_base, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.email_me: Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.author_email_address), null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + ": " + getString(R.string.email_author));
emailIntent.putExtra(Intent.EXTRA_TEXT, "\n\n--" + Miscellany.getDeviceInfo(this));
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/util/database/MySQLiteHelper.java
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // }
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import org.indywidualni.centrumfm.MyApplication;
package org.indywidualni.centrumfm.util.database; public class MySQLiteHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "centrum.db"; private static final int DATABASE_VERSION = 2; public static final String TABLE_NEWS = "News"; public static final String COLUMN_NEWS_GUID = "guid"; public static final String COLUMN_NEWS_LINK = "link"; public static final String COLUMN_NEWS_TITLE = "title"; public static final String COLUMN_NEWS_DATE = "pubDate"; public static final String COLUMN_NEWS_DESCRIPTION = "description"; public static final String COLUMN_NEWS_CATEGORY = "category"; public static final String COLUMN_NEWS_ENCLOSURE = "enclosure"; public static final String TABLE_SCHEDULE = "Schedule"; public static final String TABLE_FAVOURITE = "Favourite"; public static final String COLUMN_SCHEDULE_ID = "id"; public static final String COLUMN_SCHEDULE_NAME = "name"; public static final String COLUMN_SCHEDULE_BAND = "band"; public static final String COLUMN_SCHEDULE_DAYS = "weekdays"; public static final String COLUMN_SCHEDULE_DATE = "start"; public static final String COLUMN_SCHEDULE_LENGTH = "length"; public static final String TABLE_FAVOURITE_SONGS = "FavouriteSongs"; public static final String COLUMN_SONGS_ID = "id"; public static final String COLUMN_SONGS_TITLE = "title"; public static final String COLUMN_SONGS_ARTIST = "artist"; public static final String COLUMN_SONGS_DURATION = "duration"; public MySQLiteHelper() {
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/util/database/MySQLiteHelper.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import org.indywidualni.centrumfm.MyApplication; package org.indywidualni.centrumfm.util.database; public class MySQLiteHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "centrum.db"; private static final int DATABASE_VERSION = 2; public static final String TABLE_NEWS = "News"; public static final String COLUMN_NEWS_GUID = "guid"; public static final String COLUMN_NEWS_LINK = "link"; public static final String COLUMN_NEWS_TITLE = "title"; public static final String COLUMN_NEWS_DATE = "pubDate"; public static final String COLUMN_NEWS_DESCRIPTION = "description"; public static final String COLUMN_NEWS_CATEGORY = "category"; public static final String COLUMN_NEWS_ENCLOSURE = "enclosure"; public static final String TABLE_SCHEDULE = "Schedule"; public static final String TABLE_FAVOURITE = "Favourite"; public static final String COLUMN_SCHEDULE_ID = "id"; public static final String COLUMN_SCHEDULE_NAME = "name"; public static final String COLUMN_SCHEDULE_BAND = "band"; public static final String COLUMN_SCHEDULE_DAYS = "weekdays"; public static final String COLUMN_SCHEDULE_DATE = "start"; public static final String COLUMN_SCHEDULE_LENGTH = "length"; public static final String TABLE_FAVOURITE_SONGS = "FavouriteSongs"; public static final String COLUMN_SONGS_ID = "id"; public static final String COLUMN_SONGS_TITLE = "title"; public static final String COLUMN_SONGS_ARTIST = "artist"; public static final String COLUMN_SONGS_DURATION = "duration"; public MySQLiteHelper() {
super(MyApplication.getContextOfApplication(), DATABASE_NAME, null, DATABASE_VERSION);
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/StartupReceiver.java
// Path: app/src/main/java/org/indywidualni/centrumfm/util/AlarmHelper.java // public abstract class AlarmHelper { // // private static final Context context = MyApplication.getContextOfApplication(); // // public static final String EVENT_TITLE = "event_title"; // public static final String TIME_TO_START = "time_to_start"; // // private static final SharedPreferences preferences = PreferenceManager // .getDefaultSharedPreferences(context); // // public static boolean isEnabled() { // return Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)) != 0; // } // // public static void setAlarms(Schedule.Event event) { // int offset = Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // // AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // // List<Integer> weekdays = getWeekdays(event); // // for (int i = 0; i < weekdays.size(); ++i) { // long time = generateEventDateMillis(event.getStartDate(), weekdays.get(i)); // // PendingIntent alarmIntent = generatePendingIntent(event, weekdays.get(i)); // // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time + offset, // AlarmManager.INTERVAL_DAY * 7, alarmIntent); // } // } // // public static void cancelAlarms(Schedule.Event event) { // AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // List<Integer> weekdays = getWeekdays(event); // // for (int i = 0; i < weekdays.size(); ++i) { // PendingIntent pendingIntent = generatePendingIntent(event, weekdays.get(i)); // alarmManager.cancel(pendingIntent); // } // } // // public static void setAllAlarms() { // List<Schedule.Event> events = obtainFavourites(); // for (Schedule.Event event : events) { // setAlarms(event); // } // } // // public static void cancelAllAlarms() { // List<Schedule.Event> events = obtainFavourites(); // for (Schedule.Event event : events) { // cancelAlarms(event); // } // } // // private static List<Schedule.Event> obtainFavourites() { // return DataSource.getInstance().getScheduleFavourite(); // } // // private static PendingIntent generatePendingIntent(Schedule.Event event, int uniqueWeekday) { // Intent intent = new Intent(context, AlarmReceiver.class); // intent.putExtra(EVENT_TITLE, event.getName()); // intent.putExtra(TIME_TO_START, preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // int uniqueId = event.getId() * 10 + uniqueWeekday; // return PendingIntent.getBroadcast(context, uniqueId, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // } // // private static List<Integer> getWeekdays(Schedule.Event event) { // List<Integer> weekdays = new ArrayList<>(); // // for (int i = 0; i < 7; ++i) // if (event.getWeekdays().contains(Integer.toString(i))) // weekdays.add(i + 1); // // return weekdays; // } // // private static long generateEventDateMillis(String time, int weekday) { // String[] timeSplit = time.split(":"); // Calendar date = Calendar.getInstance(); // date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); // date.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); // date.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); // date.set(Calendar.MILLISECOND, 0); // date.set(Calendar.DAY_OF_WEEK, weekday); // // Calendar nowWithOffset = Calendar.getInstance(); // int offset = Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // nowWithOffset.add(Calendar.MILLISECOND, offset); // // if (date.before(nowWithOffset)) // date.add(Calendar.WEEK_OF_YEAR, 1); // // return date.getTimeInMillis(); // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import org.indywidualni.centrumfm.util.AlarmHelper;
package org.indywidualni.centrumfm; public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; final String ACTION_QUICK_BOOT = "android.intent.action.QUICKBOOT_POWERON"; final String ACTION_REPLACED = "android.intent.action.PACKAGE_REPLACED"; String action = intent.getAction(); if (ACTION_BOOT.equals(action) || ACTION_QUICK_BOOT.equals(action) || ACTION_REPLACED.equals(action)) { Log.i("StartupBroadcast", "Boot time or package replaced!"); // set all reminders
// Path: app/src/main/java/org/indywidualni/centrumfm/util/AlarmHelper.java // public abstract class AlarmHelper { // // private static final Context context = MyApplication.getContextOfApplication(); // // public static final String EVENT_TITLE = "event_title"; // public static final String TIME_TO_START = "time_to_start"; // // private static final SharedPreferences preferences = PreferenceManager // .getDefaultSharedPreferences(context); // // public static boolean isEnabled() { // return Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)) != 0; // } // // public static void setAlarms(Schedule.Event event) { // int offset = Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // // AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // // List<Integer> weekdays = getWeekdays(event); // // for (int i = 0; i < weekdays.size(); ++i) { // long time = generateEventDateMillis(event.getStartDate(), weekdays.get(i)); // // PendingIntent alarmIntent = generatePendingIntent(event, weekdays.get(i)); // // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time + offset, // AlarmManager.INTERVAL_DAY * 7, alarmIntent); // } // } // // public static void cancelAlarms(Schedule.Event event) { // AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // List<Integer> weekdays = getWeekdays(event); // // for (int i = 0; i < weekdays.size(); ++i) { // PendingIntent pendingIntent = generatePendingIntent(event, weekdays.get(i)); // alarmManager.cancel(pendingIntent); // } // } // // public static void setAllAlarms() { // List<Schedule.Event> events = obtainFavourites(); // for (Schedule.Event event : events) { // setAlarms(event); // } // } // // public static void cancelAllAlarms() { // List<Schedule.Event> events = obtainFavourites(); // for (Schedule.Event event : events) { // cancelAlarms(event); // } // } // // private static List<Schedule.Event> obtainFavourites() { // return DataSource.getInstance().getScheduleFavourite(); // } // // private static PendingIntent generatePendingIntent(Schedule.Event event, int uniqueWeekday) { // Intent intent = new Intent(context, AlarmReceiver.class); // intent.putExtra(EVENT_TITLE, event.getName()); // intent.putExtra(TIME_TO_START, preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // int uniqueId = event.getId() * 10 + uniqueWeekday; // return PendingIntent.getBroadcast(context, uniqueId, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // } // // private static List<Integer> getWeekdays(Schedule.Event event) { // List<Integer> weekdays = new ArrayList<>(); // // for (int i = 0; i < 7; ++i) // if (event.getWeekdays().contains(Integer.toString(i))) // weekdays.add(i + 1); // // return weekdays; // } // // private static long generateEventDateMillis(String time, int weekday) { // String[] timeSplit = time.split(":"); // Calendar date = Calendar.getInstance(); // date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); // date.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); // date.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); // date.set(Calendar.MILLISECOND, 0); // date.set(Calendar.DAY_OF_WEEK, weekday); // // Calendar nowWithOffset = Calendar.getInstance(); // int offset = Integer.parseInt(preferences.getString("reminders_mode", // SettingsFragment.DEFAULT_REMINDER_OFFSET)); // nowWithOffset.add(Calendar.MILLISECOND, offset); // // if (date.before(nowWithOffset)) // date.add(Calendar.WEEK_OF_YEAR, 1); // // return date.getTimeInMillis(); // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/StartupReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import org.indywidualni.centrumfm.util.AlarmHelper; package org.indywidualni.centrumfm; public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; final String ACTION_QUICK_BOOT = "android.intent.action.QUICKBOOT_POWERON"; final String ACTION_REPLACED = "android.intent.action.PACKAGE_REPLACED"; String action = intent.getAction(); if (ACTION_BOOT.equals(action) || ACTION_QUICK_BOOT.equals(action) || ACTION_REPLACED.equals(action)) { Log.i("StartupBroadcast", "Boot time or package replaced!"); // set all reminders
if (AlarmHelper.isEnabled())
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/fragment/AboutFragment.java
// Path: app/src/main/java/org/indywidualni/centrumfm/util/Miscellany.java // public abstract class Miscellany { // // public static int dpToPx(int dp) { // final float scale = MyApplication.getContextOfApplication().getResources() // .getDisplayMetrics().density; // return (int) (dp * scale + 0.5f); // } // // public static String readFromAssets(String filename) { // String result = ""; // try { // result = convertStreamToString(MyApplication.getContextOfApplication() // .getAssets().open(filename)); // } catch (IOException e) { // e.printStackTrace(); // } // return result; // } // // private static String convertStreamToString(java.io.InputStream is) { // java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // public static String convertMillisToHuman(long total) { // total /= 1000; // int minutes = (int) (total % 3600) / 60; // int seconds = (int) total % 60; // return minutes + ":" + (seconds < 10 ? "0" + seconds : seconds); // } // // public static String constructDateQueryForDay(boolean dayStart) { // DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // Date today = Calendar.getInstance(TimeZone.getTimeZone("Europe/Warsaw")).getTime(); // String reportDate = df.format(today); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static String constructDateQueryForDay(boolean dayStart, // int year, int month, int day) { // @SuppressLint("DefaultLocale") String reportDate = year + "-" + // String.format("%02d", month + 1) + "-" + String.format("%02d", day); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static void addFavouriteSongFromRds(Context context, List<Rds> rds) { // String error = context.getString(R.string.cannot_favourite_song); // if (rds == null) // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // else { // Rds now = rds.get(0); // if (!now.getTitle().isEmpty() && !now.getArtist().isEmpty()) { // Song song = new Song(); // song.setTitle(now.getTitle()); // song.setArtist(now.getArtist()); // song.setDuration(now.getTotal()); // AsyncWrapper.insertFavouriteSong(song); // String message = "\u2605 " + now.getArtist() + " – " + now.getTitle(); // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } else // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // } // } // // public static String formatSubtitleSave(Context context, String subtitle) { // return subtitle == null ? null : context.getString(R.string.songs_given_day, // subtitle.substring(0, 10)); // } // // public static String formatSubtitleRead(Context context, String subtitle) { // return subtitle == null ? context.getString(R.string.songs_current_day) : subtitle; // } // // // get some information about the device (needed for e-mail signature) // public static String getDeviceInfo(Activity activity) { // StringBuilder sb = new StringBuilder(); // // try { // PackageInfo pInfo = activity.getPackageManager().getPackageInfo( // activity.getPackageName(), PackageManager.GET_META_DATA); // sb.append("\nApp Package Name: ").append(activity.getPackageName()); // sb.append("\nApp Version Name: ").append(pInfo.versionName); // sb.append("\nApp Version Code: ").append(pInfo.versionCode); // } catch (PackageManager.NameNotFoundException ex) { // Log.e("Misc: getDeviceInfo", "" + ex.getMessage()); // } // // sb.append("\nOS Version: ").append(System.getProperty("os.version")).append(" (") // .append(android.os.Build.VERSION.RELEASE).append(")"); // sb.append("\nOS API Level: ").append(android.os.Build.VERSION.SDK_INT); // sb.append("\nDevice: ").append(android.os.Build.DEVICE); // sb.append("\nModel: ").append(android.os.Build.MODEL); // sb.append("\nManufacturer: ").append(android.os.Build.MANUFACTURER); // // DisplayMetrics metrics = new DisplayMetrics(); // activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); // // sb.append("\nScreen: ").append(metrics.heightPixels).append(" x ") // .append(metrics.widthPixels); // sb.append("\nLocale: ").append(Locale.getDefault().toString()); // // return sb.toString(); // } // // }
import android.app.Fragment; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.indywidualni.centrumfm.R; import org.indywidualni.centrumfm.util.Miscellany; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder;
package org.indywidualni.centrumfm.fragment; public class AboutFragment extends Fragment { @BindView(R.id.aboutRadio) TextView aboutRadio; @BindView(R.id.aboutText) TextView aboutText; private Unbinder unbinder; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); unbinder = ButterKnife.bind(this, view); return view; } @SuppressWarnings("deprecation") @Override public void onViewCreated(View view, Bundle savedInstanceState) { aboutRadio.setMovementMethod(LinkMovementMethod.getInstance()); aboutText.setMovementMethod(LinkMovementMethod.getInstance()); if (android.os.Build.VERSION.SDK_INT >= 24) {
// Path: app/src/main/java/org/indywidualni/centrumfm/util/Miscellany.java // public abstract class Miscellany { // // public static int dpToPx(int dp) { // final float scale = MyApplication.getContextOfApplication().getResources() // .getDisplayMetrics().density; // return (int) (dp * scale + 0.5f); // } // // public static String readFromAssets(String filename) { // String result = ""; // try { // result = convertStreamToString(MyApplication.getContextOfApplication() // .getAssets().open(filename)); // } catch (IOException e) { // e.printStackTrace(); // } // return result; // } // // private static String convertStreamToString(java.io.InputStream is) { // java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // public static String convertMillisToHuman(long total) { // total /= 1000; // int minutes = (int) (total % 3600) / 60; // int seconds = (int) total % 60; // return minutes + ":" + (seconds < 10 ? "0" + seconds : seconds); // } // // public static String constructDateQueryForDay(boolean dayStart) { // DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // Date today = Calendar.getInstance(TimeZone.getTimeZone("Europe/Warsaw")).getTime(); // String reportDate = df.format(today); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static String constructDateQueryForDay(boolean dayStart, // int year, int month, int day) { // @SuppressLint("DefaultLocale") String reportDate = year + "-" + // String.format("%02d", month + 1) + "-" + String.format("%02d", day); // return dayStart ? reportDate + "T00:00:00" : reportDate + "T23:59:59"; // } // // public static void addFavouriteSongFromRds(Context context, List<Rds> rds) { // String error = context.getString(R.string.cannot_favourite_song); // if (rds == null) // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // else { // Rds now = rds.get(0); // if (!now.getTitle().isEmpty() && !now.getArtist().isEmpty()) { // Song song = new Song(); // song.setTitle(now.getTitle()); // song.setArtist(now.getArtist()); // song.setDuration(now.getTotal()); // AsyncWrapper.insertFavouriteSong(song); // String message = "\u2605 " + now.getArtist() + " – " + now.getTitle(); // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } else // Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); // } // } // // public static String formatSubtitleSave(Context context, String subtitle) { // return subtitle == null ? null : context.getString(R.string.songs_given_day, // subtitle.substring(0, 10)); // } // // public static String formatSubtitleRead(Context context, String subtitle) { // return subtitle == null ? context.getString(R.string.songs_current_day) : subtitle; // } // // // get some information about the device (needed for e-mail signature) // public static String getDeviceInfo(Activity activity) { // StringBuilder sb = new StringBuilder(); // // try { // PackageInfo pInfo = activity.getPackageManager().getPackageInfo( // activity.getPackageName(), PackageManager.GET_META_DATA); // sb.append("\nApp Package Name: ").append(activity.getPackageName()); // sb.append("\nApp Version Name: ").append(pInfo.versionName); // sb.append("\nApp Version Code: ").append(pInfo.versionCode); // } catch (PackageManager.NameNotFoundException ex) { // Log.e("Misc: getDeviceInfo", "" + ex.getMessage()); // } // // sb.append("\nOS Version: ").append(System.getProperty("os.version")).append(" (") // .append(android.os.Build.VERSION.RELEASE).append(")"); // sb.append("\nOS API Level: ").append(android.os.Build.VERSION.SDK_INT); // sb.append("\nDevice: ").append(android.os.Build.DEVICE); // sb.append("\nModel: ").append(android.os.Build.MODEL); // sb.append("\nManufacturer: ").append(android.os.Build.MANUFACTURER); // // DisplayMetrics metrics = new DisplayMetrics(); // activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); // // sb.append("\nScreen: ").append(metrics.heightPixels).append(" x ") // .append(metrics.widthPixels); // sb.append("\nLocale: ").append(Locale.getDefault().toString()); // // return sb.toString(); // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/fragment/AboutFragment.java import android.app.Fragment; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.indywidualni.centrumfm.R; import org.indywidualni.centrumfm.util.Miscellany; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; package org.indywidualni.centrumfm.fragment; public class AboutFragment extends Fragment { @BindView(R.id.aboutRadio) TextView aboutRadio; @BindView(R.id.aboutText) TextView aboutText; private Unbinder unbinder; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); unbinder = ButterKnife.bind(this, view); return view; } @SuppressWarnings("deprecation") @Override public void onViewCreated(View view, Bundle savedInstanceState) { aboutRadio.setMovementMethod(LinkMovementMethod.getInstance()); aboutText.setMovementMethod(LinkMovementMethod.getInstance()); if (android.os.Build.VERSION.SDK_INT >= 24) {
aboutRadio.setText(Html.fromHtml(Miscellany.readFromAssets("radio.html"),
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/util/Serializer.java
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // }
import android.util.Log; import org.indywidualni.centrumfm.MyApplication; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;
package org.indywidualni.centrumfm.util; @SuppressWarnings("UnusedDeclaration") public abstract class Serializer { /** * Serialize serializable object to a file * * @param source the given object * @param filename filename (without .ser) * @param <T> type of the given object */ public static <T> void serialize(T source, String filename) { FileOutputStream fos; ObjectOutputStream oos = null; // serialization try {
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/util/Serializer.java import android.util.Log; import org.indywidualni.centrumfm.MyApplication; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; package org.indywidualni.centrumfm.util; @SuppressWarnings("UnusedDeclaration") public abstract class Serializer { /** * Serialize serializable object to a file * * @param source the given object * @param filename filename (without .ser) * @param <T> type of the given object */ public static <T> void serialize(T source, String filename) { FileOutputStream fos; ObjectOutputStream oos = null; // serialization try {
fos = new FileOutputStream(MyApplication.getContextOfApplication()
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/fragment/TrackedFragment.java
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // }
import android.support.v4.app.Fragment; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.indywidualni.centrumfm.MyApplication;
package org.indywidualni.centrumfm.fragment; public abstract class TrackedFragment extends Fragment { @Override public void onResume() { super.onResume(); if (getUserVisibleHint()) {
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/fragment/TrackedFragment.java import android.support.v4.app.Fragment; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.indywidualni.centrumfm.MyApplication; package org.indywidualni.centrumfm.fragment; public abstract class TrackedFragment extends Fragment { @Override public void onResume() { super.onResume(); if (getUserVisibleHint()) {
final Tracker tracker = ((MyApplication) getActivity().getApplication())
indywidualny/Centrum.fm
app/src/main/java/org/indywidualni/centrumfm/util/PrettyLength.java
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // }
import android.content.Context; import org.indywidualni.centrumfm.MyApplication; import org.indywidualni.centrumfm.R;
package org.indywidualni.centrumfm.util; public abstract class PrettyLength { public static String get(int hours) {
// Path: app/src/main/java/org/indywidualni/centrumfm/MyApplication.java // public class MyApplication extends Application { // // private static Context mContext; // private Tracker mTracker; // // public static Context getContextOfApplication() { // return mContext; // } // // @Override // public void onCreate() { // mContext = getApplicationContext(); // super.onCreate(); // } // // /** // * Gets the default {@link Tracker} for this {@link Application}. // * // * @return tracker // */ // synchronized public Tracker getDefaultTracker() { // if (mTracker == null) { // // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.setDryRun(BuildConfig.DEBUG); // // mTracker = analytics.newTracker(R.xml.global_tracker); // mTracker.enableAutoActivityTracking(true); // mTracker.enableExceptionReporting(true); // } // return mTracker; // } // // } // Path: app/src/main/java/org/indywidualni/centrumfm/util/PrettyLength.java import android.content.Context; import org.indywidualni.centrumfm.MyApplication; import org.indywidualni.centrumfm.R; package org.indywidualni.centrumfm.util; public abstract class PrettyLength { public static String get(int hours) {
Context context = MyApplication.getContextOfApplication();
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // }
import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService;
package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class CollectionUtils { public static final int TYPE_ANSWERS = 1; public static final int TYPE_ANSWER = 2; private static CollectionUtils mCollection;
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService; package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class CollectionUtils { public static final int TYPE_ANSWERS = 1; public static final int TYPE_ANSWER = 2; private static CollectionUtils mCollection;
private List<Collection> mLists;
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // }
import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService;
package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class CollectionUtils { public static final int TYPE_ANSWERS = 1; public static final int TYPE_ANSWER = 2; private static CollectionUtils mCollection; private List<Collection> mLists; public static CollectionUtils getInstance() { synchronized (CollectionUtils.class) { if (mCollection == null) { synchronized (CollectionUtils.class) { mCollection = new CollectionUtils(); } } } return mCollection; } private CollectionUtils() { mLists = new ArrayList<>();
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService; package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class CollectionUtils { public static final int TYPE_ANSWERS = 1; public static final int TYPE_ANSWER = 2; private static CollectionUtils mCollection; private List<Collection> mLists; public static CollectionUtils getInstance() { synchronized (CollectionUtils.class) { if (mCollection == null) { synchronized (CollectionUtils.class) { mCollection = new CollectionUtils(); } } } return mCollection; } private CollectionUtils() { mLists = new ArrayList<>();
mLists.addAll(getOperatorsService().queryAll());
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // }
import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService;
private CollectionUtils() { mLists = new ArrayList<>(); mLists.addAll(getOperatorsService().queryAll()); } public void saveItem(Collection model){ getOperatorsService().save(model); mLists.add(model); } public Observable<Collection> contailItem(final String url){ return Observable.from(mLists) .filter(new Func1<Collection, Boolean>() { @Override public Boolean call(Collection model) { return model.getUrl().equals(url); } }); } public void removeItem(String mQuestionUrl) { for (int i = 0; i < mLists.size(); i++) { if(mLists.get(i).getUrl().equals(mQuestionUrl)){
// Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/collection.java // public class Collection { // // private Long id; // private String title; // private String detail; // private String url; // private Integer type; // // public Collection() { // } // // public Collection(Long id) { // this.id = id; // } // // public Collection(Long id, String title, String detail, String url, Integer type) { // this.id = id; // this.title = title; // this.detail = detail; // this.url = url; // this.type = type; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public class DbUtil { // // private static CollectionService operatorsService; // // // private static CollectionDao getOperatorsDao() { // return DbCore.getDaoSession().getCollectionDao(); // } // // // // // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbUtil.java // public static CollectionService getOperatorsService() { // if (operatorsService == null) { // operatorsService = new CollectionService(getOperatorsDao()); // } // return operatorsService; // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/utils/CollectionUtils.java import com.jiang.android.zhihu_topanswer.db.Collection; import com.jiang.android.zhihu_topanswer.db.DbUtil; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Func1; import static com.jiang.android.zhihu_topanswer.db.DbUtil.getOperatorsService; private CollectionUtils() { mLists = new ArrayList<>(); mLists.addAll(getOperatorsService().queryAll()); } public void saveItem(Collection model){ getOperatorsService().save(model); mLists.add(model); } public Observable<Collection> contailItem(final String url){ return Observable.from(mLists) .filter(new Func1<Collection, Boolean>() { @Override public Boolean call(Collection model) { return model.getUrl().equals(url); } }); } public void removeItem(String mQuestionUrl) { for (int i = 0; i < mLists.size(); i++) { if(mLists.get(i).getUrl().equals(mQuestionUrl)){
List<Collection> list = DbUtil.getOperatorsService().query(" where url=?",mLists.get(i).getUrl());
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/NormalCallBack.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/ws_ret.java // public class ws_ret { // // @SerializedName("status") // @Expose // private int state; // @Expose // private String msg; // // public ws_ret() { // } // // public ws_ret(int state, String msg) { // this.state = state; // this.msg = msg; // } // // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public int getState() { // return state; // } // // public void setState(int state) { // this.state = state; // } // // @Override // public String toString() { // return "ws_ret{" + // "state=" + state + // ", msg='" + msg + '\'' + // '}'; // } // }
import com.jiang.android.architecture.okhttp.ws_ret; import okhttp3.Response;
package com.jiang.android.architecture.okhttp.callback; /** * Created by jiang on 2016/11/29. */ public abstract class NormalCallBack<T> extends BaseCallBack<T> { @Override
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/ws_ret.java // public class ws_ret { // // @SerializedName("status") // @Expose // private int state; // @Expose // private String msg; // // public ws_ret() { // } // // public ws_ret(int state, String msg) { // this.state = state; // this.msg = msg; // } // // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public int getState() { // return state; // } // // public void setState(int state) { // this.state = state; // } // // @Override // public String toString() { // return "ws_ret{" + // "state=" + state + // ", msg='" + msg + '\'' + // '}'; // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/NormalCallBack.java import com.jiang.android.architecture.okhttp.ws_ret; import okhttp3.Response; package com.jiang.android.architecture.okhttp.callback; /** * Created by jiang on 2016/11/29. */ public abstract class NormalCallBack<T> extends BaseCallBack<T> { @Override
public void onNoData(ws_ret ret) {
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/utils/LuBan.java
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/Preconditions.java // static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static com.jiang.android.architecture.utils.Preconditions.checkNotNull;
} return degree; } /** * 旋转图片 * rotate the image with specified angle * * @param angle the angle will be rotating 旋转的角度 * @param bitmap target image 目标图片 */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 保存图片到指定路径 * Save image with specified size * * @param filePath the image file save path 储存路径 * @param bitmap the image what be save 目标图片 * @param size the file size of image 期望大小 */ private File saveImage(String filePath, Bitmap bitmap, long size) {
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/Preconditions.java // static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: architecture/src/main/java/com/jiang/android/architecture/utils/LuBan.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static com.jiang.android.architecture.utils.Preconditions.checkNotNull; } return degree; } /** * 旋转图片 * rotate the image with specified angle * * @param angle the angle will be rotating 旋转的角度 * @param bitmap target image 目标图片 */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 保存图片到指定路径 * Save image with specified size * * @param filePath the image file save path 储存路径 * @param bitmap the image what be save 目标图片 * @param size the file size of image 期望大小 */ private File saveImage(String filePath, Bitmap bitmap, long size) {
checkNotNull(bitmap, TAG + "bitmap cannot be null");
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // }
import android.text.TextUtils; import com.jiang.android.architecture.okhttp.Param; import java.util.Map; import java.util.Set; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.utils; /** * 相关网络请求的工具类 * Created by jiang on 15/10/16. */ public class HttpUtils { public static String parseParams2String(Map<String, String> param) { if (param == null || param.size() == 0) return ""; StringBuffer buffer = new StringBuffer(); Set<Map.Entry<String, String>> entrySet = param.entrySet(); for (Map.Entry<String, String> entry : entrySet) {
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java import android.text.TextUtils; import com.jiang.android.architecture.okhttp.Param; import java.util.Map; import java.util.Set; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.utils; /** * 相关网络请求的工具类 * Created by jiang on 15/10/16. */ public class HttpUtils { public static String parseParams2String(Map<String, String> param) { if (param == null || param.size() == 0) return ""; StringBuffer buffer = new StringBuffer(); Set<Map.Entry<String, String>> entrySet = param.entrySet(); for (Map.Entry<String, String> entry : entrySet) {
Param par = new Param(entry.getKey(), entry.getValue());
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/BaseCallBack.java // public abstract class BaseCallBack<T> { // // /** // * 失败 // * // * @param ret 数据 // */ // public abstract void onFail(ws_ret ret); //失败 // // /** // * 成功 // * // * @param t 数据 // */ // public abstract void onSuccess(T t); //成功 // // // /** // * 无数据, 只在get中用到 // * // * @param ret 数据 // */ // public abstract void onNoData(ws_ret ret); //无数据, 注意: 当是post请求的时候该方法不会回调 // // /** // * 网络请求开始时执行 // */ // public abstract void onBefore(); // // /** // * 网络请求结束时执行, 比如停止下拉刷新控件的执行 // */ // public abstract void onAfter(); // // /** // * 所有的网络请求成功以后都会走这个方法, // * // * @param response 数据 // */ // public abstract void onFinishResponse(Response response); // // /** // * 下载文件事 的进度 // * // * @param progress 进度 // */ // public abstract void onProgress(long progress); // // /** // * 获得泛型的类型 // */ // public Type mType; // // public BaseCallBack() { // mType = getSuperclassTypeParameter(getClass()); // } // // static Type getSuperclassTypeParameter(Class<?> subclass) { // Type superclass = subclass.getGenericSuperclass(); // if (superclass instanceof Class) { // throw new RuntimeException("泛型参数不能为空"); // } // ParameterizedType parameterized = (ParameterizedType) superclass; // return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/NotPermissionException.java // public class NotPermissionException extends RuntimeException { // // private static final long serialVersionUID = 110L; // // public NotPermissionException() { // } // // public NotPermissionException(String detailMessage) { // super(detailMessage); // } // }
import com.jiang.android.architecture.okhttp.callback.BaseCallBack; import com.jiang.android.architecture.okhttp.exception.NotPermissionException; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import android.text.TextUtils;
this.callBack = c; type = OkHttpTask.TYPE_GET; if (validateParams()) { downLoadFile(url, path, fileName, callBack, tag); } } public void execute(BaseCallBack c) { this.callBack = c; if (validateParams()) { doJob(url, tag, params, callBack, headers, type); } } /** * 上传文件必传 * url,files,header(用来验证),callBack * * @param c */ public void upload(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_POST; if (validateParams()) { uploadFile(url, headers, files, callBack, tag); } } private boolean validateParams() { if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/BaseCallBack.java // public abstract class BaseCallBack<T> { // // /** // * 失败 // * // * @param ret 数据 // */ // public abstract void onFail(ws_ret ret); //失败 // // /** // * 成功 // * // * @param t 数据 // */ // public abstract void onSuccess(T t); //成功 // // // /** // * 无数据, 只在get中用到 // * // * @param ret 数据 // */ // public abstract void onNoData(ws_ret ret); //无数据, 注意: 当是post请求的时候该方法不会回调 // // /** // * 网络请求开始时执行 // */ // public abstract void onBefore(); // // /** // * 网络请求结束时执行, 比如停止下拉刷新控件的执行 // */ // public abstract void onAfter(); // // /** // * 所有的网络请求成功以后都会走这个方法, // * // * @param response 数据 // */ // public abstract void onFinishResponse(Response response); // // /** // * 下载文件事 的进度 // * // * @param progress 进度 // */ // public abstract void onProgress(long progress); // // /** // * 获得泛型的类型 // */ // public Type mType; // // public BaseCallBack() { // mType = getSuperclassTypeParameter(getClass()); // } // // static Type getSuperclassTypeParameter(Class<?> subclass) { // Type superclass = subclass.getGenericSuperclass(); // if (superclass instanceof Class) { // throw new RuntimeException("泛型参数不能为空"); // } // ParameterizedType parameterized = (ParameterizedType) superclass; // return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/NotPermissionException.java // public class NotPermissionException extends RuntimeException { // // private static final long serialVersionUID = 110L; // // public NotPermissionException() { // } // // public NotPermissionException(String detailMessage) { // super(detailMessage); // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpRequest.java import com.jiang.android.architecture.okhttp.callback.BaseCallBack; import com.jiang.android.architecture.okhttp.exception.NotPermissionException; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import android.text.TextUtils; this.callBack = c; type = OkHttpTask.TYPE_GET; if (validateParams()) { downLoadFile(url, path, fileName, callBack, tag); } } public void execute(BaseCallBack c) { this.callBack = c; if (validateParams()) { doJob(url, tag, params, callBack, headers, type); } } /** * 上传文件必传 * url,files,header(用来验证),callBack * * @param c */ public void upload(BaseCallBack c) { this.callBack = c; type = OkHttpTask.TYPE_POST; if (validateParams()) { uploadFile(url, headers, files, callBack, tag); } } private boolean validateParams() { if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
throw new NotPermissionException("url不合法");
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java // public class TopicAnswers { // private String url; // private String title; // private String img; // private String vote; // private String body; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getVote() { // return vote; // } // // public void setVote(String vote) { // this.vote = vote; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImg() { // return img; // } // // public void setImg(String img) { // this.img = img; // } // // @Override // public String toString() { // return "url:" + url + " :title:" + title + " :img:" + img + " :vote:" + vote + " :body:" + body; // } // }
import android.text.TextUtils; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class JSoupUtils { private static final String TAG = "JSoupUtils"; /** * 首页获取列表信息 * @param document * @return */
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java // public class TopicAnswers { // private String url; // private String title; // private String img; // private String vote; // private String body; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getVote() { // return vote; // } // // public void setVote(String vote) { // this.vote = vote; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImg() { // return img; // } // // public void setImg(String img) { // this.img = img; // } // // @Override // public String toString() { // return "url:" + url + " :title:" + title + " :img:" + img + " :vote:" + vote + " :body:" + body; // } // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java import android.text.TextUtils; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.jiang.android.zhihu_topanswer.utils; /** * Created by jiang on 2016/12/28. */ public class JSoupUtils { private static final String TAG = "JSoupUtils"; /** * 首页获取列表信息 * @param document * @return */
public static List<TopicAnswers> getTopicList(Document document) {
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java // public class TopicAnswers { // private String url; // private String title; // private String img; // private String vote; // private String body; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getVote() { // return vote; // } // // public void setVote(String vote) { // this.vote = vote; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImg() { // return img; // } // // public void setImg(String img) { // this.img = img; // } // // @Override // public String toString() { // return "url:" + url + " :title:" + title + " :img:" + img + " :vote:" + vote + " :body:" + body; // } // }
import android.text.TextUtils; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
} Elements votes = body.select("a.zm-item-vote-count.js-expand.js-vote-count"); if (votes.size() > 0) { if (votes.iterator().hasNext()) { Element aVotes = votes.iterator().next(); answers.setVote(aVotes.text()); } } Elements divs = body.select("div.zh-summary.summary.clearfix"); String descBody = divs.text(); if (descBody.length() > 4) { descBody = descBody.substring(0, descBody.length() - 4); } answers.setBody(descBody); if (divs.size() > 0) { if (divs.iterator().hasNext()) { Element aDiv = divs.iterator().next(); Element img = aDiv.children().first(); if (img.tagName().equals("img")) { String imgUrl = img.attr("src"); answers.setImg(imgUrl); } } } if (!TextUtils.isEmpty(answers.getTitle()) && !TextUtils.isEmpty(answers.getUrl())) {
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/model/TopicAnswers.java // public class TopicAnswers { // private String url; // private String title; // private String img; // private String vote; // private String body; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getVote() { // return vote; // } // // public void setVote(String vote) { // this.vote = vote; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImg() { // return img; // } // // public void setImg(String img) { // this.img = img; // } // // @Override // public String toString() { // return "url:" + url + " :title:" + title + " :img:" + img + " :vote:" + vote + " :body:" + body; // } // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/utils/JSoupUtils.java import android.text.TextUtils; import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List; } Elements votes = body.select("a.zm-item-vote-count.js-expand.js-vote-count"); if (votes.size() > 0) { if (votes.iterator().hasNext()) { Element aVotes = votes.iterator().next(); answers.setVote(aVotes.text()); } } Elements divs = body.select("div.zh-summary.summary.clearfix"); String descBody = divs.text(); if (descBody.length() > 4) { descBody = descBody.substring(0, descBody.length() - 4); } answers.setBody(descBody); if (divs.size() > 0) { if (divs.iterator().hasNext()) { Element aDiv = divs.iterator().next(); Element img = aDiv.children().first(); if (img.tagName().equals("img")) { String imgUrl = img.attr("src"); answers.setImg(imgUrl); } } } if (!TextUtils.isEmpty(answers.getTitle()) && !TextUtils.isEmpty(answers.getUrl())) {
L.i(TAG, answers.toString());
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成post需要的request * Created by jiang on 15/10/16. */ public class PostRequest { public static Request buildPostRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成post需要的request * Created by jiang on 15/10/16. */ public class PostRequest { public static Request buildPostRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成post需要的request * Created by jiang on 15/10/16. */ public class PostRequest { public static Request buildPostRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成post需要的request * Created by jiang on 15/10/16. */ public class PostRequest { public static Request buildPostRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java // public interface CookieStore // { // // public void add(HttpUrl uri, List<Cookie> cookie); // // public List<Cookie> get(HttpUrl uri); // // public List<Cookie> getCookies(); // // public boolean remove(HttpUrl uri, Cookie cookie); // // public boolean removeAll(); // // // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java // public interface HasCookieStore // { // CookieStore getCookieStore(); // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java // public class Exceptions // { // public static void illegalArgument(String msg, Object... params) // { // throw new IllegalArgumentException(String.format(msg, params)); // } // // // }
import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl;
package com.jiang.android.architecture.okhttp.cookie; /** * Created by zhy on 16/3/10. */ public class CookieJarImpl implements CookieJar, HasCookieStore {
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java // public interface CookieStore // { // // public void add(HttpUrl uri, List<Cookie> cookie); // // public List<Cookie> get(HttpUrl uri); // // public List<Cookie> getCookies(); // // public boolean remove(HttpUrl uri, Cookie cookie); // // public boolean removeAll(); // // // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java // public interface HasCookieStore // { // CookieStore getCookieStore(); // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java // public class Exceptions // { // public static void illegalArgument(String msg, Object... params) // { // throw new IllegalArgumentException(String.format(msg, params)); // } // // // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; package com.jiang.android.architecture.okhttp.cookie; /** * Created by zhy on 16/3/10. */ public class CookieJarImpl implements CookieJar, HasCookieStore {
private CookieStore cookieStore;
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java // public interface CookieStore // { // // public void add(HttpUrl uri, List<Cookie> cookie); // // public List<Cookie> get(HttpUrl uri); // // public List<Cookie> getCookies(); // // public boolean remove(HttpUrl uri, Cookie cookie); // // public boolean removeAll(); // // // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java // public interface HasCookieStore // { // CookieStore getCookieStore(); // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java // public class Exceptions // { // public static void illegalArgument(String msg, Object... params) // { // throw new IllegalArgumentException(String.format(msg, params)); // } // // // }
import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl;
package com.jiang.android.architecture.okhttp.cookie; /** * Created by zhy on 16/3/10. */ public class CookieJarImpl implements CookieJar, HasCookieStore { private CookieStore cookieStore; public CookieJarImpl(CookieStore cookieStore) {
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java // public interface CookieStore // { // // public void add(HttpUrl uri, List<Cookie> cookie); // // public List<Cookie> get(HttpUrl uri); // // public List<Cookie> getCookies(); // // public boolean remove(HttpUrl uri, Cookie cookie); // // public boolean removeAll(); // // // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java // public interface HasCookieStore // { // CookieStore getCookieStore(); // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java // public class Exceptions // { // public static void illegalArgument(String msg, Object... params) // { // throw new IllegalArgumentException(String.format(msg, params)); // } // // // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; package com.jiang.android.architecture.okhttp.cookie; /** * Created by zhy on 16/3/10. */ public class CookieJarImpl implements CookieJar, HasCookieStore { private CookieStore cookieStore; public CookieJarImpl(CookieStore cookieStore) {
if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null.");
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/view/SelectPopupWindow.java
// Path: architecture/src/main/java/com/jiang/android/architecture/adapter/BaseAdapter.java // public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> { // // // @Override // public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false)); // // if (clickable()) { // holder.getConvertView().setClickable(true); // holder.getConvertView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onItemClick(v, holder.getLayoutPosition()); // } // }); // } // return holder; // } // // @Override // public void onBindViewHolder(final BaseViewHolder holder, final int position) { // // onBindView(holder, holder.getLayoutPosition()); // // } // // public abstract void onBindView(BaseViewHolder holder, int position); // // @Override // public int getItemViewType(int position) { // return getLayoutID(position); // } // // // public abstract int getLayoutID(int position); // // public abstract boolean clickable(); // // public void onItemClick(View v, int position) { // } // // // }
import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.zhihu_topanswer.R;
package com.jiang.android.zhihu_topanswer.view; /** * Created by jiang on 2016/12/24. */ public class SelectPopupWindow extends PopupWindow { private final View mMenuView; private final RecyclerView mRecyclerView; public SelectPopupWindow(Activity context) { super(context); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMenuView = inflater.inflate(R.layout.popwindow_layout, null); mRecyclerView = (RecyclerView) mMenuView.findViewById(R.id.pop_layout1); this.setContentView(mMenuView); this.setWidth(ViewGroup.LayoutParams.FILL_PARENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); this.setFocusable(true); ColorDrawable dw = new ColorDrawable(0xb0000000); this.setBackgroundDrawable(dw); setOutsideTouchable(false); }
// Path: architecture/src/main/java/com/jiang/android/architecture/adapter/BaseAdapter.java // public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> { // // // @Override // public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false)); // // if (clickable()) { // holder.getConvertView().setClickable(true); // holder.getConvertView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onItemClick(v, holder.getLayoutPosition()); // } // }); // } // return holder; // } // // @Override // public void onBindViewHolder(final BaseViewHolder holder, final int position) { // // onBindView(holder, holder.getLayoutPosition()); // // } // // public abstract void onBindView(BaseViewHolder holder, int position); // // @Override // public int getItemViewType(int position) { // return getLayoutID(position); // } // // // public abstract int getLayoutID(int position); // // public abstract boolean clickable(); // // public void onItemClick(View v, int position) { // } // // // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/view/SelectPopupWindow.java import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.zhihu_topanswer.R; package com.jiang.android.zhihu_topanswer.view; /** * Created by jiang on 2016/12/24. */ public class SelectPopupWindow extends PopupWindow { private final View mMenuView; private final RecyclerView mRecyclerView; public SelectPopupWindow(Activity context) { super(context); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMenuView = inflater.inflate(R.layout.popwindow_layout, null); mRecyclerView = (RecyclerView) mMenuView.findViewById(R.id.pop_layout1); this.setContentView(mMenuView); this.setWidth(ViewGroup.LayoutParams.FILL_PARENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); this.setFocusable(true); ColorDrawable dw = new ColorDrawable(0xb0000000); this.setBackgroundDrawable(dw); setOutsideTouchable(false); }
public void setAdapter(BaseAdapter adapter) {
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxAppCompatActivity.java
// Path: architecture/src/main/java/com/jiang/android/architecture/AppManager.java // public class AppManager { // private static Stack<Activity> activityStack; // private static AppManager instance; // // // private AppManager() { // } // // /** // * 单一实例 // */ // public static AppManager getAppManager() { // if (instance == null) { // instance = new AppManager(); // } // return instance; // } // // /** // * 添加Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<>(); // } // activityStack.add(activity); // } // // // /** // * 包括包名的类 // * // * @param className // * @return // */ // public boolean existClass(String className) { // if (activityStack == null || activityStack.size() == 0 || TextUtils.isEmpty(className)) // return false; // // for (int i = 0; i < activityStack.size(); i++) { // String name = activityStack.get(i).getClass().getName(); // if (className.equals(name)) // return true; // } // return false; // } // // /** // * 获取当前Activity(堆栈中最后一个压入的) // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // public int size() { // return (activityStack == null || activityStack.size() == 0) ? 0 : activityStack.size(); // } // // /** // * 结束当前Activity(堆栈中最后一个压入的) // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // } // } // // public void removeActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // } // } // // /** // * 结束指定类名的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // } // } // } // // /** // * 结束所有Activity // */ // public void finishAllActivity() { // if (activityStack == null || activityStack.size() == 0) // return; // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // /** // * 退出应用程序 // */ // public void exit(Context context) { // try { // finishAllActivity(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // // }
import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.jiang.android.architecture.AppManager; import com.trello.rxlifecycle.LifecycleProvider; import com.trello.rxlifecycle.LifecycleTransformer; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.android.ActivityEvent; import com.trello.rxlifecycle.android.RxLifecycleAndroid; import rx.Observable; import rx.subjects.BehaviorSubject;
package com.jiang.android.architecture.rxsupport; public class RxAppCompatActivity extends AppCompatActivity implements LifecycleProvider<ActivityEvent> { private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable<ActivityEvent> lifecycle() { return lifecycleSubject.asObservable(); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: architecture/src/main/java/com/jiang/android/architecture/AppManager.java // public class AppManager { // private static Stack<Activity> activityStack; // private static AppManager instance; // // // private AppManager() { // } // // /** // * 单一实例 // */ // public static AppManager getAppManager() { // if (instance == null) { // instance = new AppManager(); // } // return instance; // } // // /** // * 添加Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<>(); // } // activityStack.add(activity); // } // // // /** // * 包括包名的类 // * // * @param className // * @return // */ // public boolean existClass(String className) { // if (activityStack == null || activityStack.size() == 0 || TextUtils.isEmpty(className)) // return false; // // for (int i = 0; i < activityStack.size(); i++) { // String name = activityStack.get(i).getClass().getName(); // if (className.equals(name)) // return true; // } // return false; // } // // /** // * 获取当前Activity(堆栈中最后一个压入的) // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // public int size() { // return (activityStack == null || activityStack.size() == 0) ? 0 : activityStack.size(); // } // // /** // * 结束当前Activity(堆栈中最后一个压入的) // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // } // } // // public void removeActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // } // } // // /** // * 结束指定类名的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // } // } // } // // /** // * 结束所有Activity // */ // public void finishAllActivity() { // if (activityStack == null || activityStack.size() == 0) // return; // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // /** // * 退出应用程序 // */ // public void exit(Context context) { // try { // finishAllActivity(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // // } // Path: architecture/src/main/java/com/jiang/android/architecture/rxsupport/RxAppCompatActivity.java import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.jiang.android.architecture.AppManager; import com.trello.rxlifecycle.LifecycleProvider; import com.trello.rxlifecycle.LifecycleTransformer; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.android.ActivityEvent; import com.trello.rxlifecycle.android.RxLifecycleAndroid; import rx.Observable; import rx.subjects.BehaviorSubject; package com.jiang.android.architecture.rxsupport; public class RxAppCompatActivity extends AppCompatActivity implements LifecycleProvider<ActivityEvent> { private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable<ActivityEvent> lifecycle() { return lifecycleSubject.asObservable(); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
AppManager.getAppManager().addActivity(this);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // }
import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder();
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder();
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // }
import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder();
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder();
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // }
import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder(); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() != 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; builder.addHeader(key, value); } } if (params != null && params.size() != 0) {
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java // public class HttpUtils { // // public static String parseParams2String(Map<String, String> param) { // if (param == null || param.size() == 0) // return ""; // // StringBuffer buffer = new StringBuffer(); // Set<Map.Entry<String, String>> entrySet = param.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param par = new Param(entry.getKey(), entry.getValue()); // buffer.append(par.toString()).append("&"); // // } // return buffer.substring(0, buffer.length() - 1); // // } // // // public static boolean isNetworkConnected(Context ct) { // ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo ni = cm.getActiveNetworkInfo(); // return ni != null && ni.isConnectedOrConnecting(); // } // // public static final int NETTYPE_WIFI = 0x01; // public static final int NETTYPE_CMWAP = 0x02; // public static final int NETTYPE_CMNET = 0x03; // // public static int getNetworkType(Context ct) { // int netType = 0; // ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo == null) { // return netType; // } // int nType = networkInfo.getType(); // if (nType == ConnectivityManager.TYPE_MOBILE) { // String extraInfo = networkInfo.getExtraInfo(); // if (!TextUtils.isEmpty(extraInfo)) { // if (extraInfo.toLowerCase().equals("cmnet")) { // netType = NETTYPE_CMNET; // } else { // netType = NETTYPE_CMWAP; // } // } // } else if (nType == ConnectivityManager.TYPE_WIFI) { // netType = NETTYPE_WIFI; // } // return netType; // } // // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java import java.util.List; import java.util.Map; import okhttp3.Request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder(); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() != 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; builder.addHeader(key, value); } } if (params != null && params.size() != 0) {
String par = HttpUtils.parseParams2String(params);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * delete * Created by jiang on 15/10/16. */ public class DeleteRequest { public static Request buildDeleteRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } Request.Builder reqBuilder = new Request.Builder(); if (params != null && params.size() > 0) { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); reqBuilder.delete(requestBody); } else { reqBuilder.delete(); } reqBuilder.url(url);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * delete * Created by jiang on 15/10/16. */ public class DeleteRequest { public static Request buildDeleteRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } Request.Builder reqBuilder = new Request.Builder(); if (params != null && params.size() > 0) { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); reqBuilder.delete(requestBody); } else { reqBuilder.delete(); } reqBuilder.url(url);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils;
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * delete * Created by jiang on 15/10/16. */ public class DeleteRequest { public static Request buildDeleteRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } Request.Builder reqBuilder = new Request.Builder(); if (params != null && params.size() > 0) { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); reqBuilder.delete(requestBody); } else { reqBuilder.delete(); } reqBuilder.url(url);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; /** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; /** * delete * Created by jiang on 15/10/16. */ public class DeleteRequest { public static Request buildDeleteRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } Request.Builder reqBuilder = new Request.Builder(); if (params != null && params.size() > 0) { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); reqBuilder.delete(requestBody); } else { reqBuilder.delete(); } reqBuilder.url(url);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/App.java
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java // public class DbCore { // private static final String DEFAULT_DB_NAME = "collection.db"; // private static DaoMaster daoMaster; // private static DaoSession daoSession; // // private static Context mContext; // private static String DB_NAME; // // public static void init(Context context) { // init(context, DEFAULT_DB_NAME); // } // // public static void init(Context context, String dbName) { // if (context == null) { // throw new IllegalArgumentException("context can't be null"); // } // mContext = context.getApplicationContext(); // DB_NAME = dbName; // } // // public static DaoMaster getDaoMaster() { // if (daoMaster == null) { // DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); // daoMaster = new DaoMaster(helper.getWritableDatabase()); // } // return daoMaster; // } // // public static DaoSession getDaoSession() { // if (daoSession == null) { // if (daoMaster == null) { // daoMaster = getDaoMaster(); // } // daoSession = daoMaster.newSession(); // } // return daoSession; // } // // }
import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.db.DbCore;
package com.jiang.android.zhihu_topanswer; /** * Created by jiang on 2016/12/24. */ public class App extends com.jiang.android.architecture.App { @Override public void onCreate() { super.onCreate();
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java // public class DbCore { // private static final String DEFAULT_DB_NAME = "collection.db"; // private static DaoMaster daoMaster; // private static DaoSession daoSession; // // private static Context mContext; // private static String DB_NAME; // // public static void init(Context context) { // init(context, DEFAULT_DB_NAME); // } // // public static void init(Context context, String dbName) { // if (context == null) { // throw new IllegalArgumentException("context can't be null"); // } // mContext = context.getApplicationContext(); // DB_NAME = dbName; // } // // public static DaoMaster getDaoMaster() { // if (daoMaster == null) { // DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); // daoMaster = new DaoMaster(helper.getWritableDatabase()); // } // return daoMaster; // } // // public static DaoSession getDaoSession() { // if (daoSession == null) { // if (daoMaster == null) { // daoMaster = getDaoMaster(); // } // daoSession = daoMaster.newSession(); // } // return daoSession; // } // // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/App.java import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.db.DbCore; package com.jiang.android.zhihu_topanswer; /** * Created by jiang on 2016/12/24. */ public class App extends com.jiang.android.architecture.App { @Override public void onCreate() { super.onCreate();
DbCore.init(this);
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/App.java
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java // public class DbCore { // private static final String DEFAULT_DB_NAME = "collection.db"; // private static DaoMaster daoMaster; // private static DaoSession daoSession; // // private static Context mContext; // private static String DB_NAME; // // public static void init(Context context) { // init(context, DEFAULT_DB_NAME); // } // // public static void init(Context context, String dbName) { // if (context == null) { // throw new IllegalArgumentException("context can't be null"); // } // mContext = context.getApplicationContext(); // DB_NAME = dbName; // } // // public static DaoMaster getDaoMaster() { // if (daoMaster == null) { // DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); // daoMaster = new DaoMaster(helper.getWritableDatabase()); // } // return daoMaster; // } // // public static DaoSession getDaoSession() { // if (daoSession == null) { // if (daoMaster == null) { // daoMaster = getDaoMaster(); // } // daoSession = daoMaster.newSession(); // } // return daoSession; // } // // }
import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.db.DbCore;
package com.jiang.android.zhihu_topanswer; /** * Created by jiang on 2016/12/24. */ public class App extends com.jiang.android.architecture.App { @Override public void onCreate() { super.onCreate(); DbCore.init(this);
// Path: architecture/src/main/java/com/jiang/android/architecture/utils/L.java // public class L { // // private static boolean isDEBUG = true; // // // public static void debug(boolean debug) { // isDEBUG = debug; // } // // public static void i(String value) { // if (isDEBUG) { // LogUtils.i(value); // } // } // // public static void i(String key, String value) { // if (isDEBUG) { // Log.i(key, value); // } // } // // public static void d(String value) { // if (isDEBUG) { // LogUtils.d(value); // } // } // // // public static void e(String value) { // if (isDEBUG) { // LogUtils.e(value); // } // } // // public static void v(String value) { // if (isDEBUG) { // LogUtils.v(value); // } // } // // // /** // * 打印json // * // * @param value // */ // public static void json(String value) { // if (isDEBUG) { // LogUtils.json(value); // } // } // } // // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/db/DbCore.java // public class DbCore { // private static final String DEFAULT_DB_NAME = "collection.db"; // private static DaoMaster daoMaster; // private static DaoSession daoSession; // // private static Context mContext; // private static String DB_NAME; // // public static void init(Context context) { // init(context, DEFAULT_DB_NAME); // } // // public static void init(Context context, String dbName) { // if (context == null) { // throw new IllegalArgumentException("context can't be null"); // } // mContext = context.getApplicationContext(); // DB_NAME = dbName; // } // // public static DaoMaster getDaoMaster() { // if (daoMaster == null) { // DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); // daoMaster = new DaoMaster(helper.getWritableDatabase()); // } // return daoMaster; // } // // public static DaoSession getDaoSession() { // if (daoSession == null) { // if (daoMaster == null) { // daoMaster = getDaoMaster(); // } // daoSession = daoMaster.newSession(); // } // return daoSession; // } // // } // Path: app/src/main/java/com/jiang/android/zhihu_topanswer/App.java import com.jiang.android.architecture.utils.L; import com.jiang.android.zhihu_topanswer.db.DbCore; package com.jiang.android.zhihu_topanswer; /** * Created by jiang on 2016/12/24. */ public class App extends com.jiang.android.architecture.App { @Override public void onCreate() { super.onCreate(); DbCore.init(this);
L.debug(true);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.List; import java.util.Map; import okhttp3.Request; import okhttp3.RequestBody;
package com.jiang.android.architecture.okhttp.request; /** * Created by jiang on 16/7/28. */ public class UploadRequest { public static Request buildPostRequest(String url, Map<String, String> headers, Object tab, RequestBody requestBody) { Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); reqBuilder.tag(tab);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.List; import java.util.Map; import okhttp3.Request; import okhttp3.RequestBody; package com.jiang.android.architecture.okhttp.request; /** * Created by jiang on 16/7/28. */ public class UploadRequest { public static Request buildPostRequest(String url, Map<String, String> headers, Object tab, RequestBody requestBody) { Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); reqBuilder.tag(tab);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
jiang111/ZhiHu-TopAnswer
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // }
import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.List; import java.util.Map; import okhttp3.Request; import okhttp3.RequestBody;
package com.jiang.android.architecture.okhttp.request; /** * Created by jiang on 16/7/28. */ public class UploadRequest { public static Request buildPostRequest(String url, Map<String, String> headers, Object tab, RequestBody requestBody) { Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); reqBuilder.tag(tab);
// Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java // public class Param { // public Param(String key,String value) { // this.key = key; // this.value = value; // } // // public String key; // public String value; // // // @Override // public String toString() { // return key + "=" + value; // } // } // // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java // public class HeaderUtils { // // public static List<Param> validateHeaders(Map<String, String> header) { // if (header == null || header.size() == 0) // return null; // List<Param> results = new LinkedList<>(); // Set<Map.Entry<String, String>> entrySet = header.entrySet(); // for (Map.Entry<String, String> entry : entrySet) { // Param param = new Param(entry.getKey(), entry.getValue()); // results.add(param); // } // return results; // // // } // } // Path: architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.List; import java.util.Map; import okhttp3.Request; import okhttp3.RequestBody; package com.jiang.android.architecture.okhttp.request; /** * Created by jiang on 16/7/28. */ public class UploadRequest { public static Request buildPostRequest(String url, Map<String, String> headers, Object tab, RequestBody requestBody) { Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); reqBuilder.tag(tab);
List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers);
ehcache/sizeof
src/main/java/org/ehcache/sizeof/SizeOfFilterSource.java
// Path: src/main/java/org/ehcache/sizeof/filters/TypeFilter.java // public class TypeFilter implements SizeOfFilter { // // private final WeakIdentityConcurrentMap<Class<?>, Object> classesIgnored = new WeakIdentityConcurrentMap<>(); // private final WeakIdentityConcurrentMap<Class<?>, Object> superClasses = new WeakIdentityConcurrentMap<>(); // private final WeakIdentityConcurrentMap<Class<?>, ConcurrentMap<Field, Object>> fieldsIgnored = new WeakIdentityConcurrentMap<>(); // // @Override // public Collection<Field> filterFields(final Class<?> klazz, final Collection<Field> fields) { // final ConcurrentMap<Field, Object> fieldsToIgnore = fieldsIgnored.get(klazz); // if (fieldsToIgnore != null) { // fields.removeIf(fieldsToIgnore::containsKey); // } // return fields; // } // // @Override // public boolean filterClass(final Class<?> klazz) { // if (!classesIgnored.containsKey(klazz)) { // for (Class<?> aClass : superClasses.keySet()) { // if (aClass.isAssignableFrom(klazz)) { // classesIgnored.put(klazz, this); // return false; // } // } // return true; // } else { // return false; // } // } // // public void addClass(final Class<?> classToFilterOut, final boolean strict) { // if (!strict) { // superClasses.putIfAbsent(classToFilterOut, this); // } else { // classesIgnored.put(classToFilterOut, this); // } // } // // public void addField(final Field fieldToFilterOut) { // final Class<?> klazz = fieldToFilterOut.getDeclaringClass(); // ConcurrentMap<Field, Object> fields = fieldsIgnored.get(klazz); // if (fields == null) { // fields = new ConcurrentHashMap<>(); // final ConcurrentMap<Field, Object> previous = fieldsIgnored.putIfAbsent(klazz, fields); // if (previous != null) { // fields = previous; // } // } // fields.put(fieldToFilterOut, this); // } // }
import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.ehcache.sizeof.filters.SizeOfFilter; import org.ehcache.sizeof.filters.TypeFilter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList;
/** * Copyright Terracotta, Inc. * * 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 org.ehcache.sizeof; /** * @author Alex Snaps */ public final class SizeOfFilterSource implements Filter { private final CopyOnWriteArrayList<SizeOfFilter> filters = new CopyOnWriteArrayList<>();
// Path: src/main/java/org/ehcache/sizeof/filters/TypeFilter.java // public class TypeFilter implements SizeOfFilter { // // private final WeakIdentityConcurrentMap<Class<?>, Object> classesIgnored = new WeakIdentityConcurrentMap<>(); // private final WeakIdentityConcurrentMap<Class<?>, Object> superClasses = new WeakIdentityConcurrentMap<>(); // private final WeakIdentityConcurrentMap<Class<?>, ConcurrentMap<Field, Object>> fieldsIgnored = new WeakIdentityConcurrentMap<>(); // // @Override // public Collection<Field> filterFields(final Class<?> klazz, final Collection<Field> fields) { // final ConcurrentMap<Field, Object> fieldsToIgnore = fieldsIgnored.get(klazz); // if (fieldsToIgnore != null) { // fields.removeIf(fieldsToIgnore::containsKey); // } // return fields; // } // // @Override // public boolean filterClass(final Class<?> klazz) { // if (!classesIgnored.containsKey(klazz)) { // for (Class<?> aClass : superClasses.keySet()) { // if (aClass.isAssignableFrom(klazz)) { // classesIgnored.put(klazz, this); // return false; // } // } // return true; // } else { // return false; // } // } // // public void addClass(final Class<?> classToFilterOut, final boolean strict) { // if (!strict) { // superClasses.putIfAbsent(classToFilterOut, this); // } else { // classesIgnored.put(classToFilterOut, this); // } // } // // public void addField(final Field fieldToFilterOut) { // final Class<?> klazz = fieldToFilterOut.getDeclaringClass(); // ConcurrentMap<Field, Object> fields = fieldsIgnored.get(klazz); // if (fields == null) { // fields = new ConcurrentHashMap<>(); // final ConcurrentMap<Field, Object> previous = fieldsIgnored.putIfAbsent(klazz, fields); // if (previous != null) { // fields = previous; // } // } // fields.put(fieldToFilterOut, this); // } // } // Path: src/main/java/org/ehcache/sizeof/SizeOfFilterSource.java import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.ehcache.sizeof.filters.SizeOfFilter; import org.ehcache.sizeof.filters.TypeFilter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; /** * Copyright Terracotta, Inc. * * 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 org.ehcache.sizeof; /** * @author Alex Snaps */ public final class SizeOfFilterSource implements Filter { private final CopyOnWriteArrayList<SizeOfFilter> filters = new CopyOnWriteArrayList<>();
private final TypeFilter typeFilter = new TypeFilter();
ehcache/sizeof
src/test/java/org/ehcache/sizeof/FilteredSizeOfTest.java
// Path: src/test/java/org/ehcache/sizeof/filteredtest/AnnotationFilteredPackage.java // public class AnnotationFilteredPackage { // // private final byte[] bigArray = new byte[16 * 1024]; // } // // Path: src/test/java/org/ehcache/sizeof/filteredtest/custom/CustomAnnotationFilteredPackage.java // public class CustomAnnotationFilteredPackage { // }
import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.sizeof.filteredtest.AnnotationFilteredPackage; import org.ehcache.sizeof.filteredtest.custom.CustomAnnotationFilteredPackage; import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat;
/** * Copyright Terracotta, Inc. * * 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 org.ehcache.sizeof; /** * @author Alex Snaps */ public class FilteredSizeOfTest extends AbstractSizeOfTest { private static long deepSizeOf(SizeOf sizeOf, Object... obj) { return sizeOf.deepSizeOf(obj); } @BeforeClass public static void setup() { deepSizeOf(new CrossCheckingSizeOf(), new Object()); System.out.println("Testing for a " + System.getProperty("java.version") + " JDK " + ") on a " + System.getProperty("sun.arch.data.model") + "-bit VM " + "(compressed-oops: " + COMPRESSED_OOPS + ", Hotspot CMS: " + HOTSPOT_CMS + ")"); } @Test public void testAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredClass()), equalTo(0L));
// Path: src/test/java/org/ehcache/sizeof/filteredtest/AnnotationFilteredPackage.java // public class AnnotationFilteredPackage { // // private final byte[] bigArray = new byte[16 * 1024]; // } // // Path: src/test/java/org/ehcache/sizeof/filteredtest/custom/CustomAnnotationFilteredPackage.java // public class CustomAnnotationFilteredPackage { // } // Path: src/test/java/org/ehcache/sizeof/FilteredSizeOfTest.java import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.sizeof.filteredtest.AnnotationFilteredPackage; import org.ehcache.sizeof.filteredtest.custom.CustomAnnotationFilteredPackage; import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; /** * Copyright Terracotta, Inc. * * 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 org.ehcache.sizeof; /** * @author Alex Snaps */ public class FilteredSizeOfTest extends AbstractSizeOfTest { private static long deepSizeOf(SizeOf sizeOf, Object... obj) { return sizeOf.deepSizeOf(obj); } @BeforeClass public static void setup() { deepSizeOf(new CrossCheckingSizeOf(), new Object()); System.out.println("Testing for a " + System.getProperty("java.version") + " JDK " + ") on a " + System.getProperty("sun.arch.data.model") + "-bit VM " + "(compressed-oops: " + COMPRESSED_OOPS + ", Hotspot CMS: " + HOTSPOT_CMS + ")"); } @Test public void testAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredClass()), equalTo(0L));
assertThat(deepSizeOf(sizeOf, new AnnotationFilteredPackage()), equalTo(0L));
ehcache/sizeof
src/test/java/org/ehcache/sizeof/FilteredSizeOfTest.java
// Path: src/test/java/org/ehcache/sizeof/filteredtest/AnnotationFilteredPackage.java // public class AnnotationFilteredPackage { // // private final byte[] bigArray = new byte[16 * 1024]; // } // // Path: src/test/java/org/ehcache/sizeof/filteredtest/custom/CustomAnnotationFilteredPackage.java // public class CustomAnnotationFilteredPackage { // }
import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.sizeof.filteredtest.AnnotationFilteredPackage; import org.ehcache.sizeof.filteredtest.custom.CustomAnnotationFilteredPackage; import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat;
@Test public void testAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredClass()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredPackage()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredFieldSubclass()), allOf(greaterThan(128L), lessThan(16 * 1024L))); long emptyReferrerSize = deepSizeOf(sizeOf, new Referrer(null)); assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredClass())), equalTo(emptyReferrerSize)); assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredPackage())), equalTo(emptyReferrerSize)); assertThat(deepSizeOf(sizeOf, new Parent()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new Child()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new ChildChild()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new ChildChildChild()), equalTo(0L)); } @Test @SuppressWarnings("unchecked") public void testCustomAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new MatchingPatternOrNotAnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotation()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationChild()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationNoInheritedChild()), allOf(greaterThan(4L))); assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation1()), allOf(greaterThan(4L))); assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation2()), allOf(greaterThan(4L)));
// Path: src/test/java/org/ehcache/sizeof/filteredtest/AnnotationFilteredPackage.java // public class AnnotationFilteredPackage { // // private final byte[] bigArray = new byte[16 * 1024]; // } // // Path: src/test/java/org/ehcache/sizeof/filteredtest/custom/CustomAnnotationFilteredPackage.java // public class CustomAnnotationFilteredPackage { // } // Path: src/test/java/org/ehcache/sizeof/FilteredSizeOfTest.java import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.sizeof.filteredtest.AnnotationFilteredPackage; import org.ehcache.sizeof.filteredtest.custom.CustomAnnotationFilteredPackage; import org.ehcache.sizeof.filters.AnnotationSizeOfFilter; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; @Test public void testAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredClass()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredPackage()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new AnnotationFilteredFieldSubclass()), allOf(greaterThan(128L), lessThan(16 * 1024L))); long emptyReferrerSize = deepSizeOf(sizeOf, new Referrer(null)); assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredClass())), equalTo(emptyReferrerSize)); assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredPackage())), equalTo(emptyReferrerSize)); assertThat(deepSizeOf(sizeOf, new Parent()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new Child()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new ChildChild()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new ChildChildChild()), equalTo(0L)); } @Test @SuppressWarnings("unchecked") public void testCustomAnnotationFiltering() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); assertThat(deepSizeOf(sizeOf, new MatchingPatternOrNotAnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotation()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationChild()), equalTo(0L)); assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationNoInheritedChild()), allOf(greaterThan(4L))); assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation1()), allOf(greaterThan(4L))); assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation2()), allOf(greaterThan(4L)));
assertThat(deepSizeOf(sizeOf, new CustomAnnotationFilteredPackage()), equalTo(0L));
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/fragments/InformationFragment.java
// Path: app/src/main/java/com/kaliturin/blacklist/adapters/InformationArrayAdapter.java // public class InformationArrayAdapter extends ArrayAdapter<InformationArrayAdapter.Model> { // private SparseArray<ViewHolder> rowsArray = new SparseArray<>(); // // public InformationArrayAdapter(Context context) { // super(context, 0); // } // // @Override // @NonNull // public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // // get created row by position // View rowView; // ViewHolder viewHolder = rowsArray.get(position); // if (viewHolder != null) { // rowView = viewHolder.rowView; // } else { // // get model by position // Model model = getItem(position); // // get row layout // int layoutId = R.layout.row_info; // if (model != null) { // if (model.type == Model.TITLE) { // layoutId = R.layout.row_title; // } // } // // create row // LayoutInflater inflater = LayoutInflater.from(getContext()); // rowView = inflater.inflate(layoutId, parent, false); // if (model != null) { // viewHolder = new ViewHolder(rowView, model, position); // rowsArray.put(position, viewHolder); // } // } // // return rowView; // } // // private void addModel(int type, @StringRes int titleId, @StringRes int commentId) { // add(new Model(type, getString(titleId), getString(commentId))); // } // // public void addTitle(@StringRes int titleId) { // addModel(Model.TITLE, titleId, 0); // } // // public void addText(@StringRes int commentId) { // addText(null, getString(commentId)); // } // // public void addText(String title, String comment) { // add(new Model(Model.TEXT, title, comment)); // } // // @Nullable // private String getString(@StringRes int stringRes) { // return (stringRes != 0 ? getContext().getString(stringRes) : null); // } // // // Row item data // class Model { // private static final int TITLE = 1; // private static final int TEXT = 2; // // final int type; // final String title; // final String comment; // // Model(int type, String title, String comment) { // this.type = type; // this.title = title; // this.comment = comment; // } // } // // // Row view holder // private class ViewHolder { // final Model model; // final View rowView; // // ViewHolder(View rowView, Model model, int position) { // this.rowView = rowView; // this.model = model; // rowView.setTag(this); // // // title // TextView titleView = (TextView) rowView.findViewById(R.id.text_title); // if (titleView != null) { // if (model.title != null) { // titleView.setText(model.title); // titleView.setVisibility(View.VISIBLE); // } else { // titleView.setVisibility(View.GONE); // } // } // if (model.type == Model.TITLE) { // if (position == 0) { // View borderView = rowView.findViewById(R.id.top_border); // if (borderView != null) { // borderView.setVisibility(View.GONE); // } // } // } // // // comment // if (model.comment != null) { // TextView commentView = (TextView) rowView.findViewById(R.id.text_comment); // if (commentView != null) { // commentView.setText(model.comment); // commentView.setVisibility(View.VISIBLE); // } // } // } // } // }
import com.kaliturin.blacklist.R; import com.kaliturin.blacklist.adapters.InformationArrayAdapter; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView;
/* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.fragments; /** * Information fragment */ public class InformationFragment extends Fragment implements FragmentArguments { private static final String TAG = InformationFragment.class.getName(); private ListView listView = null; private int listPosition = 0; public InformationFragment() { // Required empty public constructor } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // set activity title Bundle arguments = getArguments(); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (arguments != null && actionBar != null) { actionBar.setTitle(arguments.getString(TITLE)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { listPosition = savedInstanceState.getInt(LIST_POSITION, 0); } // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_information, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); listView = (ListView) view.findViewById(R.id.help_list);
// Path: app/src/main/java/com/kaliturin/blacklist/adapters/InformationArrayAdapter.java // public class InformationArrayAdapter extends ArrayAdapter<InformationArrayAdapter.Model> { // private SparseArray<ViewHolder> rowsArray = new SparseArray<>(); // // public InformationArrayAdapter(Context context) { // super(context, 0); // } // // @Override // @NonNull // public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // // get created row by position // View rowView; // ViewHolder viewHolder = rowsArray.get(position); // if (viewHolder != null) { // rowView = viewHolder.rowView; // } else { // // get model by position // Model model = getItem(position); // // get row layout // int layoutId = R.layout.row_info; // if (model != null) { // if (model.type == Model.TITLE) { // layoutId = R.layout.row_title; // } // } // // create row // LayoutInflater inflater = LayoutInflater.from(getContext()); // rowView = inflater.inflate(layoutId, parent, false); // if (model != null) { // viewHolder = new ViewHolder(rowView, model, position); // rowsArray.put(position, viewHolder); // } // } // // return rowView; // } // // private void addModel(int type, @StringRes int titleId, @StringRes int commentId) { // add(new Model(type, getString(titleId), getString(commentId))); // } // // public void addTitle(@StringRes int titleId) { // addModel(Model.TITLE, titleId, 0); // } // // public void addText(@StringRes int commentId) { // addText(null, getString(commentId)); // } // // public void addText(String title, String comment) { // add(new Model(Model.TEXT, title, comment)); // } // // @Nullable // private String getString(@StringRes int stringRes) { // return (stringRes != 0 ? getContext().getString(stringRes) : null); // } // // // Row item data // class Model { // private static final int TITLE = 1; // private static final int TEXT = 2; // // final int type; // final String title; // final String comment; // // Model(int type, String title, String comment) { // this.type = type; // this.title = title; // this.comment = comment; // } // } // // // Row view holder // private class ViewHolder { // final Model model; // final View rowView; // // ViewHolder(View rowView, Model model, int position) { // this.rowView = rowView; // this.model = model; // rowView.setTag(this); // // // title // TextView titleView = (TextView) rowView.findViewById(R.id.text_title); // if (titleView != null) { // if (model.title != null) { // titleView.setText(model.title); // titleView.setVisibility(View.VISIBLE); // } else { // titleView.setVisibility(View.GONE); // } // } // if (model.type == Model.TITLE) { // if (position == 0) { // View borderView = rowView.findViewById(R.id.top_border); // if (borderView != null) { // borderView.setVisibility(View.GONE); // } // } // } // // // comment // if (model.comment != null) { // TextView commentView = (TextView) rowView.findViewById(R.id.text_comment); // if (commentView != null) { // commentView.setText(model.comment); // commentView.setVisibility(View.VISIBLE); // } // } // } // } // } // Path: app/src/main/java/com/kaliturin/blacklist/fragments/InformationFragment.java import com.kaliturin.blacklist.R; import com.kaliturin.blacklist.adapters.InformationArrayAdapter; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.fragments; /** * Information fragment */ public class InformationFragment extends Fragment implements FragmentArguments { private static final String TAG = InformationFragment.class.getName(); private ListView listView = null; private int listPosition = 0; public InformationFragment() { // Required empty public constructor } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // set activity title Bundle arguments = getArguments(); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (arguments != null && actionBar != null) { actionBar.setTitle(arguments.getString(TITLE)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { listPosition = savedInstanceState.getInt(LIST_POSITION, 0); } // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_information, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); listView = (ListView) view.findViewById(R.id.help_list);
InformationArrayAdapter adapter = new InformationArrayAdapter(getContext());
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/services/SMSSendService.java
// Path: app/src/main/java/com/kaliturin/blacklist/utils/SMSSendHelper.java // public class SMSSendHelper { // public static final String PHONE_NUMBER = "PHONE_NUMBER"; // public static final String MESSAGE_ID = "MESSAGE_ID"; // public static final String MESSAGE_PART = "MESSAGE_PART"; // public static final String MESSAGE_PART_ID = "MESSAGE_PART_ID"; // public static final String MESSAGE_PARTS = "MESSAGE_PARTS"; // public static final String DELIVERY = "DELIVERY"; // // // Sends SMS // public boolean sendSMS(Context context, @NonNull String phoneNumber, @NonNull String message) { // if (phoneNumber.isEmpty() || message.isEmpty()) { // return false; // } // // // get application context // context = context.getApplicationContext(); // // // get flag of delivery waiting // boolean delivery = false; // if (Settings.getBooleanValue(context, Settings.DELIVERY_SMS_NOTIFICATION)) { // delivery = true; // } // // // write the sent message to the Outbox // long messageId = writeSMSMessageToOutbox(context, phoneNumber, message); // // // divide message into parts // SmsManager smsManager = getSmsManager(context); // ArrayList<String> messageParts = smsManager.divideMessage(message); // // // create pending intents for each part of message // ArrayList<PendingIntent> sentIntents = new ArrayList<>(messageParts.size()); // ArrayList<PendingIntent> deliveryIntents = new ArrayList<>(messageParts.size()); // for (int i = 0; i < messageParts.size(); i++) { // String messagePart = messageParts.get(i); // int messagePartId = i + 1; // // // pending intent for getting result of SMS sending // PendingIntent pendingIntent = createPendingIntent(context, SMS_SENT, messageId, // phoneNumber, messagePart, messagePartId, messageParts.size(), delivery); // sentIntents.add(pendingIntent); // // if (delivery) { // // pending intent for getting result of SMS delivery // pendingIntent = createPendingIntent(context, SMS_DELIVERY, messageId, // phoneNumber, messagePart, messagePartId, messageParts.size(), true); // deliveryIntents.add(pendingIntent); // } // } // // // send message // smsManager.sendMultipartTextMessage(phoneNumber, null, messageParts, sentIntents, deliveryIntents); // // // send internal event message // InternalEventBroadcast.sendSMSWasWritten(context, phoneNumber); // // return true; // } // // // Writes the sending SMS to the Outbox // private long writeSMSMessageToOutbox(Context context, String phoneNumber, String message) { // long id = -1; // // // if older than KITKAT or if app is default // if (!DefaultSMSAppHelper.isAvailable() || // DefaultSMSAppHelper.isDefault(context)) { // // write SMS to the outbox // ContactsAccessHelper db = ContactsAccessHelper.getInstance(context); // id = db.writeSMSMessageToOutbox(context, phoneNumber, message); // } // // else SMS will be written by the system // // return id; // } // // // Creates pending intent for getting result of SMS sending/delivery // private PendingIntent createPendingIntent(Context context, String action, long messageId, // String phoneNumber, String messagePart, // int messagePartId, int messageParts, boolean delivery) { // // attaches static broadcast receiver for processing the results // Intent intent = new Intent(context, SMSSendResultBroadcastReceiver.class); // intent.setAction(action); // intent.putExtra(MESSAGE_ID, messageId); // intent.putExtra(PHONE_NUMBER, phoneNumber); // intent.putExtra(MESSAGE_PART, messagePart); // intent.putExtra(MESSAGE_PART_ID, messagePartId); // intent.putExtra(MESSAGE_PARTS, messageParts); // intent.putExtra(DELIVERY, delivery); // // return PendingIntent.getBroadcast(context, intent.hashCode(), intent, 0); // } // // // Returns current SmsManager // private SmsManager getSmsManager(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { // Integer subscriptionId = SubscriptionHelper.getCurrentSubscriptionId(context); // if (subscriptionId != null) { // return SmsManager.getSmsManagerForSubscriptionId(subscriptionId); // } // } // // return SmsManager.getDefault(); // } // // }
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; import com.kaliturin.blacklist.utils.SMSSendHelper;
/* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.services; /** * SMS message sending service */ public class SMSSendService extends IntentService { private static final String MESSAGE = "MESSAGE"; private static final String ADDRESSES = "ADDRESSES"; public SMSSendService() { super(SMSSendService.class.getName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { if (intent == null) { return; } // get message body and addresses String message = intent.getStringExtra(MESSAGE); String[] addresses = intent.getStringArrayExtra(ADDRESSES); if (message == null || addresses == null) { return; } // send SMS message
// Path: app/src/main/java/com/kaliturin/blacklist/utils/SMSSendHelper.java // public class SMSSendHelper { // public static final String PHONE_NUMBER = "PHONE_NUMBER"; // public static final String MESSAGE_ID = "MESSAGE_ID"; // public static final String MESSAGE_PART = "MESSAGE_PART"; // public static final String MESSAGE_PART_ID = "MESSAGE_PART_ID"; // public static final String MESSAGE_PARTS = "MESSAGE_PARTS"; // public static final String DELIVERY = "DELIVERY"; // // // Sends SMS // public boolean sendSMS(Context context, @NonNull String phoneNumber, @NonNull String message) { // if (phoneNumber.isEmpty() || message.isEmpty()) { // return false; // } // // // get application context // context = context.getApplicationContext(); // // // get flag of delivery waiting // boolean delivery = false; // if (Settings.getBooleanValue(context, Settings.DELIVERY_SMS_NOTIFICATION)) { // delivery = true; // } // // // write the sent message to the Outbox // long messageId = writeSMSMessageToOutbox(context, phoneNumber, message); // // // divide message into parts // SmsManager smsManager = getSmsManager(context); // ArrayList<String> messageParts = smsManager.divideMessage(message); // // // create pending intents for each part of message // ArrayList<PendingIntent> sentIntents = new ArrayList<>(messageParts.size()); // ArrayList<PendingIntent> deliveryIntents = new ArrayList<>(messageParts.size()); // for (int i = 0; i < messageParts.size(); i++) { // String messagePart = messageParts.get(i); // int messagePartId = i + 1; // // // pending intent for getting result of SMS sending // PendingIntent pendingIntent = createPendingIntent(context, SMS_SENT, messageId, // phoneNumber, messagePart, messagePartId, messageParts.size(), delivery); // sentIntents.add(pendingIntent); // // if (delivery) { // // pending intent for getting result of SMS delivery // pendingIntent = createPendingIntent(context, SMS_DELIVERY, messageId, // phoneNumber, messagePart, messagePartId, messageParts.size(), true); // deliveryIntents.add(pendingIntent); // } // } // // // send message // smsManager.sendMultipartTextMessage(phoneNumber, null, messageParts, sentIntents, deliveryIntents); // // // send internal event message // InternalEventBroadcast.sendSMSWasWritten(context, phoneNumber); // // return true; // } // // // Writes the sending SMS to the Outbox // private long writeSMSMessageToOutbox(Context context, String phoneNumber, String message) { // long id = -1; // // // if older than KITKAT or if app is default // if (!DefaultSMSAppHelper.isAvailable() || // DefaultSMSAppHelper.isDefault(context)) { // // write SMS to the outbox // ContactsAccessHelper db = ContactsAccessHelper.getInstance(context); // id = db.writeSMSMessageToOutbox(context, phoneNumber, message); // } // // else SMS will be written by the system // // return id; // } // // // Creates pending intent for getting result of SMS sending/delivery // private PendingIntent createPendingIntent(Context context, String action, long messageId, // String phoneNumber, String messagePart, // int messagePartId, int messageParts, boolean delivery) { // // attaches static broadcast receiver for processing the results // Intent intent = new Intent(context, SMSSendResultBroadcastReceiver.class); // intent.setAction(action); // intent.putExtra(MESSAGE_ID, messageId); // intent.putExtra(PHONE_NUMBER, phoneNumber); // intent.putExtra(MESSAGE_PART, messagePart); // intent.putExtra(MESSAGE_PART_ID, messagePartId); // intent.putExtra(MESSAGE_PARTS, messageParts); // intent.putExtra(DELIVERY, delivery); // // return PendingIntent.getBroadcast(context, intent.hashCode(), intent, 0); // } // // // Returns current SmsManager // private SmsManager getSmsManager(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { // Integer subscriptionId = SubscriptionHelper.getCurrentSubscriptionId(context); // if (subscriptionId != null) { // return SmsManager.getSmsManagerForSubscriptionId(subscriptionId); // } // } // // return SmsManager.getDefault(); // } // // } // Path: app/src/main/java/com/kaliturin/blacklist/services/SMSSendService.java import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; import com.kaliturin.blacklist.utils.SMSSendHelper; /* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.services; /** * SMS message sending service */ public class SMSSendService extends IntentService { private static final String MESSAGE = "MESSAGE"; private static final String ADDRESSES = "ADDRESSES"; public SMSSendService() { super(SMSSendService.class.getName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { if (intent == null) { return; } // get message body and addresses String message = intent.getStringExtra(MESSAGE); String[] addresses = intent.getStringArrayExtra(ADDRESSES); if (message == null || addresses == null) { return; } // send SMS message
SMSSendHelper smsSendHelper = new SMSSendHelper();
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // }
import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
case FROM_CALLS_LOG: return Permissions.READ_CALL_LOG; case FROM_SMS_LIST: return Permissions.READ_SMS; case FROM_BLACK_LIST: case FROM_WHITE_LIST: return Permissions.WRITE_EXTERNAL_STORAGE; } return null; } // Returns contacts from specified source @Nullable public Cursor getContacts(Context context, ContactSourceType sourceType, @Nullable String filter) { // check permission final String permission = getPermission(sourceType); if (permission == null || !Permissions.isGranted(context, permission)) { return null; } // return contacts switch (sourceType) { case FROM_CONTACTS: return getContacts(filter); case FROM_CALLS_LOG: return getContactsFromCallsLog(filter); case FROM_SMS_LIST: return getContactsFromSMSList(filter); case FROM_BLACK_LIST: { DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context); if (db != null) {
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // } // Path: app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; case FROM_CALLS_LOG: return Permissions.READ_CALL_LOG; case FROM_SMS_LIST: return Permissions.READ_SMS; case FROM_BLACK_LIST: case FROM_WHITE_LIST: return Permissions.WRITE_EXTERNAL_STORAGE; } return null; } // Returns contacts from specified source @Nullable public Cursor getContacts(Context context, ContactSourceType sourceType, @Nullable String filter) { // check permission final String permission = getPermission(sourceType); if (permission == null || !Permissions.isGranted(context, permission)) { return null; } // return contacts switch (sourceType) { case FROM_CONTACTS: return getContacts(filter); case FROM_CALLS_LOG: return getContactsFromCallsLog(filter); case FROM_SMS_LIST: return getContactsFromSMSList(filter); case FROM_BLACK_LIST: { DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context); if (db != null) {
return db.getContacts(DatabaseAccessHelper.Contact.TYPE_BLACK_LIST, filter);
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // }
import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null); return (validate(cursor) ? new ContactCursorWrapper(cursor) : null); } @Nullable private Contact getContact(String number) { Contact contact = null; ContactCursorWrapper cursor = getContactCursor(number); if (cursor != null) { contact = cursor.getContact(false); cursor.close(); } return contact; } @Nullable public Contact getContact(Context context, String number) { if (!Permissions.isGranted(context, Permissions.READ_CONTACTS)) { return null; } return getContact(number); } // Contact's cursor wrapper
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // } // Path: app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null); return (validate(cursor) ? new ContactCursorWrapper(cursor) : null); } @Nullable private Contact getContact(String number) { Contact contact = null; ContactCursorWrapper cursor = getContactCursor(number); if (cursor != null) { contact = cursor.getContact(false); cursor.close(); } return contact; } @Nullable public Contact getContact(Context context, String number) { if (!Permissions.isGranted(context, Permissions.READ_CONTACTS)) { return null; } return getContact(number); } // Contact's cursor wrapper
private class ContactCursorWrapper extends CursorWrapper implements ContactSource {
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // }
import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
@Nullable public Contact getContact(Context context, String number) { if (!Permissions.isGranted(context, Permissions.READ_CONTACTS)) { return null; } return getContact(number); } // Contact's cursor wrapper private class ContactCursorWrapper extends CursorWrapper implements ContactSource { private final int ID; private final int NAME; private ContactCursorWrapper(Cursor cursor) { super(cursor); cursor.moveToFirst(); ID = getColumnIndex(Contacts._ID); NAME = getColumnIndex(Contacts.DISPLAY_NAME); } @Override public Contact getContact() { return getContact(true); } Contact getContact(boolean withNumbers) { long id = getLong(ID); String name = getString(NAME);
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class Contact { // public static final int TYPE_BLACK_LIST = 1; // public static final int TYPE_WHITE_LIST = 2; // // public final long id; // public final String name; // public final int type; // public final List<ContactNumber> numbers; // // Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) { // this.id = id; // this.name = name; // this.type = type; // this.numbers = numbers; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public static class ContactNumber { // public static final int TYPE_EQUALS = 0; // public static final int TYPE_CONTAINS = 1; // public static final int TYPE_STARTS = 2; // public static final int TYPE_ENDS = 3; // // public final long id; // public final String number; // public final int type; // public final long contactId; // // public ContactNumber(long id, @NonNull String number, long contactId) { // this(id, number, TYPE_EQUALS, contactId); // } // // public ContactNumber(long id, @NonNull String number, int type, long contactId) { // this.id = id; // this.number = number; // this.type = type; // this.contactId = contactId; // } // } // // Path: app/src/main/java/com/kaliturin/blacklist/utils/DatabaseAccessHelper.java // public interface ContactSource { // Contact getContact(); // } // Path: app/src/main/java/com/kaliturin/blacklist/utils/ContactsAccessHelper.java import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.MatrixCursor; import android.net.Uri; import android.provider.CallLog.Calls; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.Contact; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactNumber; import com.kaliturin.blacklist.utils.DatabaseAccessHelper.ContactSource; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; @Nullable public Contact getContact(Context context, String number) { if (!Permissions.isGranted(context, Permissions.READ_CONTACTS)) { return null; } return getContact(number); } // Contact's cursor wrapper private class ContactCursorWrapper extends CursorWrapper implements ContactSource { private final int ID; private final int NAME; private ContactCursorWrapper(Cursor cursor) { super(cursor); cursor.moveToFirst(); ID = getColumnIndex(Contacts._ID); NAME = getColumnIndex(Contacts.DISPLAY_NAME); } @Override public Contact getContact() { return getContact(true); } Contact getContact(boolean withNumbers) { long id = getLong(ID); String name = getString(NAME);
List<ContactNumber> numbers = new LinkedList<>();
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/receivers/MMSBroadcastReceiver.java
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DefaultSMSAppHelper.java // public class DefaultSMSAppHelper { // // public static boolean isAvailable() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // } // // public static void updateState(Context context) { // boolean ready = isDefault(context); // enableSMSReceiving(context, ready); // } // // public static void enableSMSReceiving(Context context, boolean enable) { // int state = (enable ? // PackageManager.COMPONENT_ENABLED_STATE_ENABLED : // PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // PackageManager packageManager = context.getPackageManager(); // ComponentName componentName = new ComponentName(context, SMSBroadcastReceiver.class); // packageManager.setComponentEnabledSetting( // componentName, // state, // PackageManager.DONT_KILL_APP); // } // // @TargetApi(19) // public static boolean isDefault(Context context) { // if (!isAvailable()) return true; // String myPackage = context.getPackageName(); // String smsPackage = Telephony.Sms.getDefaultSmsPackage(context); // return (smsPackage != null && smsPackage.equals(myPackage)); // } // // @TargetApi(19) // public static void askForDefaultAppChange(Fragment fragment, int requestCode) { // if (!isAvailable()) return; // Context context = fragment.getContext().getApplicationContext(); // String packageName; // // current app package is already set as default // if (isDefault(context)) { // // get previously saved app package as default // packageName = Settings.getStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE); // } else { // // get blacklist app package as default // packageName = context.getPackageName(); // // save current default sms app package to the settings // String nativePackage = Telephony.Sms.getDefaultSmsPackage(context); // if (nativePackage != null) { // Settings.setStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE, nativePackage); // } // } // // start sms app change dialog // askForDefaultAppChange(fragment, packageName, requestCode); // } // // @TargetApi(19) // private static void askForDefaultAppChange(Fragment fragment, @Nullable String packageName, int requestCode) { // if (!isAvailable()) return; // Intent intent; // if (packageName == null) { // String action; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // action = android.provider.Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS; // } else { // action = android.provider.Settings.ACTION_WIRELESS_SETTINGS; // } // intent = new Intent(action); // } else { // intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); // intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName); // } // fragment.startActivityForResult(intent, requestCode); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kaliturin.blacklist.utils.DefaultSMSAppHelper;
/* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.receivers; /** * MMSBroadcastReceiver stub */ public class MMSBroadcastReceiver extends BroadcastReceiver { private static final String MMS_RECEIVED = "android.provider.Telephony.WAP_PUSH_RECEIVED"; private static final String MMS_DELIVER = "android.provider.Telephony.WAP_PUSH_DELIVER"; private static final String MMS_TYPE = "application/vnd.wap.mms-message"; @Override public void onReceive(Context context, Intent intent) { // check action String action = intent.getAction(); String type = intent.getType(); if (action == null || type == null || !action.equals(getAction()) || !type.equals(MMS_TYPE)) { return; } // if not default sms app
// Path: app/src/main/java/com/kaliturin/blacklist/utils/DefaultSMSAppHelper.java // public class DefaultSMSAppHelper { // // public static boolean isAvailable() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // } // // public static void updateState(Context context) { // boolean ready = isDefault(context); // enableSMSReceiving(context, ready); // } // // public static void enableSMSReceiving(Context context, boolean enable) { // int state = (enable ? // PackageManager.COMPONENT_ENABLED_STATE_ENABLED : // PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // PackageManager packageManager = context.getPackageManager(); // ComponentName componentName = new ComponentName(context, SMSBroadcastReceiver.class); // packageManager.setComponentEnabledSetting( // componentName, // state, // PackageManager.DONT_KILL_APP); // } // // @TargetApi(19) // public static boolean isDefault(Context context) { // if (!isAvailable()) return true; // String myPackage = context.getPackageName(); // String smsPackage = Telephony.Sms.getDefaultSmsPackage(context); // return (smsPackage != null && smsPackage.equals(myPackage)); // } // // @TargetApi(19) // public static void askForDefaultAppChange(Fragment fragment, int requestCode) { // if (!isAvailable()) return; // Context context = fragment.getContext().getApplicationContext(); // String packageName; // // current app package is already set as default // if (isDefault(context)) { // // get previously saved app package as default // packageName = Settings.getStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE); // } else { // // get blacklist app package as default // packageName = context.getPackageName(); // // save current default sms app package to the settings // String nativePackage = Telephony.Sms.getDefaultSmsPackage(context); // if (nativePackage != null) { // Settings.setStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE, nativePackage); // } // } // // start sms app change dialog // askForDefaultAppChange(fragment, packageName, requestCode); // } // // @TargetApi(19) // private static void askForDefaultAppChange(Fragment fragment, @Nullable String packageName, int requestCode) { // if (!isAvailable()) return; // Intent intent; // if (packageName == null) { // String action; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // action = android.provider.Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS; // } else { // action = android.provider.Settings.ACTION_WIRELESS_SETTINGS; // } // intent = new Intent(action); // } else { // intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); // intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName); // } // fragment.startActivityForResult(intent, requestCode); // } // } // Path: app/src/main/java/com/kaliturin/blacklist/receivers/MMSBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kaliturin.blacklist.utils.DefaultSMSAppHelper; /* * Copyright (C) 2017 Anton Kaliturin <kaliturin@gmail.com> * * 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.kaliturin.blacklist.receivers; /** * MMSBroadcastReceiver stub */ public class MMSBroadcastReceiver extends BroadcastReceiver { private static final String MMS_RECEIVED = "android.provider.Telephony.WAP_PUSH_RECEIVED"; private static final String MMS_DELIVER = "android.provider.Telephony.WAP_PUSH_DELIVER"; private static final String MMS_TYPE = "application/vnd.wap.mms-message"; @Override public void onReceive(Context context, Intent intent) { // check action String action = intent.getAction(); String type = intent.getType(); if (action == null || type == null || !action.equals(getAction()) || !type.equals(MMS_TYPE)) { return; } // if not default sms app
if (!DefaultSMSAppHelper.isDefault(context)) {
MammatusTech/qbit-microservices-examples
swagger-client-todo/src/main/java/io/swagger/client/ApiClient.java
// Path: swagger-client-todo/src/main/java/io/swagger/client/auth/HttpBasicAuth.java // public class HttpBasicAuth implements Authentication { // private String username; // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); // try { // headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/ApiKeyAuth.java // public class ApiKeyAuth implements Authentication { // private final String location; // private final String paramName; // // private String apiKey; // private String apiKeyPrefix; // // public ApiKeyAuth(String location, String paramName) { // this.location = location; // this.paramName = paramName; // } // // public String getLocation() { // return location; // } // // public String getParamName() { // return paramName; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getApiKeyPrefix() { // return apiKeyPrefix; // } // // public void setApiKeyPrefix(String apiKeyPrefix) { // this.apiKeyPrefix = apiKeyPrefix; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String value; // if (apiKeyPrefix != null) { // value = apiKeyPrefix + " " + apiKey; // } else { // value = apiKey; // } // if (location == "query") { // queryParams.add(new Pair(paramName, value)); // } else if (location == "header") { // headerParams.put(paramName, value); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/OAuth.java // public class OAuth implements Authentication { // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // // TODO: support oauth // } // }
import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth;
package io.swagger.client; public class ApiClient { private Map<String, Client> hostMap = new HashMap<String, Client>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private boolean debugging = false; private String basePath = "http://localhost:8888/v1"; private Map<String, Authentication> authentications; private DateFormat dateFormat; public ApiClient() { // Use ISO 8601 format for date and datetime. // See https://en.wikipedia.org/wiki/ISO_8601 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap<String, Authentication>(); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } public String getBasePath() { return basePath; } public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; } /** * Get authentications (key: authentication name, value: authentication). */ public Map<String, Authentication> getAuthentications() { return authentications; } /** * Get authentication for the given name. * * @param authName The authentication name * @return The authentication, null if not found */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** * Helper method to set username for the first HTTP basic authentication. */ public void setUsername(String username) { for (Authentication auth : authentications.values()) {
// Path: swagger-client-todo/src/main/java/io/swagger/client/auth/HttpBasicAuth.java // public class HttpBasicAuth implements Authentication { // private String username; // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); // try { // headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/ApiKeyAuth.java // public class ApiKeyAuth implements Authentication { // private final String location; // private final String paramName; // // private String apiKey; // private String apiKeyPrefix; // // public ApiKeyAuth(String location, String paramName) { // this.location = location; // this.paramName = paramName; // } // // public String getLocation() { // return location; // } // // public String getParamName() { // return paramName; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getApiKeyPrefix() { // return apiKeyPrefix; // } // // public void setApiKeyPrefix(String apiKeyPrefix) { // this.apiKeyPrefix = apiKeyPrefix; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String value; // if (apiKeyPrefix != null) { // value = apiKeyPrefix + " " + apiKey; // } else { // value = apiKey; // } // if (location == "query") { // queryParams.add(new Pair(paramName, value)); // } else if (location == "header") { // headerParams.put(paramName, value); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/OAuth.java // public class OAuth implements Authentication { // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // // TODO: support oauth // } // } // Path: swagger-client-todo/src/main/java/io/swagger/client/ApiClient.java import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; package io.swagger.client; public class ApiClient { private Map<String, Client> hostMap = new HashMap<String, Client>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private boolean debugging = false; private String basePath = "http://localhost:8888/v1"; private Map<String, Authentication> authentications; private DateFormat dateFormat; public ApiClient() { // Use ISO 8601 format for date and datetime. // See https://en.wikipedia.org/wiki/ISO_8601 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap<String, Authentication>(); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } public String getBasePath() { return basePath; } public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; } /** * Get authentications (key: authentication name, value: authentication). */ public Map<String, Authentication> getAuthentications() { return authentications; } /** * Get authentication for the given name. * * @param authName The authentication name * @return The authentication, null if not found */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** * Helper method to set username for the first HTTP basic authentication. */ public void setUsername(String username) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
MammatusTech/qbit-microservices-examples
swagger-client-todo/src/main/java/io/swagger/client/ApiClient.java
// Path: swagger-client-todo/src/main/java/io/swagger/client/auth/HttpBasicAuth.java // public class HttpBasicAuth implements Authentication { // private String username; // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); // try { // headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/ApiKeyAuth.java // public class ApiKeyAuth implements Authentication { // private final String location; // private final String paramName; // // private String apiKey; // private String apiKeyPrefix; // // public ApiKeyAuth(String location, String paramName) { // this.location = location; // this.paramName = paramName; // } // // public String getLocation() { // return location; // } // // public String getParamName() { // return paramName; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getApiKeyPrefix() { // return apiKeyPrefix; // } // // public void setApiKeyPrefix(String apiKeyPrefix) { // this.apiKeyPrefix = apiKeyPrefix; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String value; // if (apiKeyPrefix != null) { // value = apiKeyPrefix + " " + apiKey; // } else { // value = apiKey; // } // if (location == "query") { // queryParams.add(new Pair(paramName, value)); // } else if (location == "header") { // headerParams.put(paramName, value); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/OAuth.java // public class OAuth implements Authentication { // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // // TODO: support oauth // } // }
import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth;
* Helper method to set username for the first HTTP basic authentication. */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set password for the first HTTP basic authentication. */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set API key value for the first API key authentication. */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) {
// Path: swagger-client-todo/src/main/java/io/swagger/client/auth/HttpBasicAuth.java // public class HttpBasicAuth implements Authentication { // private String username; // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); // try { // headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/ApiKeyAuth.java // public class ApiKeyAuth implements Authentication { // private final String location; // private final String paramName; // // private String apiKey; // private String apiKeyPrefix; // // public ApiKeyAuth(String location, String paramName) { // this.location = location; // this.paramName = paramName; // } // // public String getLocation() { // return location; // } // // public String getParamName() { // return paramName; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getApiKeyPrefix() { // return apiKeyPrefix; // } // // public void setApiKeyPrefix(String apiKeyPrefix) { // this.apiKeyPrefix = apiKeyPrefix; // } // // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // String value; // if (apiKeyPrefix != null) { // value = apiKeyPrefix + " " + apiKey; // } else { // value = apiKey; // } // if (location == "query") { // queryParams.add(new Pair(paramName, value)); // } else if (location == "header") { // headerParams.put(paramName, value); // } // } // } // // Path: swagger-client-todo/src/main/java/io/swagger/client/auth/OAuth.java // public class OAuth implements Authentication { // @Override // public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // // TODO: support oauth // } // } // Path: swagger-client-todo/src/main/java/io/swagger/client/ApiClient.java import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; * Helper method to set username for the first HTTP basic authentication. */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set password for the first HTTP basic authentication. */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set API key value for the first API key authentication. */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
MammatusTech/qbit-microservices-examples
swagger-client-resource-url/src/main/java/io/swagger/client/model/Department.java
// Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/Employee.java // @ApiModel(description = "") // public class Employee { // // private Long id = null; // private String name = null; // private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(); // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("id") // public Long getId() { // return id; // } // public void setId(Long id) { // this.id = id; // } // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("name") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("phoneNumbers") // public List<PhoneNumber> getPhoneNumbers() { // return phoneNumbers; // } // public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { // this.phoneNumbers = phoneNumbers; // } // // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("class Employee {\n"); // // sb.append(" id: ").append(id).append("\n"); // sb.append(" name: ").append(name).append("\n"); // sb.append(" phoneNumbers: ").append(phoneNumbers).append("\n"); // sb.append("}\n"); // return sb.toString(); // } // }
import io.swagger.client.model.Employee; import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty;
package io.swagger.client.model; @ApiModel(description = "") public class Department { private Long id = null;
// Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/Employee.java // @ApiModel(description = "") // public class Employee { // // private Long id = null; // private String name = null; // private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(); // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("id") // public Long getId() { // return id; // } // public void setId(Long id) { // this.id = id; // } // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("name") // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("phoneNumbers") // public List<PhoneNumber> getPhoneNumbers() { // return phoneNumbers; // } // public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { // this.phoneNumbers = phoneNumbers; // } // // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("class Employee {\n"); // // sb.append(" id: ").append(id).append("\n"); // sb.append(" name: ").append(name).append("\n"); // sb.append(" phoneNumbers: ").append(phoneNumbers).append("\n"); // sb.append("}\n"); // return sb.toString(); // } // } // Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/Department.java import io.swagger.client.model.Employee; import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; package io.swagger.client.model; @ApiModel(description = "") public class Department { private Long id = null;
private List<Employee> employeeList = new ArrayList<Employee>();
MammatusTech/qbit-microservices-examples
swagger-client-resource-url/src/main/java/io/swagger/client/model/Employee.java
// Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/PhoneNumber.java // @ApiModel(description = "") // public class PhoneNumber { // // private String phoneNumber = null; // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("phoneNumber") // public String getPhoneNumber() { // return phoneNumber; // } // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("class PhoneNumber {\n"); // // sb.append(" phoneNumber: ").append(phoneNumber).append("\n"); // sb.append("}\n"); // return sb.toString(); // } // }
import io.swagger.client.model.PhoneNumber; import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty;
package io.swagger.client.model; @ApiModel(description = "") public class Employee { private Long id = null; private String name = null;
// Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/PhoneNumber.java // @ApiModel(description = "") // public class PhoneNumber { // // private String phoneNumber = null; // // // /** // **/ // @ApiModelProperty(value = "") // @JsonProperty("phoneNumber") // public String getPhoneNumber() { // return phoneNumber; // } // public void setPhoneNumber(String phoneNumber) { // this.phoneNumber = phoneNumber; // } // // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("class PhoneNumber {\n"); // // sb.append(" phoneNumber: ").append(phoneNumber).append("\n"); // sb.append("}\n"); // return sb.toString(); // } // } // Path: swagger-client-resource-url/src/main/java/io/swagger/client/model/Employee.java import io.swagger.client.model.PhoneNumber; import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; package io.swagger.client.model; @ApiModel(description = "") public class Employee { private Long id = null; private String name = null;
private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
jeluard/stone
implementations/dispatchers/blocking-queue/src/main/java/com/github/jeluard/stone/dispatcher/blocking_queue/BlockingQueueDispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.blocking_queue; /** * {@link Dispatcher} implementation executing {@link Listener#onPublication(long, long, int)} * through a {@link ExecutorService} waiting for new execution to be available via a {@link BlockingQueue}. */ public class BlockingQueueDispatcher extends Dispatcher { /** * Holder for {@link Listener#onPublication(long, long, int)} invocation details. */ public static final class Entry { public final long previousTimestamp; public final long currentTimestamp; public final int value;
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: implementations/dispatchers/blocking-queue/src/main/java/com/github/jeluard/stone/dispatcher/blocking_queue/BlockingQueueDispatcher.java import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.blocking_queue; /** * {@link Dispatcher} implementation executing {@link Listener#onPublication(long, long, int)} * through a {@link ExecutorService} waiting for new execution to be available via a {@link BlockingQueue}. */ public class BlockingQueueDispatcher extends Dispatcher { /** * Holder for {@link Listener#onPublication(long, long, int)} invocation details. */ public static final class Entry { public final long previousTimestamp; public final long currentTimestamp; public final int value;
public final Listener listener;
jeluard/stone
implementations/dispatchers/blocking-queue/src/main/java/com/github/jeluard/stone/dispatcher/blocking_queue/BlockingQueueDispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger;
public Entry(final long previousTimestamp, final long currentTimestamp, final int value, final Listener listener) { this.previousTimestamp = previousTimestamp; this.currentTimestamp = currentTimestamp; this.value = value; this.listener = listener; } } private final class Consumer implements Runnable { @Override public void run() { try { while (true) { final Entry entry = BlockingQueueDispatcher.this.queue.take(); try { entry.listener.onPublication(entry.previousTimestamp, entry.currentTimestamp, entry.value); } catch (Exception e) { notifyExceptionHandler(e); } } } catch (InterruptedException e) { if (BlockingQueueDispatcher.LOGGER.isLoggable(Level.INFO)) { BlockingQueueDispatcher.LOGGER.log(Level.INFO, "Consumer <{0}> interrupted; letting it die", Thread.currentThread().getName()); } } } }
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: implementations/dispatchers/blocking-queue/src/main/java/com/github/jeluard/stone/dispatcher/blocking_queue/BlockingQueueDispatcher.java import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; public Entry(final long previousTimestamp, final long currentTimestamp, final int value, final Listener listener) { this.previousTimestamp = previousTimestamp; this.currentTimestamp = currentTimestamp; this.value = value; this.listener = listener; } } private final class Consumer implements Runnable { @Override public void run() { try { while (true) { final Entry entry = BlockingQueueDispatcher.this.queue.take(); try { entry.listener.onPublication(entry.previousTimestamp, entry.currentTimestamp, entry.value); } catch (Exception e) { notifyExceptionHandler(e); } } } catch (InterruptedException e) { if (BlockingQueueDispatcher.LOGGER.isLoggable(Level.INFO)) { BlockingQueueDispatcher.LOGGER.log(Level.INFO, "Consumer <{0}> interrupted; letting it die", Thread.currentThread().getName()); } } } }
private static final Logger LOGGER = Loggers.create("dispatcher.blocking-queue");
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/WindowTest.java
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowTest extends AbstractTest<Window> { private static final int DURATION_TWO = 2; private static final int DURATION_THREE = 3; @Rule
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/api/WindowTest.java import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowTest extends AbstractTest<Window> { private static final int DURATION_TWO = 2; private static final int DURATION_THREE = 3; @Rule
public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/WindowTest.java
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowTest extends AbstractTest<Window> { private static final int DURATION_TWO = 2; private static final int DURATION_THREE = 3; @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<Window> getType() { return Window.class; } @Override protected Window createInstance() throws Exception {
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/api/WindowTest.java import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowTest extends AbstractTest<Window> { private static final int DURATION_TWO = 2; private static final int DURATION_THREE = 3; @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<Window> getType() { return Window.class; } @Override protected Window createInstance() throws Exception {
return Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/WindowTest.java
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
@Override protected Window createInstance() throws Exception { return Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class); } @Test(expected=IllegalArgumentException.class) public void shouldNegativeSizeBeInvalid() { Window.of(-1).consolidatedBy(MaxConsolidator.class); } @Test(expected=IllegalArgumentException.class) public void shouldTooSmallSizeBeInvalid() { Window.of(1).consolidatedBy(MaxConsolidator.class); } @Test public void shouldWindowBeCorrectlyCreated() { Assert.assertEquals(WindowTest.DURATION_TWO, Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).getSize()); Assert.assertEquals(Collections.singletonList(MaxConsolidator.class), Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).getConsolidatorTypes()); } @Test public void shouldListenerBeAccessibleIfProvided() { Assert.assertFalse (Window.of(WindowTest.DURATION_TWO).listenedBy(Mockito.mock(ConsolidationListener.class)).consolidatedBy(MaxConsolidator.class).getConsolidationListeners().isEmpty()); } @Test public void shouldEqualsRelyOnAllArgument() { Assert.assertFalse(Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).equals(Window.of(WindowTest.DURATION_THREE).consolidatedBy(MaxConsolidator.class)));
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/api/WindowTest.java import com.github.jeluard.guayaba.test.AbstractTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.helper.Loggers; import java.util.Collections; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; @Override protected Window createInstance() throws Exception { return Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class); } @Test(expected=IllegalArgumentException.class) public void shouldNegativeSizeBeInvalid() { Window.of(-1).consolidatedBy(MaxConsolidator.class); } @Test(expected=IllegalArgumentException.class) public void shouldTooSmallSizeBeInvalid() { Window.of(1).consolidatedBy(MaxConsolidator.class); } @Test public void shouldWindowBeCorrectlyCreated() { Assert.assertEquals(WindowTest.DURATION_TWO, Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).getSize()); Assert.assertEquals(Collections.singletonList(MaxConsolidator.class), Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).getConsolidatorTypes()); } @Test public void shouldListenerBeAccessibleIfProvided() { Assert.assertFalse (Window.of(WindowTest.DURATION_TWO).listenedBy(Mockito.mock(ConsolidationListener.class)).consolidatedBy(MaxConsolidator.class).getConsolidationListeners().isEmpty()); } @Test public void shouldEqualsRelyOnAllArgument() { Assert.assertFalse(Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).equals(Window.of(WindowTest.DURATION_THREE).consolidatedBy(MaxConsolidator.class)));
Assert.assertFalse(Window.of(WindowTest.DURATION_TWO).consolidatedBy(MaxConsolidator.class).equals(Window.of(WindowTest.DURATION_TWO).consolidatedBy(MinConsolidator.class)));
jeluard/stone
core/src/main/java/com/github/jeluard/stone/spi/StorageFactory.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.util.concurrent.ConcurrentMaps; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import javax.annotation.concurrent.ThreadSafe;
}); } /** * @param id * @param maximumSize * @return an initialized {@link Storage} unique for this {@code id} * @throws IOException */ protected abstract T create(String id, int maximumSize) throws IOException; /** * @return all currently created {@link Storage}s */ protected final Iterable<T> getStorages() { return this.cache.values(); } /** * {@inheritDoc} */ @Idempotent @Override public final void close() throws IOException { cleanup(); for (final T storage : this.cache.values()) { try { close(storage); } catch (IOException e) {
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/main/java/com/github/jeluard/stone/spi/StorageFactory.java import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.util.concurrent.ConcurrentMaps; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import javax.annotation.concurrent.ThreadSafe; }); } /** * @param id * @param maximumSize * @return an initialized {@link Storage} unique for this {@code id} * @throws IOException */ protected abstract T create(String id, int maximumSize) throws IOException; /** * @return all currently created {@link Storage}s */ protected final Iterable<T> getStorages() { return this.cache.values(); } /** * {@inheritDoc} */ @Idempotent @Override public final void close() throws IOException { cleanup(); for (final T storage : this.cache.values()) { try { close(storage); } catch (IOException e) {
if (Loggers.BASE_LOGGER.isLoggable(Level.WARNING)) {
jeluard/stone
core/src/main/java/com/github/jeluard/stone/api/WindowedTimeSeries.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Consolidators.java // public final class Consolidators { // // private Consolidators() { // } // // /** // * Instantiate a {@link Consolidator} from specified {@code type}. // * First look for a constructor accepting an int as unique argument then fallback to the default constructor. // * // * @param type // * @param maxSamples // * @return a {@link Consolidator} from specified {@code type} // */ // public static Consolidator createConsolidator(final Class<? extends Consolidator> type, final int maxSamples) { // Preconditions.checkNotNull(type, "null type"); // Preconditions2.checkSize(maxSamples); // // try { // //First look for a constructor accepting int as argument // try { // return type.getConstructor(int.class).newInstance(maxSamples); // } catch (NoSuchMethodException e) { // if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { // Loggers.BASE_LOGGER.log(Level.FINEST, "{0} does not define a constructor accepting int", type.getCanonicalName()); // } // } // // //If we can't find such fallback to defaut constructor // try { // final Constructor<? extends Consolidator> defaultConstructor = type.getConstructor(); // return defaultConstructor.newInstance(); // } catch (NoSuchMethodException e) { // throw new IllegalArgumentException("Failed to find int or default constructor for "+type.getCanonicalName(), e); // } // } catch (ReflectiveOperationException e) { // throw new RuntimeException(e); // } // } // // /** // * @param consolidatorTypes // * @param maxSamples // * @return all {@link Consolidator} instances // * @see #createConsolidator(java.lang.Class) // */ // public static Consolidator[] createConsolidators(final List<? extends Class<? extends Consolidator>> consolidatorTypes, final int maxSamples) { // Preconditions.checkNotNull(consolidatorTypes, "null consolidatorTypes"); // Preconditions2.checkSize(maxSamples); // // final Consolidator[] consolidators = new Consolidator[consolidatorTypes.size()]; // for (final Iterables2.Indexed<? extends Class<? extends Consolidator>> indexed : Iterables2.withIndex(consolidatorTypes)) { // consolidators[indexed.index] = createConsolidator(indexed.value, maxSamples); // } // return consolidators; // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.stone.helper.Consolidators; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
@Override public void onPublication(final long previousTimestamp, final long currentTimestamp, final int value) { recordBeginningTimestampIfNeeded(previousTimestamp, currentTimestamp); final long currentWindowId = windowId(currentTimestamp); final long previousWindowId = windowId(previousTimestamp); final boolean newWindow = previousWindowId >= 0 && currentWindowId != previousWindowId; //New window, previous timestamp didn't trigger a consolidation (wasn't last slot): trigger it now. if (newWindow) { if (!isLatestFromWindow(previousTimestamp)) { final long previousWindowEnd = windowEnd(previousWindowId); generateConsolidatesThenNotify(previousWindowEnd); } } accumulate(currentTimestamp, value); //Last slot: trigger a consolidation. if (isLatestFromWindow(currentTimestamp)) { generateConsolidatesThenNotify(currentTimestamp); } } } /** * @param id * @param granularity * @param windows * @param dispatcher */
// Path: core/src/main/java/com/github/jeluard/stone/helper/Consolidators.java // public final class Consolidators { // // private Consolidators() { // } // // /** // * Instantiate a {@link Consolidator} from specified {@code type}. // * First look for a constructor accepting an int as unique argument then fallback to the default constructor. // * // * @param type // * @param maxSamples // * @return a {@link Consolidator} from specified {@code type} // */ // public static Consolidator createConsolidator(final Class<? extends Consolidator> type, final int maxSamples) { // Preconditions.checkNotNull(type, "null type"); // Preconditions2.checkSize(maxSamples); // // try { // //First look for a constructor accepting int as argument // try { // return type.getConstructor(int.class).newInstance(maxSamples); // } catch (NoSuchMethodException e) { // if (Loggers.BASE_LOGGER.isLoggable(Level.FINEST)) { // Loggers.BASE_LOGGER.log(Level.FINEST, "{0} does not define a constructor accepting int", type.getCanonicalName()); // } // } // // //If we can't find such fallback to defaut constructor // try { // final Constructor<? extends Consolidator> defaultConstructor = type.getConstructor(); // return defaultConstructor.newInstance(); // } catch (NoSuchMethodException e) { // throw new IllegalArgumentException("Failed to find int or default constructor for "+type.getCanonicalName(), e); // } // } catch (ReflectiveOperationException e) { // throw new RuntimeException(e); // } // } // // /** // * @param consolidatorTypes // * @param maxSamples // * @return all {@link Consolidator} instances // * @see #createConsolidator(java.lang.Class) // */ // public static Consolidator[] createConsolidators(final List<? extends Class<? extends Consolidator>> consolidatorTypes, final int maxSamples) { // Preconditions.checkNotNull(consolidatorTypes, "null consolidatorTypes"); // Preconditions2.checkSize(maxSamples); // // final Consolidator[] consolidators = new Consolidator[consolidatorTypes.size()]; // for (final Iterables2.Indexed<? extends Class<? extends Consolidator>> indexed : Iterables2.withIndex(consolidatorTypes)) { // consolidators[indexed.index] = createConsolidator(indexed.value, maxSamples); // } // return consolidators; // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/main/java/com/github/jeluard/stone/api/WindowedTimeSeries.java import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.stone.helper.Consolidators; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Override public void onPublication(final long previousTimestamp, final long currentTimestamp, final int value) { recordBeginningTimestampIfNeeded(previousTimestamp, currentTimestamp); final long currentWindowId = windowId(currentTimestamp); final long previousWindowId = windowId(previousTimestamp); final boolean newWindow = previousWindowId >= 0 && currentWindowId != previousWindowId; //New window, previous timestamp didn't trigger a consolidation (wasn't last slot): trigger it now. if (newWindow) { if (!isLatestFromWindow(previousTimestamp)) { final long previousWindowEnd = windowEnd(previousWindowId); generateConsolidatesThenNotify(previousWindowEnd); } } accumulate(currentTimestamp, value); //Last slot: trigger a consolidation. if (isLatestFromWindow(currentTimestamp)) { generateConsolidatesThenNotify(currentTimestamp); } } } /** * @param id * @param granularity * @param windows * @param dispatcher */
public WindowedTimeSeries(final String id, final int granularity, final List<Window> windows, final Dispatcher dispatcher) throws IOException {
jeluard/stone
core/src/main/java/com/github/jeluard/stone/helper/Consolidators.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // }
import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Iterables2; import com.github.jeluard.stone.api.Consolidator; import com.google.common.base.Preconditions; import java.lang.reflect.Constructor; import java.util.List; import java.util.logging.Level;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; /** * Helper methods for {@link Consolidator}. */ public final class Consolidators { private Consolidators() { } /** * Instantiate a {@link Consolidator} from specified {@code type}. * First look for a constructor accepting an int as unique argument then fallback to the default constructor. * * @param type * @param maxSamples * @return a {@link Consolidator} from specified {@code type} */
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // Path: core/src/main/java/com/github/jeluard/stone/helper/Consolidators.java import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Iterables2; import com.github.jeluard.stone.api.Consolidator; import com.google.common.base.Preconditions; import java.lang.reflect.Constructor; import java.util.List; import java.util.logging.Level; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; /** * Helper methods for {@link Consolidator}. */ public final class Consolidators { private Consolidators() { } /** * Instantiate a {@link Consolidator} from specified {@code type}. * First look for a constructor accepting an int as unique argument then fallback to the default constructor. * * @param type * @param maxSamples * @return a {@link Consolidator} from specified {@code type} */
public static Consolidator createConsolidator(final Class<? extends Consolidator> type, final int maxSamples) {
jeluard/stone
core/src/main/java/com/github/jeluard/stone/helper/Storages.java
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // }
import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; /** * Helper methods for {@link Storage}. */ public final class Storages { private static class StorageWrapper implements ConsolidationListener, ConsolidationListener.Persistent {
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // } // Path: core/src/main/java/com/github/jeluard/stone/helper/Storages.java import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; /** * Helper methods for {@link Storage}. */ public final class Storages { private static class StorageWrapper implements ConsolidationListener, ConsolidationListener.Persistent {
private final Storage storage;
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/TimeSeriesBenchmark.java
// Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.carrotsearch.junitbenchmarks.AbstractBenchmark; import com.github.jeluard.stone.spi.Dispatcher; import java.io.IOException; import java.util.Arrays; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesBenchmark extends AbstractBenchmark { private final TimeSeries createTimeSeries() throws IOException { final Listener listener = new Listener() { @Override public void onPublication(long previousTimestamp, long currentTimestamp, int value) { } };
// Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/test/java/com/github/jeluard/stone/api/TimeSeriesBenchmark.java import com.carrotsearch.junitbenchmarks.AbstractBenchmark; import com.github.jeluard.stone.spi.Dispatcher; import java.io.IOException; import java.util.Arrays; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesBenchmark extends AbstractBenchmark { private final TimeSeries createTimeSeries() throws IOException { final Listener listener = new Listener() { @Override public void onPublication(long previousTimestamp, long currentTimestamp, int value) { } };
return new TimeSeries("id", 1, Arrays.asList(listener), Mockito.mock(Dispatcher.class));
jeluard/stone
implementations/dispatchers/disruptor/src/main/java/com/github/jeluard/stone/dispatcher/disruptor/DisruptorDispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import com.lmax.disruptor.AbstractMultithreadedClaimStrategy; import com.lmax.disruptor.EventFactory; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.MultiThreadedLowContentionClaimStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SleepingWaitStrategy; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.disruptor; public class DisruptorDispatcher extends Dispatcher implements Cancelable { /** * {@link RingBuffer} event encapsulating a {@link DataPoint}. */ private static final class Event { private volatile long previousTimestamp; private volatile long currentTimestamp; private volatile int value;
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: implementations/dispatchers/disruptor/src/main/java/com/github/jeluard/stone/dispatcher/disruptor/DisruptorDispatcher.java import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import com.lmax.disruptor.AbstractMultithreadedClaimStrategy; import com.lmax.disruptor.EventFactory; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.MultiThreadedLowContentionClaimStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SleepingWaitStrategy; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.disruptor; public class DisruptorDispatcher extends Dispatcher implements Cancelable { /** * {@link RingBuffer} event encapsulating a {@link DataPoint}. */ private static final class Event { private volatile long previousTimestamp; private volatile long currentTimestamp; private volatile int value;
private volatile Listener listener;
jeluard/stone
implementations/dispatchers/disruptor/src/main/java/com/github/jeluard/stone/dispatcher/disruptor/DisruptorDispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import com.lmax.disruptor.AbstractMultithreadedClaimStrategy; import com.lmax.disruptor.EventFactory; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.MultiThreadedLowContentionClaimStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SleepingWaitStrategy; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.disruptor; public class DisruptorDispatcher extends Dispatcher implements Cancelable { /** * {@link RingBuffer} event encapsulating a {@link DataPoint}. */ private static final class Event { private volatile long previousTimestamp; private volatile long currentTimestamp; private volatile int value; private volatile Listener listener; /** * Unique {@link EventFactory} instance for all published arguments. */ private static final EventFactory<Event> EVENT_FACTORY = new EventFactory<Event>() { @Override public Event newInstance() { return new Event(); } }; }
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: implementations/dispatchers/disruptor/src/main/java/com/github/jeluard/stone/dispatcher/disruptor/DisruptorDispatcher.java import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.guayaba.lang.Cancelable; import com.github.jeluard.guayaba.util.concurrent.ThreadFactoryBuilders; import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Preconditions; import com.lmax.disruptor.AbstractMultithreadedClaimStrategy; import com.lmax.disruptor.EventFactory; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.MultiThreadedLowContentionClaimStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SleepingWaitStrategy; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.disruptor; public class DisruptorDispatcher extends Dispatcher implements Cancelable { /** * {@link RingBuffer} event encapsulating a {@link DataPoint}. */ private static final class Event { private volatile long previousTimestamp; private volatile long currentTimestamp; private volatile int value; private volatile Listener listener; /** * Unique {@link EventFactory} instance for all published arguments. */ private static final EventFactory<Event> EVENT_FACTORY = new EventFactory<Event>() { @Override public Event newInstance() { return new Event(); } }; }
static final Logger LOGGER = Loggers.create("dispatcher.disruptor");
jeluard/stone
core/src/test/java/com/github/jeluard/stone/spi/BaseDispatcherTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // }
import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Listener; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; public abstract class BaseDispatcherTest<T extends Dispatcher> { @Rule public LoggerRule loggerRule = new LoggerRule(Dispatcher.LOGGER); protected T createDispatcher() { return createDispatcher(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } protected abstract T createDispatcher(Dispatcher.ExceptionHandler exceptionHandler);
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // Path: core/src/test/java/com/github/jeluard/stone/spi/BaseDispatcherTest.java import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Listener; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; public abstract class BaseDispatcherTest<T extends Dispatcher> { @Rule public LoggerRule loggerRule = new LoggerRule(Dispatcher.LOGGER); protected T createDispatcher() { return createDispatcher(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } protected abstract T createDispatcher(Dispatcher.ExceptionHandler exceptionHandler);
protected Listener createListener() {
jeluard/stone
implementations/dispatchers/sequential/src/main/java/com/github/jeluard/stone/dispatcher/sequential/SequentialDispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.spi.Dispatcher;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.sequential; /** * {@link Dispatcher} implementation executing {@link Listener} one by one using caller thread. */ public class SequentialDispatcher extends Dispatcher { public SequentialDispatcher() { this(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } public SequentialDispatcher(final ExceptionHandler exceptionHandler) { super(exceptionHandler); } @Override
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: implementations/dispatchers/sequential/src/main/java/com/github/jeluard/stone/dispatcher/sequential/SequentialDispatcher.java import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.spi.Dispatcher; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.dispatcher.sequential; /** * {@link Dispatcher} implementation executing {@link Listener} one by one using caller thread. */ public class SequentialDispatcher extends Dispatcher { public SequentialDispatcher() { this(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } public SequentialDispatcher(final ExceptionHandler exceptionHandler) { super(exceptionHandler); } @Override
public boolean dispatch(final long previousTimestamp, final long currentTimestamp, final int value, final Listener[] listeners) {
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/WindowedTimeSeriesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowedTimeSeriesTest { private static class DumbDispatcher extends Dispatcher { public DumbDispatcher() { super(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } @Override public boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners) { for (final Listener listener : listeners) { listener.onPublication(previousTimestamp, currentTimestamp, value); } return true; } } private static class PersistentConsolidationListener implements ConsolidationListener, ConsolidationListener.Persistent { private final Optional<Long> timestamp; public PersistentConsolidationListener(final Optional<Long> timestamp) { this.timestamp = timestamp; } @Override public Optional<Long> getLatestTimestamp() { return this.timestamp; } @Override public void onConsolidation(long timestamp, int[] consolidates) { } } @Test public void shouldWindowWithoutListenerDoNothing() throws IOException {
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/test/java/com/github/jeluard/stone/api/WindowedTimeSeriesTest.java import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class WindowedTimeSeriesTest { private static class DumbDispatcher extends Dispatcher { public DumbDispatcher() { super(Dispatcher.DEFAULT_EXCEPTION_HANDLER); } @Override public boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners) { for (final Listener listener : listeners) { listener.onPublication(previousTimestamp, currentTimestamp, value); } return true; } } private static class PersistentConsolidationListener implements ConsolidationListener, ConsolidationListener.Persistent { private final Optional<Long> timestamp; public PersistentConsolidationListener(final Optional<Long> timestamp) { this.timestamp = timestamp; } @Override public Optional<Long> getLatestTimestamp() { return this.timestamp; } @Override public void onConsolidation(long timestamp, int[] consolidates) { } } @Test public void shouldWindowWithoutListenerDoNothing() throws IOException {
final Window window = Window.of(10).consolidatedBy(MaxConsolidator.class);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/WindowedTimeSeriesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito;
public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class); final Window window = Window.of(3).listenedBy(consolidationListener).consolidatedBy(MaxConsolidator.class); final WindowedTimeSeries timeSeries = new WindowedTimeSeries("id", 1, Arrays.asList(window), new DumbDispatcher()); timeSeries.publish(1, 1); timeSeries.publish(2, 1); timeSeries.publish(3, 1); Mockito.verify(consolidationListener).onConsolidation(Mockito.anyLong(), Mockito.<int[]>any()); timeSeries.close(); Mockito.verifyNoMoreInteractions(consolidationListener); } @Test public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished2() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class); final Window window = Window.of(3).listenedBy(consolidationListener).consolidatedBy(MaxConsolidator.class); final WindowedTimeSeries timeSeries = new WindowedTimeSeries("id", 1, Arrays.asList(window), new DumbDispatcher()); timeSeries.publish(1, 1); timeSeries.publish(3, 1); timeSeries.close(); Mockito.verify(consolidationListener).onConsolidation(Mockito.anyLong(), Mockito.<int[]>any()); } @Test public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished3() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class);
// Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/test/java/com/github/jeluard/stone/api/WindowedTimeSeriesTest.java import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class); final Window window = Window.of(3).listenedBy(consolidationListener).consolidatedBy(MaxConsolidator.class); final WindowedTimeSeries timeSeries = new WindowedTimeSeries("id", 1, Arrays.asList(window), new DumbDispatcher()); timeSeries.publish(1, 1); timeSeries.publish(2, 1); timeSeries.publish(3, 1); Mockito.verify(consolidationListener).onConsolidation(Mockito.anyLong(), Mockito.<int[]>any()); timeSeries.close(); Mockito.verifyNoMoreInteractions(consolidationListener); } @Test public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished2() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class); final Window window = Window.of(3).listenedBy(consolidationListener).consolidatedBy(MaxConsolidator.class); final WindowedTimeSeries timeSeries = new WindowedTimeSeries("id", 1, Arrays.asList(window), new DumbDispatcher()); timeSeries.publish(1, 1); timeSeries.publish(3, 1); timeSeries.close(); Mockito.verify(consolidationListener).onConsolidation(Mockito.anyLong(), Mockito.<int[]>any()); } @Test public void shouldConsolidationBeTriggeredWhenLastElementOfWindowIsPublished3() throws IOException { final ConsolidationListener consolidationListener = Mockito.mock(ConsolidationListener.class);
final Window window = Window.of(3).listenedBy(consolidationListener).consolidatedBy(MinConsolidator.class, MaxConsolidator.class);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // }
import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test;
} } static class ConsolidatorWithFailingConstructor extends Consolidator { public ConsolidatorWithFailingConstructor() { throw new RuntimeException(); } @Override public void accumulate(long timestamp, int value) { } @Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() {
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; } } static class ConsolidatorWithFailingConstructor extends Consolidator { public ConsolidatorWithFailingConstructor() { throw new RuntimeException(); } @Override public void accumulate(long timestamp, int value) { } @Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() {
Assert.assertEquals(2, Consolidators.createConsolidators(Arrays.asList(MinConsolidator.class, MaxConsolidator.class), 1).length);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // }
import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test;
} } static class ConsolidatorWithFailingConstructor extends Consolidator { public ConsolidatorWithFailingConstructor() { throw new RuntimeException(); } @Override public void accumulate(long timestamp, int value) { } @Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() {
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; } } static class ConsolidatorWithFailingConstructor extends Consolidator { public ConsolidatorWithFailingConstructor() { throw new RuntimeException(); } @Override public void accumulate(long timestamp, int value) { } @Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() {
Assert.assertEquals(2, Consolidators.createConsolidators(Arrays.asList(MinConsolidator.class, MaxConsolidator.class), 1).length);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // }
import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test;
@Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() { Assert.assertEquals(2, Consolidators.createConsolidators(Arrays.asList(MinConsolidator.class, MaxConsolidator.class), 1).length); } @Test public void shouldCreationWithConsolidatorDefiningDefaultConstructorBeSuccessful() { Consolidators.createConsolidator(MaxConsolidator.class, 1); } @Test public void shouldCreationWithConsolidatorDefiningIntConstructorBeSuccessful() {
// Path: core/src/main/java/com/github/jeluard/stone/api/Consolidator.java // public abstract class Consolidator { // // /** // * Accumulate a new value that will be considered for the consolidation process. // * // * @param timestamp // * @param value // */ // public abstract void accumulate(long timestamp, int value); // // /** // * Atomically compute consolidated value and reset itself for next consolidation cycle. // * <br /> // * When called {@link #accumulate(long, int)} has been called at least once. // * // * @return result of consolidation of all values accumulated since last call // */ // public final int consolidateAndReset() { // final int consolidate = consolidate(); // reset(); // return consolidate; // } // // /** // * Called right after {@link #consolidate()}. // */ // protected abstract void reset(); // // /** // * @return final consolidated value // */ // protected abstract int consolidate(); // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MaxConsolidator.java // public final class MaxConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MIN_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value > getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/MinConsolidator.java // public final class MinConsolidator extends BaseStreamingConsolidator { // // @Override // protected int initialValue() { // return Integer.MAX_VALUE; // } // // @Override // public void accumulate(final long timestamp, final int value) { // //Not atomic but not needed. // if (value < getCurrentResult()) { // setCurrentResult(value); // } // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/consolidator/Percentile90Consolidator.java // public final class Percentile90Consolidator extends BasePercentileConsolidator { // // public Percentile90Consolidator(final int maxSamples) { // super(maxSamples, 90); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/helper/ConsolidatorsTest.java import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.Consolidator; import com.github.jeluard.stone.consolidator.MaxConsolidator; import com.github.jeluard.stone.consolidator.MinConsolidator; import com.github.jeluard.stone.consolidator.Percentile90Consolidator; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @Override protected int consolidate() { return 0; } @Override protected void reset() { } } @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Consolidators.class; } @Test public void shouldConsolidatorsBeSuccessful() { Assert.assertEquals(2, Consolidators.createConsolidators(Arrays.asList(MinConsolidator.class, MaxConsolidator.class), 1).length); } @Test public void shouldCreationWithConsolidatorDefiningDefaultConstructorBeSuccessful() { Consolidators.createConsolidator(MaxConsolidator.class, 1); } @Test public void shouldCreationWithConsolidatorDefiningIntConstructorBeSuccessful() {
Consolidators.createConsolidator(Percentile90Consolidator.class, 1);
jeluard/stone
core/src/main/java/com/github/jeluard/stone/api/TimeSeries.java
// Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import javax.annotation.concurrent.NotThreadSafe; import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.lang.Identifiable; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; /** * Main abstraction allowing to publish {@code timestamp}/{@code value} pair. Provided {@code timestamp} must monotonically increased and compatible with {@code granularity}. * <br> * If {@code granularity} is {@code 1} then {@code timestamp} can be any value (as long as it follows the monotonicity rule). * <br> * If {@code granularity} is greater than {@code 1} each successive {@code timestamp}s must have {@code granularity - 1} values in between. Note this does not imply only {@code granularity} multiples are accepted as there can be more than {@code granularity - 1} in between two timestamps. * <br> * An invalid {@code timestamp} will be signaled via return value of {@link #publish(long, int)}. * <br> * <br> * Each accepted value then is passed to all associated {@link Listener}. * <br> * <br> * Once {@link #close()} has been called {@link #publish(long, int)} behaviour is undefined. * <br> * <br> * <b>WARNING</b> {@link TimeSeries} is not threadsafe and not supposed to be manipulated concurrently from different threads. Note it can be manipulated by different threads as long as you ensure they don't call {@link #publish(long, int)} concurrently. */ @NotThreadSafe public class TimeSeries implements Identifiable<String>, Closeable { private static final Set<String> IDS = new CopyOnWriteArraySet<String>(); private final String id; private final int granularity; private final Listener[] listeners;
// Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/main/java/com/github/jeluard/stone/api/TimeSeries.java import javax.annotation.concurrent.NotThreadSafe; import com.github.jeluard.guayaba.annotation.Idempotent; import com.github.jeluard.guayaba.lang.Identifiable; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; /** * Main abstraction allowing to publish {@code timestamp}/{@code value} pair. Provided {@code timestamp} must monotonically increased and compatible with {@code granularity}. * <br> * If {@code granularity} is {@code 1} then {@code timestamp} can be any value (as long as it follows the monotonicity rule). * <br> * If {@code granularity} is greater than {@code 1} each successive {@code timestamp}s must have {@code granularity - 1} values in between. Note this does not imply only {@code granularity} multiples are accepted as there can be more than {@code granularity - 1} in between two timestamps. * <br> * An invalid {@code timestamp} will be signaled via return value of {@link #publish(long, int)}. * <br> * <br> * Each accepted value then is passed to all associated {@link Listener}. * <br> * <br> * Once {@link #close()} has been called {@link #publish(long, int)} behaviour is undefined. * <br> * <br> * <b>WARNING</b> {@link TimeSeries} is not threadsafe and not supposed to be manipulated concurrently from different threads. Note it can be manipulated by different threads as long as you ensure they don't call {@link #publish(long, int)} concurrently. */ @NotThreadSafe public class TimeSeries implements Identifiable<String>, Closeable { private static final Set<String> IDS = new CopyOnWriteArraySet<String>(); private final String id; private final int granularity; private final Listener[] listeners;
private final Dispatcher dispatcher;
jeluard/stone
core/src/test/java/com/github/jeluard/stone/helper/StoragesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // }
import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; public class StoragesTest extends AbstractHelperClassTest { @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Storages.class; } @Test public void shouldConsolidationBePropagated() throws IOException {
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // } // Path: core/src/test/java/com/github/jeluard/stone/helper/StoragesTest.java import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; public class StoragesTest extends AbstractHelperClassTest { @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Storages.class; } @Test public void shouldConsolidationBePropagated() throws IOException {
final Storage storage = Mockito.mock(Storage.class);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/helper/StoragesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // }
import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; public class StoragesTest extends AbstractHelperClassTest { @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Storages.class; } @Test public void shouldConsolidationBePropagated() throws IOException { final Storage storage = Mockito.mock(Storage.class);
// Path: core/src/main/java/com/github/jeluard/stone/api/ConsolidationListener.java // public interface ConsolidationListener { // // interface Persistent extends ConsolidationListener { // // /** // * @return latest (most recent) timestamp persisted // */ // Optional<Long> getLatestTimestamp(); // // } // // /** // * Invoked each time a newly published value cross a {@link Window} boundary triggering the consolidation process. // * <br> // * Different thread might invoke this method but never concurrently. Consecutive {@code timestamp} values are guaranteed to be monotonically increasing. // * // * @param timestamp end timestamp for window just crossed // * @param consolidates array of consolidated values in the {@link Window#getConsolidatorTypes()} order; array will be reused so don't store as is // */ // void onConsolidation(long timestamp, int[] consolidates); // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Storage.java // @ThreadSafe // public abstract class Storage implements Reader { // // private final int maximumSize; // // public Storage(final int maximumSize) { // this.maximumSize = maximumSize; // } // // /** // * @return // */ // protected final int getMaximumSize() { // return this.maximumSize; // } // // /** // * Default implementation relying on {@link #all()}. // * // * @return // */ // @Override // public Optional<Long> beginning() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(consolidates.next().first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one. // * // * @return // * @see Iterables#getLast(java.lang.Iterable) // */ // @Override // public Optional<Long> end() throws IOException { // try { // final Iterator<Pair<Long, int[]>> consolidates = all().iterator(); // return Optional.of(Iterators.getLast(consolidates).first); // } catch (NoSuchElementException e) { // return Optional.absent(); // } // } // // /** // * Default implementation relying on {@link #all()}: it iterates over all elements while they are parts of specified {@code interval}. // * // * @param beginning // * @param end // * @return // * @see AbstractIterator // */ // @Override // public Iterable<Pair<Long, int[]>> during(final long beginning, final long end) throws IOException { // return new Iterable<Pair<Long, int[]>>() { // final Iterable<Pair<Long, int[]>> all = all(); // @Override // public Iterator<Pair<Long, int[]>> iterator() { // return new AbstractIterator<Pair<Long, int[]>>() { // final Iterator<Pair<Long, int[]>> iterator = all.iterator(); // @Override // protected Pair<Long, int[]> computeNext() { // while (this.iterator.hasNext()) { // final Pair<Long, int[]> consolidates = this.iterator.next(); // final long timestamp = consolidates.first; // if (timestamp < beginning) { // //Before the beginning // continue; // } // if (timestamp > end) { // //After the beginning // break; // } // // return consolidates; // } // return endOfData(); // } // }; // } // }; // } // // /** // * Append {@code values} associated to {@code timestamp}. // * // * @param timestamp // * @param values // * @throws IOException // */ // public abstract void append(long timestamp, int[] values) throws IOException; // // } // Path: core/src/test/java/com/github/jeluard/stone/helper/StoragesTest.java import com.github.jeluard.guayaba.test.AbstractHelperClassTest; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.api.ConsolidationListener; import com.github.jeluard.stone.spi.Storage; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.helper; public class StoragesTest extends AbstractHelperClassTest { @Rule public LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); @Override protected Class<?> getType() { return Storages.class; } @Test public void shouldConsolidationBePropagated() throws IOException { final Storage storage = Mockito.mock(Storage.class);
final ConsolidationListener consolidationListener = Storages.asConsolidationListener(storage, Loggers.BASE_LOGGER);
jeluard/stone
core/src/main/java/com/github/jeluard/stone/api/Window.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.annotation.concurrent.Immutable;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; /** * Encapsulate details about how published data will be kept. */ @Immutable public final class Window { /** * Builder for {@link Window}. */ public static final class Builder { private final int size; private final List<ConsolidationListener> consolidationListeners = new LinkedList<ConsolidationListener>(); private Builder(final int size) { this.size = size; } /** * Add {@link ConsolidationListener}s. Each call accumulates new values. * * @param consolidationListeners * @return this */ public Window.Builder listenedBy(final ConsolidationListener ... consolidationListeners) { this.consolidationListeners.addAll(Arrays.asList(consolidationListeners)); return this; } public Window consolidatedBy(final Class<? extends Consolidator> ... consolidatorTypes) { return new Window(this.size, Arrays.asList(consolidatorTypes), this.consolidationListeners); } } private final int size; private final List<? extends Class<? extends Consolidator>> consolidatorTypes; private final List<? extends ConsolidationListener> consolidationListeners; public Window(final int size, final List<? extends Class<? extends Consolidator>> consolidatorTypes, final List<? extends ConsolidationListener> consolidationListeners) { Preconditions.checkArgument(size > 1, "size must be greater than 1"); this.size = size; this.consolidatorTypes = Collections.unmodifiableList(new ArrayList<Class<? extends Consolidator>>(Preconditions2.checkNotEmpty(consolidatorTypes, "null consolidatorTypes"))); this.consolidationListeners = Collections.unmodifiableList(new ArrayList<ConsolidationListener>(Preconditions.checkNotNull(consolidationListeners, "null consolidationListeners"))); if (consolidationListeners.isEmpty()) {
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/main/java/com/github/jeluard/stone/api/Window.java import com.github.jeluard.guayaba.base.Preconditions2; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.annotation.concurrent.Immutable; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; /** * Encapsulate details about how published data will be kept. */ @Immutable public final class Window { /** * Builder for {@link Window}. */ public static final class Builder { private final int size; private final List<ConsolidationListener> consolidationListeners = new LinkedList<ConsolidationListener>(); private Builder(final int size) { this.size = size; } /** * Add {@link ConsolidationListener}s. Each call accumulates new values. * * @param consolidationListeners * @return this */ public Window.Builder listenedBy(final ConsolidationListener ... consolidationListeners) { this.consolidationListeners.addAll(Arrays.asList(consolidationListeners)); return this; } public Window consolidatedBy(final Class<? extends Consolidator> ... consolidatorTypes) { return new Window(this.size, Arrays.asList(consolidatorTypes), this.consolidationListeners); } } private final int size; private final List<? extends Class<? extends Consolidator>> consolidatorTypes; private final List<? extends ConsolidationListener> consolidationListeners; public Window(final int size, final List<? extends Class<? extends Consolidator>> consolidatorTypes, final List<? extends ConsolidationListener> consolidationListeners) { Preconditions.checkArgument(size > 1, "size must be greater than 1"); this.size = size; this.consolidatorTypes = Collections.unmodifiableList(new ArrayList<Class<? extends Consolidator>>(Preconditions2.checkNotEmpty(consolidatorTypes, "null consolidatorTypes"))); this.consolidationListeners = Collections.unmodifiableList(new ArrayList<ConsolidationListener>(Preconditions.checkNotNull(consolidationListeners, "null consolidationListeners"))); if (consolidationListeners.isEmpty()) {
if (Loggers.BASE_LOGGER.isLoggable(Level.FINE)) {
jeluard/stone
core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.logging.Level; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; /** * Encapsulate the logic that calls {@link Listener#onPublication(long, long, int)}. */ public abstract class Dispatcher { /** * Intercept {@link Exception} thrown when a {@code value} is published. */ public interface ExceptionHandler { /** * Invoked when an {@link Exception} is thrown during accumulation/persistency process. * * @param exception */ void onException(Exception exception); }
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.logging.Level; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; /** * Encapsulate the logic that calls {@link Listener#onPublication(long, long, int)}. */ public abstract class Dispatcher { /** * Intercept {@link Exception} thrown when a {@code value} is published. */ public interface ExceptionHandler { /** * Invoked when an {@link Exception} is thrown during accumulation/persistency process. * * @param exception */ void onException(Exception exception); }
static final Logger LOGGER = Loggers.create("dispatcher");
jeluard/stone
core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.logging.Level; import java.util.logging.Logger;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; /** * Encapsulate the logic that calls {@link Listener#onPublication(long, long, int)}. */ public abstract class Dispatcher { /** * Intercept {@link Exception} thrown when a {@code value} is published. */ public interface ExceptionHandler { /** * Invoked when an {@link Exception} is thrown during accumulation/persistency process. * * @param exception */ void onException(Exception exception); } static final Logger LOGGER = Loggers.create("dispatcher"); private final ExceptionHandler exceptionHandler; protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { @Override public void onException(final Exception exception) { if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); } } }; /** * @param exceptionHandler */ public Dispatcher(final ExceptionHandler exceptionHandler) { this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); } /** * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} * * @param exception */ protected final void notifyExceptionHandler(final Exception exception) { try { this.exceptionHandler.onException(exception); } catch (Exception e) { if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); } } } /** * Dispatch {@link Listener}s executions. * * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist * @param currentTimestamp * @param value * @param listeners * @return true if dispatch has been accepted; false if rejected */
// Path: core/src/main/java/com/github/jeluard/stone/api/Listener.java // public interface Listener { // // /** // * Invoked each time a {@code value} is published. // * // * @param previousTimestamp // * @param currentTimestamp // * @param value // */ // void onPublication(long previousTimestamp, long currentTimestamp, int value); // // } // // Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java import com.github.jeluard.stone.api.Listener; import com.github.jeluard.stone.helper.Loggers; import com.google.common.base.Preconditions; import java.util.logging.Level; import java.util.logging.Logger; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; /** * Encapsulate the logic that calls {@link Listener#onPublication(long, long, int)}. */ public abstract class Dispatcher { /** * Intercept {@link Exception} thrown when a {@code value} is published. */ public interface ExceptionHandler { /** * Invoked when an {@link Exception} is thrown during accumulation/persistency process. * * @param exception */ void onException(Exception exception); } static final Logger LOGGER = Loggers.create("dispatcher"); private final ExceptionHandler exceptionHandler; protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { @Override public void onException(final Exception exception) { if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); } } }; /** * @param exceptionHandler */ public Dispatcher(final ExceptionHandler exceptionHandler) { this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); } /** * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} * * @param exception */ protected final void notifyExceptionHandler(final Exception exception) { try { this.exceptionHandler.onException(exception); } catch (Exception e) { if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); } } } /** * Dispatch {@link Listener}s executions. * * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist * @param currentTimestamp * @param value * @param listeners * @return true if dispatch has been accepted; false if rejected */
public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/TimeSeriesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesTest { @Rule
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/test/java/com/github/jeluard/stone/api/TimeSeriesTest.java import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesTest { @Rule
public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER);
jeluard/stone
core/src/test/java/com/github/jeluard/stone/api/TimeSeriesTest.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // }
import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesTest { @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); private Listener createListener() { return new Listener() { @Override public void onPublication(long previousTimestamp, long currentTimestamp, int value) { } }; } @Test public void shouldCreationBeSuccessful() throws IOException {
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // // Path: core/src/main/java/com/github/jeluard/stone/spi/Dispatcher.java // public abstract class Dispatcher { // // /** // * Intercept {@link Exception} thrown when a {@code value} is published. // */ // public interface ExceptionHandler { // // /** // * Invoked when an {@link Exception} is thrown during accumulation/persistency process. // * // * @param exception // */ // void onException(Exception exception); // // } // // static final Logger LOGGER = Loggers.create("dispatcher"); // // private final ExceptionHandler exceptionHandler; // protected static final ExceptionHandler DEFAULT_EXCEPTION_HANDLER = new ExceptionHandler() { // @Override // public void onException(final Exception exception) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while publishing", exception); // } // } // }; // // /** // * @param exceptionHandler // */ // public Dispatcher(final ExceptionHandler exceptionHandler) { // this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler, "null exceptionHandler"); // } // // /** // * Safely execute {@link ExceptionHandler#onException(java.lang.Exception)} // * // * @param exception // */ // protected final void notifyExceptionHandler(final Exception exception) { // try { // this.exceptionHandler.onException(exception); // } catch (Exception e) { // if (Dispatcher.LOGGER.isLoggable(Level.WARNING)) { // Dispatcher.LOGGER.log(Level.WARNING, "Got exception while executing "+ExceptionHandler.class.getSimpleName()+" <"+this.exceptionHandler+">", e); // } // } // } // // /** // * Dispatch {@link Listener}s executions. // * // * @param previousTimestamp {@linkplain com.github.jeluard.stone.api.TimeSeries#DEFAULT_LATEST_TIMESTAMP} if does not exist // * @param currentTimestamp // * @param value // * @param listeners // * @return true if dispatch has been accepted; false if rejected // */ // public abstract boolean dispatch(long previousTimestamp, long currentTimestamp, int value, Listener[] listeners); // // } // Path: core/src/test/java/com/github/jeluard/stone/api/TimeSeriesTest.java import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.github.jeluard.stone.spi.Dispatcher; import com.google.common.base.Optional; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.api; public class TimeSeriesTest { @Rule public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER); private Listener createListener() { return new Listener() { @Override public void onPublication(long previousTimestamp, long currentTimestamp, int value) { } }; } @Test public void shouldCreationBeSuccessful() throws IOException {
final TimeSeries timeSeries = new TimeSeries("id", 1, Arrays.asList(createListener()), Mockito.mock(Dispatcher.class));
jeluard/stone
core/src/test/java/com/github/jeluard/stone/spi/StorageFactoryTest.java
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // }
import com.github.jeluard.guayaba.base.Pair; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.google.common.collect.Iterables; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Rule; import org.junit.Test;
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; public class StorageFactoryTest { @Rule
// Path: core/src/main/java/com/github/jeluard/stone/helper/Loggers.java // public final class Loggers { // // private Loggers() { // } // // private static final String BASE_LOGGER_NAME = "com.github.jeluard.stone"; // public static final Logger BASE_LOGGER = Logger.getLogger(Loggers.BASE_LOGGER_NAME); // // /** // * @param suffix // * @return a configured {@link Logger} // */ // public static Logger create(final String suffix) { // Preconditions.checkNotNull(suffix, "null suffix"); // // return Logger.getLogger(Loggers.BASE_LOGGER_NAME+"."+suffix); // } // // } // Path: core/src/test/java/com/github/jeluard/stone/spi/StorageFactoryTest.java import com.github.jeluard.guayaba.base.Pair; import com.github.jeluard.guayaba.test.junit.LoggerRule; import com.github.jeluard.stone.helper.Loggers; import com.google.common.collect.Iterables; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; /** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.stone.spi; public class StorageFactoryTest { @Rule
public final LoggerRule loggerRule = new LoggerRule(Loggers.BASE_LOGGER);
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override
protected ProcessTask get() {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override protected ProcessTask get() { return get(1); } protected ProcessTask get(long id) { return new OriginalFileFiller(id, new FileSystemLocationImpl(getAllowedFolder())); } /** * Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle");
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override protected ProcessTask get() { return get(1); } protected ProcessTask get(long id) { return new OriginalFileFiller(id, new FileSystemLocationImpl(getAllowedFolder())); } /** * Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle");
EntityManager manager = new PersistenceProvider().get();
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override protected ProcessTask get() { return get(1); } protected ProcessTask get(long id) { return new OriginalFileFiller(id, new FileSystemLocationImpl(getAllowedFolder())); } /** * Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle"); EntityManager manager = new PersistenceProvider().get(); manager.getTransaction().begin(); IOUtils.copyAndClose( getClass().getResourceAsStream("/test.txt"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/steamapps/common/Stellaris/test.txt")) );
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; public class OriginalFileFillerTest extends TestATask { @Override protected ProcessTask get() { return get(1); } protected ProcessTask get(long id) { return new OriginalFileFiller(id, new FileSystemLocationImpl(getAllowedFolder())); } /** * Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle"); EntityManager manager = new PersistenceProvider().get(); manager.getTransaction().begin(); IOUtils.copyAndClose( getClass().getResourceAsStream("/test.txt"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/steamapps/common/Stellaris/test.txt")) );
Original original = new Original("test.txt");
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test;
* Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle"); EntityManager manager = new PersistenceProvider().get(); manager.getTransaction().begin(); IOUtils.copyAndClose( getClass().getResourceAsStream("/test.txt"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/steamapps/common/Stellaris/test.txt")) ); Original original = new Original("test.txt"); manager.persist(original); manager.getTransaction().commit(); List<ProcessTask> result = get(original.getAid()).handle(manager); Assert.assertEquals( "Follow-up number is wrong", 1, result.size() ); manager.getTransaction().begin(); manager.refresh(original); Assert.assertTrue( "Content was not written", original.getContent().length() > 0 ); manager.getTransaction().commit(); }
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestATask.java // public abstract class TestATask extends FileBased { // // protected abstract ProcessTask get(); // // @Test // public void testInterface() { // System.out.println("interface"); // Assert.assertTrue("This task does not implement the required interface.", ProcessTask.class.isAssignableFrom(get().getClass())); // } // // /** // * Test of getFullIdentifier method, of class Task. // */ // @Test // public void testGetFullIdentifier() { // System.out.println("getIdentifier"); // Assert.assertTrue("Full Identifier is not correct", get().getIdentifier().length() > 0); // } // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFillerTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestATask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; import org.h2.util.IOUtils; import org.junit.Assert; import org.junit.Test; * Test of handle method, of class Task. * @throws java.lang.Exception * @deprecated has to be implemented on a case by case basis */ @Test public void testHandle() throws Exception { System.out.println("handle"); EntityManager manager = new PersistenceProvider().get(); manager.getTransaction().begin(); IOUtils.copyAndClose( getClass().getResourceAsStream("/test.txt"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/steamapps/common/Stellaris/test.txt")) ); Original original = new Original("test.txt"); manager.persist(original); manager.getTransaction().commit(); List<ProcessTask> result = get(original.getAid()).handle(manager); Assert.assertEquals( "Follow-up number is wrong", 1, result.size() ); manager.getTransaction().begin(); manager.refresh(original); Assert.assertTrue( "Content was not written", original.getContent().length() > 0 ); manager.getTransaction().commit(); }
private class FileSystemLocationImpl implements FileSystemLocation {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process/QueueTest.java
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javax.persistence.EntityManager; import junit.framework.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class QueueTest { /** * Test of add method, of class Queue. */ @Test public void testAdd() { System.out.println("add"); TestProcessTask task = new TestProcessTask();
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/test/java/de/idrinth/stellaris/modtools/process/QueueTest.java import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javax.persistence.EntityManager; import junit.framework.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class QueueTest { /** * Test of add method, of class Queue. */ @Test public void testAdd() { System.out.println("add"); TestProcessTask task = new TestProcessTask();
Queue instance = new Queue(new TestDataInitializer(new TestProcessTask()),new TestCallable(),new TestProgressElementGroup(),"", new PersistenceProvider());
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process/QueueTest.java
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javax.persistence.EntityManager; import junit.framework.Assert; import org.junit.Test;
public ProcessTask poll() { wasPulled = true; return task; } @Override public boolean hasNext() { return !wasPulled; } @Override public int getQueueSize() { return 1; } } private class TestProcessTask implements ProcessTask { public volatile boolean done=false; @Override public List<ProcessTask> handle(EntityManager manager) { done=true; return new ArrayList<>(); } @Override public String getIdentifier() { return "demo"; } }
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/test/java/de/idrinth/stellaris/modtools/process/QueueTest.java import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javax.persistence.EntityManager; import junit.framework.Assert; import org.junit.Test; public ProcessTask poll() { wasPulled = true; return task; } @Override public boolean hasNext() { return !wasPulled; } @Override public int getQueueSize() { return 1; } } private class TestProcessTask implements ProcessTask { public volatile boolean done=false; @Override public List<ProcessTask> handle(EntityManager manager) { done=true; return new ArrayList<>(); } @Override public String getIdentifier() { return "demo"; } }
private class TestProgressElementGroup implements ProgressElementGroup {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/filesystem/DirectoryLookupTest.java
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/DirectoryLookup.java // class DirectoryLookup { // // protected static File modDir; // protected static File steamDir; // // public static File getModDir() throws IOException { // if (null == modDir) { // if(SystemUtils.IS_OS_WINDOWS) { // modDir = test(new File(SystemUtils.getUserHome() + "\\Documents\\Paradox Interactive\\Stellaris\\mod")); // } else if(SystemUtils.IS_OS_MAC) { // modDir = test(new File(SystemUtils.getUserHome() + "/Documents/Paradox Interactive/Stellaris/mod")); // } else if(SystemUtils.IS_OS_LINUX) { // modDir = test(new File(SystemUtils.getUserHome() + "/.local/share/Paradox Interactive/Stellaris/mod")); // } // } // return modDir; // } // // public static File getSteamDir() throws RegistryException, IOException { // if (null == steamDir) { // if(SystemUtils.IS_OS_WINDOWS) { // steamDir = test(new File(WindowsRegistry.getInstance().readString(HKey.HKCU, "Software\\Valve\\Steam", "SteamPath"))); // } else if(SystemUtils.IS_OS_MAC) { // steamDir = test(new File(SystemUtils.getUserHome()+"/Library/Application Support/Steam")); // } else if(SystemUtils.IS_OS_LINUX) { // ArrayList<File> fl = new ArrayList<>(); // fl.add(new File(SystemUtils.getUserHome()+"/.steam/steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.steam/Steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.local/share/steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.local/share/Steam")); // steamDir = test(fl); // } // } // return steamDir; // } // // private static File test(File file) throws IOException { // if (!file.exists() && file.isDirectory()) { // throw new IOException(file.getAbsolutePath() + " is expected but can't be found."); // } // return file; // } // // private static File test(ArrayList<File> files) throws IOException { // StringBuilder sb = new StringBuilder(); // for(File file:files) { // try { // return test(file); // } catch(IOException e) { // sb.append(e.getMessage()); // } // } // throw new IOException(sb.toString()); // } // }
import de.idrinth.stellaris.modtools.filesystem.DirectoryLookup; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.filesystem; public class DirectoryLookupTest { /** * Test of getModDir method, of class DirectoryLookup. */ @Test public void testGetModDir() throws Exception { System.out.println("getModDir");
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/DirectoryLookup.java // class DirectoryLookup { // // protected static File modDir; // protected static File steamDir; // // public static File getModDir() throws IOException { // if (null == modDir) { // if(SystemUtils.IS_OS_WINDOWS) { // modDir = test(new File(SystemUtils.getUserHome() + "\\Documents\\Paradox Interactive\\Stellaris\\mod")); // } else if(SystemUtils.IS_OS_MAC) { // modDir = test(new File(SystemUtils.getUserHome() + "/Documents/Paradox Interactive/Stellaris/mod")); // } else if(SystemUtils.IS_OS_LINUX) { // modDir = test(new File(SystemUtils.getUserHome() + "/.local/share/Paradox Interactive/Stellaris/mod")); // } // } // return modDir; // } // // public static File getSteamDir() throws RegistryException, IOException { // if (null == steamDir) { // if(SystemUtils.IS_OS_WINDOWS) { // steamDir = test(new File(WindowsRegistry.getInstance().readString(HKey.HKCU, "Software\\Valve\\Steam", "SteamPath"))); // } else if(SystemUtils.IS_OS_MAC) { // steamDir = test(new File(SystemUtils.getUserHome()+"/Library/Application Support/Steam")); // } else if(SystemUtils.IS_OS_LINUX) { // ArrayList<File> fl = new ArrayList<>(); // fl.add(new File(SystemUtils.getUserHome()+"/.steam/steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.steam/Steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.local/share/steam")); // fl.add(new File(SystemUtils.getUserHome()+"/.local/share/Steam")); // steamDir = test(fl); // } // } // return steamDir; // } // // private static File test(File file) throws IOException { // if (!file.exists() && file.isDirectory()) { // throw new IOException(file.getAbsolutePath() + " is expected but can't be found."); // } // return file; // } // // private static File test(ArrayList<File> files) throws IOException { // StringBuilder sb = new StringBuilder(); // for(File file:files) { // try { // return test(file); // } catch(IOException e) { // sb.append(e.getMessage()); // } // } // throw new IOException(sb.toString()); // } // } // Path: src/test/java/de/idrinth/stellaris/modtools/filesystem/DirectoryLookupTest.java import de.idrinth.stellaris.modtools.filesystem.DirectoryLookup; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.filesystem; public class DirectoryLookupTest { /** * Test of getModDir method, of class DirectoryLookup. */ @Test public void testGetModDir() throws Exception { System.out.println("getModDir");
Assert.assertTrue("Mod Directory was not found to exists.", DirectoryLookup.getModDir().exists());
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/gui/AbstractDataRow.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // }
import de.idrinth.stellaris.modtools.persistence.entity.Modification; import java.util.Set; import javax.persistence.EntityManager;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.gui; abstract class AbstractDataRow { protected final EntityManager manager; public AbstractDataRow(EntityManager manager) { this.manager = manager; } public String getCollisions() {
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/gui/AbstractDataRow.java import de.idrinth.stellaris.modtools.persistence.entity.Modification; import java.util.Set; import javax.persistence.EntityManager; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.gui; abstract class AbstractDataRow { protected final EntityManager manager; public AbstractDataRow(EntityManager manager) { this.manager = manager; } public String getCollisions() {
Set<Modification> list = getCollisionList();
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process/FillerThreadTest.java
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // }
import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import java.util.ArrayList; import java.util.concurrent.Callable; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class FillerThreadTest { /** * Test of run method, of class FillerThread. */ @Test public void testRun() { System.out.println("run"); Assert.assertTrue("Is not a runnable", Runnable.class.isInstance(new FillerThread(new ArrayList<>(), new TestProgressElementGroup()))); } /** * Test of call method, of class FillerThread. */ @Test public void testCall() throws Exception { System.out.println("call"); Assert.assertTrue("Is not a callable", Callable.class.isInstance(new FillerThread(new ArrayList<>(), new TestProgressElementGroup()))); }
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // Path: src/test/java/de/idrinth/stellaris/modtools/process/FillerThreadTest.java import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import java.util.ArrayList; import java.util.concurrent.Callable; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class FillerThreadTest { /** * Test of run method, of class FillerThread. */ @Test public void testRun() { System.out.println("run"); Assert.assertTrue("Is not a runnable", Runnable.class.isInstance(new FillerThread(new ArrayList<>(), new TestProgressElementGroup()))); } /** * Test of call method, of class FillerThread. */ @Test public void testCall() throws Exception { System.out.println("call"); Assert.assertTrue("Is not a callable", Callable.class.isInstance(new FillerThread(new ArrayList<>(), new TestProgressElementGroup()))); }
private class TestProgressElementGroup implements ProgressElementGroup {
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process/Queue.java
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class Queue implements ProcessHandlingQueue { private final ExecutorService executor; private final List<Future<?>> futures = new LinkedList<>(); private final List<String> known = new LinkedList<>(); private final Callable callable;
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/process/Queue.java import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class Queue implements ProcessHandlingQueue { private final ExecutorService executor; private final List<Future<?>> futures = new LinkedList<>(); private final List<String> known = new LinkedList<>(); private final Callable callable;
private final ProgressElementGroup progress;
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process/Queue.java
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class Queue implements ProcessHandlingQueue { private final ExecutorService executor; private final List<Future<?>> futures = new LinkedList<>(); private final List<String> known = new LinkedList<>(); private final Callable callable; private final ProgressElementGroup progress;
// Path: src/main/java/de/idrinth/stellaris/modtools/gui/ProgressElementGroup.java // public interface ProgressElementGroup { // // void addToStepLabels(String text); // // void update(int current, int maximum); // // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/process/Queue.java import de.idrinth.stellaris.modtools.gui.ProgressElementGroup; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process; public class Queue implements ProcessHandlingQueue { private final ExecutorService executor; private final List<Future<?>> futures = new LinkedList<>(); private final List<String> known = new LinkedList<>(); private final Callable callable; private final ProgressElementGroup progress;
private final PersistenceProvider persistence;
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/filesystem/FileExtensionsTest.java
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // }
import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import org.junit.Assert; import org.junit.Test;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.filesystem; public class FileExtensionsTest { /** * Test of isPatchable method, of class FileExtensions. */ @Test public void testIsPatchable() { System.out.println("isPatchable");
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // Path: src/test/java/de/idrinth/stellaris/modtools/filesystem/FileExtensionsTest.java import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import org.junit.Assert; import org.junit.Test; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.filesystem; public class FileExtensionsTest { /** * Test of isPatchable method, of class FileExtensions. */ @Test public void testIsPatchable() { System.out.println("isPatchable");
Assert.assertTrue(FileExtensions.isPatchable("demo.txt"));
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process1datacollection/ConfigParser.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import com.github.sarxos.winreg.RegistryException; import de.idrinth.stellaris.modtools.persistence.entity.Modification; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process1datacollection; class ConfigParser implements ProcessTask { private final File configuration; private final ArrayList<ProcessTask> todo = new ArrayList<>();
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process1datacollection/ConfigParser.java import com.github.sarxos.winreg.RegistryException; import de.idrinth.stellaris.modtools.persistence.entity.Modification; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process1datacollection; class ConfigParser implements ProcessTask { private final File configuration; private final ArrayList<ProcessTask> todo = new ArrayList<>();
private final FileSystemLocation modDir;
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process1datacollection/ConfigParser.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import com.github.sarxos.winreg.RegistryException; import de.idrinth.stellaris.modtools.persistence.entity.Modification; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process1datacollection; class ConfigParser implements ProcessTask { private final File configuration; private final ArrayList<ProcessTask> todo = new ArrayList<>(); private final FileSystemLocation modDir; public ConfigParser(File configuration, FileSystemLocation modDir) { this.configuration = configuration; this.modDir = modDir; } protected File getWithPrefix(String path) throws IOException { File file = new File(path); if (file.exists()) { return file; } if (!file.isAbsolute()) { file = new File(modDir.get().getParent() + "/" + path); if (file.exists()) { return file; } } throw new IOException("No valid path to mod found: " + file.getAbsolutePath()); } private ProcessTask handlePath(String path) throws IOException, RegistryException { File file = getWithPrefix(path); if (path.endsWith(".zip")) { return new ZipContentParser(configuration.getName(), file); } return new FileSystemParser(configuration.getName(), file); }
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process1datacollection/ConfigParser.java import com.github.sarxos.winreg.RegistryException; import de.idrinth.stellaris.modtools.persistence.entity.Modification; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process1datacollection; class ConfigParser implements ProcessTask { private final File configuration; private final ArrayList<ProcessTask> todo = new ArrayList<>(); private final FileSystemLocation modDir; public ConfigParser(File configuration, FileSystemLocation modDir) { this.configuration = configuration; this.modDir = modDir; } protected File getWithPrefix(String path) throws IOException { File file = new File(path); if (file.exists()) { return file; } if (!file.isAbsolute()) { file = new File(modDir.get().getParent() + "/" + path); if (file.exists()) { return file; } } throw new IOException("No valid path to mod found: " + file.getAbsolutePath()); } private ProcessTask handlePath(String path) throws IOException, RegistryException { File file = getWithPrefix(path); if (path.endsWith(".zip")) { return new ZipContentParser(configuration.getName(), file); } return new FileSystemParser(configuration.getName(), file); }
private void persist(Modification mod, EntityManager manager) {
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process5modcreation/Mod.java
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // }
import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.IOException; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; class Mod { private final String filename; private final ModLine name = new SingleValue(); private final ModLine path = new SingleValue(); private final ModLine dependencies = new MultiValue(); private final ModLine supported_version = new SingleValue(); private final ModLine tags = new MultiValue();
// Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process5modcreation/Mod.java import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.IOException; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; class Mod { private final String filename; private final ModLine name = new SingleValue(); private final ModLine path = new SingleValue(); private final ModLine dependencies = new MultiValue(); private final ModLine supported_version = new SingleValue(); private final ModLine tags = new MultiValue();
private final FileSystemLocation modDir;
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/gui/FXMLController.java
// Path: src/main/java/de/idrinth/stellaris/modtools/process/FillerThread.java // public class FillerThread implements Runnable, Callable { // // private final ArrayList<ClickableTableView> list; // private final LinkedList<ProcessHandlingQueue> tasks = new LinkedList<>(); // private final PersistenceProvider persistence = new PersistenceProvider(); // // public FillerThread(ArrayList<ClickableTableView> list, ProgressElementGroup progress) { // this.list = list; // tasks.add(new Queue(new Process1Initializer(), this, progress, "Collecting data", persistence)); // tasks.add(new Queue(new Process2Initializer(persistence), this, progress, "Removing manually patched", persistence)); // tasks.add(new Queue(new Process3Initializer(persistence),this, progress, "Creating patches", persistence)); // tasks.add(new Queue(new Process4Initializer(persistence), this, progress, "Merging patches", persistence)); // tasks.add(new Queue(new Process5Initializer(), this, progress, "Building Mod", persistence)); // } // // @Override // public void run() { // try { // call(); // } catch (Exception exception) { // System.out.println(exception.getLocalizedMessage()); // } // } // // @Override // public synchronized Object call() throws Exception { // if (!tasks.isEmpty()) { // new Thread(tasks.poll()).start(); // return null; // } // EntityManager manager = persistence.get(); // list.forEach((ctv) -> { // ctv.setManager(manager); // ctv.addItems(); // }); // return null; // } // // }
import de.idrinth.stellaris.modtools.process.FillerThread; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.web.WebView; import javafx.stage.Modality; import javafx.stage.Stage; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkEvent.EventType; import org.codefx.libfx.control.webview.WebViews;
popup.initModality(Modality.APPLICATION_MODAL); popup.initOwner(mods.getScene().getWindow()); description.setContextMenuEnabled(false); description.getEngine().setJavaScriptEnabled(false); description.getEngine().setUserAgent("Idrinth's Stellaris Mod Tools/" + getClass().getPackage().getImplementationVersion() + " (https://github.com/Idrinths-Stellaris-Mods/Mod-Tools)"); WebViews.addHyperlinkListener( description, (HyperlinkEvent event) -> { if (event.getEventType() == EventType.ACTIVATED) { try { Desktop.getDesktop().browse(new URI(event.getURL().toString())); } catch (URISyntaxException | IOException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } return true;//do NOT navigate }, EventType.ACTIVATED ); } return popup; } @FXML private void handleButtonAction(ActionEvent event) { button.disarm();//no more events button.setDisable(true); ArrayList<ClickableTableView> list = new ArrayList<>(); list.add(mods); list.add(collisions);
// Path: src/main/java/de/idrinth/stellaris/modtools/process/FillerThread.java // public class FillerThread implements Runnable, Callable { // // private final ArrayList<ClickableTableView> list; // private final LinkedList<ProcessHandlingQueue> tasks = new LinkedList<>(); // private final PersistenceProvider persistence = new PersistenceProvider(); // // public FillerThread(ArrayList<ClickableTableView> list, ProgressElementGroup progress) { // this.list = list; // tasks.add(new Queue(new Process1Initializer(), this, progress, "Collecting data", persistence)); // tasks.add(new Queue(new Process2Initializer(persistence), this, progress, "Removing manually patched", persistence)); // tasks.add(new Queue(new Process3Initializer(persistence),this, progress, "Creating patches", persistence)); // tasks.add(new Queue(new Process4Initializer(persistence), this, progress, "Merging patches", persistence)); // tasks.add(new Queue(new Process5Initializer(), this, progress, "Building Mod", persistence)); // } // // @Override // public void run() { // try { // call(); // } catch (Exception exception) { // System.out.println(exception.getLocalizedMessage()); // } // } // // @Override // public synchronized Object call() throws Exception { // if (!tasks.isEmpty()) { // new Thread(tasks.poll()).start(); // return null; // } // EntityManager manager = persistence.get(); // list.forEach((ctv) -> { // ctv.setManager(manager); // ctv.addItems(); // }); // return null; // } // // } // Path: src/main/java/de/idrinth/stellaris/modtools/gui/FXMLController.java import de.idrinth.stellaris.modtools.process.FillerThread; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.web.WebView; import javafx.stage.Modality; import javafx.stage.Stage; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkEvent.EventType; import org.codefx.libfx.control.webview.WebViews; popup.initModality(Modality.APPLICATION_MODAL); popup.initOwner(mods.getScene().getWindow()); description.setContextMenuEnabled(false); description.getEngine().setJavaScriptEnabled(false); description.getEngine().setUserAgent("Idrinth's Stellaris Mod Tools/" + getClass().getPackage().getImplementationVersion() + " (https://github.com/Idrinths-Stellaris-Mods/Mod-Tools)"); WebViews.addHyperlinkListener( description, (HyperlinkEvent event) -> { if (event.getEventType() == EventType.ACTIVATED) { try { Desktop.getDesktop().browse(new URI(event.getURL().toString())); } catch (URISyntaxException | IOException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } return true;//do NOT navigate }, EventType.ACTIVATED ); } return popup; } @FXML private void handleButtonAction(ActionEvent event) { button.disarm();//no more events button.setDisable(true); ArrayList<ClickableTableView> list = new ArrayList<>(); list.add(mods); list.add(collisions);
new Thread(new FillerThread(list, test)).start();
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // }
import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; class OriginalFileFiller implements ProcessTask { private final long aid;
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; class OriginalFileFiller implements ProcessTask { private final long aid;
private final FileSystemLocation steamDir;
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // }
import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; class OriginalFileFiller implements ProcessTask { private final long aid; private final FileSystemLocation steamDir; public OriginalFileFiller(long aid, FileSystemLocation steamDir) { this.aid = aid; this.steamDir = steamDir; } protected String getContent(String path) {
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process3filepatch; class OriginalFileFiller implements ProcessTask { private final long aid; private final FileSystemLocation steamDir; public OriginalFileFiller(long aid, FileSystemLocation steamDir) { this.aid = aid; this.steamDir = steamDir; } protected String getContent(String path) {
if (!FileExtensions.isPatchable(path)) {
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // }
import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils;
public OriginalFileFiller(long aid, FileSystemLocation steamDir) { this.aid = aid; this.steamDir = steamDir; } protected String getContent(String path) { if (!FileExtensions.isPatchable(path)) { return "-unpatchable-";//nothing to do } try { File file = new File( steamDir.get().getAbsolutePath() + "steamapps/common/Stellaris/"//at least ubutu's steam uses lower case + path ); if(file.exists() && file.canRead()){ return FileUtils.readFileToString(file, "utf-8"); } } catch (IOException exception) { System.out.println(exception.getLocalizedMessage()); } return "-not readable-"; } @Override public List<ProcessTask> handle(EntityManager manager) { if (!manager.getTransaction().isActive()) { manager.getTransaction().begin(); } ArrayList<ProcessTask> list = new ArrayList<>();
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileExtensions.java // public class FileExtensions { // // private static final String[] PATCH = "txt,yml,asset,csv,gfx,shader,fxh,gui".split(","); // private static final String[] REPLACE = "wav,ogg,ods,dds,bmp,png,psd,jpg,ani,cur,ttf,fnt,tga,otf,anim,mesh".split(","); // // private FileExtensions() { // //this is a static class only // } // // public static boolean isPatchable(String filename) { // return isInList(PATCH, filename); // } // // public static boolean isReplaceable(String filename) { // return isInList(REPLACE, filename); // } // // public static String[] getPatchable() { // return PATCH; // } // // public static String[] getReplaceable() { // return REPLACE; // } // // private static boolean isInList(String[] list, String filename) { // for (String ext : list) { // if (filename.endsWith("."+ext)) { // return true; // } // } // return false; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // Path: src/main/java/de/idrinth/stellaris/modtools/process3filepatch/OriginalFileFiller.java import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.ProcessTask; import de.idrinth.stellaris.modtools.filesystem.FileExtensions; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.apache.commons.io.FileUtils; public OriginalFileFiller(long aid, FileSystemLocation steamDir) { this.aid = aid; this.steamDir = steamDir; } protected String getContent(String path) { if (!FileExtensions.isPatchable(path)) { return "-unpatchable-";//nothing to do } try { File file = new File( steamDir.get().getAbsolutePath() + "steamapps/common/Stellaris/"//at least ubutu's steam uses lower case + path ); if(file.exists() && file.canRead()){ return FileUtils.readFileToString(file, "utf-8"); } } catch (IOException exception) { System.out.println(exception.getLocalizedMessage()); } return "-not readable-"; } @Override public List<ProcessTask> handle(EntityManager manager) { if (!manager.getTransaction().isActive()) { manager.getTransaction().begin(); } ArrayList<ProcessTask> list = new ArrayList<>();
Original file = (Original) manager.find(Original.class, aid);
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process2prepatchcleaning/Process2Initializer.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/AbstractQueueInitializer.java // abstract public class AbstractQueueInitializer implements DataInitializer { // private boolean isInitialized = false; // protected final LinkedList<ProcessTask> tasks = new LinkedList<>(); // // abstract protected void init(); // // private void initOnce() { // if(isInitialized) { // return; // } // isInitialized = true; // init(); // } // // @Override // public final ProcessTask poll() { // initOnce(); // return tasks.poll(); // } // // @Override // public final boolean hasNext() { // initOnce(); // return !tasks.isEmpty(); // } // // @Override // public int getQueueSize() { // return 20; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/DataInitializer.java // public interface DataInitializer { // ProcessTask poll(); // boolean hasNext(); // int getQueueSize(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.AbstractQueueInitializer; import de.idrinth.stellaris.modtools.process.DataInitializer; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process2prepatchcleaning; public class Process2Initializer extends AbstractQueueInitializer implements DataInitializer { private final PersistenceProvider persistence; public Process2Initializer(PersistenceProvider persistence) { this.persistence = persistence; } @Override protected void init() {
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/AbstractQueueInitializer.java // abstract public class AbstractQueueInitializer implements DataInitializer { // private boolean isInitialized = false; // protected final LinkedList<ProcessTask> tasks = new LinkedList<>(); // // abstract protected void init(); // // private void initOnce() { // if(isInitialized) { // return; // } // isInitialized = true; // init(); // } // // @Override // public final ProcessTask poll() { // initOnce(); // return tasks.poll(); // } // // @Override // public final boolean hasNext() { // initOnce(); // return !tasks.isEmpty(); // } // // @Override // public int getQueueSize() { // return 20; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/DataInitializer.java // public interface DataInitializer { // ProcessTask poll(); // boolean hasNext(); // int getQueueSize(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/process2prepatchcleaning/Process2Initializer.java import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.AbstractQueueInitializer; import de.idrinth.stellaris.modtools.process.DataInitializer; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process2prepatchcleaning; public class Process2Initializer extends AbstractQueueInitializer implements DataInitializer { private final PersistenceProvider persistence; public Process2Initializer(PersistenceProvider persistence) { this.persistence = persistence; } @Override protected void init() {
persistence.get().createNamedQuery("originals", Original.class).getResultList().forEach((o) -> {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process5modcreation/ModTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/FileBased.java // abstract public class FileBased { // private static final String FILE_BASE = System.getProperty("java.io.tmpdir")+"/tests/"; // private File dir; // protected File getAllowedFolder() { // if(null == dir) { // dir = new File(FILE_BASE+this.getClass().getName().replace("\\.", "-")); // dir.mkdirs(); // dir.deleteOnExit(); // } // return dir; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // }
import de.idrinth.stellaris.modtools.abstract_cases.FileBased; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import org.junit.Test; import org.junit.Assert;
"tags = {\n" + "\t\"Merge\"\n" + "}\n", instance.toString() ); } /** * Test of addTagValue method, of class Mod. * @throws java.io.IOException */ @Test public void testAddTagValue() throws IOException { System.out.println("addTagValue"); Mod instance = new Mod("file", "Mod", new ModDirFake(getAllowedFolder())); instance.addTagValue("MyOtherMod"); Assert.assertEquals( "Mod differs from expected content", "name = \"Mod\"\n" + "path = \""+ getAllowedFolder() + "/file.zip\"\n" + "dependencies = {\n" + "}\n" + "supported_version = \"1.0.*\"\n" + "tags = {\n" + "\t\"Merge\"\n" + "\t\"MyOtherMod\"\n" + "}\n", instance.toString() ); }
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/FileBased.java // abstract public class FileBased { // private static final String FILE_BASE = System.getProperty("java.io.tmpdir")+"/tests/"; // private File dir; // protected File getAllowedFolder() { // if(null == dir) { // dir = new File(FILE_BASE+this.getClass().getName().replace("\\.", "-")); // dir.mkdirs(); // dir.deleteOnExit(); // } // return dir; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process5modcreation/ModTest.java import de.idrinth.stellaris.modtools.abstract_cases.FileBased; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import java.io.File; import java.io.IOException; import org.junit.Test; import org.junit.Assert; "tags = {\n" + "\t\"Merge\"\n" + "}\n", instance.toString() ); } /** * Test of addTagValue method, of class Mod. * @throws java.io.IOException */ @Test public void testAddTagValue() throws IOException { System.out.println("addTagValue"); Mod instance = new Mod("file", "Mod", new ModDirFake(getAllowedFolder())); instance.addTagValue("MyOtherMod"); Assert.assertEquals( "Mod differs from expected content", "name = \"Mod\"\n" + "path = \""+ getAllowedFolder() + "/file.zip\"\n" + "dependencies = {\n" + "}\n" + "supported_version = \"1.0.*\"\n" + "tags = {\n" + "\t\"Merge\"\n" + "\t\"MyOtherMod\"\n" + "}\n", instance.toString() ); }
private class ModDirFake implements FileSystemLocation {
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/process4applypatch/Process4Initializer.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/AbstractQueueInitializer.java // abstract public class AbstractQueueInitializer implements DataInitializer { // private boolean isInitialized = false; // protected final LinkedList<ProcessTask> tasks = new LinkedList<>(); // // abstract protected void init(); // // private void initOnce() { // if(isInitialized) { // return; // } // isInitialized = true; // init(); // } // // @Override // public final ProcessTask poll() { // initOnce(); // return tasks.poll(); // } // // @Override // public final boolean hasNext() { // initOnce(); // return !tasks.isEmpty(); // } // // @Override // public int getQueueSize() { // return 20; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/DataInitializer.java // public interface DataInitializer { // ProcessTask poll(); // boolean hasNext(); // int getQueueSize(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // }
import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.AbstractQueueInitializer; import de.idrinth.stellaris.modtools.process.DataInitializer; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process4applypatch; public class Process4Initializer extends AbstractQueueInitializer implements DataInitializer { private final PersistenceProvider persistence; public Process4Initializer(PersistenceProvider persistence) { this.persistence = persistence; } @Override protected void init() {
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Original.java // @NamedQueries({ // @NamedQuery( // name = "originals", // query = "select f from Original f" // ) // , // @NamedQuery( // name = "original.path", // query = "select f from Original f where f.relativePath=:path" // ) // }) // @Entity // public class Original extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //original // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText content; // protected String relativePath; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="file") // @Cascade({CascadeType.DELETE}) // protected Set<Patch> patches = new HashSet<>(); // // public Original() { // } // // public Original(String relativePath) { // this.relativePath = relativePath; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public String getContent() { // if(null == content) { // content = new LazyText(); // } // return content.getText(); // } // // public void setContent(String content) { // if(null == this.content) { // this.content = new LazyText(); // } // this.content.setText(content); // } // // public String getRelativePath() { // return relativePath; // } // // public void setRelativePath(String relativePath) { // this.relativePath = relativePath; // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> patches) { // this.patches = patches; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/AbstractQueueInitializer.java // abstract public class AbstractQueueInitializer implements DataInitializer { // private boolean isInitialized = false; // protected final LinkedList<ProcessTask> tasks = new LinkedList<>(); // // abstract protected void init(); // // private void initOnce() { // if(isInitialized) { // return; // } // isInitialized = true; // init(); // } // // @Override // public final ProcessTask poll() { // initOnce(); // return tasks.poll(); // } // // @Override // public final boolean hasNext() { // initOnce(); // return !tasks.isEmpty(); // } // // @Override // public int getQueueSize() { // return 20; // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/DataInitializer.java // public interface DataInitializer { // ProcessTask poll(); // boolean hasNext(); // int getQueueSize(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/persistence/PersistenceProvider.java // public class PersistenceProvider { // // private final EntityManagerFactory entityManager; // // public EntityManager get() { // return entityManager.createEntityManager(); // } // // public PersistenceProvider() { // entityManager = Persistence.createEntityManagerFactory("de.idrinth_Stellaris.ModTools"); // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/process4applypatch/Process4Initializer.java import de.idrinth.stellaris.modtools.persistence.entity.Original; import de.idrinth.stellaris.modtools.process.AbstractQueueInitializer; import de.idrinth.stellaris.modtools.process.DataInitializer; import de.idrinth.stellaris.modtools.persistence.PersistenceProvider; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process4applypatch; public class Process4Initializer extends AbstractQueueInitializer implements DataInitializer { private final PersistenceProvider persistence; public Process4Initializer(PersistenceProvider persistence) { this.persistence = persistence; } @Override protected void init() {
persistence.get().createNamedQuery("originals", Original.class).getResultList().forEach((o) -> {
Idrinths-Stellaris-Mods/Mod-Tools
src/main/java/de/idrinth/stellaris/modtools/gui/ModDataRow.java
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // }
import de.idrinth.stellaris.modtools.persistence.entity.Modification; import java.util.Set; import javax.persistence.EntityManager;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.gui; public class ModDataRow extends AbstractDataRow { private final long mod;
// Path: src/main/java/de/idrinth/stellaris/modtools/persistence/entity/Modification.java // @NamedQueries({ // @NamedQuery( // name = "modifications", // query = "select m from Modification m" // ) // , // @NamedQuery( // name = "modifications.id", // query = "select m from Modification m where m.id=:id" // ) // , // @NamedQuery( // name = "modifications.config", // query = "select m from Modification m where m.configPath=:configPath" // ) // }) // @Entity // public class Modification extends EntityCompareAndHash { // // @Id // @GeneratedValue // private long aid; // //basics // protected String configPath; // protected int id; // protected String name; // protected String version; // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.DELETE,CascadeType.PERSIST}) // private LazyText description; // //connection // @OneToMany(fetch = FetchType.LAZY, mappedBy="mod") // protected Set<Patch> patches = new HashSet<>(); // @ManyToMany(fetch = FetchType.LAZY) // protected Set<Modification> overwrite = new HashSet<>(); // @OneToOne(fetch = FetchType.LAZY) // @Cascade({CascadeType.ALL}) // protected Colliding collides = new Colliding(); // // public Modification() { // } // // public Modification(String configPath, int id) { // this.configPath = configPath; // this.id = id; // } // // @Override // public long getAid() { // return aid; // } // // @Override // public void setAid(long aid) { // this.aid = aid; // } // // public Set<Patch> getFiles() { // return patches; // } // // public void setFiles(Set<Patch> files) { // this.patches = files; // } // // public Colliding getCollides() { // return collides; // } // // public void setCollides(Colliding collides) { // this.collides = collides; // } // // public String getName() { // return name; // } // // public String getConfigPath() { // return configPath; // } // // public void setConfigPath(String configPath) { // this.configPath = configPath; // } // // public void setName(String name) { // this.name = name; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public Set<Modification> getOverwrite() { // return overwrite; // } // // public void setOverwrite(Set<Modification> overwrite) { // this.overwrite = overwrite; // } // // public String getDescription() { // if(null == description) { // description = new LazyText(); // } // return description.getText(); // } // // public void setDescription(String description) { // if(null == this.description) { // this.description = new LazyText(); // } // this.description.setText(description); // } // // public Set<Patch> getPatches() { // return patches; // } // // public void setPatches(Set<Patch> files) { // this.patches = files; // } // } // Path: src/main/java/de/idrinth/stellaris/modtools/gui/ModDataRow.java import de.idrinth.stellaris.modtools.persistence.entity.Modification; import java.util.Set; import javax.persistence.EntityManager; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.gui; public class ModDataRow extends AbstractDataRow { private final long mod;
public ModDataRow(Modification mod, EntityManager manager) {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process5modcreation/CreateModTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestAnyTask.java // abstract public class TestAnyTask extends TestATask { // // // /** // * Test of handle method, of class Task. // * @deprecated has to be implemented on a case by case basis // */ // @Test // public void testHandle() { // System.out.println("fake handle test"); // Assert.assertTrue(true);//@todo implement the requirements for all tasks // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestAnyTask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; public class CreateModTest extends TestAnyTask { @Override
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestAnyTask.java // abstract public class TestAnyTask extends TestATask { // // // /** // * Test of handle method, of class Task. // * @deprecated has to be implemented on a case by case basis // */ // @Test // public void testHandle() { // System.out.println("fake handle test"); // Assert.assertTrue(true);//@todo implement the requirements for all tasks // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process5modcreation/CreateModTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestAnyTask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; public class CreateModTest extends TestAnyTask { @Override
protected ProcessTask get() {
Idrinths-Stellaris-Mods/Mod-Tools
src/test/java/de/idrinth/stellaris/modtools/process5modcreation/CreateModTest.java
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestAnyTask.java // abstract public class TestAnyTask extends TestATask { // // // /** // * Test of handle method, of class Task. // * @deprecated has to be implemented on a case by case basis // */ // @Test // public void testHandle() { // System.out.println("fake handle test"); // Assert.assertTrue(true);//@todo implement the requirements for all tasks // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // }
import de.idrinth.stellaris.modtools.abstract_cases.TestAnyTask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File;
/* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; public class CreateModTest extends TestAnyTask { @Override protected ProcessTask get() { return new CreateMod(new ModDirFake()); }
// Path: src/test/java/de/idrinth/stellaris/modtools/abstract_cases/TestAnyTask.java // abstract public class TestAnyTask extends TestATask { // // // /** // * Test of handle method, of class Task. // * @deprecated has to be implemented on a case by case basis // */ // @Test // public void testHandle() { // System.out.println("fake handle test"); // Assert.assertTrue(true);//@todo implement the requirements for all tasks // } // } // // Path: src/main/java/de/idrinth/stellaris/modtools/filesystem/FileSystemLocation.java // public interface FileSystemLocation { // public File get(); // } // // Path: src/main/java/de/idrinth/stellaris/modtools/process/ProcessTask.java // public interface ProcessTask { // // List<ProcessTask> handle(EntityManager manager) throws Exception; // String getIdentifier(); // } // Path: src/test/java/de/idrinth/stellaris/modtools/process5modcreation/CreateModTest.java import de.idrinth.stellaris.modtools.abstract_cases.TestAnyTask; import de.idrinth.stellaris.modtools.filesystem.FileSystemLocation; import de.idrinth.stellaris.modtools.process.ProcessTask; import java.io.File; /* * Copyright (C) 2017 Björn Büttner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.idrinth.stellaris.modtools.process5modcreation; public class CreateModTest extends TestAnyTask { @Override protected ProcessTask get() { return new CreateMod(new ModDirFake()); }
private class ModDirFake implements FileSystemLocation {