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
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/MainActivity.java
// Path: app/src/main/java/om/sstvencoder/TextOverlay/LabelSettings.java // public class LabelSettings implements Parcelable { // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // @Override // public LabelSettings createFromParcel(Parcel source) { // return new LabelSettings(source); // } // // @Override // public LabelSettings[] newArray(int size) { // return new LabelSettings[size]; // } // }; // // private float mTextSize; // private String mText; // private int mColor; // // public LabelSettings() { // mText = ""; // mTextSize = 2.0f; // mColor = Color.BLACK; // } // // public LabelSettings(Parcel src) { // readFromParcel(src); // } // // private void readFromParcel(Parcel src) { // setText(src.readString()); // mTextSize = src.readFloat(); // setColor(src.readInt()); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mText); // dest.writeFloat(mTextSize); // dest.writeInt(mColor); // } // // @Override // public int describeContents() { // return 0; // } // // public void setText(String text) { // if (text != null) // mText = text.trim(); // else // mText = ""; // } // // public String getText() { // return mText; // } // // public void setColor(int color) { // mColor = color; // } // // public int getColor() { // return mColor; // } // // public void setTextSize(float textSize) { // mTextSize = textSize; // } // // public float getTextSize() { // return mTextSize; // } // }
import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.system.ErrnoException; import android.system.OsConstants; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.FileNotFoundException; import om.sstvencoder.TextOverlay.LabelSettings;
return true; case R.id.action_scottie2: mCropView.setModeSize(mEncoder.setScottie2()); setTitle(R.string.action_scottie2); return true; case R.id.action_scottiedx: mCropView.setModeSize(mEncoder.setScottieDX()); setTitle(R.string.action_scottiedx); return true; case R.id.action_robot36: mCropView.setModeSize(mEncoder.setRobot36()); setTitle(R.string.action_robot36); return true; case R.id.action_robot72: mCropView.setModeSize(mEncoder.setRobot72()); setTitle(R.string.action_robot72); return true; case R.id.action_wraase: mCropView.setModeSize(mEncoder.setWraase()); setTitle(R.string.action_wraase); return true; default: return super.onOptionsItemSelected(item); } } private void send() { mEncoder.send(mCropView.getBitmap()); }
// Path: app/src/main/java/om/sstvencoder/TextOverlay/LabelSettings.java // public class LabelSettings implements Parcelable { // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // @Override // public LabelSettings createFromParcel(Parcel source) { // return new LabelSettings(source); // } // // @Override // public LabelSettings[] newArray(int size) { // return new LabelSettings[size]; // } // }; // // private float mTextSize; // private String mText; // private int mColor; // // public LabelSettings() { // mText = ""; // mTextSize = 2.0f; // mColor = Color.BLACK; // } // // public LabelSettings(Parcel src) { // readFromParcel(src); // } // // private void readFromParcel(Parcel src) { // setText(src.readString()); // mTextSize = src.readFloat(); // setColor(src.readInt()); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mText); // dest.writeFloat(mTextSize); // dest.writeInt(mColor); // } // // @Override // public int describeContents() { // return 0; // } // // public void setText(String text) { // if (text != null) // mText = text.trim(); // else // mText = ""; // } // // public String getText() { // return mText; // } // // public void setColor(int color) { // mColor = color; // } // // public int getColor() { // return mColor; // } // // public void setTextSize(float textSize) { // mTextSize = textSize; // } // // public float getTextSize() { // return mTextSize; // } // } // Path: app/src/main/java/om/sstvencoder/MainActivity.java import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.system.ErrnoException; import android.system.OsConstants; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.io.FileNotFoundException; import om.sstvencoder.TextOverlay.LabelSettings; return true; case R.id.action_scottie2: mCropView.setModeSize(mEncoder.setScottie2()); setTitle(R.string.action_scottie2); return true; case R.id.action_scottiedx: mCropView.setModeSize(mEncoder.setScottieDX()); setTitle(R.string.action_scottiedx); return true; case R.id.action_robot36: mCropView.setModeSize(mEncoder.setRobot36()); setTitle(R.string.action_robot36); return true; case R.id.action_robot72: mCropView.setModeSize(mEncoder.setRobot72()); setTitle(R.string.action_robot72); return true; case R.id.action_wraase: mCropView.setModeSize(mEncoder.setWraase()); setTitle(R.string.action_wraase); return true; default: return super.onOptionsItemSelected(item); } } private void send() { mEncoder.send(mCropView.getBitmap()); }
public void startEditTextActivity(LabelSettings settings) {
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/TextOverlay/Label.java
// Path: app/src/main/java/om/sstvencoder/Utility.java // public final class Utility { // // public static android.graphics.Rect getEmbeddedRect(int w, int h, int iw, int ih) { // android.graphics.Rect rect; // // int ow = (9 * w) / 10; // int oh = (9 * h) / 10; // // if (iw * oh < ow * ih) { // rect = new android.graphics.Rect(0, 0, (iw * oh) / ih, oh); // rect.offset((w - (iw * oh) / ih) / 2, (h - oh) / 2); // } else { // rect = new android.graphics.Rect(0, 0, ow, (ih * ow) / iw); // rect.offset((w - ow) / 2, (h - (ih * ow) / iw) / 2); // } // return rect; // } // // /* public static void vibrate(int duration, android.content.Context context) { // android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(android.content.Context.VIBRATOR_SERVICE); // vibrator.vibrate(duration); // } */ // // public static String createMessage(Exception ex) { // String message = ex.getMessage() + "\n"; // for (StackTraceElement el : ex.getStackTrace()) // message += "\n" + el.toString(); // return message; // } // // public static Intent createEmailIntent(final String subject, final String text) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("text/email"); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"olga.rgb@googlemail.com"}); // intent.putExtra(Intent.EXTRA_SUBJECT, subject); // intent.putExtra(Intent.EXTRA_TEXT, text); // return intent; // } // // public static int convertToDegrees(int exifOrientation) { // switch (exifOrientation) { // case ExifInterface.ORIENTATION_ROTATE_90: // return 90; // case ExifInterface.ORIENTATION_ROTATE_180: // return 180; // case ExifInterface.ORIENTATION_ROTATE_270: // return 270; // } // return 0; // } // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import om.sstvencoder.Utility;
x = mCurrent.mW + mBounds.left - mCurrent.mX - m / 2.0f; if (mBounds.top + mBounds.height() < m) y = mCurrent.mY - mBounds.top - m / 2.0f; else if (mCurrent.mH - mBounds.top >= m) y = mCurrent.mY; else y = mCurrent.mH + mCurrent.mY - mBounds.bottom + m / 2.0f; mCurrent.set(x, y); adjustGeometry(); } adjust(); } public void update(float w, float h) { setCurrentGeometry(w, h); setTextSizeFactor(); adjust(); } private void setCurrentGeometry(float w, float h) { if (mVertical == null) mVertical = new Geometry(mHorizontal.mX - (mHorizontal.mW - w) / 2.0f, (h - mHorizontal.mH) / 2.0f + mHorizontal.mY, w, h); else if (mHorizontal == null) mHorizontal = new Geometry((w - mVertical.mW) / 2.0f + mVertical.mX, mVertical.mY - (mVertical.mH - h) / 2.0f, w, h); mCurrent = w < h ? mVertical : mHorizontal; } private void setTextSizeFactor() {
// Path: app/src/main/java/om/sstvencoder/Utility.java // public final class Utility { // // public static android.graphics.Rect getEmbeddedRect(int w, int h, int iw, int ih) { // android.graphics.Rect rect; // // int ow = (9 * w) / 10; // int oh = (9 * h) / 10; // // if (iw * oh < ow * ih) { // rect = new android.graphics.Rect(0, 0, (iw * oh) / ih, oh); // rect.offset((w - (iw * oh) / ih) / 2, (h - oh) / 2); // } else { // rect = new android.graphics.Rect(0, 0, ow, (ih * ow) / iw); // rect.offset((w - ow) / 2, (h - (ih * ow) / iw) / 2); // } // return rect; // } // // /* public static void vibrate(int duration, android.content.Context context) { // android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(android.content.Context.VIBRATOR_SERVICE); // vibrator.vibrate(duration); // } */ // // public static String createMessage(Exception ex) { // String message = ex.getMessage() + "\n"; // for (StackTraceElement el : ex.getStackTrace()) // message += "\n" + el.toString(); // return message; // } // // public static Intent createEmailIntent(final String subject, final String text) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("text/email"); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"olga.rgb@googlemail.com"}); // intent.putExtra(Intent.EXTRA_SUBJECT, subject); // intent.putExtra(Intent.EXTRA_TEXT, text); // return intent; // } // // public static int convertToDegrees(int exifOrientation) { // switch (exifOrientation) { // case ExifInterface.ORIENTATION_ROTATE_90: // return 90; // case ExifInterface.ORIENTATION_ROTATE_180: // return 180; // case ExifInterface.ORIENTATION_ROTATE_270: // return 270; // } // return 0; // } // } // Path: app/src/main/java/om/sstvencoder/TextOverlay/Label.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import om.sstvencoder.Utility; x = mCurrent.mW + mBounds.left - mCurrent.mX - m / 2.0f; if (mBounds.top + mBounds.height() < m) y = mCurrent.mY - mBounds.top - m / 2.0f; else if (mCurrent.mH - mBounds.top >= m) y = mCurrent.mY; else y = mCurrent.mH + mCurrent.mY - mBounds.bottom + m / 2.0f; mCurrent.set(x, y); adjustGeometry(); } adjust(); } public void update(float w, float h) { setCurrentGeometry(w, h); setTextSizeFactor(); adjust(); } private void setCurrentGeometry(float w, float h) { if (mVertical == null) mVertical = new Geometry(mHorizontal.mX - (mHorizontal.mW - w) / 2.0f, (h - mHorizontal.mH) / 2.0f + mHorizontal.mY, w, h); else if (mHorizontal == null) mHorizontal = new Geometry((w - mVertical.mW) / 2.0f + mVertical.mX, mVertical.mY - (mVertical.mH - h) / 2.0f, w, h); mCurrent = w < h ? mVertical : mHorizontal; } private void setTextSizeFactor() {
Rect bounds = Utility.getEmbeddedRect((int) mCurrent.mW, (int) mCurrent.mH, 320, 240);
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/EditTextActivity.java
// Path: app/src/main/java/om/sstvencoder/TextOverlay/LabelSettings.java // public class LabelSettings implements Parcelable { // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // @Override // public LabelSettings createFromParcel(Parcel source) { // return new LabelSettings(source); // } // // @Override // public LabelSettings[] newArray(int size) { // return new LabelSettings[size]; // } // }; // // private float mTextSize; // private String mText; // private int mColor; // // public LabelSettings() { // mText = ""; // mTextSize = 2.0f; // mColor = Color.BLACK; // } // // public LabelSettings(Parcel src) { // readFromParcel(src); // } // // private void readFromParcel(Parcel src) { // setText(src.readString()); // mTextSize = src.readFloat(); // setColor(src.readInt()); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mText); // dest.writeFloat(mTextSize); // dest.writeInt(mColor); // } // // @Override // public int describeContents() { // return 0; // } // // public void setText(String text) { // if (text != null) // mText = text.trim(); // else // mText = ""; // } // // public String getText() { // return mText; // } // // public void setColor(int color) { // mColor = color; // } // // public int getColor() { // return mColor; // } // // public void setTextSize(float textSize) { // mTextSize = textSize; // } // // public float getTextSize() { // return mTextSize; // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import om.sstvencoder.TextOverlay.LabelSettings;
/* Copyright 2015 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder; public class EditTextActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public static final int REQUEST_CODE = 101; public static final String SETTINGS_ID = "EditLabel"; private EditText mEditText; private ColorView mColorView; private float mTextSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_text); mEditText = (EditText) findViewById(R.id.edit_text); mColorView = (ColorView) findViewById(R.id.edit_color); } // Now ColorView should have width and height unequal 0. @Override protected void onStart() { super.onStart();
// Path: app/src/main/java/om/sstvencoder/TextOverlay/LabelSettings.java // public class LabelSettings implements Parcelable { // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // @Override // public LabelSettings createFromParcel(Parcel source) { // return new LabelSettings(source); // } // // @Override // public LabelSettings[] newArray(int size) { // return new LabelSettings[size]; // } // }; // // private float mTextSize; // private String mText; // private int mColor; // // public LabelSettings() { // mText = ""; // mTextSize = 2.0f; // mColor = Color.BLACK; // } // // public LabelSettings(Parcel src) { // readFromParcel(src); // } // // private void readFromParcel(Parcel src) { // setText(src.readString()); // mTextSize = src.readFloat(); // setColor(src.readInt()); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mText); // dest.writeFloat(mTextSize); // dest.writeInt(mColor); // } // // @Override // public int describeContents() { // return 0; // } // // public void setText(String text) { // if (text != null) // mText = text.trim(); // else // mText = ""; // } // // public String getText() { // return mText; // } // // public void setColor(int color) { // mColor = color; // } // // public int getColor() { // return mColor; // } // // public void setTextSize(float textSize) { // mTextSize = textSize; // } // // public float getTextSize() { // return mTextSize; // } // } // Path: app/src/main/java/om/sstvencoder/EditTextActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import om.sstvencoder.TextOverlay.LabelSettings; /* Copyright 2015 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder; public class EditTextActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public static final int REQUEST_CODE = 101; public static final String SETTINGS_ID = "EditLabel"; private EditText mEditText; private ColorView mColorView; private float mTextSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_text); mEditText = (EditText) findViewById(R.id.edit_text); mColorView = (ColorView) findViewById(R.id.edit_color); } // Now ColorView should have width and height unequal 0. @Override protected void onStart() { super.onStart();
LabelSettings settings = getIntent().getParcelableExtra(SETTINGS_ID);
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/Modes/Robot36.java
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // }
import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat;
/* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot36 extends Mode {
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // } // Path: app/src/main/java/om/sstvencoder/Modes/Robot36.java import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat; /* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot36 extends Mode {
private final Yuv mYuv;
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/Modes/Robot36.java
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // }
import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat;
/* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot36 extends Mode { private final Yuv mYuv; private final int mLumaScanSamples; private final int mChrominanceScanSamples; private final int mSyncPulseSamples; private final double mSyncPulseFrequency; private final int mSyncPorchSamples; private final double mSyncPorchFrequency; private final int mPorchSamples; private final double mPorchFrequency; private final int mSeparatorSamples; private final double mEvenSeparatorFrequency; private final double mOddSeparatorFrequency; public Robot36(Bitmap bitmap) { super(bitmap);
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // } // Path: app/src/main/java/om/sstvencoder/Modes/Robot36.java import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat; /* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot36 extends Mode { private final Yuv mYuv; private final int mLumaScanSamples; private final int mChrominanceScanSamples; private final int mSyncPulseSamples; private final double mSyncPulseFrequency; private final int mSyncPorchSamples; private final double mSyncPorchFrequency; private final int mPorchSamples; private final double mPorchFrequency; private final int mSeparatorSamples; private final double mEvenSeparatorFrequency; private final double mOddSeparatorFrequency; public Robot36(Bitmap bitmap) { super(bitmap);
mYuv = Yuv.createYuv(mBitmap, YuvImageFormat.NV21);
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/Modes/Robot72.java
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // }
import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat;
/* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot72 extends Mode {
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // } // Path: app/src/main/java/om/sstvencoder/Modes/Robot72.java import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat; /* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot72 extends Mode {
private final Yuv mYuv;
olgamiller/SSTVEncoder
app/src/main/java/om/sstvencoder/Modes/Robot72.java
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // }
import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat;
/* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot72 extends Mode { private final Yuv mYuv; private final int mLumaScanSamples; private final int mChrominanceScanSamples; private final int mSyncPulseSamples; private final double mSyncPulseFrequency; private final int mSyncPorchSamples; private final double mSyncPorchFrequency; private final int mPorchSamples; private final double mPorchFrequency; private final int mSeparatorSamples; private final double mFirstSeparatorFrequency; private final double mSecondSeparatorFrequency; public Robot72(Bitmap bitmap) { super(bitmap);
// Path: app/src/main/java/om/sstvencoder/ImageFormats/Yuv.java // public abstract class Yuv { // protected byte[] mYuv; // protected final int mFormat; // protected final int mWidth; // protected final int mHeight; // // protected Yuv(Bitmap bitmap, int format) { // mFormat = format; // mWidth = bitmap.getWidth(); // mHeight = bitmap.getHeight(); // convertBitmapToYuv(bitmap); // } // // protected abstract void convertBitmapToYuv(Bitmap bitmap); // // public static Yuv createYuv(Bitmap bitmap, int format) { // switch (format) { // case YuvImageFormat.YV12: // return new YV12(bitmap, format); // case YuvImageFormat.NV21: // return new NV21(bitmap, format); // case YuvImageFormat.YUY2: // return new YUY2(bitmap, format); // case YuvImageFormat.YUV440P: // return new YUV440P(bitmap, format); // default: // throw new IllegalArgumentException("Only support YV12, NV21, YUY2 and YUV440P"); // } // } // // public int getWidth() { // return mWidth; // } // // public int getHeight() { // return mHeight; // } // // public YuvImage getYuvImage() { // return new YuvImage(mYuv, mFormat, mWidth, mHeight, null); // } // // public abstract int getY(int x, int y); // // public abstract int getU(int x, int y); // // public abstract int getV(int x, int y); // // public static int convertToY(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(16.0 + (.003906 * ((65.738 * R) + (129.057 * G) + (25.064 * B)))); // } // // public static int convertToU(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((-37.945 * R) + (-74.494 * G) + (112.439 * B)))); // } // // public static int convertToV(int color) { // double R = Color.red(color); // double G = Color.green(color); // double B = Color.blue(color); // return clamp(128.0 + (.003906 * ((112.439 * R) + (-94.154 * G) + (-18.285 * B)))); // } // // private static int clamp(double value) { // return value < 0.0 ? 0 : (value > 255.0 ? 255 : (int) value); // } // } // // Path: app/src/main/java/om/sstvencoder/ImageFormats/YuvImageFormat.java // public class YuvImageFormat extends ImageFormat { // public static final int YUV440P = 0x50303434; // } // Path: app/src/main/java/om/sstvencoder/Modes/Robot72.java import android.graphics.Bitmap; import om.sstvencoder.ImageFormats.Yuv; import om.sstvencoder.ImageFormats.YuvImageFormat; /* Copyright 2014 Olga Miller <olga.rgb@googlemail.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 om.sstvencoder.Modes; @ModeSize(getWidth = 320, getHeight = 240) public class Robot72 extends Mode { private final Yuv mYuv; private final int mLumaScanSamples; private final int mChrominanceScanSamples; private final int mSyncPulseSamples; private final double mSyncPulseFrequency; private final int mSyncPorchSamples; private final double mSyncPorchFrequency; private final int mPorchSamples; private final double mPorchFrequency; private final int mSeparatorSamples; private final double mFirstSeparatorFrequency; private final double mSecondSeparatorFrequency; public Robot72(Bitmap bitmap) { super(bitmap);
mYuv = Yuv.createYuv(mBitmap, YuvImageFormat.YUY2);
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/SaltEdgeSDK.java // public class SaltEdgeSDK { // // private static SaltEdgeSDK instance; // private Context applicationContext; // private String appId; // private String appSecret; // private String returnToUrl; // private boolean loggingEnabled; // // public static SaltEdgeSDK getInstance() { // if (instance == null) { // instance = new SaltEdgeSDK(); // } // return instance; // } // // public String getAppId() { // return appId; // } // // public String getAppSecret() { // return appSecret; // } // // public static String getReturnToUrl() { // return getInstance().returnToUrl; // } // // public static void setReturnToUrl(String returnToUrl) { // getInstance().returnToUrl = returnToUrl; // } // // public static boolean isLoggingEnabled() { // return getInstance().loggingEnabled; // } // // public Context getContext() { // return applicationContext; // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false); // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param enableLogging flag, which enable or disable network logging // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init( // Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean enableLogging // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false, enableLogging); // } // // private void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean actAsPartner, // boolean enableLogging // ) { // if (clientAppId.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_ID_IS_NULL); // } // if (clientAppSecret.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_SECRET_IS_NULL); // } // this.applicationContext = applicationContext; // this.appId = clientAppId; // this.appSecret = clientAppSecret; // this.loggingEnabled = enableLogging; // this.returnToUrl = returnToUrl; // } // // public static void printToLogcat(String tag, String message) { // if (isLoggingEnabled()) { // Log.d(tag, message); // } // } // }
import com.saltedge.sdk.SaltEdgeSDK; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.network; public class HeaderInterceptor implements Interceptor { private String acceptType; public HeaderInterceptor(String acceptType) { this.acceptType = acceptType; } @Override public Response intercept(Chain chain) throws IOException { Request.Builder requestBuilder = chain.request().newBuilder() .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON)
// Path: saltedge-library/src/main/java/com/saltedge/sdk/SaltEdgeSDK.java // public class SaltEdgeSDK { // // private static SaltEdgeSDK instance; // private Context applicationContext; // private String appId; // private String appSecret; // private String returnToUrl; // private boolean loggingEnabled; // // public static SaltEdgeSDK getInstance() { // if (instance == null) { // instance = new SaltEdgeSDK(); // } // return instance; // } // // public String getAppId() { // return appId; // } // // public String getAppSecret() { // return appSecret; // } // // public static String getReturnToUrl() { // return getInstance().returnToUrl; // } // // public static void setReturnToUrl(String returnToUrl) { // getInstance().returnToUrl = returnToUrl; // } // // public static boolean isLoggingEnabled() { // return getInstance().loggingEnabled; // } // // public Context getContext() { // return applicationContext; // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false); // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param enableLogging flag, which enable or disable network logging // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init( // Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean enableLogging // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false, enableLogging); // } // // private void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean actAsPartner, // boolean enableLogging // ) { // if (clientAppId.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_ID_IS_NULL); // } // if (clientAppSecret.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_SECRET_IS_NULL); // } // this.applicationContext = applicationContext; // this.appId = clientAppId; // this.appSecret = clientAppSecret; // this.loggingEnabled = enableLogging; // this.returnToUrl = returnToUrl; // } // // public static void printToLogcat(String tag, String message) { // if (isLoggingEnabled()) { // Log.d(tag, message); // } // } // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java import com.saltedge.sdk.SaltEdgeSDK; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.network; public class HeaderInterceptor implements Interceptor { private String acceptType; public HeaderInterceptor(String acceptType) { this.acceptType = acceptType; } @Override public Response intercept(Chain chain) throws IOException { Request.Builder requestBuilder = chain.request().newBuilder() .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON)
.header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId())
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/connector/DuplicatedTransactionsFetchConnector.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/interfaces/FetchTransactionsResult.java // public interface FetchTransactionsResult { // // /** // * Callback method is invoked when Fetch Transactions operation finished with success // * // * @param transactions List of SETransaction objects // */ // void onSuccess(List<SETransaction> transactions); // // /** // * Callback method is invoked when Fetch Transactions operation finished with error // * // * @param errorMessage String which describes occurred error // */ // void onFailure(String errorMessage); // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/SERestClient.java // public class SERestClient { // // private SERestClient() {} // // private static final String TAG = "SERestClient"; // // public SEApiInterface service = createRetrofit().create(SEApiInterface.class); // public static Gson gson = createDefaultGson(); // private static SERestClient instance; // // public static SERestClient getInstance() { // if (instance == null) { // instance = new SERestClient(); // } // return instance; // } // // public void initService() { // service = createRetrofit().create(SEApiInterface.class); // } // // private Retrofit createRetrofit() { // String baseUrl = SEApiConstants.API_BASE_URL + SEApiConstants.BASE_API_PATH; // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(createOkHttpClient()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .build(); // } // // private static Gson createDefaultGson() { // return new GsonBuilder() // .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) // .create(); // } // // private OkHttpClient createOkHttpClient() { // OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() // .addInterceptor(prepareLoggingInterceptor()); // boolean pinsAdded = addCertificatePinner(clientBuilder); // addSSLSocketFactory(clientBuilder); // addHeaderInterceptor(clientBuilder, pinsAdded); // return clientBuilder.build(); // } // // private void addHeaderInterceptor(OkHttpClient.Builder clientBuilder, boolean acceptJson) { // clientBuilder.addInterceptor(new HeaderInterceptor(acceptJson ? SEApiConstants.MIME_TYPE_JSON : null)); // } // // private boolean addCertificatePinner(OkHttpClient.Builder clientBuilder) { // try { // String[] pins = SEPreferencesRepository.getInstance().getPins(); // if (pins != null && pins.length > 0) { // CertificatePinner.Builder pinnerBuilder = new CertificatePinner.Builder(); // pinnerBuilder.add(SEApiConstants.API_HOST_NAME, pins); // clientBuilder.certificatePinner(pinnerBuilder.build()); // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // private void addSSLSocketFactory(OkHttpClient.Builder builder) { // try { // TLSSocketFactory factory = new TLSSocketFactory(SaltEdgeSDK.getInstance().getContext()); // builder.sslSocketFactory(factory, factory.getTrustManager()); // } catch (Exception e) { // Log.e(TAG, "Can't add SSL Socket factory"); // e.printStackTrace(); // } // } // // private HttpLoggingInterceptor prepareLoggingInterceptor() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(SaltEdgeSDK.isLoggingEnabled() // ? HttpLoggingInterceptor.Level.BODY // : HttpLoggingInterceptor.Level.NONE); // return interceptor; // } // }
import com.saltedge.sdk.network.SERestClient; import com.saltedge.sdk.interfaces.FetchTransactionsResult;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.connector; public class DuplicatedTransactionsFetchConnector extends TransactionsConnector { public DuplicatedTransactionsFetchConnector(FetchTransactionsResult callback) { super(callback); } @Override public void enqueueCall() {
// Path: saltedge-library/src/main/java/com/saltedge/sdk/interfaces/FetchTransactionsResult.java // public interface FetchTransactionsResult { // // /** // * Callback method is invoked when Fetch Transactions operation finished with success // * // * @param transactions List of SETransaction objects // */ // void onSuccess(List<SETransaction> transactions); // // /** // * Callback method is invoked when Fetch Transactions operation finished with error // * // * @param errorMessage String which describes occurred error // */ // void onFailure(String errorMessage); // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/SERestClient.java // public class SERestClient { // // private SERestClient() {} // // private static final String TAG = "SERestClient"; // // public SEApiInterface service = createRetrofit().create(SEApiInterface.class); // public static Gson gson = createDefaultGson(); // private static SERestClient instance; // // public static SERestClient getInstance() { // if (instance == null) { // instance = new SERestClient(); // } // return instance; // } // // public void initService() { // service = createRetrofit().create(SEApiInterface.class); // } // // private Retrofit createRetrofit() { // String baseUrl = SEApiConstants.API_BASE_URL + SEApiConstants.BASE_API_PATH; // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(createOkHttpClient()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .build(); // } // // private static Gson createDefaultGson() { // return new GsonBuilder() // .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) // .create(); // } // // private OkHttpClient createOkHttpClient() { // OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() // .addInterceptor(prepareLoggingInterceptor()); // boolean pinsAdded = addCertificatePinner(clientBuilder); // addSSLSocketFactory(clientBuilder); // addHeaderInterceptor(clientBuilder, pinsAdded); // return clientBuilder.build(); // } // // private void addHeaderInterceptor(OkHttpClient.Builder clientBuilder, boolean acceptJson) { // clientBuilder.addInterceptor(new HeaderInterceptor(acceptJson ? SEApiConstants.MIME_TYPE_JSON : null)); // } // // private boolean addCertificatePinner(OkHttpClient.Builder clientBuilder) { // try { // String[] pins = SEPreferencesRepository.getInstance().getPins(); // if (pins != null && pins.length > 0) { // CertificatePinner.Builder pinnerBuilder = new CertificatePinner.Builder(); // pinnerBuilder.add(SEApiConstants.API_HOST_NAME, pins); // clientBuilder.certificatePinner(pinnerBuilder.build()); // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // private void addSSLSocketFactory(OkHttpClient.Builder builder) { // try { // TLSSocketFactory factory = new TLSSocketFactory(SaltEdgeSDK.getInstance().getContext()); // builder.sslSocketFactory(factory, factory.getTrustManager()); // } catch (Exception e) { // Log.e(TAG, "Can't add SSL Socket factory"); // e.printStackTrace(); // } // } // // private HttpLoggingInterceptor prepareLoggingInterceptor() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(SaltEdgeSDK.isLoggingEnabled() // ? HttpLoggingInterceptor.Level.BODY // : HttpLoggingInterceptor.Level.NONE); // return interceptor; // } // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/connector/DuplicatedTransactionsFetchConnector.java import com.saltedge.sdk.network.SERestClient; import com.saltedge.sdk.interfaces.FetchTransactionsResult; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.connector; public class DuplicatedTransactionsFetchConnector extends TransactionsConnector { public DuplicatedTransactionsFetchConnector(FetchTransactionsResult callback) { super(callback); } @Override public void enqueueCall() {
SERestClient.getInstance().service
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/utils/SEJsonTools.java // public class SEJsonTools { // // /** // * Extract string, int, boolean, double, array, object, stringToJSON or errorMessage value from JSONObject by key. // * // * @param jsonObject // * @param key // * @return string value by key from json Object or empty string // */ // public static String getString(JSONObject jsonObject, String key) { // String result = ""; // return (String) parse(jsonObject, key, result); // } // // public static int getInt(JSONObject jsonObject, String key) { // int result = 0; // return (int) parse(jsonObject, key, result); // } // // public static Boolean getBoolean(JSONObject jsonObject, String key) { // Boolean result = false; // return (Boolean) parse(jsonObject, key, result); // } // // public static Double getDouble(JSONObject jsonObject, String key) { // double result = 0d; // return (Double) parse(jsonObject, key, result); // } // // public static JSONArray getJSONArray(JSONObject jsonObject, String key) { // JSONArray result = new JSONArray(); // return (JSONArray) parse(jsonObject, key, result); // } // // public static JSONObject getObject(JSONObject jsonObject, String key) { // JSONObject result = new JSONObject(); // return (JSONObject) parse(jsonObject, key, result); // } // // public static JSONObject stringToJSON(String string) { // JSONObject result = new JSONObject(); // if (string == null || string.isEmpty()) return result; // try { // return new JSONObject(string); // } catch (JSONException e) { // e.printStackTrace(); // } // return new JSONObject(); // } // // public static String getErrorMessage(ResponseBody error) { // return getErrorMessage(error, SEConstants.REQUEST_ERROR); // } // // public static String getErrorMessage(ResponseBody error, String defaultMessage) { // try { // SEApiError apiError = new Gson().fromJson(error.string(), SEApiError.class); // String result = (apiError != null) ? apiError.getErrorMessage() : defaultMessage; // return (result != null) ? result : defaultMessage; // } catch (Exception e) { // e.printStackTrace(); // return defaultMessage; // } // } // // private static boolean validation(JSONObject jsonObject, String key) { // return jsonObject == null || key == null || key.isEmpty() || jsonObject.isNull(key); // } // // private static Object parse(JSONObject jsonObject, String key, Object result) { // if (validation(jsonObject, key)) { // return result; // } // try { // if (result.getClass().equals(JSONObject.class)) { // return jsonObject.getJSONObject(key); // } else if (result.getClass().equals(String.class)) { // return jsonObject.getString(key); // } else if (result.getClass().equals(JSONArray.class)) { // return jsonObject.getJSONArray(key); // } else if (result.getClass().equals(Double.class)) { // return jsonObject.getDouble(key); // } else if (result.getClass().equals(Boolean.class)) { // return jsonObject.getBoolean(key); // } else if (result.getClass().equals(Integer.class)) { // return jsonObject.getInt(key); // } // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // // }
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.saltedge.sdk.utils.SEJsonTools; import org.json.JSONObject; import java.lang.reflect.Type;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.network; public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { @Override public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Path: saltedge-library/src/main/java/com/saltedge/sdk/utils/SEJsonTools.java // public class SEJsonTools { // // /** // * Extract string, int, boolean, double, array, object, stringToJSON or errorMessage value from JSONObject by key. // * // * @param jsonObject // * @param key // * @return string value by key from json Object or empty string // */ // public static String getString(JSONObject jsonObject, String key) { // String result = ""; // return (String) parse(jsonObject, key, result); // } // // public static int getInt(JSONObject jsonObject, String key) { // int result = 0; // return (int) parse(jsonObject, key, result); // } // // public static Boolean getBoolean(JSONObject jsonObject, String key) { // Boolean result = false; // return (Boolean) parse(jsonObject, key, result); // } // // public static Double getDouble(JSONObject jsonObject, String key) { // double result = 0d; // return (Double) parse(jsonObject, key, result); // } // // public static JSONArray getJSONArray(JSONObject jsonObject, String key) { // JSONArray result = new JSONArray(); // return (JSONArray) parse(jsonObject, key, result); // } // // public static JSONObject getObject(JSONObject jsonObject, String key) { // JSONObject result = new JSONObject(); // return (JSONObject) parse(jsonObject, key, result); // } // // public static JSONObject stringToJSON(String string) { // JSONObject result = new JSONObject(); // if (string == null || string.isEmpty()) return result; // try { // return new JSONObject(string); // } catch (JSONException e) { // e.printStackTrace(); // } // return new JSONObject(); // } // // public static String getErrorMessage(ResponseBody error) { // return getErrorMessage(error, SEConstants.REQUEST_ERROR); // } // // public static String getErrorMessage(ResponseBody error, String defaultMessage) { // try { // SEApiError apiError = new Gson().fromJson(error.string(), SEApiError.class); // String result = (apiError != null) ? apiError.getErrorMessage() : defaultMessage; // return (result != null) ? result : defaultMessage; // } catch (Exception e) { // e.printStackTrace(); // return defaultMessage; // } // } // // private static boolean validation(JSONObject jsonObject, String key) { // return jsonObject == null || key == null || key.isEmpty() || jsonObject.isNull(key); // } // // private static Object parse(JSONObject jsonObject, String key, Object result) { // if (validation(jsonObject, key)) { // return result; // } // try { // if (result.getClass().equals(JSONObject.class)) { // return jsonObject.getJSONObject(key); // } else if (result.getClass().equals(String.class)) { // return jsonObject.getString(key); // } else if (result.getClass().equals(JSONArray.class)) { // return jsonObject.getJSONArray(key); // } else if (result.getClass().equals(Double.class)) { // return jsonObject.getDouble(key); // } else if (result.getClass().equals(Boolean.class)) { // return jsonObject.getBoolean(key); // } else if (result.getClass().equals(Integer.class)) { // return jsonObject.getInt(key); // } // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.saltedge.sdk.utils.SEJsonTools; import org.json.JSONObject; import java.lang.reflect.Type; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.network; public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { @Override public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return SEJsonTools.stringToJSON(json.getAsJsonObject().toString());
saltedge/saltedge-android
saltedge-library/src/androidTest/java/com/saltedge/sdk/network/SERestClientTest.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/response/ProvidersResponse.java // public class ProvidersResponse { // // @SerializedName(SEConstants.KEY_DATA) // private List<SEProvider> data; // // @SerializedName(SEConstants.KEY_META) // private Meta meta; // // public List<SEProvider> getData() { // return data; // } // // public Meta getMeta() { // return meta; // } // }
import androidx.test.runner.AndroidJUnit4; import com.saltedge.sdk.model.response.ProvidersResponse; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import retrofit2.Call;
package com.saltedge.sdk.network; @RunWith(AndroidJUnit4.class) public class SERestClientTest { @Test public void createRetrofitTest() throws Exception { SERestClient.getInstance().initService();
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/response/ProvidersResponse.java // public class ProvidersResponse { // // @SerializedName(SEConstants.KEY_DATA) // private List<SEProvider> data; // // @SerializedName(SEConstants.KEY_META) // private Meta meta; // // public List<SEProvider> getData() { // return data; // } // // public Meta getMeta() { // return meta; // } // } // Path: saltedge-library/src/androidTest/java/com/saltedge/sdk/network/SERestClientTest.java import androidx.test.runner.AndroidJUnit4; import com.saltedge.sdk.model.response.ProvidersResponse; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import retrofit2.Call; package com.saltedge.sdk.network; @RunWith(AndroidJUnit4.class) public class SERestClientTest { @Test public void createRetrofitTest() throws Exception { SERestClient.getInstance().initService();
Call<ProvidersResponse> call = SERestClient.getInstance().service.getProviders("", true, "");
saltedge/saltedge-android
app/src/main/java/com/saltedge/sdk/sample/adapters/TransactionsAdapter.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SETransaction.java // public class SETransaction extends BaseModel { // // @SerializedName(SEConstants.KEY_DUPLICATED) // private boolean duplicated; // // @SerializedName(SEConstants.KEY_MODE) // private String mode; // // @SerializedName(SEConstants.KEY_STATUS) // private String status; // // @SerializedName(SEConstants.KEY_MADE_ON) // private String madeOn; // // @SerializedName(SEConstants.KEY_AMOUNT) // private double amount; // // @SerializedName(SEConstants.KEY_CURRENCY_CODE) // private String currencyCode; // // @SerializedName(SEConstants.KEY_DESCRIPTION) // private String description; // // @SerializedName(SEConstants.KEY_CATEGORY) // private String category; // // @SerializedName(SEConstants.KEY_ACCOUNT_ID) // private String accountId; // // @SerializedName(SEConstants.KEY_EXTRA) // private JSONObject extra; // // // GETTER AND SETTERS // // public boolean isDuplicated() { // return duplicated; // } // // public void setDuplicated(boolean duplicated) { // this.duplicated = duplicated; // } // // public String getMode() { // return mode; // } // // public void setMode(String mode) { // this.mode = mode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getMadeOn() { // return madeOn; // } // // public Date getMadeOnDate() { // return SEDateTools.parseShortStringToDate(madeOn); // } // // public void setMadeOn(String madeOn) { // this.madeOn = madeOn; // } // // public double getAmount() { // return amount; // } // // public void setAmount(double amount) { // this.amount = amount; // } // // public String getCurrencyCode() { // return currencyCode; // } // // public void setCurrencyCode(String currencyCode) { // this.currencyCode = currencyCode; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setAccountId(String accountId) { // this.accountId = accountId; // } // // public String getAccountId() { // return accountId; // } // // public JSONObject getExtra() { // return extra; // } // // public void setExtra(JSONObject extra) { // this.extra = extra; // } // } // // Path: app/src/main/java/com/saltedge/sdk/sample/utils/DateTools.java // public class DateTools { // // public static String formatDateToString(Date date) { // SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()); // try { // return sdf.format(date); // } catch (NullPointerException e) { // e.printStackTrace(); // } // return ""; // } // }
import com.saltedge.sdk.model.SETransaction; import com.saltedge.sdk.sample.R; import com.saltedge.sdk.sample.utils.DateTools; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import androidx.annotation.NonNull;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.sample.adapters; public class TransactionsAdapter extends ArrayAdapter<SETransaction> { public TransactionsAdapter(Context context, ArrayList<SETransaction> transactions) { super(context, 0, transactions); } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { SETransaction transaction = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_transaction, parent, false); } // Lookup view for data population TextView dateLabel = convertView.findViewById(R.id.dateLabel); TextView amountLabel = convertView.findViewById(R.id.amountLabel); TextView descriptionLabel = convertView.findViewById(R.id.description); // Populate the data into the template view using the data object String dateText = "Invalid entry"; String amountText = ""; String descriptionText = ""; if (transaction != null) {
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SETransaction.java // public class SETransaction extends BaseModel { // // @SerializedName(SEConstants.KEY_DUPLICATED) // private boolean duplicated; // // @SerializedName(SEConstants.KEY_MODE) // private String mode; // // @SerializedName(SEConstants.KEY_STATUS) // private String status; // // @SerializedName(SEConstants.KEY_MADE_ON) // private String madeOn; // // @SerializedName(SEConstants.KEY_AMOUNT) // private double amount; // // @SerializedName(SEConstants.KEY_CURRENCY_CODE) // private String currencyCode; // // @SerializedName(SEConstants.KEY_DESCRIPTION) // private String description; // // @SerializedName(SEConstants.KEY_CATEGORY) // private String category; // // @SerializedName(SEConstants.KEY_ACCOUNT_ID) // private String accountId; // // @SerializedName(SEConstants.KEY_EXTRA) // private JSONObject extra; // // // GETTER AND SETTERS // // public boolean isDuplicated() { // return duplicated; // } // // public void setDuplicated(boolean duplicated) { // this.duplicated = duplicated; // } // // public String getMode() { // return mode; // } // // public void setMode(String mode) { // this.mode = mode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getMadeOn() { // return madeOn; // } // // public Date getMadeOnDate() { // return SEDateTools.parseShortStringToDate(madeOn); // } // // public void setMadeOn(String madeOn) { // this.madeOn = madeOn; // } // // public double getAmount() { // return amount; // } // // public void setAmount(double amount) { // this.amount = amount; // } // // public String getCurrencyCode() { // return currencyCode; // } // // public void setCurrencyCode(String currencyCode) { // this.currencyCode = currencyCode; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setAccountId(String accountId) { // this.accountId = accountId; // } // // public String getAccountId() { // return accountId; // } // // public JSONObject getExtra() { // return extra; // } // // public void setExtra(JSONObject extra) { // this.extra = extra; // } // } // // Path: app/src/main/java/com/saltedge/sdk/sample/utils/DateTools.java // public class DateTools { // // public static String formatDateToString(Date date) { // SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()); // try { // return sdf.format(date); // } catch (NullPointerException e) { // e.printStackTrace(); // } // return ""; // } // } // Path: app/src/main/java/com/saltedge/sdk/sample/adapters/TransactionsAdapter.java import com.saltedge.sdk.model.SETransaction; import com.saltedge.sdk.sample.R; import com.saltedge.sdk.sample.utils.DateTools; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import androidx.annotation.NonNull; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.sample.adapters; public class TransactionsAdapter extends ArrayAdapter<SETransaction> { public TransactionsAdapter(Context context, ArrayList<SETransaction> transactions) { super(context, 0, transactions); } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { SETransaction transaction = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_transaction, parent, false); } // Lookup view for data population TextView dateLabel = convertView.findViewById(R.id.dateLabel); TextView amountLabel = convertView.findViewById(R.id.amountLabel); TextView descriptionLabel = convertView.findViewById(R.id.description); // Populate the data into the template view using the data object String dateText = "Invalid entry"; String amountText = ""; String descriptionText = ""; if (transaction != null) {
dateText = DateTools.formatDateToString(transaction.getMadeOnDate());
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/connector/PendingTransactionsFetchConnector.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/interfaces/FetchTransactionsResult.java // public interface FetchTransactionsResult { // // /** // * Callback method is invoked when Fetch Transactions operation finished with success // * // * @param transactions List of SETransaction objects // */ // void onSuccess(List<SETransaction> transactions); // // /** // * Callback method is invoked when Fetch Transactions operation finished with error // * // * @param errorMessage String which describes occurred error // */ // void onFailure(String errorMessage); // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/SERestClient.java // public class SERestClient { // // private SERestClient() {} // // private static final String TAG = "SERestClient"; // // public SEApiInterface service = createRetrofit().create(SEApiInterface.class); // public static Gson gson = createDefaultGson(); // private static SERestClient instance; // // public static SERestClient getInstance() { // if (instance == null) { // instance = new SERestClient(); // } // return instance; // } // // public void initService() { // service = createRetrofit().create(SEApiInterface.class); // } // // private Retrofit createRetrofit() { // String baseUrl = SEApiConstants.API_BASE_URL + SEApiConstants.BASE_API_PATH; // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(createOkHttpClient()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .build(); // } // // private static Gson createDefaultGson() { // return new GsonBuilder() // .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) // .create(); // } // // private OkHttpClient createOkHttpClient() { // OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() // .addInterceptor(prepareLoggingInterceptor()); // boolean pinsAdded = addCertificatePinner(clientBuilder); // addSSLSocketFactory(clientBuilder); // addHeaderInterceptor(clientBuilder, pinsAdded); // return clientBuilder.build(); // } // // private void addHeaderInterceptor(OkHttpClient.Builder clientBuilder, boolean acceptJson) { // clientBuilder.addInterceptor(new HeaderInterceptor(acceptJson ? SEApiConstants.MIME_TYPE_JSON : null)); // } // // private boolean addCertificatePinner(OkHttpClient.Builder clientBuilder) { // try { // String[] pins = SEPreferencesRepository.getInstance().getPins(); // if (pins != null && pins.length > 0) { // CertificatePinner.Builder pinnerBuilder = new CertificatePinner.Builder(); // pinnerBuilder.add(SEApiConstants.API_HOST_NAME, pins); // clientBuilder.certificatePinner(pinnerBuilder.build()); // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // private void addSSLSocketFactory(OkHttpClient.Builder builder) { // try { // TLSSocketFactory factory = new TLSSocketFactory(SaltEdgeSDK.getInstance().getContext()); // builder.sslSocketFactory(factory, factory.getTrustManager()); // } catch (Exception e) { // Log.e(TAG, "Can't add SSL Socket factory"); // e.printStackTrace(); // } // } // // private HttpLoggingInterceptor prepareLoggingInterceptor() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(SaltEdgeSDK.isLoggingEnabled() // ? HttpLoggingInterceptor.Level.BODY // : HttpLoggingInterceptor.Level.NONE); // return interceptor; // } // }
import com.saltedge.sdk.network.SERestClient; import com.saltedge.sdk.interfaces.FetchTransactionsResult;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.connector; public class PendingTransactionsFetchConnector extends TransactionsConnector { public PendingTransactionsFetchConnector(FetchTransactionsResult callback) { super(callback); } @Override public void enqueueCall() {
// Path: saltedge-library/src/main/java/com/saltedge/sdk/interfaces/FetchTransactionsResult.java // public interface FetchTransactionsResult { // // /** // * Callback method is invoked when Fetch Transactions operation finished with success // * // * @param transactions List of SETransaction objects // */ // void onSuccess(List<SETransaction> transactions); // // /** // * Callback method is invoked when Fetch Transactions operation finished with error // * // * @param errorMessage String which describes occurred error // */ // void onFailure(String errorMessage); // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/SERestClient.java // public class SERestClient { // // private SERestClient() {} // // private static final String TAG = "SERestClient"; // // public SEApiInterface service = createRetrofit().create(SEApiInterface.class); // public static Gson gson = createDefaultGson(); // private static SERestClient instance; // // public static SERestClient getInstance() { // if (instance == null) { // instance = new SERestClient(); // } // return instance; // } // // public void initService() { // service = createRetrofit().create(SEApiInterface.class); // } // // private Retrofit createRetrofit() { // String baseUrl = SEApiConstants.API_BASE_URL + SEApiConstants.BASE_API_PATH; // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(createOkHttpClient()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .build(); // } // // private static Gson createDefaultGson() { // return new GsonBuilder() // .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) // .create(); // } // // private OkHttpClient createOkHttpClient() { // OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() // .addInterceptor(prepareLoggingInterceptor()); // boolean pinsAdded = addCertificatePinner(clientBuilder); // addSSLSocketFactory(clientBuilder); // addHeaderInterceptor(clientBuilder, pinsAdded); // return clientBuilder.build(); // } // // private void addHeaderInterceptor(OkHttpClient.Builder clientBuilder, boolean acceptJson) { // clientBuilder.addInterceptor(new HeaderInterceptor(acceptJson ? SEApiConstants.MIME_TYPE_JSON : null)); // } // // private boolean addCertificatePinner(OkHttpClient.Builder clientBuilder) { // try { // String[] pins = SEPreferencesRepository.getInstance().getPins(); // if (pins != null && pins.length > 0) { // CertificatePinner.Builder pinnerBuilder = new CertificatePinner.Builder(); // pinnerBuilder.add(SEApiConstants.API_HOST_NAME, pins); // clientBuilder.certificatePinner(pinnerBuilder.build()); // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // private void addSSLSocketFactory(OkHttpClient.Builder builder) { // try { // TLSSocketFactory factory = new TLSSocketFactory(SaltEdgeSDK.getInstance().getContext()); // builder.sslSocketFactory(factory, factory.getTrustManager()); // } catch (Exception e) { // Log.e(TAG, "Can't add SSL Socket factory"); // e.printStackTrace(); // } // } // // private HttpLoggingInterceptor prepareLoggingInterceptor() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(SaltEdgeSDK.isLoggingEnabled() // ? HttpLoggingInterceptor.Level.BODY // : HttpLoggingInterceptor.Level.NONE); // return interceptor; // } // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/connector/PendingTransactionsFetchConnector.java import com.saltedge.sdk.network.SERestClient; import com.saltedge.sdk.interfaces.FetchTransactionsResult; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.connector; public class PendingTransactionsFetchConnector extends TransactionsConnector { public PendingTransactionsFetchConnector(FetchTransactionsResult callback) { super(callback); } @Override public void enqueueCall() {
SERestClient.getInstance().service
saltedge/saltedge-android
app/src/main/java/com/saltedge/sdk/sample/utils/Constants.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SEConsent.java // public class SEConsent extends BaseModel implements Serializable { // // /** // * Consent scopes constants // */ // public final static String SCOPE_HOLDER_INFORMATION = "holder_information"; // public final static String SCOPE_ACCOUNT_DETAILS = "account_details"; // public final static String SCOPE_TRANSACTIONS_DETAILS = "transactions_details"; // // /** // * Consent Status possible values // */ // public enum STATUS { // ACTIVE, REVOKED // } // // @SerializedName(SEConstants.KEY_CONNECTION_ID) // private String connectionId; // // @SerializedName(SEConstants.KEY_CUSTOMER_ID) // private String customerId; // // @SerializedName(SEConstants.KEY_STATUS) // private String status; // // @SerializedName(SEConstants.KEY_SCOPES) // private String[] scopes; // // @SerializedName(SEConstants.KEY_FROM_DATE) // private String fromDate; // // @SerializedName(SEConstants.KEY_TO_DATE) // private String toDate; // // @SerializedName(SEConstants.KEY_PERIOD_DAYS) // private Integer periodDays; // // @SerializedName(SEConstants.KEY_EXPIRES_AT) // private String expiresAt; // // @SerializedName(SEConstants.KEY_REVOKED_BY) // private String revokedBy; // // @SerializedName(SEConstants.KEY_REVOKED_AT) // private String revokedAt; // // @SerializedName(SEConstants.KEY_COLLECTED_BY) // private String collectedBy; // // // CONSTRUCTOR // // public SEConsent(String[] scopes) { // this.scopes = scopes; // } // // // GETTER AND SETTERS // // public String[] getScopes() { // return scopes; // } // // public void setScopes(String[] scopes) { // this.scopes = scopes; // } // // public String getFromDate() { // return fromDate; // } // // public void setFromDate(String fromDate) { // this.fromDate = fromDate; // } // // public String getToDate() { // return toDate; // } // // public void setToDate(String toDate) { // this.toDate = toDate; // } // // public Integer getPeriodDays() { // return periodDays; // } // // public void setPeriodDays(Integer periodDays) { // this.periodDays = periodDays; // } // // public String getExpiresAt() { // return expiresAt; // } // // public void setExpiresAt(String expiresAt) { // this.expiresAt = expiresAt; // } // // public String getConnectionId() { // return connectionId; // } // // public void setConnectionId(String connectionId) { // this.connectionId = connectionId; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public String getRevokedAt() { // return revokedAt; // } // // public void setRevokedAt(String revokedAt) { // this.revokedAt = revokedAt; // } // // public String getCollectedBy() { // return collectedBy; // } // // public void setCollectedBy(String collectedBy) { // this.collectedBy = collectedBy; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getRevokedBy() { // return revokedBy; // } // // public void setRevokedBy(String revokedBy) { // this.revokedBy = revokedBy; // } // }
import com.saltedge.sdk.model.SEConsent;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.sample.utils; public class Constants { static String CONNECTIONS_SECRETS_ARRAY = "CONNECTIONS_SECRETS_ARRAY"; public static final String KEY_CUSTOMER_SECRET = "secret"; public static final String KEY_CUSTOMER_IDENTIFIER = "identifier"; public static final String KEY_CONNECTION = "connection"; public static final String KEY_CONNECTION_SECRET = "connection_secret"; public static final String KEY_REFRESH = "refresh"; public static final String KEY_OVERRIDE_CREDENTIALS = "override_credentials"; public static final String KEY_OAUTH = "oauth";
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SEConsent.java // public class SEConsent extends BaseModel implements Serializable { // // /** // * Consent scopes constants // */ // public final static String SCOPE_HOLDER_INFORMATION = "holder_information"; // public final static String SCOPE_ACCOUNT_DETAILS = "account_details"; // public final static String SCOPE_TRANSACTIONS_DETAILS = "transactions_details"; // // /** // * Consent Status possible values // */ // public enum STATUS { // ACTIVE, REVOKED // } // // @SerializedName(SEConstants.KEY_CONNECTION_ID) // private String connectionId; // // @SerializedName(SEConstants.KEY_CUSTOMER_ID) // private String customerId; // // @SerializedName(SEConstants.KEY_STATUS) // private String status; // // @SerializedName(SEConstants.KEY_SCOPES) // private String[] scopes; // // @SerializedName(SEConstants.KEY_FROM_DATE) // private String fromDate; // // @SerializedName(SEConstants.KEY_TO_DATE) // private String toDate; // // @SerializedName(SEConstants.KEY_PERIOD_DAYS) // private Integer periodDays; // // @SerializedName(SEConstants.KEY_EXPIRES_AT) // private String expiresAt; // // @SerializedName(SEConstants.KEY_REVOKED_BY) // private String revokedBy; // // @SerializedName(SEConstants.KEY_REVOKED_AT) // private String revokedAt; // // @SerializedName(SEConstants.KEY_COLLECTED_BY) // private String collectedBy; // // // CONSTRUCTOR // // public SEConsent(String[] scopes) { // this.scopes = scopes; // } // // // GETTER AND SETTERS // // public String[] getScopes() { // return scopes; // } // // public void setScopes(String[] scopes) { // this.scopes = scopes; // } // // public String getFromDate() { // return fromDate; // } // // public void setFromDate(String fromDate) { // this.fromDate = fromDate; // } // // public String getToDate() { // return toDate; // } // // public void setToDate(String toDate) { // this.toDate = toDate; // } // // public Integer getPeriodDays() { // return periodDays; // } // // public void setPeriodDays(Integer periodDays) { // this.periodDays = periodDays; // } // // public String getExpiresAt() { // return expiresAt; // } // // public void setExpiresAt(String expiresAt) { // this.expiresAt = expiresAt; // } // // public String getConnectionId() { // return connectionId; // } // // public void setConnectionId(String connectionId) { // this.connectionId = connectionId; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public String getRevokedAt() { // return revokedAt; // } // // public void setRevokedAt(String revokedAt) { // this.revokedAt = revokedAt; // } // // public String getCollectedBy() { // return collectedBy; // } // // public void setCollectedBy(String collectedBy) { // this.collectedBy = collectedBy; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getRevokedBy() { // return revokedBy; // } // // public void setRevokedBy(String revokedBy) { // this.revokedBy = revokedBy; // } // } // Path: app/src/main/java/com/saltedge/sdk/sample/utils/Constants.java import com.saltedge.sdk.model.SEConsent; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.sample.utils; public class Constants { static String CONNECTIONS_SECRETS_ARRAY = "CONNECTIONS_SECRETS_ARRAY"; public static final String KEY_CUSTOMER_SECRET = "secret"; public static final String KEY_CUSTOMER_IDENTIFIER = "identifier"; public static final String KEY_CONNECTION = "connection"; public static final String KEY_CONNECTION_SECRET = "connection_secret"; public static final String KEY_REFRESH = "refresh"; public static final String KEY_OVERRIDE_CREDENTIALS = "override_credentials"; public static final String KEY_OAUTH = "oauth";
public static final String[] CONSENT_SCOPES = { SEConsent.SCOPE_ACCOUNT_DETAILS, SEConsent.SCOPE_TRANSACTIONS_DETAILS };
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/utils/SEJsonTools.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SEApiError.java // public class SEApiError { // // @SerializedName(SEConstants.KEY_ERROR) // private ApiErrorContent error; // // public String getErrorMessage() { // return error.errorMessage; // } // // public String getErrorClass() { // return error.errorClass; // } // // public String getDocumentationUrl() { // return error.documentationUrl; // } // // private class ApiErrorContent { // @SerializedName(SEConstants.KEY_MESSAGE) // private String errorMessage; // // @SerializedName(SEConstants.KEY_CLASS) // private String errorClass; // // @SerializedName(SEConstants.KEY_DOCUMENTATION_URL) // private String documentationUrl; // } // }
import com.google.gson.Gson; import com.saltedge.sdk.model.SEApiError; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import okhttp3.ResponseBody;
return (Double) parse(jsonObject, key, result); } public static JSONArray getJSONArray(JSONObject jsonObject, String key) { JSONArray result = new JSONArray(); return (JSONArray) parse(jsonObject, key, result); } public static JSONObject getObject(JSONObject jsonObject, String key) { JSONObject result = new JSONObject(); return (JSONObject) parse(jsonObject, key, result); } public static JSONObject stringToJSON(String string) { JSONObject result = new JSONObject(); if (string == null || string.isEmpty()) return result; try { return new JSONObject(string); } catch (JSONException e) { e.printStackTrace(); } return new JSONObject(); } public static String getErrorMessage(ResponseBody error) { return getErrorMessage(error, SEConstants.REQUEST_ERROR); } public static String getErrorMessage(ResponseBody error, String defaultMessage) { try {
// Path: saltedge-library/src/main/java/com/saltedge/sdk/model/SEApiError.java // public class SEApiError { // // @SerializedName(SEConstants.KEY_ERROR) // private ApiErrorContent error; // // public String getErrorMessage() { // return error.errorMessage; // } // // public String getErrorClass() { // return error.errorClass; // } // // public String getDocumentationUrl() { // return error.documentationUrl; // } // // private class ApiErrorContent { // @SerializedName(SEConstants.KEY_MESSAGE) // private String errorMessage; // // @SerializedName(SEConstants.KEY_CLASS) // private String errorClass; // // @SerializedName(SEConstants.KEY_DOCUMENTATION_URL) // private String documentationUrl; // } // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/utils/SEJsonTools.java import com.google.gson.Gson; import com.saltedge.sdk.model.SEApiError; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import okhttp3.ResponseBody; return (Double) parse(jsonObject, key, result); } public static JSONArray getJSONArray(JSONObject jsonObject, String key) { JSONArray result = new JSONArray(); return (JSONArray) parse(jsonObject, key, result); } public static JSONObject getObject(JSONObject jsonObject, String key) { JSONObject result = new JSONObject(); return (JSONObject) parse(jsonObject, key, result); } public static JSONObject stringToJSON(String string) { JSONObject result = new JSONObject(); if (string == null || string.isEmpty()) return result; try { return new JSONObject(string); } catch (JSONException e) { e.printStackTrace(); } return new JSONObject(); } public static String getErrorMessage(ResponseBody error) { return getErrorMessage(error, SEConstants.REQUEST_ERROR); } public static String getErrorMessage(ResponseBody error, String defaultMessage) { try {
SEApiError apiError = new Gson().fromJson(error.string(), SEApiError.class);
saltedge/saltedge-android
saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/SaltEdgeSDK.java // public class SaltEdgeSDK { // // private static SaltEdgeSDK instance; // private Context applicationContext; // private String appId; // private String appSecret; // private String returnToUrl; // private boolean loggingEnabled; // // public static SaltEdgeSDK getInstance() { // if (instance == null) { // instance = new SaltEdgeSDK(); // } // return instance; // } // // public String getAppId() { // return appId; // } // // public String getAppSecret() { // return appSecret; // } // // public static String getReturnToUrl() { // return getInstance().returnToUrl; // } // // public static void setReturnToUrl(String returnToUrl) { // getInstance().returnToUrl = returnToUrl; // } // // public static boolean isLoggingEnabled() { // return getInstance().loggingEnabled; // } // // public Context getContext() { // return applicationContext; // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false); // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param enableLogging flag, which enable or disable network logging // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init( // Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean enableLogging // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false, enableLogging); // } // // private void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean actAsPartner, // boolean enableLogging // ) { // if (clientAppId.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_ID_IS_NULL); // } // if (clientAppSecret.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_SECRET_IS_NULL); // } // this.applicationContext = applicationContext; // this.appId = clientAppId; // this.appSecret = clientAppSecret; // this.loggingEnabled = enableLogging; // this.returnToUrl = returnToUrl; // } // // public static void printToLogcat(String tag, String message) { // if (isLoggingEnabled()) { // Log.d(tag, message); // } // } // }
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.saltedge.sdk.SaltEdgeSDK; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.preferences; public class SEPreferencesRepository { private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; private static SEPreferencesRepository instance; private String[] pinsArray = new String[0]; private long expireAt = 0L; public static SEPreferencesRepository getInstance() { if (instance == null) { instance = new SEPreferencesRepository(); } return instance; } private SEPreferencesRepository() { loadStoredValues(); } public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { try { this.pinsArray = pinsArray == null ? new String[0] : pinsArray; this.expireAt = expireAt;
// Path: saltedge-library/src/main/java/com/saltedge/sdk/SaltEdgeSDK.java // public class SaltEdgeSDK { // // private static SaltEdgeSDK instance; // private Context applicationContext; // private String appId; // private String appSecret; // private String returnToUrl; // private boolean loggingEnabled; // // public static SaltEdgeSDK getInstance() { // if (instance == null) { // instance = new SaltEdgeSDK(); // } // return instance; // } // // public String getAppId() { // return appId; // } // // public String getAppSecret() { // return appSecret; // } // // public static String getReturnToUrl() { // return getInstance().returnToUrl; // } // // public static void setReturnToUrl(String returnToUrl) { // getInstance().returnToUrl = returnToUrl; // } // // public static boolean isLoggingEnabled() { // return getInstance().loggingEnabled; // } // // public Context getContext() { // return applicationContext; // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false); // } // // /** // * Initialize Salt Edge SDK for access to Salt Edge API // * // * @param applicationContext Application context // * @param clientAppId unique app id // * @param clientAppSecret unique ap secret // * @param enableLogging flag, which enable or disable network logging // * @param returnToUrl the URL the user will be redirected to. The return_to URL should not exceed 2040 characters. // */ // public void init( // Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean enableLogging // ) { // init(applicationContext, clientAppId, clientAppSecret, returnToUrl, false, enableLogging); // } // // private void init(Context applicationContext, // String clientAppId, // String clientAppSecret, // String returnToUrl, // boolean actAsPartner, // boolean enableLogging // ) { // if (clientAppId.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_ID_IS_NULL); // } // if (clientAppSecret.isEmpty()) { // throw new RuntimeException(SEConstants.ERROR_CLIENT_APP_SECRET_IS_NULL); // } // this.applicationContext = applicationContext; // this.appId = clientAppId; // this.appSecret = clientAppSecret; // this.loggingEnabled = enableLogging; // this.returnToUrl = returnToUrl; // } // // public static void printToLogcat(String tag, String message) { // if (isLoggingEnabled()) { // Log.d(tag, message); // } // } // } // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.saltedge.sdk.SaltEdgeSDK; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk.preferences; public class SEPreferencesRepository { private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; private static SEPreferencesRepository instance; private String[] pinsArray = new String[0]; private long expireAt = 0L; public static SEPreferencesRepository getInstance() { if (instance == null) { instance = new SEPreferencesRepository(); } return instance; } private SEPreferencesRepository() { loadStoredValues(); } public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { try { this.pinsArray = pinsArray == null ? new String[0] : pinsArray; this.expireAt = expireAt;
SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit();
saltedge/saltedge-android
saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder()
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder()
.registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter())
saltedge/saltedge-android
saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder() .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) .create(); } private static OkHttpClient createTestClient() { return new OkHttpClient.Builder()
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder() .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) .create(); } private static OkHttpClient createTestClient() { return new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor("json"))
saltedge/saltedge-android
saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar;
/* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder() .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) .create(); } private static OkHttpClient createTestClient() { return new OkHttpClient.Builder() .addInterceptor(new HeaderInterceptor("json")) .addInterceptor(prepareLoggingInterceptor()) .build(); } private static HttpLoggingInterceptor prepareLoggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } public static void saveValidPinsInPreferences() { long data = Calendar.getInstance().getTimeInMillis() + 3600L * 1000L;
// Path: saltedge-library/src/main/java/com/saltedge/sdk/network/ExtraJsonDataAdapter.java // public class ExtraJsonDataAdapter implements JsonDeserializer<JSONObject> { // // @Override // public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // return SEJsonTools.stringToJSON(json.getAsJsonObject().toString()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/network/HeaderInterceptor.java // public class HeaderInterceptor implements Interceptor { // // private String acceptType; // // public HeaderInterceptor(String acceptType) { // this.acceptType = acceptType; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request.Builder requestBuilder = chain.request().newBuilder() // .header(SEApiConstants.KEY_HEADER_CONTENT_TYPE, SEApiConstants.MIME_TYPE_JSON) // .header(SEApiConstants.KEY_HEADER_APP_ID, SaltEdgeSDK.getInstance().getAppId()) // .header(SEApiConstants.KEY_HEADER_APP_SECRET, SaltEdgeSDK.getInstance().getAppSecret()); // if (acceptType != null) { // requestBuilder.header(SEApiConstants.KEY_HEADER_ACCEPT, acceptType); // } // return chain.proceed(requestBuilder.build()); // } // } // // Path: saltedge-library/src/main/java/com/saltedge/sdk/preferences/SEPreferencesRepository.java // public class SEPreferencesRepository { // // private static final String KEY_PINS_EXPIRE_AT = "KEY_SE_PINS_EXPIRE_AT"; // private static final String KEY_PINS_SET = "KEY_SE_PINS_SET"; // private static SEPreferencesRepository instance; // private String[] pinsArray = new String[0]; // private long expireAt = 0L; // // public static SEPreferencesRepository getInstance() { // if (instance == null) { // instance = new SEPreferencesRepository(); // } // return instance; // } // // private SEPreferencesRepository() { // loadStoredValues(); // } // // public void updatePinsAndMaxAge(String[] pinsArray, long expireAt) { // try { // this.pinsArray = pinsArray == null ? new String[0] : pinsArray; // this.expireAt = expireAt; // SharedPreferences.Editor editor = getPreferences(SaltEdgeSDK.getInstance().getContext()).edit(); // editor.putLong(KEY_PINS_EXPIRE_AT, this.expireAt); // editor.putStringSet(KEY_PINS_SET, new HashSet<>(Arrays.asList(this.pinsArray))); // editor.commit(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public String[] getPins() { // return pinsArray; // } // // public long getExpireAt() { // return expireAt; // } // // private static SharedPreferences getPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // private void loadStoredValues() { // try { // SharedPreferences preferences = getPreferences(SaltEdgeSDK.getInstance().getContext()); // Set<String> result = preferences.getStringSet(KEY_PINS_SET, new HashSet<String>()); // pinsArray = result.toArray(new String[result.size()]); // expireAt = preferences.getLong(KEY_PINS_EXPIRE_AT, 0L); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: saltedge-library/src/androidTest/java/com/saltedge/sdk/TestTools.java import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.saltedge.sdk.network.ExtraJsonDataAdapter; import com.saltedge.sdk.network.HeaderInterceptor; import com.saltedge.sdk.preferences.SEPreferencesRepository; import org.json.JSONObject; import java.util.Calendar; /* Copyright © 2019 Salt Edge. https://saltedge.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.saltedge.sdk; public class TestTools { public static Retrofit createMockRetrofit(HttpUrl url) { return new Retrofit.Builder() .baseUrl(url) .client(createTestClient()) .addConverterFactory(GsonConverterFactory.create(createDefaultGson())) .build(); } private static Gson createDefaultGson() { return new GsonBuilder() .registerTypeAdapter(JSONObject.class, new ExtraJsonDataAdapter()) .create(); } private static OkHttpClient createTestClient() { return new OkHttpClient.Builder() .addInterceptor(new HeaderInterceptor("json")) .addInterceptor(prepareLoggingInterceptor()) .build(); } private static HttpLoggingInterceptor prepareLoggingInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } public static void saveValidPinsInPreferences() { long data = Calendar.getInstance().getTimeInMillis() + 3600L * 1000L;
SEPreferencesRepository.getInstance().updatePinsAndMaxAge(new String[]{"sha256/q6syzBRvzhCBHB8F9PJkQHH27U/vG8a7r848qBAv5Yo="}, data);
charliem/OCM
OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/Validator.java
// Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTColumnFamily.java // public class ASTColumnFamily extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String entityName = ""; // // private String comment = ""; // private String compareWith = ""; // private String compareSubcolumnsWith = ""; // // public ASTColumnFamily(int id) { // super(id); // } // // public ASTColumnFamily(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = name; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public void setAnnotation(String anName, String anValue) // { // //Remove the outside quotes // String value = anValue.substring(1, anValue.length() - 1); // // if(anName.equals("EntityName")) // { // //Make sure the entity names first letter is upper case // entityName = value.substring(0,1).toUpperCase(Locale.UK) + value.substring(1); // } // // else if(anName.equals("Comment")) // { // comment = value; // } // // else if(anName.equals("CompareWith")) // { // compareWith = value; // } // // else if(anName.equals("CompareSubcolumnsWith")) // { // compareSubcolumnsWith = value; // } // } // // public String toString() { return "\nColumn Family: " + getName() + " Entity Name: " + entityName;} // public String toString(String prefix) { return prefix + toString(); } // // public String getEntityName() { // return entityName; // } // // public String getComment() { // return comment; // } // // public String getCompareWith() { // return compareWith; // } // // public String getCompareSubcolumnsWith() { // return compareSubcolumnsWith; // } // // // } // // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTMany2Many.java // public class ASTMany2Many extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String columnFamily; // private String field; // // // public ASTMany2Many(int id) { // super(id); // } // // public ASTMany2Many(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = nameUpperCase.toLowerCase(Locale.UK) + rest; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public String toString() { return "Many 2 Many: " + getName() + " Destination: " + columnFamily + "." + field;} // public String toString(String prefix) { return prefix + toString(); } // // public String getColumnFamily() { // return columnFamily; // } // // public void setColumnFamily(String columnFamily) { // this.columnFamily = columnFamily; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // // // // // }
import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import com.kissintellignetsystems.ocm.compiler.parser.ASTColumnFamily; import com.kissintellignetsystems.ocm.compiler.parser.ASTMany2Many;
/* Copyright 2010 KISS Intelligent Systems Limited 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.kissintellignetsystems.ocm.compiler; public class Validator {
// Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTColumnFamily.java // public class ASTColumnFamily extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String entityName = ""; // // private String comment = ""; // private String compareWith = ""; // private String compareSubcolumnsWith = ""; // // public ASTColumnFamily(int id) { // super(id); // } // // public ASTColumnFamily(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = name; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public void setAnnotation(String anName, String anValue) // { // //Remove the outside quotes // String value = anValue.substring(1, anValue.length() - 1); // // if(anName.equals("EntityName")) // { // //Make sure the entity names first letter is upper case // entityName = value.substring(0,1).toUpperCase(Locale.UK) + value.substring(1); // } // // else if(anName.equals("Comment")) // { // comment = value; // } // // else if(anName.equals("CompareWith")) // { // compareWith = value; // } // // else if(anName.equals("CompareSubcolumnsWith")) // { // compareSubcolumnsWith = value; // } // } // // public String toString() { return "\nColumn Family: " + getName() + " Entity Name: " + entityName;} // public String toString(String prefix) { return prefix + toString(); } // // public String getEntityName() { // return entityName; // } // // public String getComment() { // return comment; // } // // public String getCompareWith() { // return compareWith; // } // // public String getCompareSubcolumnsWith() { // return compareSubcolumnsWith; // } // // // } // // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTMany2Many.java // public class ASTMany2Many extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String columnFamily; // private String field; // // // public ASTMany2Many(int id) { // super(id); // } // // public ASTMany2Many(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = nameUpperCase.toLowerCase(Locale.UK) + rest; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public String toString() { return "Many 2 Many: " + getName() + " Destination: " + columnFamily + "." + field;} // public String toString(String prefix) { return prefix + toString(); } // // public String getColumnFamily() { // return columnFamily; // } // // public void setColumnFamily(String columnFamily) { // this.columnFamily = columnFamily; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // // // // // } // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/Validator.java import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import com.kissintellignetsystems.ocm.compiler.parser.ASTColumnFamily; import com.kissintellignetsystems.ocm.compiler.parser.ASTMany2Many; /* Copyright 2010 KISS Intelligent Systems Limited 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.kissintellignetsystems.ocm.compiler; public class Validator {
public boolean validate(List<ASTColumnFamily> columnFamilies)
charliem/OCM
OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/Validator.java
// Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTColumnFamily.java // public class ASTColumnFamily extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String entityName = ""; // // private String comment = ""; // private String compareWith = ""; // private String compareSubcolumnsWith = ""; // // public ASTColumnFamily(int id) { // super(id); // } // // public ASTColumnFamily(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = name; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public void setAnnotation(String anName, String anValue) // { // //Remove the outside quotes // String value = anValue.substring(1, anValue.length() - 1); // // if(anName.equals("EntityName")) // { // //Make sure the entity names first letter is upper case // entityName = value.substring(0,1).toUpperCase(Locale.UK) + value.substring(1); // } // // else if(anName.equals("Comment")) // { // comment = value; // } // // else if(anName.equals("CompareWith")) // { // compareWith = value; // } // // else if(anName.equals("CompareSubcolumnsWith")) // { // compareSubcolumnsWith = value; // } // } // // public String toString() { return "\nColumn Family: " + getName() + " Entity Name: " + entityName;} // public String toString(String prefix) { return prefix + toString(); } // // public String getEntityName() { // return entityName; // } // // public String getComment() { // return comment; // } // // public String getCompareWith() { // return compareWith; // } // // public String getCompareSubcolumnsWith() { // return compareSubcolumnsWith; // } // // // } // // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTMany2Many.java // public class ASTMany2Many extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String columnFamily; // private String field; // // // public ASTMany2Many(int id) { // super(id); // } // // public ASTMany2Many(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = nameUpperCase.toLowerCase(Locale.UK) + rest; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public String toString() { return "Many 2 Many: " + getName() + " Destination: " + columnFamily + "." + field;} // public String toString(String prefix) { return prefix + toString(); } // // public String getColumnFamily() { // return columnFamily; // } // // public void setColumnFamily(String columnFamily) { // this.columnFamily = columnFamily; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // // // // // }
import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import com.kissintellignetsystems.ocm.compiler.parser.ASTColumnFamily; import com.kissintellignetsystems.ocm.compiler.parser.ASTMany2Many;
/* Copyright 2010 KISS Intelligent Systems Limited 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.kissintellignetsystems.ocm.compiler; public class Validator { public boolean validate(List<ASTColumnFamily> columnFamilies) { //We only validate the Many 2 Many Columns so far return validateMany2ManyColumns(columnFamilies); } private boolean validateMany2ManyColumns(List<ASTColumnFamily> columnFamilies) { //In the Form Column.Family to Column.Family Hashtable<String,String> relationships = new Hashtable<String, String>(); for(int count=0; count < columnFamilies.size(); count++) { //Get the Column Family ASTColumnFamily family = columnFamilies.get(count); for(int count2=1; count2< family.jjtGetNumChildren(); count2++) { //Get the column family Object familyObj = family.jjtGetChild(count2);
// Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTColumnFamily.java // public class ASTColumnFamily extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String entityName = ""; // // private String comment = ""; // private String compareWith = ""; // private String compareSubcolumnsWith = ""; // // public ASTColumnFamily(int id) { // super(id); // } // // public ASTColumnFamily(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = name; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public void setAnnotation(String anName, String anValue) // { // //Remove the outside quotes // String value = anValue.substring(1, anValue.length() - 1); // // if(anName.equals("EntityName")) // { // //Make sure the entity names first letter is upper case // entityName = value.substring(0,1).toUpperCase(Locale.UK) + value.substring(1); // } // // else if(anName.equals("Comment")) // { // comment = value; // } // // else if(anName.equals("CompareWith")) // { // compareWith = value; // } // // else if(anName.equals("CompareSubcolumnsWith")) // { // compareSubcolumnsWith = value; // } // } // // public String toString() { return "\nColumn Family: " + getName() + " Entity Name: " + entityName;} // public String toString(String prefix) { return prefix + toString(); } // // public String getEntityName() { // return entityName; // } // // public String getComment() { // return comment; // } // // public String getCompareWith() { // return compareWith; // } // // public String getCompareSubcolumnsWith() { // return compareSubcolumnsWith; // } // // // } // // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/ASTMany2Many.java // public class ASTMany2Many extends SimpleNode { // // private String name; // private String nameUpperCase; // // private String columnFamily; // private String field; // // // public ASTMany2Many(int id) { // super(id); // } // // public ASTMany2Many(OCMParser p, int id) { // super(p, id); // } // // public String getName() { // return name; // } // // public void setName(String name) { // // this.nameUpperCase = name.substring(0,1); // this.nameUpperCase = nameUpperCase.toUpperCase(Locale.UK); // // String rest = name.substring(1); // // //Store both versions of the name // this.name = nameUpperCase.toLowerCase(Locale.UK) + rest; // this.nameUpperCase = nameUpperCase + rest; // } // // public String getNameUpperCase() { // return nameUpperCase; // } // // public String toString() { return "Many 2 Many: " + getName() + " Destination: " + columnFamily + "." + field;} // public String toString(String prefix) { return prefix + toString(); } // // public String getColumnFamily() { // return columnFamily; // } // // public void setColumnFamily(String columnFamily) { // this.columnFamily = columnFamily; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // // // // // } // Path: OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/Validator.java import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import com.kissintellignetsystems.ocm.compiler.parser.ASTColumnFamily; import com.kissintellignetsystems.ocm.compiler.parser.ASTMany2Many; /* Copyright 2010 KISS Intelligent Systems Limited 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.kissintellignetsystems.ocm.compiler; public class Validator { public boolean validate(List<ASTColumnFamily> columnFamilies) { //We only validate the Many 2 Many Columns so far return validateMany2ManyColumns(columnFamilies); } private boolean validateMany2ManyColumns(List<ASTColumnFamily> columnFamilies) { //In the Form Column.Family to Column.Family Hashtable<String,String> relationships = new Hashtable<String, String>(); for(int count=0; count < columnFamilies.size(); count++) { //Get the Column Family ASTColumnFamily family = columnFamilies.get(count); for(int count2=1; count2< family.jjtGetNumChildren(); count2++) { //Get the column family Object familyObj = family.jjtGetChild(count2);
if(familyObj instanceof ASTMany2Many)
charliem/OCM
Output Languages/Java/TestHarness/src/com/kissintelligentsystems/ocm/java/sample/generated/DummyAccounts.java
// Path: Output Languages/Java/Base Library/src/com/kissintelligentsystems/ocm/java/OCMConnection.java // public class OCMConnection // { // private final CassandraClientPool pool; // // //The Cassandra Key space // private String keySpaceName; // // private String[] connectionStr; // // public OCMConnection() // { // //Get the Cassandra Pool // pool = CassandraClientPoolFactory.INSTANCE.get(); // } // // public void connect(String address, int port, String keySpaceName) // { // //Call the main connection method with one end point // connect(new String[]{address + ":" + port}, keySpaceName); // } // // public void connect(String[] connectionStr, String keySpaceName) // { // //Store the connection params // this.connectionStr = connectionStr; // this.keySpaceName = keySpaceName; // } // // // public Keyspace borrowKeySpace() throws IllegalArgumentException, org.apache.cassandra.thrift.NotFoundException, TException, Exception // { // return pool.borrowClient(connectionStr).getKeyspace(keySpaceName); // } // // public void returnKeySpace(Keyspace keySpace) throws Exception // { // pool.releaseKeyspace(keySpace); // } // }
import java.util.Random; import com.kissintelligentsystems.ocm.java.OCMConnection;
package com.kissintelligentsystems.ocm.java.sample.generated; public class DummyAccounts extends com.kissintelligentsystems.ocm.java.BaseTable { String accountID;
// Path: Output Languages/Java/Base Library/src/com/kissintelligentsystems/ocm/java/OCMConnection.java // public class OCMConnection // { // private final CassandraClientPool pool; // // //The Cassandra Key space // private String keySpaceName; // // private String[] connectionStr; // // public OCMConnection() // { // //Get the Cassandra Pool // pool = CassandraClientPoolFactory.INSTANCE.get(); // } // // public void connect(String address, int port, String keySpaceName) // { // //Call the main connection method with one end point // connect(new String[]{address + ":" + port}, keySpaceName); // } // // public void connect(String[] connectionStr, String keySpaceName) // { // //Store the connection params // this.connectionStr = connectionStr; // this.keySpaceName = keySpaceName; // } // // // public Keyspace borrowKeySpace() throws IllegalArgumentException, org.apache.cassandra.thrift.NotFoundException, TException, Exception // { // return pool.borrowClient(connectionStr).getKeyspace(keySpaceName); // } // // public void returnKeySpace(Keyspace keySpace) throws Exception // { // pool.releaseKeyspace(keySpace); // } // } // Path: Output Languages/Java/TestHarness/src/com/kissintelligentsystems/ocm/java/sample/generated/DummyAccounts.java import java.util.Random; import com.kissintelligentsystems.ocm.java.OCMConnection; package com.kissintelligentsystems.ocm.java.sample.generated; public class DummyAccounts extends com.kissintelligentsystems.ocm.java.BaseTable { String accountID;
public DummyAccounts (OCMConnection connection, String accountID)
fredg02/se.bitcraze.crazyflie.lib
se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/usb/UsbLinkJava.java
// Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/Utilities.java // public class Utilities { // // private Utilities() { // throw new IllegalStateException("Utility class"); // } // // /** // * Returns byte array as comma separated string // * (for debugging purposes) // * // * @param data // * @return // */ // public static String getByteString(byte[] data) { // StringBuilder sb = new StringBuilder(); // for (byte b : data) { // sb.append(b); // sb.append(","); // } // return sb.toString(); // } // // public static String getHexString(byte... array) { // StringBuilder sb = new StringBuilder(); // for (byte b : array) { // sb.append(String.format("%02X", b)); // sb.append(" "); // } // return sb.toString(); // } // // /** // * Strip bytes of the beginning of an array // * // * @param array // * @param offset // * @return // */ // public static byte[] strip(byte[] array, int offset) { // byte[] strippedArray = new byte[array.length-offset]; // System.arraycopy(array, offset, strippedArray, 0, strippedArray.length); // return strippedArray; // } // // }
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import javax.usb.UsbConfiguration; import javax.usb.UsbConst; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.UsbDeviceDescriptor; import javax.usb.UsbDisconnectedException; import javax.usb.UsbEndpoint; import javax.usb.UsbException; import javax.usb.UsbHostManager; import javax.usb.UsbHub; import javax.usb.UsbInterface; import javax.usb.UsbIrp; import javax.usb.UsbPipe; import javax.usb.UsbServices; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.bitcraze.crazyflie.lib.Utilities;
return mIntf != null && mIntf.isClaimed(); } /* (non-Javadoc) * @see CrazyUsbInterface#sendControlTransfer(int, int, int, int, byte[]) */ @Override public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data) { int returnCode = -1; if(mUsbDevice != null){ try { UsbControlIrp usbControlIrp = mUsbDevice.createUsbControlIrp((byte) requestType, (byte) request, (short) value, (short) index); if(data == null){ data = new byte[0]; } usbControlIrp.setData(data); usbControlIrp.setLength(data.length); debugControlTransfer((byte) requestType, (byte) request, (byte) value, (byte) index, data); if(sendUsbControlIrp(mUsbDevice, usbControlIrp)){ returnCode = usbControlIrp.getActualLength(); } } catch (IllegalArgumentException | UsbDisconnectedException e) { e.printStackTrace(); } } return returnCode; } private void debugControlTransfer(byte requestType, byte request, byte value, byte index, byte[] data) { if (!FILTER_OUT_SEND_CONTROL_TRANSFER) {
// Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/Utilities.java // public class Utilities { // // private Utilities() { // throw new IllegalStateException("Utility class"); // } // // /** // * Returns byte array as comma separated string // * (for debugging purposes) // * // * @param data // * @return // */ // public static String getByteString(byte[] data) { // StringBuilder sb = new StringBuilder(); // for (byte b : data) { // sb.append(b); // sb.append(","); // } // return sb.toString(); // } // // public static String getHexString(byte... array) { // StringBuilder sb = new StringBuilder(); // for (byte b : array) { // sb.append(String.format("%02X", b)); // sb.append(" "); // } // return sb.toString(); // } // // /** // * Strip bytes of the beginning of an array // * // * @param array // * @param offset // * @return // */ // public static byte[] strip(byte[] array, int offset) { // byte[] strippedArray = new byte[array.length-offset]; // System.arraycopy(array, offset, strippedArray, 0, strippedArray.length); // return strippedArray; // } // // } // Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/usb/UsbLinkJava.java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import javax.usb.UsbConfiguration; import javax.usb.UsbConst; import javax.usb.UsbControlIrp; import javax.usb.UsbDevice; import javax.usb.UsbDeviceDescriptor; import javax.usb.UsbDisconnectedException; import javax.usb.UsbEndpoint; import javax.usb.UsbException; import javax.usb.UsbHostManager; import javax.usb.UsbHub; import javax.usb.UsbInterface; import javax.usb.UsbIrp; import javax.usb.UsbPipe; import javax.usb.UsbServices; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.bitcraze.crazyflie.lib.Utilities; return mIntf != null && mIntf.isClaimed(); } /* (non-Javadoc) * @see CrazyUsbInterface#sendControlTransfer(int, int, int, int, byte[]) */ @Override public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data) { int returnCode = -1; if(mUsbDevice != null){ try { UsbControlIrp usbControlIrp = mUsbDevice.createUsbControlIrp((byte) requestType, (byte) request, (short) value, (short) index); if(data == null){ data = new byte[0]; } usbControlIrp.setData(data); usbControlIrp.setLength(data.length); debugControlTransfer((byte) requestType, (byte) request, (byte) value, (byte) index, data); if(sendUsbControlIrp(mUsbDevice, usbControlIrp)){ returnCode = usbControlIrp.getActualLength(); } } catch (IllegalArgumentException | UsbDisconnectedException e) { e.printStackTrace(); } } return returnCode; } private void debugControlTransfer(byte requestType, byte request, byte value, byte index, byte[] data) { if (!FILTER_OUT_SEND_CONTROL_TRANSFER) {
mLogger.debug("sendControlTransfer, requestType: {}, request: {}, value: {}, index: {}, data: {}", Utilities.getHexString(requestType), Utilities.getHexString(request), Utilities.getHexString(value), Utilities.getHexString(index), Utilities.getHexString(data));
fredg02/se.bitcraze.crazyflie.lib
se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/crazyradio/Crazyradio.java
// Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/usb/CrazyUsbInterface.java // public interface CrazyUsbInterface { // // /** // * Init device // * // * @param usbVid // * @param usbPid // */ // public void initDevice(int usbVid, int usbPid) throws IOException, SecurityException; // // /** // * Release UsbInterface // * // */ // public void releaseInterface(); // // /** // * Returns the state of the USB connection // * // * @return true if USB device is connected, else false // */ // public boolean isUsbConnected(); // // /** // * Send control data // * // * @param requestType // * @param request // * @param value // * @param index // * @param data // * @return // */ // public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data); // // /** // * Sends bulk data // * // * @param data // * @param receiveData // * @return // */ // public int sendBulkTransfer(byte[] data, byte[] receiveData); // // /** // * Returns a list of CrazyRadio devices currently connected to the computer // * // * @param usbVid // * @param usbPid // * @return // */ // public List<UsbDevice> findDevices(int usbVid, int usbPid); // // /** // * Returns the firmware version of the USB device // * // * @return firmware version // */ // public float getFirmwareVersion(); // // /** // * Returns the serial number of the USB device // * // * @return serial number // */ // public String getSerialNumber(); // // public void bulkWrite(byte[] data); // // public byte[] bulkRead(); // // }
import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.bitcraze.crazyflie.lib.usb.CrazyUsbInterface; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays;
/** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2013 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.crazyradio; /** * Used for communication with the Crazyradio USB dongle * */ public class Crazyradio { protected final Logger mLogger = LoggerFactory.getLogger(this.getClass().getSimpleName()); // USB parameters public static final int CRADIO_VID = 0x1915; //Vendor ID public static final int CRADIO_PID = 0x7777; //Product ID // Dongle configuration requests // See http://wiki.bitcraze.se/projects:crazyradio:protocol for documentation private static final int SET_RADIO_CHANNEL = 0x01; private static final int SET_RADIO_ADDRESS = 0x02; private static final int SET_DATA_RATE = 0x03; private static final int SET_RADIO_POWER = 0x04; private static final int SET_RADIO_ARD = 0x05; private static final int SET_RADIO_ARC = 0x06; //private static final int ACK_ENABLE = 0x10; private static final int SET_CONT_CARRIER = 0x20; private static final int SCAN_CHANNELS = 0x21; //private static final int LAUNCH_BOOTLOADER = 0xFF; // configuration constants public static final int DR_250KPS = 0; public static final int DR_1MPS = 1; public static final int DR_2MPS = 2; public static final int P_M18DBM = 0; public static final int P_M12DBM = 1; public static final int P_M6DBM = 2; public static final int P_0DBM = 3;
// Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/usb/CrazyUsbInterface.java // public interface CrazyUsbInterface { // // /** // * Init device // * // * @param usbVid // * @param usbPid // */ // public void initDevice(int usbVid, int usbPid) throws IOException, SecurityException; // // /** // * Release UsbInterface // * // */ // public void releaseInterface(); // // /** // * Returns the state of the USB connection // * // * @return true if USB device is connected, else false // */ // public boolean isUsbConnected(); // // /** // * Send control data // * // * @param requestType // * @param request // * @param value // * @param index // * @param data // * @return // */ // public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data); // // /** // * Sends bulk data // * // * @param data // * @param receiveData // * @return // */ // public int sendBulkTransfer(byte[] data, byte[] receiveData); // // /** // * Returns a list of CrazyRadio devices currently connected to the computer // * // * @param usbVid // * @param usbPid // * @return // */ // public List<UsbDevice> findDevices(int usbVid, int usbPid); // // /** // * Returns the firmware version of the USB device // * // * @return firmware version // */ // public float getFirmwareVersion(); // // /** // * Returns the serial number of the USB device // * // * @return serial number // */ // public String getSerialNumber(); // // public void bulkWrite(byte[] data); // // public byte[] bulkRead(); // // } // Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/crazyradio/Crazyradio.java import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.bitcraze.crazyflie.lib.usb.CrazyUsbInterface; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2013 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.crazyradio; /** * Used for communication with the Crazyradio USB dongle * */ public class Crazyradio { protected final Logger mLogger = LoggerFactory.getLogger(this.getClass().getSimpleName()); // USB parameters public static final int CRADIO_VID = 0x1915; //Vendor ID public static final int CRADIO_PID = 0x7777; //Product ID // Dongle configuration requests // See http://wiki.bitcraze.se/projects:crazyradio:protocol for documentation private static final int SET_RADIO_CHANNEL = 0x01; private static final int SET_RADIO_ADDRESS = 0x02; private static final int SET_DATA_RATE = 0x03; private static final int SET_RADIO_POWER = 0x04; private static final int SET_RADIO_ARD = 0x05; private static final int SET_RADIO_ARC = 0x06; //private static final int ACK_ENABLE = 0x10; private static final int SET_CONT_CARRIER = 0x20; private static final int SCAN_CHANNELS = 0x21; //private static final int LAUNCH_BOOTLOADER = 0xFF; // configuration constants public static final int DR_250KPS = 0; public static final int DR_1MPS = 1; public static final int DR_2MPS = 2; public static final int P_M18DBM = 0; public static final int P_M12DBM = 1; public static final int P_M6DBM = 2; public static final int P_0DBM = 3;
private CrazyUsbInterface mUsbInterface;
fredg02/se.bitcraze.crazyflie.lib
se.bitcraze.crazyflie.lib/src/test/java/se/bitcraze/crazyflie/lib/bootloader/UtilitiesTest.java
// Path: se.bitcraze.crazyflie.lib/src/test/java/se/bitcraze/crazyflie/lib/OfflineTests.java // public interface OfflineTests { // // } // // Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/bootloader/Target.java // public static class TargetTypes { // public static final int STM32 = 0xFF; // public static final int NRF51 = 0xFE; // // private TargetTypes() { // throw new IllegalStateException("Utility class"); // } // // public static String toString(int target) { // if (target == TargetTypes.STM32) { // return "stm32"; // } else if (target == TargetTypes.NRF51) { // return "nrf51"; // } // return "Unknown"; // } // // public static int fromString(String name) { // if ("stm32".equalsIgnoreCase(name)) { // return TargetTypes.STM32; // } else if ("nrf51".equalsIgnoreCase(name)) { // return TargetTypes.NRF51; // } // return 0; // } // }
import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.junit.experimental.categories.Category; import se.bitcraze.crazyflie.lib.OfflineTests; import se.bitcraze.crazyflie.lib.bootloader.Target.TargetTypes;
package se.bitcraze.crazyflie.lib.bootloader; @Category(OfflineTests.class) @SuppressWarnings("java:S106") public class UtilitiesTest { @Test public void testBootVersion() { assertEquals("Crazyflie Nano Quadcopter (1.0)", BootVersion.toVersionString(BootVersion.CF1_PROTO_VER_0)); assertEquals("Crazyflie Nano Quadcopter (1.0)", BootVersion.toVersionString(BootVersion.CF1_PROTO_VER_1)); assertEquals("Crazyflie 2.0", BootVersion.toVersionString(BootVersion.CF2_PROTO_VER)); assertEquals("Unknown", BootVersion.toVersionString(0x12)); } @Test public void testTargetTypes() {
// Path: se.bitcraze.crazyflie.lib/src/test/java/se/bitcraze/crazyflie/lib/OfflineTests.java // public interface OfflineTests { // // } // // Path: se.bitcraze.crazyflie.lib/src/main/java/se/bitcraze/crazyflie/lib/bootloader/Target.java // public static class TargetTypes { // public static final int STM32 = 0xFF; // public static final int NRF51 = 0xFE; // // private TargetTypes() { // throw new IllegalStateException("Utility class"); // } // // public static String toString(int target) { // if (target == TargetTypes.STM32) { // return "stm32"; // } else if (target == TargetTypes.NRF51) { // return "nrf51"; // } // return "Unknown"; // } // // public static int fromString(String name) { // if ("stm32".equalsIgnoreCase(name)) { // return TargetTypes.STM32; // } else if ("nrf51".equalsIgnoreCase(name)) { // return TargetTypes.NRF51; // } // return 0; // } // } // Path: se.bitcraze.crazyflie.lib/src/test/java/se/bitcraze/crazyflie/lib/bootloader/UtilitiesTest.java import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.junit.experimental.categories.Category; import se.bitcraze.crazyflie.lib.OfflineTests; import se.bitcraze.crazyflie.lib.bootloader.Target.TargetTypes; package se.bitcraze.crazyflie.lib.bootloader; @Category(OfflineTests.class) @SuppressWarnings("java:S106") public class UtilitiesTest { @Test public void testBootVersion() { assertEquals("Crazyflie Nano Quadcopter (1.0)", BootVersion.toVersionString(BootVersion.CF1_PROTO_VER_0)); assertEquals("Crazyflie Nano Quadcopter (1.0)", BootVersion.toVersionString(BootVersion.CF1_PROTO_VER_1)); assertEquals("Crazyflie 2.0", BootVersion.toVersionString(BootVersion.CF2_PROTO_VER)); assertEquals("Unknown", BootVersion.toVersionString(0x12)); } @Test public void testTargetTypes() {
assertEquals("stm32", TargetTypes.toString(TargetTypes.STM32));
EXIficient/exificient
src/main/java/com/siemens/ct/exi/main/api/stream/StAXDecoder.java
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.DocType; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.container.ProcessingInstruction; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver;
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.api.stream; /** * De-Serializes EXI to StAX * * @author Daniel.Peintner.EXT@siemens.com * @author Richard.Kuntschke@siemens.com * */ public class StAXDecoder implements XMLStreamReader // XMLEventReader { protected EXIFactory noOptionsFactory; protected EXIStreamDecoder exiStream; protected EXIBodyDecoder decoder; // protected XMLStreamReader xmlStream; protected boolean exiBodyOnly = false; protected QNameContext element; protected List<AttributeContainer> attributes; protected Value characters; protected DocType docType; protected char[] entityReference; protected char[] comment; protected ProcessingInstruction processingInstruction; protected boolean namespacePrefixes = false; /* current event */ protected EventType eventType; /* pre-read event, e.g., for attribute count */ protected EventType preReadEventType; /* namespace context */ protected EXINamespaceContext nsContext; static class AttributeContainer { final QNameContext qname; final Value value; final String prefix; public AttributeContainer(QNameContext qname, Value value, String prefix) { this.qname = qname; this.value = value; this.prefix = prefix; } } public StAXDecoder(EXIFactory noOptionsFactory) throws EXIException { this.noOptionsFactory = noOptionsFactory; if (noOptionsFactory.getSchemaIdResolver() == null) { // set default schemaId resolver
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // } // Path: src/main/java/com/siemens/ct/exi/main/api/stream/StAXDecoder.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.DocType; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.container.ProcessingInstruction; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver; /* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.api.stream; /** * De-Serializes EXI to StAX * * @author Daniel.Peintner.EXT@siemens.com * @author Richard.Kuntschke@siemens.com * */ public class StAXDecoder implements XMLStreamReader // XMLEventReader { protected EXIFactory noOptionsFactory; protected EXIStreamDecoder exiStream; protected EXIBodyDecoder decoder; // protected XMLStreamReader xmlStream; protected boolean exiBodyOnly = false; protected QNameContext element; protected List<AttributeContainer> attributes; protected Value characters; protected DocType docType; protected char[] entityReference; protected char[] comment; protected ProcessingInstruction processingInstruction; protected boolean namespacePrefixes = false; /* current event */ protected EventType eventType; /* pre-read event, e.g., for attribute count */ protected EventType preReadEventType; /* namespace context */ protected EXINamespaceContext nsContext; static class AttributeContainer { final QNameContext qname; final Value value; final String prefix; public AttributeContainer(QNameContext qname, Value value, String prefix) { this.qname = qname; this.value = value; this.prefix = prefix; } } public StAXDecoder(EXIFactory noOptionsFactory) throws EXIException { this.noOptionsFactory = noOptionsFactory; if (noOptionsFactory.getSchemaIdResolver() == null) { // set default schemaId resolver
noOptionsFactory.setSchemaIdResolver(new DefaultSchemaIdResolver());
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/core/BlockSizeTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import org.custommonkey.xmlunit.XMLTestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult;
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.core; public class BlockSizeTestCase extends XMLTestCase { String xml = "<root atA='a' atB='b' atC='c' atD='d' atE='e'>" + "... TEXT ..." + "</root>"; protected void _test(CodingMode codingMode, int blockSize) throws SAXException, IOException, EXIException { try { EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setCodingMode(codingMode); factory.setBlockSize(blockSize); ByteArrayOutputStream os = new ByteArrayOutputStream(); // write EXI stream { XMLReader xmlReader = XMLReaderFactory.createXMLReader();
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // Path: src/test/java/com/siemens/ct/exi/main/core/BlockSizeTestCase.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import org.custommonkey.xmlunit.XMLTestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; /* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.core; public class BlockSizeTestCase extends XMLTestCase { String xml = "<root atA='a' atB='b' atC='c' atD='d' atE='e'>" + "... TEXT ..." + "</root>"; protected void _test(CodingMode codingMode, int blockSize) throws SAXException, IOException, EXIException { try { EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setCodingMode(codingMode); factory.setBlockSize(blockSize); ByteArrayOutputStream os = new ByteArrayOutputStream(); // write EXI stream { XMLReader xmlReader = XMLReaderFactory.createXMLReader();
EXIResult exiResult = new EXIResult(factory);
EXIficient/exificient
src/main/java/com/siemens/ct/exi/main/api/dom/DOMBuilder.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // }
import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.main.api.sax.SAXFactory; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.DOMImplementation;
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.api.dom; /** * Builds a <code>Document</code> for a given EXI stream. * * @author Daniel.Peintner.EXT@siemens.com * @author Richard.Kuntschke@siemens.com * */ public class DOMBuilder { protected EXIFactory factory; protected DOMImplementation domImplementation; public DOMBuilder(EXIFactory factory) throws ParserConfigurationException { this.factory = factory; // setup document builder etc. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); domImplementation = builder.getDOMImplementation(); } public DocumentFragment parseFragment(InputStream is) throws EXIException { try { // // create empty document fragment // Document document = domImplementation.createDocument(null, null, // null); // DocumentFragment docFragment = document.createDocumentFragment(); // create SAX to DOM Handlers SaxToDomHandler s2dHandler = new SaxToDomHandler(domImplementation, true);
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // } // Path: src/main/java/com/siemens/ct/exi/main/api/dom/DOMBuilder.java import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.main.api.sax.SAXFactory; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.DOMImplementation; /* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.api.dom; /** * Builds a <code>Document</code> for a given EXI stream. * * @author Daniel.Peintner.EXT@siemens.com * @author Richard.Kuntschke@siemens.com * */ public class DOMBuilder { protected EXIFactory factory; protected DOMImplementation domImplementation; public DOMBuilder(EXIFactory factory) throws ParserConfigurationException { this.factory = factory; // setup document builder etc. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); domImplementation = builder.getDOMImplementation(); } public DocumentFragment parseFragment(InputStream is) throws EXIException { try { // // create empty document fragment // Document document = domImplementation.createDocument(null, null, // null); // DocumentFragment docFragment = document.createDocumentFragment(); // create SAX to DOM Handlers SaxToDomHandler s2dHandler = new SaxToDomHandler(domImplementation, true);
XMLReader reader = new SAXFactory(factory).createEXIReader();
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/api/xmlpull/ParserExample.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // }
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult;
package com.siemens.ct.exi.main.api.xmlpull; public class ParserExample { public static void main(final String[] args) throws XmlPullParserException, MalformedURLException, IOException, EXIException, SAXException { String xml = "./data/W3C/PrimerNotebook/notebook.xml"; EXIFactory factory = DefaultEXIFactory.newInstance(); // Encode to EXI ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // Path: src/test/java/com/siemens/ct/exi/main/api/xmlpull/ParserExample.java import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; package com.siemens.ct.exi.main.api.xmlpull; public class ParserExample { public static void main(final String[] args) throws XmlPullParserException, MalformedURLException, IOException, EXIException, SAXException { String xml = "./data/W3C/PrimerNotebook/notebook.xml"; EXIFactory factory = DefaultEXIFactory.newInstance(); // Encode to EXI ByteArrayOutputStream baos = new ByteArrayOutputStream();
EXIResult exiResult = new EXIResult(factory);
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/data/IssueTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXISource.java // public class EXISource extends SAXSource { // // SAXFactory saxFactory; // // public EXISource() throws EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXISource(EXIFactory exiFactory) throws EXIException { // this.saxFactory = new SAXFactory(exiFactory); // // init(); // } // // protected void init() throws EXIException { // // create sax decoder // XMLReader xmlReader = saxFactory.createEXIReader(); // // // set internal state // this.setXMLReader(xmlReader); // } // // }
import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.EXISource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer;
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; public class IssueTestCase extends AbstractTestCase { public IssueTestCase() { super("Issues Test Cases"); } // https://github.com/EXIficient/exificient/issues/20 public void testIssue20() throws Exception { EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setValueMaxLength(16); // exiFactory.setCodingMode(CodingMode.COMPRESSION); String sxmlIssue20 = "./data/issues/issue20/treebank_e.xml"; File fEXI = File.createTempFile("testIssue20", ".exi"); fEXI.deleteOnExit(); // encode { long startEncode = System.currentTimeMillis(); OutputStream osEXI = new FileOutputStream(fEXI); // EXI output
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXISource.java // public class EXISource extends SAXSource { // // SAXFactory saxFactory; // // public EXISource() throws EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXISource(EXIFactory exiFactory) throws EXIException { // this.saxFactory = new SAXFactory(exiFactory); // // init(); // } // // protected void init() throws EXIException { // // create sax decoder // XMLReader xmlReader = saxFactory.createEXIReader(); // // // set internal state // this.setXMLReader(xmlReader); // } // // } // Path: src/test/java/com/siemens/ct/exi/main/data/IssueTestCase.java import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.EXISource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer; /* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; public class IssueTestCase extends AbstractTestCase { public IssueTestCase() { super("Issues Test Cases"); } // https://github.com/EXIficient/exificient/issues/20 public void testIssue20() throws Exception { EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setValueMaxLength(16); // exiFactory.setCodingMode(CodingMode.COMPRESSION); String sxmlIssue20 = "./data/issues/issue20/treebank_e.xml"; File fEXI = File.createTempFile("testIssue20", ".exi"); fEXI.deleteOnExit(); // encode { long startEncode = System.currentTimeMillis(); OutputStream osEXI = new FileOutputStream(fEXI); // EXI output
EXIResult exiResult = new EXIResult(exiFactory);
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/data/IssueTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXISource.java // public class EXISource extends SAXSource { // // SAXFactory saxFactory; // // public EXISource() throws EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXISource(EXIFactory exiFactory) throws EXIException { // this.saxFactory = new SAXFactory(exiFactory); // // init(); // } // // protected void init() throws EXIException { // // create sax decoder // XMLReader xmlReader = saxFactory.createEXIReader(); // // // set internal state // this.setXMLReader(xmlReader); // } // // }
import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.EXISource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer;
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; public class IssueTestCase extends AbstractTestCase { public IssueTestCase() { super("Issues Test Cases"); } // https://github.com/EXIficient/exificient/issues/20 public void testIssue20() throws Exception { EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setValueMaxLength(16); // exiFactory.setCodingMode(CodingMode.COMPRESSION); String sxmlIssue20 = "./data/issues/issue20/treebank_e.xml"; File fEXI = File.createTempFile("testIssue20", ".exi"); fEXI.deleteOnExit(); // encode { long startEncode = System.currentTimeMillis(); OutputStream osEXI = new FileOutputStream(fEXI); // EXI output EXIResult exiResult = new EXIResult(exiFactory); exiResult.setOutputStream(osEXI); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler( exiResult.getHandler() ); xmlReader.parse(sxmlIssue20); // parse XML input osEXI.close(); long endEncode = System.currentTimeMillis(); System.out.println("Encode time for " + sxmlIssue20 + " is " + (endEncode-startEncode) + "ms to " + fEXI.length() +"Bytes, " + System.getProperty("java.version")); } // decode { long startDecode = System.currentTimeMillis(); Result result = new StreamResult(File.createTempFile("testIssue20", ".xml")); InputSource is = new InputSource(new FileInputStream(fEXI));
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXISource.java // public class EXISource extends SAXSource { // // SAXFactory saxFactory; // // public EXISource() throws EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXISource(EXIFactory exiFactory) throws EXIException { // this.saxFactory = new SAXFactory(exiFactory); // // init(); // } // // protected void init() throws EXIException { // // create sax decoder // XMLReader xmlReader = saxFactory.createEXIReader(); // // // set internal state // this.setXMLReader(xmlReader); // } // // } // Path: src/test/java/com/siemens/ct/exi/main/data/IssueTestCase.java import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.EXISource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer; /* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; public class IssueTestCase extends AbstractTestCase { public IssueTestCase() { super("Issues Test Cases"); } // https://github.com/EXIficient/exificient/issues/20 public void testIssue20() throws Exception { EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setValueMaxLength(16); // exiFactory.setCodingMode(CodingMode.COMPRESSION); String sxmlIssue20 = "./data/issues/issue20/treebank_e.xml"; File fEXI = File.createTempFile("testIssue20", ".exi"); fEXI.deleteOnExit(); // encode { long startEncode = System.currentTimeMillis(); OutputStream osEXI = new FileOutputStream(fEXI); // EXI output EXIResult exiResult = new EXIResult(exiFactory); exiResult.setOutputStream(osEXI); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler( exiResult.getHandler() ); xmlReader.parse(sxmlIssue20); // parse XML input osEXI.close(); long endEncode = System.currentTimeMillis(); System.out.println("Encode time for " + sxmlIssue20 + " is " + (endEncode-startEncode) + "ms to " + fEXI.length() +"Bytes, " + System.getProperty("java.version")); } // decode { long startDecode = System.currentTimeMillis(); Result result = new StreamResult(File.createTempFile("testIssue20", ".xml")); InputSource is = new InputSource(new FileInputStream(fEXI));
SAXSource exiSource = new EXISource(exiFactory);
EXIficient/exificient
src/main/java/com/siemens/ct/exi/main/api/sax/SAXDecoder.java
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/util/NoEntityResolver.java // public class NoEntityResolver implements EntityResolver { // // public InputSource resolveEntity(String publicId, String systemId) { // // if // // (systemId.equals("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")) // // { // // return new InputSource("./data/W3C/xhtml/xhtml1-strict.dtd"); // // } // // System.out.println( publicId + "\t" + systemId); // return new InputSource(new ByteArrayInputStream( // "<?xml version='1.0' encoding='UTF-8'?>".getBytes())); // } // }
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.List; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.DocType; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.container.ProcessingInstruction; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.values.ListValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.core.values.ValueType; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver; import com.siemens.ct.exi.main.util.NoEntityResolver;
// <!DOCTYPE foo [ // <!ELEMENT foo (#PCDATA)> // ]> // e.g., (b) External DTD // <!DOCTYPE root_element SYSTEM "DTD_location"> // <!DOCTYPE root_element PUBLIC "DTD_name" "DTD_location"> // Combining // <!DOCTYPE document SYSTEM "subjects.dtd" [ // <!ATTLIST assessment assessment_type (exam | assignment | prac)> // <!ELEMENT results (#PCDATA)> // ]> // DeclHandler dh; XMLReader xmlReader; public DocTypeTextLexicalHandler(DeclHandler dh) throws SAXException { // this.dh = dh; xmlReader = XMLReaderFactory.createXMLReader(); // xmlReader.setProperty( // "http://xml.org/sax/properties/lexical-handler", // lh); // DTD xmlReader.setFeature( "http://xml.org/sax/features/resolve-dtd-uris", false); // *skip* resolving entities like DTDs
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/util/NoEntityResolver.java // public class NoEntityResolver implements EntityResolver { // // public InputSource resolveEntity(String publicId, String systemId) { // // if // // (systemId.equals("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")) // // { // // return new InputSource("./data/W3C/xhtml/xhtml1-strict.dtd"); // // } // // System.out.println( publicId + "\t" + systemId); // return new InputSource(new ByteArrayInputStream( // "<?xml version='1.0' encoding='UTF-8'?>".getBytes())); // } // } // Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXDecoder.java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.List; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.DocType; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.container.ProcessingInstruction; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.values.ListValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.core.values.ValueType; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver; import com.siemens.ct.exi.main.util.NoEntityResolver; // <!DOCTYPE foo [ // <!ELEMENT foo (#PCDATA)> // ]> // e.g., (b) External DTD // <!DOCTYPE root_element SYSTEM "DTD_location"> // <!DOCTYPE root_element PUBLIC "DTD_name" "DTD_location"> // Combining // <!DOCTYPE document SYSTEM "subjects.dtd" [ // <!ATTLIST assessment assessment_type (exam | assignment | prac)> // <!ELEMENT results (#PCDATA)> // ]> // DeclHandler dh; XMLReader xmlReader; public DocTypeTextLexicalHandler(DeclHandler dh) throws SAXException { // this.dh = dh; xmlReader = XMLReaderFactory.createXMLReader(); // xmlReader.setProperty( // "http://xml.org/sax/properties/lexical-handler", // lh); // DTD xmlReader.setFeature( "http://xml.org/sax/features/resolve-dtd-uris", false); // *skip* resolving entities like DTDs
xmlReader.setEntityResolver(new NoEntityResolver());
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/core/EXIHeaderTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.namespace.QName; import junit.framework.TestCase; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SchemaIdResolver; import com.siemens.ct.exi.core.coder.EXIHeaderDecoder; import com.siemens.ct.exi.core.coder.EXIHeaderEncoder; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.BitDecoderChannel; import com.siemens.ct.exi.core.io.channel.BitEncoderChannel; import com.siemens.ct.exi.core.io.channel.DecoderChannel; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver;
fail("No Valid Cookie"); } catch (Exception e) { // no valid cookie } } protected void _testOptions(EXIFactory test) throws EXIException, IOException { _testOptions(test, null); } protected void _testOptions(EXIFactory test, EXIFactory noOptionsFactory) throws EXIException, IOException { EXIHeaderEncoder headerEncoder = new EXIHeaderEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); EncoderChannel encoderChannel = new BitEncoderChannel(baos); headerEncoder.writeEXIOptions(test, encoderChannel); encoderChannel.flush(); DecoderChannel decoderChannel = new BitDecoderChannel( new ByteArrayInputStream(baos.toByteArray())); EXIHeaderDecoder headerDecoder = new EXIHeaderDecoder(); if (noOptionsFactory == null) { noOptionsFactory = DefaultEXIFactory.newInstance(); } if (noOptionsFactory.getSchemaIdResolver() == null) { // set default schemaId resolver
// Path: src/main/java/com/siemens/ct/exi/main/helpers/DefaultSchemaIdResolver.java // public class DefaultSchemaIdResolver implements SchemaIdResolver { // // // protected GrammarFactory gf; // // public DefaultSchemaIdResolver() { // // } // // protected GrammarFactory getGrammarFactory() { // return GrammarFactory.newInstance(); // // if (gf == null) { // // gf = GrammarFactory.newInstance(); // // } // // return gf; // } // // public Grammars resolveSchemaId(String schemaId) throws EXIException { // if (schemaId == null) { // return getGrammarFactory().createSchemaLessGrammars(); // } else if ("".equals(schemaId)) { // return getGrammarFactory().createXSDTypesOnlyGrammars(); // } else { // // interpret schemaId as location // try { // return getGrammarFactory().createGrammars(schemaId); // } catch (Exception e) { // throw new EXIException(this.getClass().getName() // + " failed to retrieve schemaId == " + schemaId, e); // } // } // } // // } // Path: src/test/java/com/siemens/ct/exi/main/core/EXIHeaderTestCase.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.namespace.QName; import junit.framework.TestCase; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SchemaIdResolver; import com.siemens.ct.exi.core.coder.EXIHeaderDecoder; import com.siemens.ct.exi.core.coder.EXIHeaderEncoder; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.BitDecoderChannel; import com.siemens.ct.exi.core.io.channel.BitEncoderChannel; import com.siemens.ct.exi.core.io.channel.DecoderChannel; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.helpers.DefaultSchemaIdResolver; fail("No Valid Cookie"); } catch (Exception e) { // no valid cookie } } protected void _testOptions(EXIFactory test) throws EXIException, IOException { _testOptions(test, null); } protected void _testOptions(EXIFactory test, EXIFactory noOptionsFactory) throws EXIException, IOException { EXIHeaderEncoder headerEncoder = new EXIHeaderEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); EncoderChannel encoderChannel = new BitEncoderChannel(baos); headerEncoder.writeEXIOptions(test, encoderChannel); encoderChannel.flush(); DecoderChannel decoderChannel = new BitDecoderChannel( new ByteArrayInputStream(baos.toByteArray())); EXIHeaderDecoder headerDecoder = new EXIHeaderDecoder(); if (noOptionsFactory == null) { noOptionsFactory = DefaultEXIFactory.newInstance(); } if (noOptionsFactory.getSchemaIdResolver() == null) { // set default schemaId resolver
noOptionsFactory.setSchemaIdResolver(new DefaultSchemaIdResolver());
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/core/RoundtripTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; import javax.xml.namespace.QName; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.EXIStreamEncoder; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.values.IntegerValue; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.core.values.ValueType; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult;
enc2.encodeEndDocument(); enc2.flush(); /* * Check equality of streams */ assertTrue(os1.size() == os2.size()); assertTrue(Arrays.equals(os1.toByteArray(), os2.toByteArray())); } // type-aware roundtrip of notebook example public void testNotebook() throws Exception { String xsd = "./data/W3C/PrimerNotebook/notebook.xsd"; String xml = "./data/W3C/PrimerNotebook/notebook.xml"; GrammarFactory gf = GrammarFactory.newInstance(); Grammars grammar = gf.createGrammars(xsd); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setCodingMode(CodingMode.BYTE_PACKED); factory.setGrammars(grammar); factory.setFidelityOptions(FidelityOptions.createStrict()); /* * Encode to EXI */ EXIBodyEncoder enc1 = factory.createEXIBodyEncoder(); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); enc1.setOutputStream(os1); XMLReader xmlReader = XMLReaderFactory.createXMLReader();
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // Path: src/test/java/com/siemens/ct/exi/main/core/RoundtripTestCase.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; import javax.xml.namespace.QName; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EXIStreamDecoder; import com.siemens.ct.exi.core.EXIStreamEncoder; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.container.NamespaceDeclaration; import com.siemens.ct.exi.core.context.QNameContext; import com.siemens.ct.exi.core.grammars.Grammars; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.values.IntegerValue; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.core.values.ValueType; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; enc2.encodeEndDocument(); enc2.flush(); /* * Check equality of streams */ assertTrue(os1.size() == os2.size()); assertTrue(Arrays.equals(os1.toByteArray(), os2.toByteArray())); } // type-aware roundtrip of notebook example public void testNotebook() throws Exception { String xsd = "./data/W3C/PrimerNotebook/notebook.xsd"; String xml = "./data/W3C/PrimerNotebook/notebook.xml"; GrammarFactory gf = GrammarFactory.newInstance(); Grammars grammar = gf.createGrammars(xsd); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setCodingMode(CodingMode.BYTE_PACKED); factory.setGrammars(grammar); factory.setFidelityOptions(FidelityOptions.createStrict()); /* * Encode to EXI */ EXIBodyEncoder enc1 = factory.createEXIBodyEncoder(); ByteArrayOutputStream os1 = new ByteArrayOutputStream(); enc1.setOutputStream(os1); XMLReader xmlReader = XMLReaderFactory.createXMLReader();
EXIResult exiResult = new EXIResult(factory);
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/core/SelfContainedTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SelfContainedHandler; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.SAXFactory;
} } protected void _testSelfContained2(boolean bytePacked) throws Exception { String xmlAsString = "<foo><foo>text</foo><bla>btext</bla></foo>"; // boolean t1 = xmlAsString.matches("*"); // boolean t2 = xmlAsString.matches(".*"); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setFidelityOptions(FidelityOptions.createDefault()); // factory.setCodingMode(CodingMode.BIT_PACKED); if (bytePacked) { factory.setCodingMode(CodingMode.BYTE_PACKED); } FidelityOptions fo = factory.getFidelityOptions(); fo.setFidelity(FidelityOptions.FEATURE_SC, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // QName sc = new QName("", "bla"); QName sc = new QName(".*", ".*"); // any QName[] scElements = new QName[1]; scElements[0] = sc; SelfContainedHandlerTracker scHandler = new SelfContainedHandlerTracker(); factory.setSelfContainedElements(scElements, scHandler);
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // } // Path: src/test/java/com/siemens/ct/exi/main/core/SelfContainedTestCase.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SelfContainedHandler; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.SAXFactory; } } protected void _testSelfContained2(boolean bytePacked) throws Exception { String xmlAsString = "<foo><foo>text</foo><bla>btext</bla></foo>"; // boolean t1 = xmlAsString.matches("*"); // boolean t2 = xmlAsString.matches(".*"); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setFidelityOptions(FidelityOptions.createDefault()); // factory.setCodingMode(CodingMode.BIT_PACKED); if (bytePacked) { factory.setCodingMode(CodingMode.BYTE_PACKED); } FidelityOptions fo = factory.getFidelityOptions(); fo.setFidelity(FidelityOptions.FEATURE_SC, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // QName sc = new QName("", "bla"); QName sc = new QName(".*", ".*"); // any QName[] scElements = new QName[1]; scElements[0] = sc; SelfContainedHandlerTracker scHandler = new SelfContainedHandlerTracker(); factory.setSelfContainedElements(scElements, scHandler);
EXIResult exiResult = new EXIResult(factory);
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/core/SelfContainedTestCase.java
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SelfContainedHandler; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.SAXFactory;
// boolean t2 = xmlAsString.matches(".*"); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setFidelityOptions(FidelityOptions.createDefault()); // factory.setCodingMode(CodingMode.BIT_PACKED); if (bytePacked) { factory.setCodingMode(CodingMode.BYTE_PACKED); } FidelityOptions fo = factory.getFidelityOptions(); fo.setFidelity(FidelityOptions.FEATURE_SC, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // QName sc = new QName("", "bla"); QName sc = new QName(".*", ".*"); // any QName[] scElements = new QName[1]; scElements[0] = sc; SelfContainedHandlerTracker scHandler = new SelfContainedHandlerTracker(); factory.setSelfContainedElements(scElements, scHandler); EXIResult exiResult = new EXIResult(factory); exiResult.setOutputStream(baos); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(exiResult.getHandler()); xmlReader.parse(new InputSource(new StringReader(xmlAsString))); // decode overall document { TransformerFactory tf = TransformerFactory.newInstance();
// Path: src/main/java/com/siemens/ct/exi/main/api/sax/EXIResult.java // public class EXIResult extends SAXResult { // // protected SAXEncoder handler; // // public EXIResult() throws IOException, EXIException { // // use default exi-factory // this(DefaultEXIFactory.newInstance()); // } // // public EXIResult(EXIFactory exiFactory) throws EXIException { // // DefaultHandler2 handler = exiFactory.createEXIWriter(os); // handler = new SAXFactory(exiFactory).createEXIWriter(); // // set internal states // setHandler(handler); // setLexicalHandler(handler); // } // // public void setOutputStream(OutputStream os) throws EXIException, // IOException { // handler.setOutputStream(os); // } // // } // // Path: src/main/java/com/siemens/ct/exi/main/api/sax/SAXFactory.java // public class SAXFactory { // // protected final EXIFactory exiFactory; // // public SAXFactory(EXIFactory exiFactory) { // this.exiFactory = exiFactory; // } // // /** // * Returns an <code>EXIReader</code> // * // * @return reader using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public XMLReader createEXIReader() throws EXIException { // return new SAXDecoder(exiFactory); // } // // /** // * Returns a <code>SAXEncoder</code> that implements // * <code>DefaultHandler2</code> // * // * <p> // * Note that the output stream MUST be set. // * </p> // * // * @return writer using the previously set coding options. // * @throws EXIException // * EXI exception // * // */ // public SAXEncoder createEXIWriter() throws EXIException { // final FidelityOptions fidelityOptions = exiFactory.getFidelityOptions(); // if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_PREFIX) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_COMMENT) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_PI) // || fidelityOptions // .isFidelityEnabled(FidelityOptions.FEATURE_DTD)) { // return new SAXEncoderExtendedHandler(exiFactory); // } else { // return new SAXEncoder(exiFactory); // } // } // // } // Path: src/test/java/com/siemens/ct/exi/main/core/SelfContainedTestCase.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import junit.framework.TestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EXIBodyDecoder; import com.siemens.ct.exi.core.EXIBodyEncoder; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.SelfContainedHandler; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.event.EventType; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.channel.EncoderChannel; import com.siemens.ct.exi.core.values.StringValue; import com.siemens.ct.exi.core.values.Value; import com.siemens.ct.exi.grammars.GrammarFactory; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.SAXFactory; // boolean t2 = xmlAsString.matches(".*"); EXIFactory factory = DefaultEXIFactory.newInstance(); factory.setFidelityOptions(FidelityOptions.createDefault()); // factory.setCodingMode(CodingMode.BIT_PACKED); if (bytePacked) { factory.setCodingMode(CodingMode.BYTE_PACKED); } FidelityOptions fo = factory.getFidelityOptions(); fo.setFidelity(FidelityOptions.FEATURE_SC, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // QName sc = new QName("", "bla"); QName sc = new QName(".*", ".*"); // any QName[] scElements = new QName[1]; scElements[0] = sc; SelfContainedHandlerTracker scHandler = new SelfContainedHandlerTracker(); factory.setSelfContainedElements(scElements, scHandler); EXIResult exiResult = new EXIResult(factory); exiResult.setOutputStream(baos); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(exiResult.getHandler()); xmlReader.parse(new InputSource(new StringReader(xmlAsString))); // decode overall document { TransformerFactory tf = TransformerFactory.newInstance();
XMLReader exiReader = new SAXFactory(factory).createEXIReader();
kamranzafar/spring-wpapi
spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/TaxonomyService.java
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Taxonomy.java // public class Taxonomy implements Serializable { // private int[] capabilities; // private String name; // private String description; // private boolean hierarchical; // private String slug; // @JsonProperty("show_cloud") // private boolean showCloud; // private String[] types; // // public int[] getCapabilities() { // return capabilities; // } // // public void setCapabilities(int[] capabilities) { // this.capabilities = capabilities; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isHierarchical() { // return hierarchical; // } // // public void setHierarchical(boolean hierarchical) { // this.hierarchical = hierarchical; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public boolean isShowCloud() { // return showCloud; // } // // public void setShowCloud(boolean showCloud) { // this.showCloud = showCloud; // } // // public String[] getTypes() { // return types; // } // // public void setTypes(String[] types) { // this.types = types; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // }
import org.kamranzafar.spring.wpapi.Taxonomy; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map;
/** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class TaxonomyService extends BaseService<Taxonomy> { @Override public Taxonomy[] getAll() { return restTemplate.getForObject(buildUri(), Taxonomy[].class); } @Override public Taxonomy[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), Taxonomy[].class); } @Override public String getUrlPostfix() { return wpApiConfig.getApiVersionBase() + "/taxonomies"; } @Override public void create(Taxonomy obj) {
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Taxonomy.java // public class Taxonomy implements Serializable { // private int[] capabilities; // private String name; // private String description; // private boolean hierarchical; // private String slug; // @JsonProperty("show_cloud") // private boolean showCloud; // private String[] types; // // public int[] getCapabilities() { // return capabilities; // } // // public void setCapabilities(int[] capabilities) { // this.capabilities = capabilities; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isHierarchical() { // return hierarchical; // } // // public void setHierarchical(boolean hierarchical) { // this.hierarchical = hierarchical; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public boolean isShowCloud() { // return showCloud; // } // // public void setShowCloud(boolean showCloud) { // this.showCloud = showCloud; // } // // public String[] getTypes() { // return types; // } // // public void setTypes(String[] types) { // this.types = types; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // } // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/TaxonomyService.java import org.kamranzafar.spring.wpapi.Taxonomy; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map; /** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class TaxonomyService extends BaseService<Taxonomy> { @Override public Taxonomy[] getAll() { return restTemplate.getForObject(buildUri(), Taxonomy[].class); } @Override public Taxonomy[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), Taxonomy[].class); } @Override public String getUrlPostfix() { return wpApiConfig.getApiVersionBase() + "/taxonomies"; } @Override public void create(Taxonomy obj) {
throw new WpApiException("Not supported");
kamranzafar/spring-wpapi
spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/PostStatusService.java
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/PostStatus.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class PostStatus implements Serializable { // private String name; // @JsonProperty("public") // private boolean postPublic; // @JsonProperty("private") // private boolean postPrivate; // @JsonProperty("protected") // private boolean postProtected; // private boolean queryable; // @JsonProperty("show_in_list") // private boolean showInList; // private String slug; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isPostPublic() { // return postPublic; // } // // public void setPostPublic(boolean postPublic) { // this.postPublic = postPublic; // } // // public boolean isPostPrivate() { // return postPrivate; // } // // public void setPostPrivate(boolean postPrivate) { // this.postPrivate = postPrivate; // } // // public boolean isPostProtected() { // return postProtected; // } // // public void setPostProtected(boolean postProtected) { // this.postProtected = postProtected; // } // // public boolean isQueryable() { // return queryable; // } // // public void setQueryable(boolean queryable) { // this.queryable = queryable; // } // // public boolean isShowInList() { // return showInList; // } // // public void setShowInList(boolean showInList) { // this.showInList = showInList; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // }
import org.kamranzafar.spring.wpapi.PostStatus; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map;
/** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class PostStatusService extends BaseService<PostStatus> { @Override public PostStatus[] getAll() { return restTemplate.getForObject(buildUri(), PostStatus[].class); } @Override public PostStatus[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), PostStatus[].class); } @Override public void create(PostStatus obj) {
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/PostStatus.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class PostStatus implements Serializable { // private String name; // @JsonProperty("public") // private boolean postPublic; // @JsonProperty("private") // private boolean postPrivate; // @JsonProperty("protected") // private boolean postProtected; // private boolean queryable; // @JsonProperty("show_in_list") // private boolean showInList; // private String slug; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isPostPublic() { // return postPublic; // } // // public void setPostPublic(boolean postPublic) { // this.postPublic = postPublic; // } // // public boolean isPostPrivate() { // return postPrivate; // } // // public void setPostPrivate(boolean postPrivate) { // this.postPrivate = postPrivate; // } // // public boolean isPostProtected() { // return postProtected; // } // // public void setPostProtected(boolean postProtected) { // this.postProtected = postProtected; // } // // public boolean isQueryable() { // return queryable; // } // // public void setQueryable(boolean queryable) { // this.queryable = queryable; // } // // public boolean isShowInList() { // return showInList; // } // // public void setShowInList(boolean showInList) { // this.showInList = showInList; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // } // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/PostStatusService.java import org.kamranzafar.spring.wpapi.PostStatus; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map; /** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class PostStatusService extends BaseService<PostStatus> { @Override public PostStatus[] getAll() { return restTemplate.getForObject(buildUri(), PostStatus[].class); } @Override public PostStatus[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), PostStatus[].class); } @Override public void create(PostStatus obj) {
throw new WpApiException("Not supported");
kamranzafar/spring-wpapi
spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/PostTypeService.java
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/PostType.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class PostType implements Serializable { // private int[] capabilities; // private String name; // private String description; // private boolean hierarchical; // private String slug; // // public int[] getCapabilities() { // return capabilities; // } // // public void setCapabilities(int[] capabilities) { // this.capabilities = capabilities; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isHierarchical() { // return hierarchical; // } // // public void setHierarchical(boolean hierarchical) { // this.hierarchical = hierarchical; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // }
import org.kamranzafar.spring.wpapi.PostType; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map;
/** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class PostTypeService extends BaseService<PostType> { @Override public PostType[] getAll() { return restTemplate.getForObject(buildUri(), PostType[].class); } @Override public PostType[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), PostType[].class); } @Override public String getUrlPostfix() { return wpApiConfig.getApiVersionBase() + "/types"; } @Override public void create(PostType obj) {
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/PostType.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class PostType implements Serializable { // private int[] capabilities; // private String name; // private String description; // private boolean hierarchical; // private String slug; // // public int[] getCapabilities() { // return capabilities; // } // // public void setCapabilities(int[] capabilities) { // this.capabilities = capabilities; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isHierarchical() { // return hierarchical; // } // // public void setHierarchical(boolean hierarchical) { // this.hierarchical = hierarchical; // } // // public String getSlug() { // return slug; // } // // public void setSlug(String slug) { // this.slug = slug; // } // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/BaseService.java // public abstract class BaseService<T> implements WpApiService<T> { // @Autowired // protected WpApiConfig wpApiConfig; // // @Autowired // protected RestTemplate restTemplate; // // @Override // public T get(int id) { // return restTemplate.getForObject(buildUri() + "/" + id, getType()); // } // // @Override // public T get(int id, Map<String, String> params) { // return restTemplate.getForObject(buildUri(buildUri() + "/" + id, params), getType()); // } // // @Override // public void create(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void update(T obj) { // restTemplate.postForLocation(buildUri(), obj); // } // // @Override // public void delete(int id) { // restTemplate.delete(buildUri() + "/" + id); // } // // protected String buildUri() { // return (wpApiConfig.isHttps() ? "https://" : "http://") + wpApiConfig.getHost() + ":" + wpApiConfig.getPort() + "/" + wpApiConfig.getApiBase() + "/" + getUrlPostfix(); // } // // protected URI buildUri(String uri, Map<String, String> params) { // UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri); // // params.forEach((k, v) -> uriComponentsBuilder.queryParam(k, v)); // // return uriComponentsBuilder.build().toUri(); // } // // protected URI buildUri(Map<String, String> params) { // return buildUri(buildUri(), params); // } // // protected abstract String getUrlPostfix(); // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiException.java // public class WpApiException extends RuntimeException { // public WpApiException(String message) { // super(message); // } // // public WpApiException(String message, Throwable cause) { // super(message, cause); // } // } // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/impl/PostTypeService.java import org.kamranzafar.spring.wpapi.PostType; import org.kamranzafar.spring.wpapi.client.BaseService; import org.kamranzafar.spring.wpapi.client.WpApiException; import org.springframework.stereotype.Service; import java.util.Map; /** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.client.impl; /** * Created by kamran on 07/08/16. */ @Service public class PostTypeService extends BaseService<PostType> { @Override public PostType[] getAll() { return restTemplate.getForObject(buildUri(), PostType[].class); } @Override public PostType[] getAll(Map<String, String> params) { return restTemplate.getForObject(buildUri(params), PostType[].class); } @Override public String getUrlPostfix() { return wpApiConfig.getApiVersionBase() + "/types"; } @Override public void create(PostType obj) {
throw new WpApiException("Not supported");
kamranzafar/spring-wpapi
spring-wpapi-test/src/main/java/org/kamranzafar/spring/wpapi/test/Application.java
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Post.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Post extends ContentBase { // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiClient.java // @Component // public class WpApiClient { // @Autowired // List<WpApiService> wpApiServices; // // public <T> WpApiService<T> getService(Class<T> clazz) { // return wpApiServices.stream() // .filter(wpApiService -> wpApiService.getType().getName().equals(clazz.getName())).findFirst().get(); // } // // public WpApiService<Post> getPostService(){ // return getService(Post.class); // } // // public WpApiService<Page> getPageService(){ // return getService(Page.class); // } // // public WpApiService<Comment> getCommentService(){ // return getService(Comment.class); // } // // public WpApiService<Media> getMediaService(){ // return getService(Media.class); // } // // public WpApiService<PostStatus> getPostStatusService(){ // return getService(PostStatus.class); // } // // public WpApiService<PostType> getPostTypeService(){ // return getService(PostType.class); // } // // public WpApiService<Tag> getTagService(){ // return getService(Tag.class); // } // // public WpApiService<Category> getCategoryService(){ // return getService(Category.class); // } // // public WpApiService<Taxonomy> getTaxonomyService(){ // return getService(Taxonomy.class); // } // }
import java.util.Map; import org.kamranzafar.spring.wpapi.Post; import org.kamranzafar.spring.wpapi.client.WpApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.client.RestTemplate; import java.util.HashMap;
/** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.test; /** * Created by kamran on 05/08/16. */ @SpringBootApplication @ComponentScan("org.kamranzafar.spring.wpapi") public class Application implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Autowired
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Post.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Post extends ContentBase { // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiClient.java // @Component // public class WpApiClient { // @Autowired // List<WpApiService> wpApiServices; // // public <T> WpApiService<T> getService(Class<T> clazz) { // return wpApiServices.stream() // .filter(wpApiService -> wpApiService.getType().getName().equals(clazz.getName())).findFirst().get(); // } // // public WpApiService<Post> getPostService(){ // return getService(Post.class); // } // // public WpApiService<Page> getPageService(){ // return getService(Page.class); // } // // public WpApiService<Comment> getCommentService(){ // return getService(Comment.class); // } // // public WpApiService<Media> getMediaService(){ // return getService(Media.class); // } // // public WpApiService<PostStatus> getPostStatusService(){ // return getService(PostStatus.class); // } // // public WpApiService<PostType> getPostTypeService(){ // return getService(PostType.class); // } // // public WpApiService<Tag> getTagService(){ // return getService(Tag.class); // } // // public WpApiService<Category> getCategoryService(){ // return getService(Category.class); // } // // public WpApiService<Taxonomy> getTaxonomyService(){ // return getService(Taxonomy.class); // } // } // Path: spring-wpapi-test/src/main/java/org/kamranzafar/spring/wpapi/test/Application.java import java.util.Map; import org.kamranzafar.spring.wpapi.Post; import org.kamranzafar.spring.wpapi.client.WpApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.client.RestTemplate; import java.util.HashMap; /** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.test; /** * Created by kamran on 05/08/16. */ @SpringBootApplication @ComponentScan("org.kamranzafar.spring.wpapi") public class Application implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Autowired
private WpApiClient wpApiClient;
kamranzafar/spring-wpapi
spring-wpapi-test/src/main/java/org/kamranzafar/spring/wpapi/test/Application.java
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Post.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Post extends ContentBase { // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiClient.java // @Component // public class WpApiClient { // @Autowired // List<WpApiService> wpApiServices; // // public <T> WpApiService<T> getService(Class<T> clazz) { // return wpApiServices.stream() // .filter(wpApiService -> wpApiService.getType().getName().equals(clazz.getName())).findFirst().get(); // } // // public WpApiService<Post> getPostService(){ // return getService(Post.class); // } // // public WpApiService<Page> getPageService(){ // return getService(Page.class); // } // // public WpApiService<Comment> getCommentService(){ // return getService(Comment.class); // } // // public WpApiService<Media> getMediaService(){ // return getService(Media.class); // } // // public WpApiService<PostStatus> getPostStatusService(){ // return getService(PostStatus.class); // } // // public WpApiService<PostType> getPostTypeService(){ // return getService(PostType.class); // } // // public WpApiService<Tag> getTagService(){ // return getService(Tag.class); // } // // public WpApiService<Category> getCategoryService(){ // return getService(Category.class); // } // // public WpApiService<Taxonomy> getTaxonomyService(){ // return getService(Taxonomy.class); // } // }
import java.util.Map; import org.kamranzafar.spring.wpapi.Post; import org.kamranzafar.spring.wpapi.client.WpApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.client.RestTemplate; import java.util.HashMap;
/** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.test; /** * Created by kamran on 05/08/16. */ @SpringBootApplication @ComponentScan("org.kamranzafar.spring.wpapi") public class Application implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Autowired private WpApiClient wpApiClient; @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Override public void run(String... args) throws Exception { Map<String, String> params = new HashMap<>(); params.put("search", "Spring"); params.put("per_page", "2"); // results per page params.put("page", "1"); // current page // See WP-API Documentation more parameters // http://v2.wp-api.org/reference/
// Path: spring-wpapi-core/src/main/java/org/kamranzafar/spring/wpapi/Post.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Post extends ContentBase { // } // // Path: spring-wpapi-client/src/main/java/org/kamranzafar/spring/wpapi/client/WpApiClient.java // @Component // public class WpApiClient { // @Autowired // List<WpApiService> wpApiServices; // // public <T> WpApiService<T> getService(Class<T> clazz) { // return wpApiServices.stream() // .filter(wpApiService -> wpApiService.getType().getName().equals(clazz.getName())).findFirst().get(); // } // // public WpApiService<Post> getPostService(){ // return getService(Post.class); // } // // public WpApiService<Page> getPageService(){ // return getService(Page.class); // } // // public WpApiService<Comment> getCommentService(){ // return getService(Comment.class); // } // // public WpApiService<Media> getMediaService(){ // return getService(Media.class); // } // // public WpApiService<PostStatus> getPostStatusService(){ // return getService(PostStatus.class); // } // // public WpApiService<PostType> getPostTypeService(){ // return getService(PostType.class); // } // // public WpApiService<Tag> getTagService(){ // return getService(Tag.class); // } // // public WpApiService<Category> getCategoryService(){ // return getService(Category.class); // } // // public WpApiService<Taxonomy> getTaxonomyService(){ // return getService(Taxonomy.class); // } // } // Path: spring-wpapi-test/src/main/java/org/kamranzafar/spring/wpapi/test/Application.java import java.util.Map; import org.kamranzafar.spring.wpapi.Post; import org.kamranzafar.spring.wpapi.client.WpApiClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.client.RestTemplate; import java.util.HashMap; /** * Copyright 2016 Kamran Zafar * * 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.kamranzafar.spring.wpapi.test; /** * Created by kamran on 05/08/16. */ @SpringBootApplication @ComponentScan("org.kamranzafar.spring.wpapi") public class Application implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Autowired private WpApiClient wpApiClient; @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Override public void run(String... args) throws Exception { Map<String, String> params = new HashMap<>(); params.put("search", "Spring"); params.put("per_page", "2"); // results per page params.put("page", "1"); // current page // See WP-API Documentation more parameters // http://v2.wp-api.org/reference/
Post[] posts = wpApiClient.getPostService().getAll(params);
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils;
package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); }
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils; package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); }
public static class SelectorFragment extends K6neleListFragment {
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils;
package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); } public static class SelectorFragment extends K6neleListFragment { public void onCreate(Bundle icicle) { super.onCreate(icicle); Activity activity = getActivity(); RecognitionServiceManager mngr = new RecognitionServiceManager();
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils; package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); } public static class SelectorFragment extends K6neleListFragment { public void onCreate(Bundle icicle) { super.onCreate(icicle); Activity activity = getActivity(); RecognitionServiceManager mngr = new RecognitionServiceManager();
List<RecService> list = new ArrayList<>();
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils;
package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); } public static class SelectorFragment extends K6neleListFragment { public void onCreate(Bundle icicle) { super.onCreate(icicle); Activity activity = getActivity(); RecognitionServiceManager mngr = new RecognitionServiceManager(); List<RecService> list = new ArrayList<>(); for (String comboAsString : mngr.getServices(activity.getPackageManager())) { list.add(new RecService(activity, comboAsString)); }
// Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java // public class RecServiceAdapter extends ArrayAdapter<RecService> { // // private final List<RecService> list; // private final Activity context; // // public RecServiceAdapter(K6neleListFragment context, List<RecService> list) { // super(context.getActivity(), R.layout.list_item_recservice, list); // this.context = context.getActivity(); // this.list = list; // } // // private static class ViewHolder { // private ImageView icon; // private TextView service; // private TextView desc; // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View view; // if (convertView == null) { // view = context.getLayoutInflater().inflate(R.layout.list_item_recservice, null); // final ViewHolder viewHolder = new ViewHolder(); // viewHolder.icon = view.findViewById(R.id.serviceIcon); // viewHolder.service = view.findViewById(R.id.service); // viewHolder.desc = view.findViewById(R.id.desc); // view.setTag(viewHolder); // } else { // view = convertView; // } // ViewHolder holder = (ViewHolder) view.getTag(); // RecService item = list.get(position); // holder.icon.setImageDrawable(item.getIcon(this.context)); // holder.service.setText(item.getService()); // String desc = item.getDesc(); // if (desc == null || desc.isEmpty()) { // holder.desc.setText(R.string.dash); // } else { // holder.desc.setText(desc); // } // return view; // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/activity/RecServiceSelectorActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.adapter.RecServiceAdapter; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; import ee.ioc.phon.android.speechutils.RecognitionServiceManager; import ee.ioc.phon.android.speechutils.utils.IntentUtils; package ee.ioc.phon.android.speak.activity; public class RecServiceSelectorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SelectorFragment fragment = new SelectorFragment(); fragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); } public static class SelectorFragment extends K6neleListFragment { public void onCreate(Bundle icicle) { super.onCreate(icicle); Activity activity = getActivity(); RecognitionServiceManager mngr = new RecognitionServiceManager(); List<RecService> list = new ArrayList<>(); for (String comboAsString : mngr.getServices(activity.getPackageManager())) { list.add(new RecService(activity, comboAsString)); }
RecServiceAdapter adapter = new RecServiceAdapter(this, list);
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService;
package ee.ioc.phon.android.speak.adapter; public class RecServiceAdapter extends ArrayAdapter<RecService> { private final List<RecService> list; private final Activity context;
// Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/RecService.java // public class RecService { // // private final String mLabel; // private final String mDesc; // private String mSettingsActivity; // private final ComponentName mComponentName; // // public RecService(Context context, String id) { // String mDesc1 = ""; // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mComponentName = pair.first; // // mLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // ServiceInfo si = RecognitionServiceManager.getServiceInfo(context, mComponentName); // int resId = si.descriptionRes; // if (resId != 0) { // try { // PackageManager manager = context.getPackageManager(); // mDesc1 = manager.getResourcesForApplication(mComponentName.getPackageName()).getString(resId); // } catch (PackageManager.NameNotFoundException e) { // // Should not happen // } // } // mDesc = mDesc1; // try { // mSettingsActivity = RecognitionServiceManager.getSettingsActivity(context, si); // Log.i(mSettingsActivity); // } catch (XmlPullParserException | IOException e) { // mSettingsActivity = null; // } // } // // public String getService() { // return mLabel; // } // // public String getDesc() { // return mDesc; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public ComponentName getComponentName() { // return mComponentName; // } // // public Intent getSettingsIntent() { // if (mSettingsActivity == null) { // return null; // } // Intent intent = new Intent(); // intent.setClassName(mComponentName.getPackageName(), mSettingsActivity); // return intent; // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/RecServiceAdapter.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.RecService; package ee.ioc.phon.android.speak.adapter; public class RecServiceAdapter extends ArrayAdapter<RecService> { private final List<RecService> list; private final Activity context;
public RecServiceAdapter(K6neleListFragment context, List<RecService> list) {
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/adapter/ComboAdapter.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/Combo.java // public class Combo { // // public static final Comparator SORT_BY_LANGUAGE = new SortByLanguage(); // public static final Comparator SORT_BY_SELECTED_BY_LANGUAGE = new SortBySelectedByLanguage(); // // private final String mId; // private final String mServiceLabel; // private final String mAsString; // private final ComponentName mComponentName; // private final String mLocaleLongLabel; // private final String mLocaleAsStr; // private final String mShortLabel; // private final String mLongLabel; // private boolean mIsSelected; // // public Combo(Context context, String id) { // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mId = id; // mComponentName = pair.first; // mLocaleAsStr = pair.second; // mServiceLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // if (mLocaleAsStr.isEmpty() || "und".equals(mLocaleAsStr)) { // mLocaleLongLabel = ""; // mAsString = String.format(context.getString(R.string.labelComboListItemWithoutLocale), mServiceLabel); // mShortLabel = mServiceLabel; // mLongLabel = mServiceLabel; // } else { // mLocaleLongLabel = RecognitionServiceManager.makeLangLabel(mLocaleAsStr); // mAsString = String.format(context.getString(R.string.labelComboListItem), mServiceLabel, mLocaleLongLabel); // String mFormatLabelComboItem = context.getString(R.string.labelComboItem); // mShortLabel = String.format(mFormatLabelComboItem, mServiceLabel, mLocaleAsStr); // mLongLabel = String.format(mFormatLabelComboItem, mServiceLabel, mLocaleLongLabel); // } // } // // public String getId() { // return mId; // } // // public ComponentName getServiceComponent() { // return mComponentName; // } // // public String getLocaleAsStr() { // return mLocaleAsStr; // } // // public String getService() { // return mServiceLabel; // } // // public String getLanguage() { // return mLocaleLongLabel; // } // // public String getShortLabel() { // return mShortLabel; // } // // public String getLongLabel() { // return mLongLabel; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public String toString() { // return mAsString; // } // // public boolean isSelected() { // return mIsSelected; // } // // public void setSelected(boolean b) { // mIsSelected = b; // } // // private static class SortByLanguage implements Comparator { // // public int compare(Object o1, Object o2) { // Combo c1 = (Combo) o1; // Combo c2 = (Combo) o2; // return c1.getLanguage().compareToIgnoreCase(c2.getLanguage()); // } // } // // private static class SortBySelectedByLanguage implements Comparator { // // public int compare(Object o1, Object o2) { // Combo c1 = (Combo) o1; // Combo c2 = (Combo) o2; // if (c1.isSelected() && c2.isSelected() || !c1.isSelected() && !c2.isSelected()) { // return c1.getLanguage().compareToIgnoreCase(c2.getLanguage()); // } // if (c1.isSelected()) return -1; // return 1; // } // } // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.Combo;
package ee.ioc.phon.android.speak.adapter; public class ComboAdapter extends ArrayAdapter<Combo> { private final List<Combo> list; private final Activity context;
// Path: app/src/main/java/ee/ioc/phon/android/speak/fragment/K6neleListFragment.java // public abstract class K6neleListFragment extends ListFragment { // // protected void toast(String message) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); // } // // protected void setEmptyView(String text) { // ListView lv = getListView(); // TextView emptyView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.empty_list, null); // emptyView.setText(text); // emptyView.setVisibility(View.GONE); // ((ViewGroup) lv.getParent()).addView(emptyView); // lv.setEmptyView(emptyView); // } // } // // Path: app/src/main/java/ee/ioc/phon/android/speak/model/Combo.java // public class Combo { // // public static final Comparator SORT_BY_LANGUAGE = new SortByLanguage(); // public static final Comparator SORT_BY_SELECTED_BY_LANGUAGE = new SortBySelectedByLanguage(); // // private final String mId; // private final String mServiceLabel; // private final String mAsString; // private final ComponentName mComponentName; // private final String mLocaleLongLabel; // private final String mLocaleAsStr; // private final String mShortLabel; // private final String mLongLabel; // private boolean mIsSelected; // // public Combo(Context context, String id) { // // Can return <null, ""> // Pair<ComponentName, String> pair = RecognitionServiceManager.unflattenFromString(id); // mId = id; // mComponentName = pair.first; // mLocaleAsStr = pair.second; // mServiceLabel = RecognitionServiceManager.getServiceLabel(context, mComponentName); // if (mLocaleAsStr.isEmpty() || "und".equals(mLocaleAsStr)) { // mLocaleLongLabel = ""; // mAsString = String.format(context.getString(R.string.labelComboListItemWithoutLocale), mServiceLabel); // mShortLabel = mServiceLabel; // mLongLabel = mServiceLabel; // } else { // mLocaleLongLabel = RecognitionServiceManager.makeLangLabel(mLocaleAsStr); // mAsString = String.format(context.getString(R.string.labelComboListItem), mServiceLabel, mLocaleLongLabel); // String mFormatLabelComboItem = context.getString(R.string.labelComboItem); // mShortLabel = String.format(mFormatLabelComboItem, mServiceLabel, mLocaleAsStr); // mLongLabel = String.format(mFormatLabelComboItem, mServiceLabel, mLocaleLongLabel); // } // } // // public String getId() { // return mId; // } // // public ComponentName getServiceComponent() { // return mComponentName; // } // // public String getLocaleAsStr() { // return mLocaleAsStr; // } // // public String getService() { // return mServiceLabel; // } // // public String getLanguage() { // return mLocaleLongLabel; // } // // public String getShortLabel() { // return mShortLabel; // } // // public String getLongLabel() { // return mLongLabel; // } // // public Drawable getIcon(Context context) { // return RecognitionServiceManager.getServiceIcon(context, mComponentName); // } // // public String toString() { // return mAsString; // } // // public boolean isSelected() { // return mIsSelected; // } // // public void setSelected(boolean b) { // mIsSelected = b; // } // // private static class SortByLanguage implements Comparator { // // public int compare(Object o1, Object o2) { // Combo c1 = (Combo) o1; // Combo c2 = (Combo) o2; // return c1.getLanguage().compareToIgnoreCase(c2.getLanguage()); // } // } // // private static class SortBySelectedByLanguage implements Comparator { // // public int compare(Object o1, Object o2) { // Combo c1 = (Combo) o1; // Combo c2 = (Combo) o2; // if (c1.isSelected() && c2.isSelected() || !c1.isSelected() && !c2.isSelected()) { // return c1.getLanguage().compareToIgnoreCase(c2.getLanguage()); // } // if (c1.isSelected()) return -1; // return 1; // } // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/adapter/ComboAdapter.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import java.util.List; import ee.ioc.phon.android.speak.R; import ee.ioc.phon.android.speak.fragment.K6neleListFragment; import ee.ioc.phon.android.speak.model.Combo; package ee.ioc.phon.android.speak.adapter; public class ComboAdapter extends ArrayAdapter<Combo> { private final List<Combo> list; private final Activity context;
public ComboAdapter(K6neleListFragment context, List<Combo> list) {
Kaljurand/K6nele
app/src/main/java/ee/ioc/phon/android/speak/activity/QuickSettingsActivity.java
// Path: app/src/main/java/ee/ioc/phon/android/speak/QuickSettingsManager.java // public class QuickSettingsManager { // // private static final Set<String> COMBOS_MULTILINGUAL; // // static { // Set<String> set = new HashSet<>(); // set.add("ee.ioc.phon.android.speak/.service.WebSocketRecognitionService"); // set.add("ee.ioc.phon.android.speak/.service.WebSocketRecognitionService;et-EE"); // set.add("ee.ioc.phon.android.speak/.service.HttpRecognitionService;et-EE"); // set.add("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"); // set.add("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService;en-US"); // COMBOS_MULTILINGUAL = Collections.unmodifiableSet(set); // } // // private SharedPreferences mPrefs; // private Resources mRes; // // public QuickSettingsManager(SharedPreferences prefs, Resources res) { // mPrefs = prefs; // mRes = res; // } // // public void setDefaultsDevel() { // SharedPreferences.Editor editor = mPrefs.edit(); // // // Speech keyboard // editor.putStringSet(mRes.getString(R.string.keyImeCombo), COMBOS_MULTILINGUAL); // editor.putBoolean(mRes.getString(R.string.keyImeHelpText), false); // editor.putBoolean(mRes.getString(R.string.keyImeAutoStart), false); // // // Search panel // editor.putStringSet(mRes.getString(R.string.keyCombo), COMBOS_MULTILINGUAL); // editor.putBoolean(mRes.getString(R.string.keyHelpText), false); // editor.putBoolean(mRes.getString(R.string.keyAutoStart), false); // editor.putInt(mRes.getString(R.string.keyMaxHypotheses), 4); // // // HTTP service // editor.putString(mRes.getString(R.string.keyAudioFormat), "audio/x-flac"); // editor.putBoolean(mRes.getString(R.string.keyAudioCues), false); // editor.putString(mRes.getString(R.string.keyAutoStopAfterTime), "10"); // // // WebSocket service // editor.putString(mRes.getString(R.string.keyImeAudioFormat), "audio/x-flac"); // editor.putBoolean(mRes.getString(R.string.keyImeAudioCues), false); // // editor.apply(); // } // }
import android.os.Bundle; import android.preference.PreferenceManager; import androidx.appcompat.app.AppCompatActivity; import ee.ioc.phon.android.speak.QuickSettingsManager; import ee.ioc.phon.android.speak.R;
package ee.ioc.phon.android.speak.activity; public class QuickSettingsActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.quick_settings);
// Path: app/src/main/java/ee/ioc/phon/android/speak/QuickSettingsManager.java // public class QuickSettingsManager { // // private static final Set<String> COMBOS_MULTILINGUAL; // // static { // Set<String> set = new HashSet<>(); // set.add("ee.ioc.phon.android.speak/.service.WebSocketRecognitionService"); // set.add("ee.ioc.phon.android.speak/.service.WebSocketRecognitionService;et-EE"); // set.add("ee.ioc.phon.android.speak/.service.HttpRecognitionService;et-EE"); // set.add("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"); // set.add("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService;en-US"); // COMBOS_MULTILINGUAL = Collections.unmodifiableSet(set); // } // // private SharedPreferences mPrefs; // private Resources mRes; // // public QuickSettingsManager(SharedPreferences prefs, Resources res) { // mPrefs = prefs; // mRes = res; // } // // public void setDefaultsDevel() { // SharedPreferences.Editor editor = mPrefs.edit(); // // // Speech keyboard // editor.putStringSet(mRes.getString(R.string.keyImeCombo), COMBOS_MULTILINGUAL); // editor.putBoolean(mRes.getString(R.string.keyImeHelpText), false); // editor.putBoolean(mRes.getString(R.string.keyImeAutoStart), false); // // // Search panel // editor.putStringSet(mRes.getString(R.string.keyCombo), COMBOS_MULTILINGUAL); // editor.putBoolean(mRes.getString(R.string.keyHelpText), false); // editor.putBoolean(mRes.getString(R.string.keyAutoStart), false); // editor.putInt(mRes.getString(R.string.keyMaxHypotheses), 4); // // // HTTP service // editor.putString(mRes.getString(R.string.keyAudioFormat), "audio/x-flac"); // editor.putBoolean(mRes.getString(R.string.keyAudioCues), false); // editor.putString(mRes.getString(R.string.keyAutoStopAfterTime), "10"); // // // WebSocket service // editor.putString(mRes.getString(R.string.keyImeAudioFormat), "audio/x-flac"); // editor.putBoolean(mRes.getString(R.string.keyImeAudioCues), false); // // editor.apply(); // } // } // Path: app/src/main/java/ee/ioc/phon/android/speak/activity/QuickSettingsActivity.java import android.os.Bundle; import android.preference.PreferenceManager; import androidx.appcompat.app.AppCompatActivity; import ee.ioc.phon.android.speak.QuickSettingsManager; import ee.ioc.phon.android.speak.R; package ee.ioc.phon.android.speak.activity; public class QuickSettingsActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.quick_settings);
final QuickSettingsManager mngr = new QuickSettingsManager(
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <K, V> Map<K, V> map(Map<K, V> otherMap) { // return new ConcurrentHashMap<K, V>(otherMap); // }
import static org.solemnsilence.util.Py.map; import java.util.Map; import android.content.Context; import android.graphics.Typeface;
package kc.spark.pixels.android.ui.assets; public class Typefaces { // NOTE: this is tightly coupled to the filenames in assets/fonts public static enum Style { BOLD("Arial.ttf"), BOLD_ITALIC("Arial.ttf"), BOOK("Arial.ttf"), BOOK_ITALIC("Arial.ttf"), LIGHT("Arial.ttf"), LIGHT_ITALIC("Arial.ttf"), MEDIUM("Arial.ttf"), MEDIUM_ITALIC("Arial.ttf"); // BOLD("gotham_bold.otf"), // BOLD_ITALIC("gotham_bold_ita.otf"), // BOOK("gotham_book.otf"), // BOOK_ITALIC("gotham_book_ita.otf"), // LIGHT("gotham_light.otf"), // LIGHT_ITALIC("gotham_light_ita.otf"), // MEDIUM("gotham_medium.otf"), // MEDIUM_ITALIC("gotham_medium_ita.otf"); public final String fileName; private Style(String name) { fileName = name; } }
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <K, V> Map<K, V> map(Map<K, V> otherMap) { // return new ConcurrentHashMap<K, V>(otherMap); // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java import static org.solemnsilence.util.Py.map; import java.util.Map; import android.content.Context; import android.graphics.Typeface; package kc.spark.pixels.android.ui.assets; public class Typefaces { // NOTE: this is tightly coupled to the filenames in assets/fonts public static enum Style { BOLD("Arial.ttf"), BOLD_ITALIC("Arial.ttf"), BOOK("Arial.ttf"), BOOK_ITALIC("Arial.ttf"), LIGHT("Arial.ttf"), LIGHT_ITALIC("Arial.ttf"), MEDIUM("Arial.ttf"), MEDIUM_ITALIC("Arial.ttf"); // BOLD("gotham_bold.otf"), // BOLD_ITALIC("gotham_bold_ita.otf"), // BOOK("gotham_book.otf"), // BOOK_ITALIC("gotham_book_ita.otf"), // LIGHT("gotham_light.otf"), // LIGHT_ITALIC("gotham_light_ita.otf"), // MEDIUM("gotham_medium.otf"), // MEDIUM_ITALIC("gotham_medium_ita.otf"); public final String fileName; private Style(String name) { fileName = name; } }
private static final Map<Style, Typeface> typefaces = map();
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/FunctionResponse.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // }
import static org.solemnsilence.util.Py.truthy; import android.os.Parcel; import android.os.Parcelable;
package kc.spark.pixels.android.cloud.api; public class FunctionResponse implements Parcelable { public static final int REQUEST_TYPE_FUNCTION = 1; public static final int REQUEST_TYPE_VARIABLE = 2; public final int requestType; public final String coreId; public final String responseValue; public final String responseType; public final boolean errorMakingRequest; public FunctionResponse(int requestType, String coreId, String responseType, String responseValue, boolean requestError) { this.requestType = requestType; this.coreId = coreId; this.responseType = responseType; this.responseValue = responseValue; this.errorMakingRequest = requestError; } public FunctionResponse(Parcel in) { this.requestType = in.readInt(); this.coreId = in.readString(); this.responseType = in.readString(); this.responseValue = in.readString();
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/FunctionResponse.java import static org.solemnsilence.util.Py.truthy; import android.os.Parcel; import android.os.Parcelable; package kc.spark.pixels.android.cloud.api; public class FunctionResponse implements Parcelable { public static final int REQUEST_TYPE_FUNCTION = 1; public static final int REQUEST_TYPE_VARIABLE = 2; public final int requestType; public final String coreId; public final String responseValue; public final String responseType; public final boolean errorMakingRequest; public FunctionResponse(int requestType, String coreId, String responseType, String responseValue, boolean requestError) { this.requestType = requestType; this.coreId = coreId; this.responseType = responseType; this.responseValue = responseValue; this.errorMakingRequest = requestError; } public FunctionResponse(Parcel in) { this.requestType = in.readInt(); this.coreId = in.readString(); this.responseType = in.readString(); this.responseValue = in.readString();
this.errorMakingRequest = truthy(in.readInt());
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/NetConnectionHelper.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // }
import static org.solemnsilence.util.Py.truthy; import android.content.Context; import android.net.ConnectivityManager; import android.net.DhcpInfo; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.text.format.Formatter;
return activeNetworkInfo.isConnected(); } else { return false; } } public boolean isConnectedViaWifi() { NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo == null) { return false; } else { return networkInfo.isConnected(); } } private WifiInfo getWifiInfo() { return wifiManager.getConnectionInfo(); } public String getGatewayIp() { DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); if (dhcpInfo == null) { return null; } else { return Formatter.formatIpAddress(dhcpInfo.gateway); } } // in Jellybean, SSIDs can have quotes around them private static String removeQuotes(String ssid) {
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/NetConnectionHelper.java import static org.solemnsilence.util.Py.truthy; import android.content.Context; import android.net.ConnectivityManager; import android.net.DhcpInfo; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.text.format.Formatter; return activeNetworkInfo.isConnected(); } else { return false; } } public boolean isConnectedViaWifi() { NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo == null) { return false; } else { return networkInfo.isConnected(); } } private WifiInfo getWifiInfo() { return wifiManager.getConnectionInfo(); } public String getGatewayIp() { DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); if (dhcpInfo == null) { return null; } else { return Formatter.formatIpAddress(dhcpInfo.gateway); } } // in Jellybean, SSIDs can have quotes around them private static String removeQuotes(String ssid) {
if (!truthy(ssid)) {
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenRequest.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <T> List<T> list(T... objects) { // return new ArrayList<T>(Arrays.asList(objects)); // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // }
import static org.solemnsilence.util.Py.list; import java.util.List; import kc.spark.pixels.android.util.Strings; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP;
package kc.spark.pixels.android.cloud.login; /** * Note: cannot be used with GSON like the other models, thus the placement in a * separate package * */ public class TokenRequest { public final String username; public final String password; public TokenRequest(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "LoginRequest [username=" + username + ", " +
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <T> List<T> list(T... objects) { // return new ArrayList<T>(Arrays.asList(objects)); // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenRequest.java import static org.solemnsilence.util.Py.list; import java.util.List; import kc.spark.pixels.android.util.Strings; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; package kc.spark.pixels.android.cloud.login; /** * Note: cannot be used with GSON like the other models, thus the placement in a * separate package * */ public class TokenRequest { public final String username; public final String password; public TokenRequest(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "LoginRequest [username=" + username + ", " +
"password=" + Strings.getRedacted(password) + "]";
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenRequest.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <T> List<T> list(T... objects) { // return new ArrayList<T>(Arrays.asList(objects)); // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // }
import static org.solemnsilence.util.Py.list; import java.util.List; import kc.spark.pixels.android.util.Strings; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP;
package kc.spark.pixels.android.cloud.login; /** * Note: cannot be used with GSON like the other models, thus the placement in a * separate package * */ public class TokenRequest { public final String username; public final String password; public TokenRequest(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "LoginRequest [username=" + username + ", " + "password=" + Strings.getRedacted(password) + "]"; } public String asFormEncodedData() {
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static <T> List<T> list(T... objects) { // return new ArrayList<T>(Arrays.asList(objects)); // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenRequest.java import static org.solemnsilence.util.Py.list; import java.util.List; import kc.spark.pixels.android.util.Strings; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; package kc.spark.pixels.android.cloud.login; /** * Note: cannot be used with GSON like the other models, thus the placement in a * separate package * */ public class TokenRequest { public final String username; public final String password; public TokenRequest(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "LoginRequest [username=" + username + ", " + "password=" + Strings.getRedacted(password) + "]"; } public String asFormEncodedData() {
List<BasicNameValuePair> pairs = list(
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenResponse.java
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // }
import kc.spark.pixels.android.util.Strings;
package kc.spark.pixels.android.cloud.login; public class TokenResponse { // only available when request is successful (HTTP 200) public final String accessToken; public final String tokenType; public final int expiresIn; // all(?) other responses public final String errorDescription; private int statusCode; public TokenResponse(String accessToken, String tokenType, int expiresIn, String errorDescription) { this.accessToken = accessToken; this.tokenType = tokenType; this.expiresIn = expiresIn; this.errorDescription = errorDescription; } public TokenResponse() { this(null, null, -1, null); } @Override public String toString() {
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/util/Strings.java // public class Strings { // // public static String getRedacted(String value) { // return (value == null) // ? "<null>" // : String.format("[ REDACTED (length: %d) ]", value.length()); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenResponse.java import kc.spark.pixels.android.util.Strings; package kc.spark.pixels.android.cloud.login; public class TokenResponse { // only available when request is successful (HTTP 200) public final String accessToken; public final String tokenType; public final int expiresIn; // all(?) other responses public final String errorDescription; private int statusCode; public TokenResponse(String accessToken, String tokenType, int expiresIn, String errorDescription) { this.accessToken = accessToken; this.tokenType = tokenType; this.expiresIn = expiresIn; this.errorDescription = errorDescription; } public TokenResponse() { this(null, null, -1, null); } @Override public String toString() {
return "LoginResponse [accessToken=" + Strings.getRedacted(accessToken) + ", tokenType="
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/Device.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // }
import static org.solemnsilence.util.Py.truthy;
package kc.spark.pixels.android.cloud.api; /** * Class representing a single Spark device (i.e.: a Core) */ public class Device { public final String id; public final String name; public final int color; private Device(String id, String name, int color) { this.id = id; this.name = name; this.color = color; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return newBuilder() .setColor(color) .setId(id) .setName(name); } public static class Builder { private String id; private String name; private int color; private Builder() { } public Device build() { return new Device(id, name, color); } public Builder fillInFalseyValuesFromOther(Device other) {
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/Device.java import static org.solemnsilence.util.Py.truthy; package kc.spark.pixels.android.cloud.api; /** * Class representing a single Spark device (i.e.: a Core) */ public class Device { public final String id; public final String name; public final int color; private Device(String id, String name, int color) { this.id = id; this.name = name; this.color = color; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return newBuilder() .setColor(color) .setId(id) .setName(name); } public static class Builder { private String id; private String name; private int color; private Builder() { } public Device build() { return new Device(id, name, color); } public Builder fillInFalseyValuesFromOther(Device other) {
this.id = (truthy(this.id)) ? this.id : other.id;
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenTool.java
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java // public class ApiUrlHelper { // // // all Uris just end up getting built from this one anyhow, no need to keep // // reconstructing them completely // private static Uri baseUri; // // // public static Uri.Builder buildUri(String authToken, String... pathSegments) { // Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); // for (String segment : pathSegments) { // builder.appendPath(segment); // } // // if (truthy(authToken)) { // builder.appendQueryParameter(AppConfig.getApiParamAccessToken(), authToken); // } // return builder; // } // // public synchronized static Uri.Builder getBaseUriBuilder() { // if (baseUri == null) { // baseUri = new Uri.Builder() // .scheme(AppConfig.getApiUrlScheme()) // .encodedAuthority(AppConfig.getApiHostname() + ":" + AppConfig.getApiHostPort()) // .build(); // } // return baseUri.buildUpon(); // } // // public static URL convertToURL(Uri.Builder uriBuilder) { // Uri builtUri = uriBuilder.build(); // try { // return new URL(builtUri.toString()); // } catch (MalformedURLException e) { // // Not printing exception here since I don't know for sure if this // // could ever include the URL itself, which in the case of a GET // // request would include the token(!) // log.e("Unable to build URL from Uri"); // return null; // } // } // // // private static final TLog log = new TLog(ApiUrlHelper.class); // // }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import kc.spark.pixels.android.cloud.ApiUrlHelper; import org.apache.http.protocol.HTTP; import org.solemnsilence.util.TLog; import android.net.Uri; import android.util.Base64; import com.google.gson.Gson; import com.squareup.okhttp.OkHttpClient;
package kc.spark.pixels.android.cloud.login; public class TokenTool { private static final TLog log = new TLog(TokenTool.class); private static final String[] PATH_SEGMENTS = new String[] { "oauth", "token" }; private final Gson gson; private final OkHttpClient okHttpclient; public TokenTool(Gson gson, OkHttpClient okHttpclient) { this.gson = gson; this.okHttpclient = okHttpclient; } public TokenResponse requestToken(TokenRequest tokenRequest) { // URL url = ApiUrlHelper.buildUrlNoVersion(PATH);
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java // public class ApiUrlHelper { // // // all Uris just end up getting built from this one anyhow, no need to keep // // reconstructing them completely // private static Uri baseUri; // // // public static Uri.Builder buildUri(String authToken, String... pathSegments) { // Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); // for (String segment : pathSegments) { // builder.appendPath(segment); // } // // if (truthy(authToken)) { // builder.appendQueryParameter(AppConfig.getApiParamAccessToken(), authToken); // } // return builder; // } // // public synchronized static Uri.Builder getBaseUriBuilder() { // if (baseUri == null) { // baseUri = new Uri.Builder() // .scheme(AppConfig.getApiUrlScheme()) // .encodedAuthority(AppConfig.getApiHostname() + ":" + AppConfig.getApiHostPort()) // .build(); // } // return baseUri.buildUpon(); // } // // public static URL convertToURL(Uri.Builder uriBuilder) { // Uri builtUri = uriBuilder.build(); // try { // return new URL(builtUri.toString()); // } catch (MalformedURLException e) { // // Not printing exception here since I don't know for sure if this // // could ever include the URL itself, which in the case of a GET // // request would include the token(!) // log.e("Unable to build URL from Uri"); // return null; // } // } // // // private static final TLog log = new TLog(ApiUrlHelper.class); // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenTool.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import kc.spark.pixels.android.cloud.ApiUrlHelper; import org.apache.http.protocol.HTTP; import org.solemnsilence.util.TLog; import android.net.Uri; import android.util.Base64; import com.google.gson.Gson; import com.squareup.okhttp.OkHttpClient; package kc.spark.pixels.android.cloud.login; public class TokenTool { private static final TLog log = new TLog(TokenTool.class); private static final String[] PATH_SEGMENTS = new String[] { "oauth", "token" }; private final Gson gson; private final OkHttpClient okHttpclient; public TokenTool(Gson gson, OkHttpClient okHttpclient) { this.gson = gson; this.okHttpclient = okHttpclient; } public TokenResponse requestToken(TokenRequest tokenRequest) { // URL url = ApiUrlHelper.buildUrlNoVersion(PATH);
Uri.Builder uriBuilder = ApiUrlHelper.getBaseUriBuilder();
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenTool.java
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java // public class ApiUrlHelper { // // // all Uris just end up getting built from this one anyhow, no need to keep // // reconstructing them completely // private static Uri baseUri; // // // public static Uri.Builder buildUri(String authToken, String... pathSegments) { // Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); // for (String segment : pathSegments) { // builder.appendPath(segment); // } // // if (truthy(authToken)) { // builder.appendQueryParameter(AppConfig.getApiParamAccessToken(), authToken); // } // return builder; // } // // public synchronized static Uri.Builder getBaseUriBuilder() { // if (baseUri == null) { // baseUri = new Uri.Builder() // .scheme(AppConfig.getApiUrlScheme()) // .encodedAuthority(AppConfig.getApiHostname() + ":" + AppConfig.getApiHostPort()) // .build(); // } // return baseUri.buildUpon(); // } // // public static URL convertToURL(Uri.Builder uriBuilder) { // Uri builtUri = uriBuilder.build(); // try { // return new URL(builtUri.toString()); // } catch (MalformedURLException e) { // // Not printing exception here since I don't know for sure if this // // could ever include the URL itself, which in the case of a GET // // request would include the token(!) // log.e("Unable to build URL from Uri"); // return null; // } // } // // // private static final TLog log = new TLog(ApiUrlHelper.class); // // }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import kc.spark.pixels.android.cloud.ApiUrlHelper; import org.apache.http.protocol.HTTP; import org.solemnsilence.util.TLog; import android.net.Uri; import android.util.Base64; import com.google.gson.Gson; import com.squareup.okhttp.OkHttpClient;
urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(15000); urlConnection.setRequestProperty("Authorization", getBasicAuthString()); try { OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(tokenRequest.asFormEncodedData().getBytes(HTTP.UTF_8)); out.close(); responseCode = urlConnection.getResponseCode(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); String responseStr = readStream(in); in.close(); if (responseStr == null) { log.e("Error logging in, response was null. HTTP response: " + responseCode); return null; } else { response = gson.fromJson(responseStr, TokenResponse.class); } } catch (IOException e) { log.e("Error requesting token"); } response.setStatusCode(responseCode); return response; } private String getBasicAuthString() { try {
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java // public class ApiUrlHelper { // // // all Uris just end up getting built from this one anyhow, no need to keep // // reconstructing them completely // private static Uri baseUri; // // // public static Uri.Builder buildUri(String authToken, String... pathSegments) { // Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); // for (String segment : pathSegments) { // builder.appendPath(segment); // } // // if (truthy(authToken)) { // builder.appendQueryParameter(AppConfig.getApiParamAccessToken(), authToken); // } // return builder; // } // // public synchronized static Uri.Builder getBaseUriBuilder() { // if (baseUri == null) { // baseUri = new Uri.Builder() // .scheme(AppConfig.getApiUrlScheme()) // .encodedAuthority(AppConfig.getApiHostname() + ":" + AppConfig.getApiHostPort()) // .build(); // } // return baseUri.buildUpon(); // } // // public static URL convertToURL(Uri.Builder uriBuilder) { // Uri builtUri = uriBuilder.build(); // try { // return new URL(builtUri.toString()); // } catch (MalformedURLException e) { // // Not printing exception here since I don't know for sure if this // // could ever include the URL itself, which in the case of a GET // // request would include the token(!) // log.e("Unable to build URL from Uri"); // return null; // } // } // // // private static final TLog log = new TLog(ApiUrlHelper.class); // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/login/TokenTool.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import kc.spark.pixels.android.cloud.ApiUrlHelper; import org.apache.http.protocol.HTTP; import org.solemnsilence.util.TLog; import android.net.Uri; import android.util.Base64; import com.google.gson.Gson; import com.squareup.okhttp.OkHttpClient; urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(15000); urlConnection.setRequestProperty("Authorization", getBasicAuthString()); try { OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(tokenRequest.asFormEncodedData().getBytes(HTTP.UTF_8)); out.close(); responseCode = urlConnection.getResponseCode(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); String responseStr = readStream(in); in.close(); if (responseStr == null) { log.e("Error logging in, response was null. HTTP response: " + responseCode); return null; } else { response = gson.fromJson(responseStr, TokenResponse.class); } } catch (IOException e) { log.e("Error requesting token"); } response.setStatusCode(responseCode); return response; } private String getBasicAuthString() { try {
byte[] asBytes = AppConfig.getSparkTokenCreationCredentials().getBytes(HTTP.UTF_8);
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/TinkerResponse.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // }
import static org.solemnsilence.util.Py.truthy; import android.os.Parcel; import android.os.Parcelable;
package kc.spark.pixels.android.cloud.api; public class TinkerResponse implements Parcelable { public static final int RESPONSE_TYPE_DIGITAL = 1; public static final int RESPONSE_TYPE_ANALOG = 2; public static final int REQUEST_TYPE_READ = 3; public static final int REQUEST_TYPE_WRITE = 4; public final int requestType; public final String coreId; public final String pin; public final int responseValue; public final int responseType; public final boolean errorMakingRequest; public TinkerResponse(int requestType, String coreId, String pin, int responseType, int responseValue, boolean requestError) { this.requestType = requestType; this.coreId = coreId; this.pin = pin; this.responseType = responseType; this.responseValue = responseValue; this.errorMakingRequest = requestError; } public TinkerResponse(Parcel in) { this.requestType = in.readInt(); this.coreId = in.readString(); this.pin = in.readString(); this.responseType = in.readInt(); this.responseValue = in.readInt();
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/api/TinkerResponse.java import static org.solemnsilence.util.Py.truthy; import android.os.Parcel; import android.os.Parcelable; package kc.spark.pixels.android.cloud.api; public class TinkerResponse implements Parcelable { public static final int RESPONSE_TYPE_DIGITAL = 1; public static final int RESPONSE_TYPE_ANALOG = 2; public static final int REQUEST_TYPE_READ = 3; public static final int REQUEST_TYPE_WRITE = 4; public final int requestType; public final String coreId; public final String pin; public final int responseValue; public final int responseType; public final boolean errorMakingRequest; public TinkerResponse(int requestType, String coreId, String pin, int responseType, int responseValue, boolean requestError) { this.requestType = requestType; this.coreId = coreId; this.pin = pin; this.responseType = responseType; this.responseValue = responseValue; this.errorMakingRequest = requestError; } public TinkerResponse(Parcel in) { this.requestType = in.readInt(); this.coreId = in.readString(); this.pin = in.readString(); this.responseType = in.readInt(); this.responseValue = in.readInt();
this.errorMakingRequest = truthy(in.readInt());
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/WebHelpers.java
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // }
import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.content.Context; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient;
package kc.spark.pixels.android.cloud; public class WebHelpers { private static final TLog log = new TLog(WebHelpers.class); private static OkHttpClient okHttpClient; private static Gson gson; private static boolean initialized = false; // should be called during Application.onCreate() to ensure availability public static void initialize(Context ctx) { if (!initialized) {
// Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/WebHelpers.java import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.content.Context; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient; package kc.spark.pixels.android.cloud; public class WebHelpers { private static final TLog log = new TLog(WebHelpers.class); private static OkHttpClient okHttpClient; private static Gson gson; private static boolean initialized = false; // should be called during Application.onCreate() to ensure availability public static void initialize(Context ctx) { if (!initialized) {
if (AppConfig.useStaging()) {
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // }
import static org.solemnsilence.util.Py.truthy; import java.net.MalformedURLException; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.net.Uri;
package kc.spark.pixels.android.cloud; public class ApiUrlHelper { // all Uris just end up getting built from this one anyhow, no need to keep // reconstructing them completely private static Uri baseUri; public static Uri.Builder buildUri(String authToken, String... pathSegments) {
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java import static org.solemnsilence.util.Py.truthy; import java.net.MalformedURLException; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.net.Uri; package kc.spark.pixels.android.cloud; public class ApiUrlHelper { // all Uris just end up getting built from this one anyhow, no need to keep // reconstructing them completely private static Uri baseUri; public static Uri.Builder buildUri(String authToken, String... pathSegments) {
Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion());
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // }
import static org.solemnsilence.util.Py.truthy; import java.net.MalformedURLException; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.net.Uri;
package kc.spark.pixels.android.cloud; public class ApiUrlHelper { // all Uris just end up getting built from this one anyhow, no need to keep // reconstructing them completely private static Uri baseUri; public static Uri.Builder buildUri(String authToken, String... pathSegments) { Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); for (String segment : pathSegments) { builder.appendPath(segment); }
// Path: AndroidApp/SparkPixels/src/org/solemnsilence/util/Py.java // public static boolean truthy(Object obj) { // if (obj == null) { // return false; // // } else if (obj instanceof Truthiable) { // return ((Truthiable) obj).isTruthy(); // // } else if (obj instanceof Collection) { // return (!((Collection<?>) obj).isEmpty()); // // } else if (obj instanceof Iterable) { // return (((Iterable<?>) obj).iterator().hasNext()); // // } else if (obj instanceof Object[]) { // return (((Object[]) obj).length > 0); // // } else if (obj instanceof Number) { // return (((Number) obj).longValue() != 0); // // } else if (obj instanceof CharSequence) { // return (((CharSequence) obj).length() > 0); // // } else if (obj instanceof JSONArray) { // return (((JSONArray) obj).length() > 0); // // } else if (obj instanceof Boolean) { // return (((Boolean) obj).booleanValue()); // // } else if (obj instanceof long[]) { // return (((long[]) obj).length > 0); // // } else if (obj instanceof int[]) { // return (((int[]) obj).length > 0); // // } else if (obj instanceof short[]) { // return (((short[]) obj).length > 0); // // } else if (obj instanceof byte[]) { // return (((byte[]) obj).length > 0); // // } else if (obj instanceof char[]) { // return (((char[]) obj).length > 0); // // } else if (obj instanceof boolean[]) { // return (((boolean[]) obj).length > 0); // // } else if (obj instanceof float[]) { // return (((float[]) obj).length > 0); // // } else if (obj instanceof double[]) { // return (((double[]) obj).length > 0); // } // // return true; // } // // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/app/AppConfig.java // public class AppConfig { // // private static Context ctx; // // // // Should be called when starting up the app, probably in // // Application.onCreate() // public static void initialize(Context context) { // ctx = context.getApplicationContext(); // } // // public static String getApiHostname() { // int resId = useStaging() ? R.string.staging_hostname : R.string.prod_hostname; // return ctx.getString(resId); // } // // public static String getApiUrlScheme() { // return ctx.getString(R.string.api_url_scheme); // } // // public static int getApiHostPort() { // return ctx.getResources().getInteger(R.integer.api_host_port); // } // // public static String getSparkTokenCreationCredentials() { // return ctx.getString(R.string.spark_token_creation_credentials); // } // // public static boolean useStaging() { // return ctx.getResources().getBoolean(R.bool.use_staging); // } // // public static String getApiVersion() { // return ctx.getString(R.string.api_version); // } // // public static String getApiParamAccessToken() { // return ctx.getString(R.string.api_param_access_token); // } // // public static String getSmartConfigHelloListenAddress() { // return ctx.getString(R.string.smart_config_hello_listen_address); // } // // public static int getSmartConfigHelloListenPort() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_port); // } // // public static int getSmartConfigHelloMessageLength() { // return ctx.getResources().getInteger(R.integer.smart_config_hello_msg_length); // } // // public static String getSmartConfigDefaultAesKey() { // return ctx.getString(R.string.smart_config_default_aes_key); // } // // } // Path: AndroidApp/SparkPixels/src/kc/spark/pixels/android/cloud/ApiUrlHelper.java import static org.solemnsilence.util.Py.truthy; import java.net.MalformedURLException; import java.net.URL; import kc.spark.pixels.android.app.AppConfig; import org.solemnsilence.util.TLog; import android.net.Uri; package kc.spark.pixels.android.cloud; public class ApiUrlHelper { // all Uris just end up getting built from this one anyhow, no need to keep // reconstructing them completely private static Uri baseUri; public static Uri.Builder buildUri(String authToken, String... pathSegments) { Uri.Builder builder = getBaseUriBuilder().appendPath(AppConfig.getApiVersion()); for (String segment : pathSegments) { builder.appendPath(segment); }
if (truthy(authToken)) {
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Lexer.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // // Path: src/main/java/io/github/gitbucket/markedj/Utils.java // public class Utils { // // public static String escape(String html){ // return escape(html, false); // } // // public static String escape(String html, boolean encode){ // if(!encode){ // html = html.replaceAll("&(?!#?\\w+;)", "&amp;"); // } else { // html = html.replace("&", "&amp;"); // } // return html.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;"); // } // // public static String or(String str1, String str2){ // if(str1 != null && str1.length() > 0){ // return str1; // } else { // return str2; // } // } // // public static boolean isEmpty(String str){ // return str == null || str.length() == 0; // } // // public static void fillList(List<String> list, int length, String value){ // while(list.size() < length){ // list.add(value); // } // } // // public static List<String> array2list(String[] array){ // List<String> list = new ArrayList<>(array.length); // for(String value: array){ // list.add(value); // } // return list; // } // // public static String trim(String str){ // if(str == null){ // return null; // } else { // return str.trim(); // } // } // // }
import io.github.gitbucket.markedj.rule.Rule; import io.github.gitbucket.markedj.token.*; import java.util.*; import static io.github.gitbucket.markedj.Utils.*;
package io.github.gitbucket.markedj; public class Lexer { protected Options options;
// Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // // Path: src/main/java/io/github/gitbucket/markedj/Utils.java // public class Utils { // // public static String escape(String html){ // return escape(html, false); // } // // public static String escape(String html, boolean encode){ // if(!encode){ // html = html.replaceAll("&(?!#?\\w+;)", "&amp;"); // } else { // html = html.replace("&", "&amp;"); // } // return html.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;"); // } // // public static String or(String str1, String str2){ // if(str1 != null && str1.length() > 0){ // return str1; // } else { // return str2; // } // } // // public static boolean isEmpty(String str){ // return str == null || str.length() == 0; // } // // public static void fillList(List<String> list, int length, String value){ // while(list.size() < length){ // list.add(value); // } // } // // public static List<String> array2list(String[] array){ // List<String> list = new ArrayList<>(array.length); // for(String value: array){ // list.add(value); // } // return list; // } // // public static String trim(String str){ // if(str == null){ // return null; // } else { // return str.trim(); // } // } // // } // Path: src/main/java/io/github/gitbucket/markedj/Lexer.java import io.github.gitbucket.markedj.rule.Rule; import io.github.gitbucket.markedj.token.*; import java.util.*; import static io.github.gitbucket.markedj.Utils.*; package io.github.gitbucket.markedj; public class Lexer { protected Options options;
protected Map<String, Rule> rules = null;
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Parser.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // }
import io.github.gitbucket.markedj.rule.Rule; import io.github.gitbucket.markedj.token.*; import java.util.Map; import java.util.Stack;
package io.github.gitbucket.markedj; public class Parser { protected Options options; protected Renderer renderer; public Parser(Options options, Renderer renderer){ this.options = options; this.renderer = renderer; } public String parse(Stack<Token> src, Map<String, Lexer.Link> links){
// Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // Path: src/main/java/io/github/gitbucket/markedj/Parser.java import io.github.gitbucket.markedj.rule.Rule; import io.github.gitbucket.markedj.token.*; import java.util.Map; import java.util.Stack; package io.github.gitbucket.markedj; public class Parser { protected Options options; protected Renderer renderer; public Parser(Options options, Renderer renderer){ this.options = options; this.renderer = renderer; } public String parse(Stack<Token> src, Map<String, Lexer.Link> links){
Map<String, Rule> rules;
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Grammer.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // }
import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map;
package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)";
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // Path: src/main/java/io/github/gitbucket/markedj/Grammer.java import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map; package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)";
public static Map<String, Rule> BLOCK_RULES = new HashMap<>();
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Grammer.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // }
import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map;
package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static {
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // Path: src/main/java/io/github/gitbucket/markedj/Grammer.java import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map; package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static {
BLOCK_RULES.put("newline", new FindFirstRule("^\n+"));
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Grammer.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // }
import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map;
package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static { BLOCK_RULES.put("newline", new FindFirstRule("^\n+")); BLOCK_RULES.put("code", new FindFirstRule("^( {4}[^\n]+\n*)+"));
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // Path: src/main/java/io/github/gitbucket/markedj/Grammer.java import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map; package io.github.gitbucket.markedj; public class Grammer { public static String BULLET = "(?:[*+-]|\\d+\\.)"; public static String COMMENT = "<!--[\\s\\S]*?-->"; public static String TAG = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; public static String CLOSED = "<(" + TAG + ")[\\s\\S]+?<\\/\\1>"; public static String CLOSING = "<" + TAG + "(?:\"[^\"]*\"|'[^']*'|[^'\">])*?>"; public static String HR = "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))"; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static { BLOCK_RULES.put("newline", new FindFirstRule("^\n+")); BLOCK_RULES.put("code", new FindFirstRule("^( {4}[^\n]+\n*)+"));
BLOCK_RULES.put("fences", new NoopRule());
gitbucket/markedj
src/main/java/io/github/gitbucket/markedj/Grammer.java
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // }
import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map;
public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static { BLOCK_RULES.put("newline", new FindFirstRule("^\n+")); BLOCK_RULES.put("code", new FindFirstRule("^( {4}[^\n]+\n*)+")); BLOCK_RULES.put("fences", new NoopRule()); BLOCK_RULES.put("hr", new FindFirstRule(BLOCK_HR)); BLOCK_RULES.put("heading", new FindFirstRule(BLOCK_HEADING)); BLOCK_RULES.put("nptable", new NoopRule()); BLOCK_RULES.put("lheading", new FindFirstRule(BLOCK_LHEADING)); BLOCK_RULES.put("blockquote", new FindFirstRule(BLOCK_BLOCKQUOTE)); BLOCK_RULES.put("list", new FindFirstRule(BLOCK_LIST)); BLOCK_RULES.put("html", new FindFirstRule("^ *(?:" + COMMENT + " *(?:\\n|\\s*$)|" + CLOSED + " *(?:\\n{2,}|\\s*$)|" + CLOSING + " *(?:\\n{2,}|\\s*$))")); BLOCK_RULES.put("def", new FindFirstRule(BLOCK_DEF)); BLOCK_RULES.put("table", new NoopRule()); BLOCK_RULES.put("paragraph", new FindFirstRule(BLOCK_PARAGRAPH)); BLOCK_RULES.put("text", new FindFirstRule("^[^\n]+"));
// Path: src/main/java/io/github/gitbucket/markedj/rule/FindFirstRule.java // public class FindFirstRule implements Rule { // // private Pattern pattern; // // public FindFirstRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // if (matcher.find()) { // List<String> result = new ArrayList<>(); // for (int i = 0; i <= matcher.groupCount(); i++) { // result.add(matcher.group(i)); // } // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/FindAllRule.java // public class FindAllRule implements Rule { // // private Pattern pattern; // // public FindAllRule(String regex){ // this.pattern = Pattern.compile(regex); // } // // public List<String> exec(String src) { // try { // Matcher matcher = pattern.matcher(src); // List<String> result = new ArrayList<>(); // while (matcher.find()) { // result.add(matcher.group(0)); // } // if (!result.isEmpty()) { // return result; // } // } catch(StackOverflowError e){ // // ignore // } // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/NoopRule.java // public class NoopRule implements Rule { // public List<String> exec(String src) { // return Collections.emptyList(); // } // } // // Path: src/main/java/io/github/gitbucket/markedj/rule/Rule.java // public interface Rule { // List<String> exec(String src); // } // Path: src/main/java/io/github/gitbucket/markedj/Grammer.java import io.github.gitbucket.markedj.rule.FindFirstRule; import io.github.gitbucket.markedj.rule.FindAllRule; import io.github.gitbucket.markedj.rule.NoopRule; import io.github.gitbucket.markedj.rule.Rule; import java.util.HashMap; import java.util.Map; public static String DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_HR = "^( *[-*_]){3,} *(?:\\n+|$)"; public static String BLOCK_HEADING = "^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)"; public static String BLOCK_LHEADING = "^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)"; public static String BLOCK_BLOCKQUOTE = "^( *>[^\\n]+(\\n(?!" + removeLineStart(DEF) + ")[^\\n]+)*\\n*)+"; //public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:" + HR + "|\\n+(?=" + removeLineStart(DEF) + ")|\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_LIST = "^( *)(" + BULLET + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + BULLET + " )\\n*|\\s*$)"; public static String BLOCK_DEF = "^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +[\"(]([^\\n]+)[\")])? *(?:\\n+|$)"; public static String BLOCK_PARAGRAPH = "^((?:[^\\n]+\\n?(?!" + removeLineStart(BLOCK_HR) + "|" + removeLineStart(BLOCK_HEADING) + "|" + removeLineStart(BLOCK_LHEADING) + "|" + removeLineStart(BLOCK_BLOCKQUOTE) + "|<" + TAG + "|" + removeLineStart(BLOCK_DEF) + "))+)\\n*"; public static String BLOCK_GFM_FENCES = "^ *(`{3,}|~{3,})([ \\S]+)?\\n([\\s\\S]*?)\\s*\\1 *(?:\\n+|$)"; public static Map<String, Rule> BLOCK_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_GFM_RULES = new HashMap<>(); public static Map<String, Rule> BLOCK_TABLE_RULES = new HashMap<>(); static { BLOCK_RULES.put("newline", new FindFirstRule("^\n+")); BLOCK_RULES.put("code", new FindFirstRule("^( {4}[^\n]+\n*)+")); BLOCK_RULES.put("fences", new NoopRule()); BLOCK_RULES.put("hr", new FindFirstRule(BLOCK_HR)); BLOCK_RULES.put("heading", new FindFirstRule(BLOCK_HEADING)); BLOCK_RULES.put("nptable", new NoopRule()); BLOCK_RULES.put("lheading", new FindFirstRule(BLOCK_LHEADING)); BLOCK_RULES.put("blockquote", new FindFirstRule(BLOCK_BLOCKQUOTE)); BLOCK_RULES.put("list", new FindFirstRule(BLOCK_LIST)); BLOCK_RULES.put("html", new FindFirstRule("^ *(?:" + COMMENT + " *(?:\\n|\\s*$)|" + CLOSED + " *(?:\\n{2,}|\\s*$)|" + CLOSING + " *(?:\\n{2,}|\\s*$))")); BLOCK_RULES.put("def", new FindFirstRule(BLOCK_DEF)); BLOCK_RULES.put("table", new NoopRule()); BLOCK_RULES.put("paragraph", new FindFirstRule(BLOCK_PARAGRAPH)); BLOCK_RULES.put("text", new FindFirstRule("^[^\n]+"));
BLOCK_RULES.put("item", new FindAllRule(("(?m)^( *)(" + BULLET + ") [^\\n]*(?:\\n(?!\\1" + BULLET + " )[^\\n]*)*")));
SquidDev-CC/howl.ci
runner/src/main/java/org/squiddev/howl/ci/run/HowlAPI.java
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // }
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.core.apis.ILuaAPI; import org.squiddev.howl.ci.TRoRLogger;
@Override public void shutdown() { } @Override public String[] getMethodNames() { return new String[]{ "log", "status", "getEnv", "getConfig", "setDay", "setTime", "close", "resize", // TODO: open }; } @Override public Object[] callMethod(ILuaContext context, int method, Object[] args) throws LuaException, InterruptedException { switch (method) { case 0: { // log if (args.length < 2) throw new LuaException("Expected level, message"); String levelName = String.valueOf(args[0]); emulator.getLogger().log(computer.getIdentifier(), levelName, String.valueOf(args[1])); return null; } case 1: { // status if (args.length < 2) throw new LuaException("Expected status, message"); String statusName = String.valueOf(args[0]);
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // } // Path: runner/src/main/java/org/squiddev/howl/ci/run/HowlAPI.java import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.core.apis.ILuaAPI; import org.squiddev.howl.ci.TRoRLogger; @Override public void shutdown() { } @Override public String[] getMethodNames() { return new String[]{ "log", "status", "getEnv", "getConfig", "setDay", "setTime", "close", "resize", // TODO: open }; } @Override public Object[] callMethod(ILuaContext context, int method, Object[] args) throws LuaException, InterruptedException { switch (method) { case 0: { // log if (args.length < 2) throw new LuaException("Expected level, message"); String levelName = String.valueOf(args[0]); emulator.getLogger().log(computer.getIdentifier(), levelName, String.valueOf(args[1])); return null; } case 1: { // status if (args.length < 2) throw new LuaException("Expected status, message"); String statusName = String.valueOf(args[0]);
TRoRLogger.Status status;
SquidDev-CC/howl.ci
runner/src/main/java/org/squiddev/howl/ci/run/TerminalStreaming.java
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // }
import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.util.Palette; import org.squiddev.howl.ci.TRoRLogger; import java.text.DecimalFormat;
package org.squiddev.howl.ci.run; /** * A terminal which emits TRoR tokens */ public class TerminalStreaming extends Terminal implements ComputerInstance.IComputerListener { private static final String[] COLORS = new String[]{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; private static final DecimalFormat PALETTE_FORMAT; static { PALETTE_FORMAT = new DecimalFormat(); PALETTE_FORMAT.setMaximumFractionDigits(3); } private final String id;
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // } // Path: runner/src/main/java/org/squiddev/howl/ci/run/TerminalStreaming.java import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.util.Palette; import org.squiddev.howl.ci.TRoRLogger; import java.text.DecimalFormat; package org.squiddev.howl.ci.run; /** * A terminal which emits TRoR tokens */ public class TerminalStreaming extends Terminal implements ComputerInstance.IComputerListener { private static final String[] COLORS = new String[]{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; private static final DecimalFormat PALETTE_FORMAT; static { PALETTE_FORMAT = new DecimalFormat(); PALETTE_FORMAT.setMaximumFractionDigits(3); } private final String id;
private final TRoRLogger logger;
SquidDev-CC/howl.ci
runner/src/main/java/org/squiddev/howl/ci/run/TerminalChunking.java
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // }
import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.core.terminal.TextBuffer; import org.squiddev.howl.ci.TRoRLogger; import java.util.Arrays;
package org.squiddev.howl.ci.run; /** * A terminal which emits TRoR tokens */ public class TerminalChunking extends Terminal implements ComputerInstance.IComputerListener { private static final String[] COLORS = new String[]{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; private final String id;
// Path: runner/src/main/java/org/squiddev/howl/ci/TRoRLogger.java // public class TRoRLogger { // public static final String CORE_ID = "core"; // // private static final String EXTENSION_LOG = "XL"; // private static final String EXTENSION_STATUS = "XS"; // // private final PrintStream stream; // private Status status = Status.NONE; // // public TRoRLogger(PrintStream stream) { // this.stream = stream; // } // // public void message(String code, String id, String data) { // assert code.length() == 2 : "code must be two characters"; // assert code.indexOf('\n') == -1 : "code cannot contain \\n"; // assert id.indexOf('\n') == -1 : "id cannot contain \\n"; // assert data.indexOf('\n') == -1 : "data cannot contain \\n"; // // stream.print(code + ":" + id + "," + System.nanoTime() + ";" + data + "\n"); // stream.flush(); // } // // public void log(String id, String level, String message) { // message(EXTENSION_LOG, id, level.toLowerCase().replaceAll("[^\\w-]", "") + "," + normaliseLines(message)); // } // // public void debug(String id, String message) { // log(id, "debug", normaliseLines(message)); // } // // public void warn(String id, String message) { // log(id, "warn", normaliseLines(message)); // } // // public void error(String id, String message) { // log(id, "error", normaliseLines(message)); // } // // public void error(String id, String message, Throwable e) { // if (e == null) { // error(id, message); // } else { // error(id, message + ": " + e); // } // } // // public void status(String id, Status status, String message) { // message(EXTENSION_STATUS, id, status.name().toLowerCase() + "," + message.replace('\n', '\r')); // // if (status.ordinal() > this.status.ordinal()) this.status = status; // } // // public Status getStatus() { // return status; // } // // public enum Status { // NONE, // SUCCESS, // FAILURE, // ERROR, // } // // private static String normaliseLines(String text) { // return text.replace("\r\n", "\r").replace('\n', '\r'); // } // } // Path: runner/src/main/java/org/squiddev/howl/ci/run/TerminalChunking.java import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.core.terminal.TextBuffer; import org.squiddev.howl.ci.TRoRLogger; import java.util.Arrays; package org.squiddev.howl.ci.run; /** * A terminal which emits TRoR tokens */ public class TerminalChunking extends Terminal implements ComputerInstance.IComputerListener { private static final String[] COLORS = new String[]{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; private final String id;
private final TRoRLogger logger;
Sinton/BookStore
src/edu/zjut/dao/impl/CategoryDaoImpl.java
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class CategoryDaoImpl implements CategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/CategoryDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class CategoryDaoImpl implements CategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
private DBHelp dbHelp = new DBHelp();
Sinton/BookStore
src/edu/zjut/dao/impl/CategoryDaoImpl.java
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class CategoryDaoImpl implements CategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public CategoryDaoImpl() { connection = dbHelp.getConn(); } /** * 添加一级分类 * @param category * @return * @throws SQLException */ @Override
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/CategoryDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class CategoryDaoImpl implements CategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public CategoryDaoImpl() { connection = dbHelp.getConn(); } /** * 添加一级分类 * @param category * @return * @throws SQLException */ @Override
public boolean createCategory(Category category) throws SQLException {
Sinton/BookStore
src/edu/zjut/dao/impl/CategoryDaoImpl.java
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp;
* @param category * @return * @throws SQLException */ @Override public boolean deleteCategory(int categoryId) throws SQLException { String sql = "DELETE FORM `t_category` WHERE category_id = ?"; pstmt = connection.prepareStatement(sql); pstmt.setInt(1, categoryId); int result = pstmt.executeUpdate(); if (pstmt != null) pstmt.close(); dbHelp.closeConn(); return result > 0 ? true : false; } /** * 获取全部一级分类 * @return * @throws SQLException */ @Override public ArrayList<Category> getAllCategories() throws SQLException { String sql = "SELECT * FROM t_category;"; pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); ArrayList<Category> categories = new ArrayList<Category>(); SecondCategoryDaoImpl secondCategoryDao = new SecondCategoryDaoImpl(); while (rs.next()) { Category category = new Category();
// Path: src/edu/zjut/dao/CategoryDao.java // public interface CategoryDao { // boolean createCategory(Category category) throws SQLException; // boolean updateCategory(Category category) throws SQLException; // boolean deleteCategory(int categoryId) throws SQLException; // ArrayList<Category> getAllCategories() throws SQLException; // String getCategoryNameByCategoryId(int categoryId) throws SQLException; // } // // Path: src/edu/zjut/model/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = 1L; // // private int categoryId; // private String name; // private String desc; // private ArrayList<SecondCategory> secondCategories; // // public Category() { // } // // public Category(int categoryId, String name, String desc, ArrayList<SecondCategory> secondCategories) { // setCategoryId(categoryId); // setName(name); // setDesc(desc); // setSecondCategories(secondCategories); // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public ArrayList<SecondCategory> getSecondCategories() { // return secondCategories; // } // // public void setSecondCategories(ArrayList<SecondCategory> secondCategories) { // this.secondCategories = secondCategories; // } // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/CategoryDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.CategoryDao; import edu.zjut.model.Category; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp; * @param category * @return * @throws SQLException */ @Override public boolean deleteCategory(int categoryId) throws SQLException { String sql = "DELETE FORM `t_category` WHERE category_id = ?"; pstmt = connection.prepareStatement(sql); pstmt.setInt(1, categoryId); int result = pstmt.executeUpdate(); if (pstmt != null) pstmt.close(); dbHelp.closeConn(); return result > 0 ? true : false; } /** * 获取全部一级分类 * @return * @throws SQLException */ @Override public ArrayList<Category> getAllCategories() throws SQLException { String sql = "SELECT * FROM t_category;"; pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); ArrayList<Category> categories = new ArrayList<Category>(); SecondCategoryDaoImpl secondCategoryDao = new SecondCategoryDaoImpl(); while (rs.next()) { Category category = new Category();
ArrayList<SecondCategory> secondCategories = secondCategoryDao.getSecondCategoriesByCategoryId(rs.getInt("category_id"));
Sinton/BookStore
src/edu/zjut/dao/impl/SecondCategoryDaoImpl.java
// Path: src/edu/zjut/dao/SecondCategoryDao.java // public interface SecondCategoryDao { // boolean createSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean updateSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean deleteSecondCategory(int categorySecondId) throws SQLException; // ArrayList<SecondCategory> getAllSecondCategories() throws SQLException; // ArrayList<SecondCategory> getSecondCategoriesByCategoryId(int categoryId) throws SQLException; // int getCategoryIdByName(String categoryName) throws SQLException; // int getSecondCategoryIdByName(String categoryName) throws SQLException; // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.SecondCategoryDao; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class SecondCategoryDaoImpl implements SecondCategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
// Path: src/edu/zjut/dao/SecondCategoryDao.java // public interface SecondCategoryDao { // boolean createSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean updateSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean deleteSecondCategory(int categorySecondId) throws SQLException; // ArrayList<SecondCategory> getAllSecondCategories() throws SQLException; // ArrayList<SecondCategory> getSecondCategoriesByCategoryId(int categoryId) throws SQLException; // int getCategoryIdByName(String categoryName) throws SQLException; // int getSecondCategoryIdByName(String categoryName) throws SQLException; // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/SecondCategoryDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.SecondCategoryDao; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class SecondCategoryDaoImpl implements SecondCategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
private DBHelp dbHelp = new DBHelp();
Sinton/BookStore
src/edu/zjut/dao/impl/SecondCategoryDaoImpl.java
// Path: src/edu/zjut/dao/SecondCategoryDao.java // public interface SecondCategoryDao { // boolean createSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean updateSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean deleteSecondCategory(int categorySecondId) throws SQLException; // ArrayList<SecondCategory> getAllSecondCategories() throws SQLException; // ArrayList<SecondCategory> getSecondCategoriesByCategoryId(int categoryId) throws SQLException; // int getCategoryIdByName(String categoryName) throws SQLException; // int getSecondCategoryIdByName(String categoryName) throws SQLException; // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.SecondCategoryDao; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class SecondCategoryDaoImpl implements SecondCategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public SecondCategoryDaoImpl() { connection = dbHelp.getConn(); } /** * 添加二级分类 * @param categorySecond * @return * @throws SQLException */ @Override
// Path: src/edu/zjut/dao/SecondCategoryDao.java // public interface SecondCategoryDao { // boolean createSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean updateSecondCategory(SecondCategory categorySecond) throws SQLException; // boolean deleteSecondCategory(int categorySecondId) throws SQLException; // ArrayList<SecondCategory> getAllSecondCategories() throws SQLException; // ArrayList<SecondCategory> getSecondCategoriesByCategoryId(int categoryId) throws SQLException; // int getCategoryIdByName(String categoryName) throws SQLException; // int getSecondCategoryIdByName(String categoryName) throws SQLException; // } // // Path: src/edu/zjut/model/SecondCategory.java // public class SecondCategory implements Serializable { // // private static final long serialVersionUID = 1L; // // private int secondCategoryId; // private String secondCategoryName; // private int categoryId; // // public SecondCategory() { // } // // public SecondCategory(int secondCategoryId, String secondCategoryName, int categoryId) { // setSecondCategoryId(secondCategoryId); // setSecondCategoryName(secondCategoryName); // setCategoryId(categoryId); // } // // public int getSecondCategoryId() { // return secondCategoryId; // } // // public void setSecondCategoryId(int secondCategoryId) { // this.secondCategoryId = secondCategoryId; // } // // public String getSecondCategoryName() { // return secondCategoryName; // } // // public void setSecondCategoryName(String secondCategoryName) { // this.secondCategoryName = secondCategoryName; // } // // public int getCategoryId() { // return categoryId; // } // // public void setCategoryId(int categoryId) { // this.categoryId = categoryId; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/SecondCategoryDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import edu.zjut.dao.SecondCategoryDao; import edu.zjut.model.SecondCategory; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class SecondCategoryDaoImpl implements SecondCategoryDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public SecondCategoryDaoImpl() { connection = dbHelp.getConn(); } /** * 添加二级分类 * @param categorySecond * @return * @throws SQLException */ @Override
public boolean createSecondCategory(SecondCategory categorySecond) throws SQLException {
Sinton/BookStore
src/edu/zjut/dao/impl/AdminDaoImpl.java
// Path: src/edu/zjut/dao/AdminDao.java // public interface AdminDao { // public Admin getAdmin(String email, String password) throws SQLException; // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.zjut.dao.AdminDao; import edu.zjut.model.Admin; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class AdminDaoImpl implements AdminDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
// Path: src/edu/zjut/dao/AdminDao.java // public interface AdminDao { // public Admin getAdmin(String email, String password) throws SQLException; // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/AdminDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.zjut.dao.AdminDao; import edu.zjut.model.Admin; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class AdminDaoImpl implements AdminDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null;
private DBHelp dbHelp = new DBHelp();
Sinton/BookStore
src/edu/zjut/dao/impl/AdminDaoImpl.java
// Path: src/edu/zjut/dao/AdminDao.java // public interface AdminDao { // public Admin getAdmin(String email, String password) throws SQLException; // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.zjut.dao.AdminDao; import edu.zjut.model.Admin; import edu.zjut.utils.DBHelp;
package edu.zjut.dao.impl; public class AdminDaoImpl implements AdminDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public AdminDaoImpl() { connection = dbHelp.getConn(); } /** * 通过Email和密码获取管理对象 * @param email * @param password * @return * @throws SQLException */ @Override
// Path: src/edu/zjut/dao/AdminDao.java // public interface AdminDao { // public Admin getAdmin(String email, String password) throws SQLException; // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/edu/zjut/utils/DBHelp.java // public class DBHelp { // // private final String DB_DRIVER = "com.mysql.jdbc.Driver"; // private final String DB_HOST = "localhost:"; // private final String DB_USER = "root"; // private final String DB_PASSWORD = "root"; // private final String DB_DBNAME = "bookstore"; // private final String DB_PORT = "3306/"; // private final String DB_URL = "jdbc:mysql://" + DB_HOST + DB_PORT + DB_DBNAME; // public Connection connection = null; // // /** // * 创建数据库连接 // * @return // */ // public Connection getConn() { // if (connection != null) { // return connection; // } // else { // try { // Class.forName(DB_DRIVER); // connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // } catch (ClassNotFoundException | SQLException exception) { // exception.printStackTrace(); // return null; // } // return connection; // } // } // // /** // * 关闭数据库连接 // * @return // */ // public boolean closeConn() { // try { // connection.close(); // return true; // } catch (SQLException exception) { // exception.printStackTrace(); // return false; // } // } // } // Path: src/edu/zjut/dao/impl/AdminDaoImpl.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.zjut.dao.AdminDao; import edu.zjut.model.Admin; import edu.zjut.utils.DBHelp; package edu.zjut.dao.impl; public class AdminDaoImpl implements AdminDao { private PreparedStatement pstmt = null; private ResultSet rs = null; private Connection connection = null; private DBHelp dbHelp = new DBHelp(); public AdminDaoImpl() { connection = dbHelp.getConn(); } /** * 通过Email和密码获取管理对象 * @param email * @param password * @return * @throws SQLException */ @Override
public Admin getAdmin(String email, String password) throws SQLException {
Sinton/BookStore
src/edu/zjut/servlet/AdminLoginServlet.java
// Path: src/edu/zjut/dao/impl/AdminDaoImpl.java // public class AdminDaoImpl implements AdminDao { // // private PreparedStatement pstmt = null; // private ResultSet rs = null; // private Connection connection = null; // private DBHelp dbHelp = new DBHelp(); // // public AdminDaoImpl() { // connection = dbHelp.getConn(); // } // // /** // * 通过Email和密码获取管理对象 // * @param email // * @param password // * @return // * @throws SQLException // */ // @Override // public Admin getAdmin(String email, String password) throws SQLException { // connection = dbHelp.getConn(); // String sql = "SELECT * FROM t_admin WHERE name = ? AND adminpwd = ?"; // pstmt = connection.prepareStatement(sql); // pstmt.setString(1, email); // pstmt.setString(2, password); // rs = pstmt.executeQuery(); // Admin admin = new Admin(); // if (rs.next()) { // admin.setAdminId(rs.getInt("adminId")); // admin.setName(rs.getString("name")); // admin.setPassword(rs.getString("password")); // } // dbHelp.closeConn(); // return admin; // } // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.io.IOException; import java.sql.SQLException; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.zjut.dao.impl.AdminDaoImpl; import edu.zjut.model.Admin;
package edu.zjut.servlet; @WebServlet(name = "AdminLoginServlet", urlPatterns = { "/admin/login.do" }) public class AdminLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String USERNAME = "RG@zjut.edu.cn"; private static final String PASSWORD = "admin201615162"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email").trim().toString(); String password = request.getParameter("password").trim().toString();
// Path: src/edu/zjut/dao/impl/AdminDaoImpl.java // public class AdminDaoImpl implements AdminDao { // // private PreparedStatement pstmt = null; // private ResultSet rs = null; // private Connection connection = null; // private DBHelp dbHelp = new DBHelp(); // // public AdminDaoImpl() { // connection = dbHelp.getConn(); // } // // /** // * 通过Email和密码获取管理对象 // * @param email // * @param password // * @return // * @throws SQLException // */ // @Override // public Admin getAdmin(String email, String password) throws SQLException { // connection = dbHelp.getConn(); // String sql = "SELECT * FROM t_admin WHERE name = ? AND adminpwd = ?"; // pstmt = connection.prepareStatement(sql); // pstmt.setString(1, email); // pstmt.setString(2, password); // rs = pstmt.executeQuery(); // Admin admin = new Admin(); // if (rs.next()) { // admin.setAdminId(rs.getInt("adminId")); // admin.setName(rs.getString("name")); // admin.setPassword(rs.getString("password")); // } // dbHelp.closeConn(); // return admin; // } // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/edu/zjut/servlet/AdminLoginServlet.java import java.io.IOException; import java.sql.SQLException; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.zjut.dao.impl.AdminDaoImpl; import edu.zjut.model.Admin; package edu.zjut.servlet; @WebServlet(name = "AdminLoginServlet", urlPatterns = { "/admin/login.do" }) public class AdminLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String USERNAME = "RG@zjut.edu.cn"; private static final String PASSWORD = "admin201615162"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email").trim().toString(); String password = request.getParameter("password").trim().toString();
AdminDaoImpl adminDao = new AdminDaoImpl();
Sinton/BookStore
src/edu/zjut/servlet/AdminLoginServlet.java
// Path: src/edu/zjut/dao/impl/AdminDaoImpl.java // public class AdminDaoImpl implements AdminDao { // // private PreparedStatement pstmt = null; // private ResultSet rs = null; // private Connection connection = null; // private DBHelp dbHelp = new DBHelp(); // // public AdminDaoImpl() { // connection = dbHelp.getConn(); // } // // /** // * 通过Email和密码获取管理对象 // * @param email // * @param password // * @return // * @throws SQLException // */ // @Override // public Admin getAdmin(String email, String password) throws SQLException { // connection = dbHelp.getConn(); // String sql = "SELECT * FROM t_admin WHERE name = ? AND adminpwd = ?"; // pstmt = connection.prepareStatement(sql); // pstmt.setString(1, email); // pstmt.setString(2, password); // rs = pstmt.executeQuery(); // Admin admin = new Admin(); // if (rs.next()) { // admin.setAdminId(rs.getInt("adminId")); // admin.setName(rs.getString("name")); // admin.setPassword(rs.getString("password")); // } // dbHelp.closeConn(); // return admin; // } // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.io.IOException; import java.sql.SQLException; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.zjut.dao.impl.AdminDaoImpl; import edu.zjut.model.Admin;
package edu.zjut.servlet; @WebServlet(name = "AdminLoginServlet", urlPatterns = { "/admin/login.do" }) public class AdminLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String USERNAME = "RG@zjut.edu.cn"; private static final String PASSWORD = "admin201615162"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email").trim().toString(); String password = request.getParameter("password").trim().toString(); AdminDaoImpl adminDao = new AdminDaoImpl(); try { adminDao.getAdmin(email, password); } catch (SQLException e) { e.printStackTrace(); } // 判断用户名、密码是否为空 if (!"".equals(email) && !"".equals(password)) { // 判断用户名、密码是否符合规则 if(validateEmail(email)) { if (validatePassword(password)) { // 判断用户名、密码是否正确 if (email.equals(USERNAME) && password.equals(PASSWORD)) {
// Path: src/edu/zjut/dao/impl/AdminDaoImpl.java // public class AdminDaoImpl implements AdminDao { // // private PreparedStatement pstmt = null; // private ResultSet rs = null; // private Connection connection = null; // private DBHelp dbHelp = new DBHelp(); // // public AdminDaoImpl() { // connection = dbHelp.getConn(); // } // // /** // * 通过Email和密码获取管理对象 // * @param email // * @param password // * @return // * @throws SQLException // */ // @Override // public Admin getAdmin(String email, String password) throws SQLException { // connection = dbHelp.getConn(); // String sql = "SELECT * FROM t_admin WHERE name = ? AND adminpwd = ?"; // pstmt = connection.prepareStatement(sql); // pstmt.setString(1, email); // pstmt.setString(2, password); // rs = pstmt.executeQuery(); // Admin admin = new Admin(); // if (rs.next()) { // admin.setAdminId(rs.getInt("adminId")); // admin.setName(rs.getString("name")); // admin.setPassword(rs.getString("password")); // } // dbHelp.closeConn(); // return admin; // } // } // // Path: src/edu/zjut/model/Admin.java // public class Admin implements Serializable { // // private static final long serialVersionUID = 1L; // // private int adminId; // private String name; // private String salt; // private String password; // // public Admin() { // } // // public Admin(String name, String password) { // setName(name); // setPassword(password); // } // // public int getAdminId() { // return adminId; // } // // public void setAdminId(int adminId) { // this.adminId = adminId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/edu/zjut/servlet/AdminLoginServlet.java import java.io.IOException; import java.sql.SQLException; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.zjut.dao.impl.AdminDaoImpl; import edu.zjut.model.Admin; package edu.zjut.servlet; @WebServlet(name = "AdminLoginServlet", urlPatterns = { "/admin/login.do" }) public class AdminLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String USERNAME = "RG@zjut.edu.cn"; private static final String PASSWORD = "admin201615162"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email").trim().toString(); String password = request.getParameter("password").trim().toString(); AdminDaoImpl adminDao = new AdminDaoImpl(); try { adminDao.getAdmin(email, password); } catch (SQLException e) { e.printStackTrace(); } // 判断用户名、密码是否为空 if (!"".equals(email) && !"".equals(password)) { // 判断用户名、密码是否符合规则 if(validateEmail(email)) { if (validatePassword(password)) { // 判断用户名、密码是否正确 if (email.equals(USERNAME) && password.equals(PASSWORD)) {
Admin admin = new Admin(email, password);
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filename/SimpleDateFormatFileNameStrategy.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileNameStrategy.java // public interface IFileNameStrategy extends ISubscriberStrategy{ // // /** // * Get the new fileName (not including folder name!). // * @param trace // * @param driverParams // * @throws XDSParameterException // */ // public String getNewFileName(Map<String,String> record); // }
import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.RequiredConstraint; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IDriver; import info.vancauwenberge.filedriver.api.IFileNameStrategy;
public String getDefaultValue() { return "GMT"; } @Override public Constraint[] getConstraints() { return null; } }; public abstract String getParameterName(); public abstract String getDefaultValue(); public DataType getDataType() { return DataType.STRING; } public abstract Constraint[] getConstraints(); } private String formatString; private TimeZone timeZone; /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.INewFileNamer#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileNameStrategy.java // public interface IFileNameStrategy extends ISubscriberStrategy{ // // /** // * Get the new fileName (not including folder name!). // * @param trace // * @param driverParams // * @throws XDSParameterException // */ // public String getNewFileName(Map<String,String> record); // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filename/SimpleDateFormatFileNameStrategy.java import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.RequiredConstraint; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IDriver; import info.vancauwenberge.filedriver.api.IFileNameStrategy; public String getDefaultValue() { return "GMT"; } @Override public Constraint[] getConstraints() { return null; } }; public abstract String getParameterName(); public abstract String getDefaultValue(); public DataType getDataType() { return DataType.STRING; } public abstract Constraint[] getConstraints(); } private String formatString; private TimeZone timeZone; /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.INewFileNamer#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
public void init(Trace trace, Map<String, Parameter> driverParams, IDriver driver)
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/query/AssociationMatcher.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // }
import com.novell.nds.dirxml.driver.Trace; import info.vancauwenberge.filedriver.api.IDriver; import java.util.Map;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.query; public class AssociationMatcher extends QueryMatcher { private String associationValue; private String destDNValue;
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/query/AssociationMatcher.java import com.novell.nds.dirxml.driver.Trace; import info.vancauwenberge.filedriver.api.IDriver; import java.util.Map; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.query; public class AssociationMatcher extends QueryMatcher { private String associationValue; private String destDNValue;
private IDriver driver;
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filepubclean/NoPubCleaningStrategy.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IPubFileCleanStrategy.java // public interface IPubFileCleanStrategy extends IPublisherStrategy { // /** // * Called before a file is processed // */ // public void onPreFile(File f); // // /** // * Called after a file is processed // */ // public void onPostFile(File f); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // }
import info.vancauwenberge.filedriver.api.IPubFileCleanStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filepubclean; public class NoPubCleaningStrategy implements IPubFileCleanStrategy{ public Map<String, Parameter> getParameterDefinitions() { return null; }
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IPubFileCleanStrategy.java // public interface IPubFileCleanStrategy extends IPublisherStrategy { // /** // * Called before a file is processed // */ // public void onPreFile(File f); // // /** // * Called after a file is processed // */ // public void onPostFile(File f); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepubclean/NoPubCleaningStrategy.java import info.vancauwenberge.filedriver.api.IPubFileCleanStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filepubclean; public class NoPubCleaningStrategy implements IPubFileCleanStrategy{ public Map<String, Parameter> getParameterDefinitions() { return null; }
public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws Exception {
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filesorter/NoSortSorter.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileSorterStrategy.java // public interface IFileSorterStrategy extends IPublisherStrategy{ // // /* // * Get the first file to process from a list of files. // */ // public File getFirstFile(File[] fileList); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // }
import info.vancauwenberge.filedriver.api.IFileSorterStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filesorter; /** * Implementation used if no sort order strategy is given. */ public class NoSortSorter implements IFileSorterStrategy{ /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getParameterDefinitions() */ public Map<String,Parameter> getParameterDefinitions() { return new HashMap<String,Parameter>(0); } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getFirstFile(com.novell.nds.dirxml.driver.Trace, java.io.File[]) */ public File getFirstFile(File[] fileList) { return fileList[0]; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileSorterStrategy.java // public interface IFileSorterStrategy extends IPublisherStrategy{ // // /* // * Get the first file to process from a list of files. // */ // public File getFirstFile(File[] fileList); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filesorter/NoSortSorter.java import info.vancauwenberge.filedriver.api.IFileSorterStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filesorter; /** * Implementation used if no sort order strategy is given. */ public class NoSortSorter implements IFileSorterStrategy{ /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getParameterDefinitions() */ public Map<String,Parameter> getParameterDefinitions() { return new HashMap<String,Parameter>(0); } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getFirstFile(com.novell.nds.dirxml.driver.Trace, java.io.File[]) */ public File getFirstFile(File[] fileList) { return fileList[0]; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
public void init(Trace trace, Map<String,Parameter> driverParams, IPublisher publisher) throws XDSParameterException {
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/api/IPublisherLoggerStrategy.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // }
import java.io.File; import java.io.IOException; import java.util.EnumMap; import java.util.Map; import com.novell.nds.dirxml.driver.xds.XDSStatusElement; import info.vancauwenberge.filedriver.exception.WriteException;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.api; public interface IPublisherLoggerStrategy extends IPublisherStrategy { public enum LogField{ RECORDNUMBER, //The Number of the record LOGSTATUS, //RETRY, ERROR, ETC LOGMESSAGE, //The message in the status LOGEVENTID //Event ID in the status message } /** * Tells the logger to prepare for writing a given file. * @param schema * @param f * @throws IOException */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IPublisherLoggerStrategy.java import java.io.File; import java.io.IOException; import java.util.EnumMap; import java.util.Map; import com.novell.nds.dirxml.driver.xds.XDSStatusElement; import info.vancauwenberge.filedriver.exception.WriteException; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.api; public interface IPublisherLoggerStrategy extends IPublisherStrategy { public enum LogField{ RECORDNUMBER, //The Number of the record LOGSTATUS, //RETRY, ERROR, ETC LOGMESSAGE, //The message in the status LOGEVENTID //Event ID in the status message } /** * Tells the logger to prepare for writing a given file. * @param schema * @param f * @throws IOException */
public void openFile(File f, String[] schema, EnumMap<LogField, String> logFieldSchemaMap) throws WriteException;
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filelogger/PublisherNoLogger.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IPublisherLoggerStrategy.java // public interface IPublisherLoggerStrategy extends IPublisherStrategy { // public enum LogField{ // RECORDNUMBER, //The Number of the record // LOGSTATUS, //RETRY, ERROR, ETC // LOGMESSAGE, //The message in the status // LOGEVENTID //Event ID in the status message // } // /** // * Tells the logger to prepare for writing a given file. // * @param schema // * @param f // * @throws IOException // */ // public void openFile(File f, String[] schema, EnumMap<LogField, String> logFieldSchemaMap) throws WriteException; // /** // * Write one record to the file. // * @param m A map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @return // * @throws IOException // */ // public void logCommand(int recordNumber, Map<String,String> thisRecord, XDSStatusElement xdsStatusElement) throws WriteException; // /** // * Tells the logger that no more records will be added to this file. // * The writer should release all resources associated with the file and close the file. // * @throws IOException // */ // public File close() throws WriteException; // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // }
import com.novell.nds.dirxml.driver.xds.XDSStatusElement; import info.vancauwenberge.filedriver.api.IPublisherLoggerStrategy; import info.vancauwenberge.filedriver.exception.WriteException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filelogger; public class PublisherNoLogger implements IPublisherLoggerStrategy{ public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws Exception { } public Map<String, Parameter> getParameterDefinitions() { return new HashMap<String, Parameter>(0); }
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IPublisherLoggerStrategy.java // public interface IPublisherLoggerStrategy extends IPublisherStrategy { // public enum LogField{ // RECORDNUMBER, //The Number of the record // LOGSTATUS, //RETRY, ERROR, ETC // LOGMESSAGE, //The message in the status // LOGEVENTID //Event ID in the status message // } // /** // * Tells the logger to prepare for writing a given file. // * @param schema // * @param f // * @throws IOException // */ // public void openFile(File f, String[] schema, EnumMap<LogField, String> logFieldSchemaMap) throws WriteException; // /** // * Write one record to the file. // * @param m A map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @return // * @throws IOException // */ // public void logCommand(int recordNumber, Map<String,String> thisRecord, XDSStatusElement xdsStatusElement) throws WriteException; // /** // * Tells the logger that no more records will be added to this file. // * The writer should release all resources associated with the file and close the file. // * @throws IOException // */ // public File close() throws WriteException; // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filelogger/PublisherNoLogger.java import com.novell.nds.dirxml.driver.xds.XDSStatusElement; import info.vancauwenberge.filedriver.api.IPublisherLoggerStrategy; import info.vancauwenberge.filedriver.exception.WriteException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.File; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filelogger; public class PublisherNoLogger implements IPublisherLoggerStrategy{ public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws Exception { } public Map<String, Parameter> getParameterDefinitions() { return new HashMap<String, Parameter>(0); }
public File close() throws WriteException {
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/api/ISubscriberShim.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/shim/ConnectionInfo.java // public class ConnectionInfo { // // private final String password; // private final String userName; // private final String connectURL; // // public ConnectionInfo(final String password, final String userName, final String connectURL) { // this.password=password; // this.userName=userName; // this.connectURL=connectURL; // } // // public String getPassword() { // return password; // } // // public String getUserName() { // return userName; // } // // public String getConnectURL() { // return connectURL; // } // // }
import info.vancauwenberge.filedriver.exception.WriteException; import info.vancauwenberge.filedriver.shim.ConnectionInfo;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.api; public interface ISubscriberShim { /** * Forcefully close the current file. This file already places a synchronized block on the file lock. If this * is the only file operation you inted to do, no need to add an additional synchronized block on the file lock. * Used to be part of IFileOwnerCallback * @return true if a file was actually closed. False otherwise. * @throws WriteException */ public boolean finishFile() throws WriteException; /** * Get the filelock that is used by this object to read and write to the file or close a new file. * Used to be part of IFileOwnerCallback. Synchronize on this object to perform tests on hte current file. * @return */ public Object getFileLock(); /** * Get the number of records in the current file or -1 if no current file. */ public abstract int getCurrentFileRecordCount(); /** * Does the subscriber currently have an open file */ public abstract boolean isFileOpen(); /** * Add a file operation listener to the subscriber * @param listener */ public void addFileListener(ISubscriberFileListener listener); /** * Remove a file operation listener from the subscriber * @param listener */ public void removeFileListener(ISubscriberFileListener listener); /** * Returns a data wrapper holding the configured connection information. * @return */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/WriteException.java // public class WriteException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public WriteException(String message, Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public WriteException(Exception cause) { // super(cause); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/shim/ConnectionInfo.java // public class ConnectionInfo { // // private final String password; // private final String userName; // private final String connectURL; // // public ConnectionInfo(final String password, final String userName, final String connectURL) { // this.password=password; // this.userName=userName; // this.connectURL=connectURL; // } // // public String getPassword() { // return password; // } // // public String getUserName() { // return userName; // } // // public String getConnectURL() { // return connectURL; // } // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/ISubscriberShim.java import info.vancauwenberge.filedriver.exception.WriteException; import info.vancauwenberge.filedriver.shim.ConnectionInfo; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.api; public interface ISubscriberShim { /** * Forcefully close the current file. This file already places a synchronized block on the file lock. If this * is the only file operation you inted to do, no need to add an additional synchronized block on the file lock. * Used to be part of IFileOwnerCallback * @return true if a file was actually closed. False otherwise. * @throws WriteException */ public boolean finishFile() throws WriteException; /** * Get the filelock that is used by this object to read and write to the file or close a new file. * Used to be part of IFileOwnerCallback. Synchronize on this object to perform tests on hte current file. * @return */ public Object getFileLock(); /** * Get the number of records in the current file or -1 if no current file. */ public abstract int getCurrentFileRecordCount(); /** * Does the subscriber currently have an open file */ public abstract boolean isFileOpen(); /** * Add a file operation listener to the subscriber * @param listener */ public void addFileListener(ISubscriberFileListener listener); /** * Remove a file operation listener from the subscriber * @param listener */ public void removeFileListener(ISubscriberFileListener listener); /** * Returns a data wrapper holding the configured connection information. * @return */
public ConnectionInfo getConnectionInfo();
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filename/GUIDFileNameStrategy.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileNameStrategy.java // public interface IFileNameStrategy extends ISubscriberStrategy{ // // /** // * Get the new fileName (not including folder name!). // * @param trace // * @param driverParams // * @throws XDSParameterException // */ // public String getNewFileName(Map<String,String> record); // }
import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import java.util.HashMap; import java.util.Map; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IDriver; import info.vancauwenberge.filedriver.api.IFileNameStrategy; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType;
return "GUIDNamer_FilePreFix"; } @Override public String getDefaultValue() { return ""; } }; public abstract String getParameterName(); public abstract String getDefaultValue(); public DataType getDataType() { return DataType.STRING; } public Constraint[] getConstraints() { return null; } } private String fileExtention; private String filePreFix; /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.INewFileNamer#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileNameStrategy.java // public interface IFileNameStrategy extends ISubscriberStrategy{ // // /** // * Get the new fileName (not including folder name!). // * @param trace // * @param driverParams // * @throws XDSParameterException // */ // public String getNewFileName(Map<String,String> record); // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filename/GUIDFileNameStrategy.java import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import java.util.HashMap; import java.util.Map; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IDriver; import info.vancauwenberge.filedriver.api.IFileNameStrategy; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; return "GUIDNamer_FilePreFix"; } @Override public String getDefaultValue() { return ""; } }; public abstract String getParameterName(); public abstract String getDefaultValue(); public DataType getDataType() { return DataType.STRING; } public Constraint[] getConstraints() { return null; } } private String fileExtention; private String filePreFix; /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.INewFileNamer#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
public void init(Trace trace, Map<String, Parameter> driverParams, IDriver driver)
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/shim/AbstractShim.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/Build.java // public class Build { // // /** The build of your driver. */ // public static final String BUILD_NO; // // /** The version of your driver. */ // static public final String PRODUCT_VERSION; // // /** Your company name. */ // static public final String COMPANY_NAME; // // /** The name of your driver. */ // static public final String PRODUCT_NAME; // // static{ // final Class<Build> clazz = Build.class; // final String className = clazz.getSimpleName() + ".class"; // Manifest manifest = null; // try { // final URLConnection connection = clazz.getResource(className).openConnection(); // if (connection instanceof JarURLConnection){ // manifest = ((JarURLConnection)connection).getManifest(); // }else{ // // Class not from JAR, but from the file system. // final String classPath = clazz.getResource(className).toString(); // final String packageName = clazz.getPackage().getName(); // final String manifestPath = classPath.substring(0, classPath.length()-className.length()-packageName.length()-1) + "META-INF" + File.separatorChar + "MANIFEST.MF"; // manifest = new Manifest(new URL(manifestPath).openStream()); // } // } catch (final Exception e1) { // e1.printStackTrace(); // } // final Attributes attr = manifest==null?null:manifest.getMainAttributes(); // BUILD_NO = getAttribute("Built-Date",attr); // PRODUCT_VERSION = getProductVersion(BUILD_NO,getAttribute("Implementation-Version",attr)); // COMPANY_NAME = getAttribute("Implementation-Vendor",attr); // PRODUCT_NAME = getAttribute("Implementation-Title",attr); // } // /* // * Get an attribute from the manifest, or unknown if no manifest is defined. // */ // private static String getAttribute(final String name, final Attributes attr ){ // if (attr!= null){ // final String value = attr.getValue(name); // if (value != null) { // return value; // } // } // return "unknown"; // } // // /** // * We reformat the date time in buildNo to YYYYMMDD-HHMMSS and append that to the productVersion // * @param buildNo // * @param productVesion // * @return // */ // private static String getProductVersion(final String buildNo, final String productVesion) { // final SimpleDateFormat fromDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // fromDf.setTimeZone(TimeZone.getTimeZone("UTC")); // final SimpleDateFormat toDf = new SimpleDateFormat("yyyyMMddHHmm"); // toDf.setTimeZone(TimeZone.getTimeZone("UTC")); // try{ // return productVesion+"."+toDf.format(fromDf.parse(buildNo)); // }catch (final Exception e) { // e.printStackTrace(); // return productVesion; // } // } // }
import com.novell.nds.dirxml.driver.xds.XDSQueryDocument; import com.novell.nds.dirxml.driver.xds.XDSResultDocument; import com.novell.nds.dirxml.driver.xds.XDSSourceElement; import info.vancauwenberge.filedriver.Build; import java.lang.reflect.Method; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.WriteableDocument; import com.novell.nds.dirxml.driver.xds.XDSCommandDocument; import com.novell.nds.dirxml.driver.xds.XDSProductElement;
Method m =c.getMethod("put", String.class, String.class); m.invoke(null, "Trace", header); if (trace != null) trace.trace("SLF4J MDC set to:"+header,3); }catch (Exception e) { if (trace != null) trace.trace("SLF4J not found. MDC not configured.",3); } } }//setTrace(String):void protected abstract String getDriverInstanceName(); /** * Appends a populated <code>&lt;source&gt;</code> element to * <code>doc</code>. * <p> * @param doc may be <code>null</code> */ public void appendSourceInfo(WriteableDocument doc) { if (doc != null) { XDSSourceElement source; XDSProductElement product; source = doc.appendSourceElement(); product = source.appendProductElement(); //TODO: MODIFY: put the time and date your driver was built here
// Path: shim/src/main/java/info/vancauwenberge/filedriver/Build.java // public class Build { // // /** The build of your driver. */ // public static final String BUILD_NO; // // /** The version of your driver. */ // static public final String PRODUCT_VERSION; // // /** Your company name. */ // static public final String COMPANY_NAME; // // /** The name of your driver. */ // static public final String PRODUCT_NAME; // // static{ // final Class<Build> clazz = Build.class; // final String className = clazz.getSimpleName() + ".class"; // Manifest manifest = null; // try { // final URLConnection connection = clazz.getResource(className).openConnection(); // if (connection instanceof JarURLConnection){ // manifest = ((JarURLConnection)connection).getManifest(); // }else{ // // Class not from JAR, but from the file system. // final String classPath = clazz.getResource(className).toString(); // final String packageName = clazz.getPackage().getName(); // final String manifestPath = classPath.substring(0, classPath.length()-className.length()-packageName.length()-1) + "META-INF" + File.separatorChar + "MANIFEST.MF"; // manifest = new Manifest(new URL(manifestPath).openStream()); // } // } catch (final Exception e1) { // e1.printStackTrace(); // } // final Attributes attr = manifest==null?null:manifest.getMainAttributes(); // BUILD_NO = getAttribute("Built-Date",attr); // PRODUCT_VERSION = getProductVersion(BUILD_NO,getAttribute("Implementation-Version",attr)); // COMPANY_NAME = getAttribute("Implementation-Vendor",attr); // PRODUCT_NAME = getAttribute("Implementation-Title",attr); // } // /* // * Get an attribute from the manifest, or unknown if no manifest is defined. // */ // private static String getAttribute(final String name, final Attributes attr ){ // if (attr!= null){ // final String value = attr.getValue(name); // if (value != null) { // return value; // } // } // return "unknown"; // } // // /** // * We reformat the date time in buildNo to YYYYMMDD-HHMMSS and append that to the productVersion // * @param buildNo // * @param productVesion // * @return // */ // private static String getProductVersion(final String buildNo, final String productVesion) { // final SimpleDateFormat fromDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // fromDf.setTimeZone(TimeZone.getTimeZone("UTC")); // final SimpleDateFormat toDf = new SimpleDateFormat("yyyyMMddHHmm"); // toDf.setTimeZone(TimeZone.getTimeZone("UTC")); // try{ // return productVesion+"."+toDf.format(fromDf.parse(buildNo)); // }catch (final Exception e) { // e.printStackTrace(); // return productVesion; // } // } // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/shim/AbstractShim.java import com.novell.nds.dirxml.driver.xds.XDSQueryDocument; import com.novell.nds.dirxml.driver.xds.XDSResultDocument; import com.novell.nds.dirxml.driver.xds.XDSSourceElement; import info.vancauwenberge.filedriver.Build; import java.lang.reflect.Method; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.WriteableDocument; import com.novell.nds.dirxml.driver.xds.XDSCommandDocument; import com.novell.nds.dirxml.driver.xds.XDSProductElement; Method m =c.getMethod("put", String.class, String.class); m.invoke(null, "Trace", header); if (trace != null) trace.trace("SLF4J MDC set to:"+header,3); }catch (Exception e) { if (trace != null) trace.trace("SLF4J not found. MDC not configured.",3); } } }//setTrace(String):void protected abstract String getDriverInstanceName(); /** * Appends a populated <code>&lt;source&gt;</code> element to * <code>doc</code>. * <p> * @param doc may be <code>null</code> */ public void appendSourceInfo(WriteableDocument doc) { if (doc != null) { XDSSourceElement source; XDSProductElement product; source = doc.appendSourceElement(); product = source.appendProductElement(); //TODO: MODIFY: put the time and date your driver was built here
product.setBuild(Build.BUILD_NO);
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/util/Test.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/Build.java // public class Build { // // /** The build of your driver. */ // public static final String BUILD_NO; // // /** The version of your driver. */ // static public final String PRODUCT_VERSION; // // /** Your company name. */ // static public final String COMPANY_NAME; // // /** The name of your driver. */ // static public final String PRODUCT_NAME; // // static{ // final Class<Build> clazz = Build.class; // final String className = clazz.getSimpleName() + ".class"; // Manifest manifest = null; // try { // final URLConnection connection = clazz.getResource(className).openConnection(); // if (connection instanceof JarURLConnection){ // manifest = ((JarURLConnection)connection).getManifest(); // }else{ // // Class not from JAR, but from the file system. // final String classPath = clazz.getResource(className).toString(); // final String packageName = clazz.getPackage().getName(); // final String manifestPath = classPath.substring(0, classPath.length()-className.length()-packageName.length()-1) + "META-INF" + File.separatorChar + "MANIFEST.MF"; // manifest = new Manifest(new URL(manifestPath).openStream()); // } // } catch (final Exception e1) { // e1.printStackTrace(); // } // final Attributes attr = manifest==null?null:manifest.getMainAttributes(); // BUILD_NO = getAttribute("Built-Date",attr); // PRODUCT_VERSION = getProductVersion(BUILD_NO,getAttribute("Implementation-Version",attr)); // COMPANY_NAME = getAttribute("Implementation-Vendor",attr); // PRODUCT_NAME = getAttribute("Implementation-Title",attr); // } // /* // * Get an attribute from the manifest, or unknown if no manifest is defined. // */ // private static String getAttribute(final String name, final Attributes attr ){ // if (attr!= null){ // final String value = attr.getValue(name); // if (value != null) { // return value; // } // } // return "unknown"; // } // // /** // * We reformat the date time in buildNo to YYYYMMDD-HHMMSS and append that to the productVersion // * @param buildNo // * @param productVesion // * @return // */ // private static String getProductVersion(final String buildNo, final String productVesion) { // final SimpleDateFormat fromDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // fromDf.setTimeZone(TimeZone.getTimeZone("UTC")); // final SimpleDateFormat toDf = new SimpleDateFormat("yyyyMMddHHmm"); // toDf.setTimeZone(TimeZone.getTimeZone("UTC")); // try{ // return productVesion+"."+toDf.format(fromDf.parse(buildNo)); // }catch (final Exception e) { // e.printStackTrace(); // return productVesion; // } // } // }
import info.vancauwenberge.filedriver.Build;
/** * @param args */ public static void main(String[] args) { try { /* XmlDocument initDoc = new XmlDocument(initDocStr); XDSInitDocument initDocument = new XDSInitDocument(initDoc); HashMap<String,Parameter> paramDefs = new HashMap<String,Parameter>(6); //Add file namer as param Parameter param1 = new Parameter("newFile_MaxFileAge", //tag name "0", //default value (optional) DataType.INT); //data type param1.add(RequiredConstraint.REQUIRED); param1.add(RequiredConstraint.REQUIRED); param1.add(rc); paramDefs.put(param1.tagName(), param1); Parameter param2 = new Parameter("newFile_MaxRecords", //tag name "0", //default value (optional) DataType.INT); //data type param2.add(RequiredConstraint.REQUIRED); param2.add(RequiredConstraint.REQUIRED); param2.add(rc); paramDefs.put(param2.tagName(), param2); initDocument.parameters(paramDefs); System.out.println(rc); System.out.println("Param:"+param1.toInteger());*/
// Path: shim/src/main/java/info/vancauwenberge/filedriver/Build.java // public class Build { // // /** The build of your driver. */ // public static final String BUILD_NO; // // /** The version of your driver. */ // static public final String PRODUCT_VERSION; // // /** Your company name. */ // static public final String COMPANY_NAME; // // /** The name of your driver. */ // static public final String PRODUCT_NAME; // // static{ // final Class<Build> clazz = Build.class; // final String className = clazz.getSimpleName() + ".class"; // Manifest manifest = null; // try { // final URLConnection connection = clazz.getResource(className).openConnection(); // if (connection instanceof JarURLConnection){ // manifest = ((JarURLConnection)connection).getManifest(); // }else{ // // Class not from JAR, but from the file system. // final String classPath = clazz.getResource(className).toString(); // final String packageName = clazz.getPackage().getName(); // final String manifestPath = classPath.substring(0, classPath.length()-className.length()-packageName.length()-1) + "META-INF" + File.separatorChar + "MANIFEST.MF"; // manifest = new Manifest(new URL(manifestPath).openStream()); // } // } catch (final Exception e1) { // e1.printStackTrace(); // } // final Attributes attr = manifest==null?null:manifest.getMainAttributes(); // BUILD_NO = getAttribute("Built-Date",attr); // PRODUCT_VERSION = getProductVersion(BUILD_NO,getAttribute("Implementation-Version",attr)); // COMPANY_NAME = getAttribute("Implementation-Vendor",attr); // PRODUCT_NAME = getAttribute("Implementation-Title",attr); // } // /* // * Get an attribute from the manifest, or unknown if no manifest is defined. // */ // private static String getAttribute(final String name, final Attributes attr ){ // if (attr!= null){ // final String value = attr.getValue(name); // if (value != null) { // return value; // } // } // return "unknown"; // } // // /** // * We reformat the date time in buildNo to YYYYMMDD-HHMMSS and append that to the productVersion // * @param buildNo // * @param productVesion // * @return // */ // private static String getProductVersion(final String buildNo, final String productVesion) { // final SimpleDateFormat fromDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // fromDf.setTimeZone(TimeZone.getTimeZone("UTC")); // final SimpleDateFormat toDf = new SimpleDateFormat("yyyyMMddHHmm"); // toDf.setTimeZone(TimeZone.getTimeZone("UTC")); // try{ // return productVesion+"."+toDf.format(fromDf.parse(buildNo)); // }catch (final Exception e) { // e.printStackTrace(); // return productVesion; // } // } // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/util/Test.java import info.vancauwenberge.filedriver.Build; /** * @param args */ public static void main(String[] args) { try { /* XmlDocument initDoc = new XmlDocument(initDocStr); XDSInitDocument initDocument = new XDSInitDocument(initDoc); HashMap<String,Parameter> paramDefs = new HashMap<String,Parameter>(6); //Add file namer as param Parameter param1 = new Parameter("newFile_MaxFileAge", //tag name "0", //default value (optional) DataType.INT); //data type param1.add(RequiredConstraint.REQUIRED); param1.add(RequiredConstraint.REQUIRED); param1.add(rc); paramDefs.put(param1.tagName(), param1); Parameter param2 = new Parameter("newFile_MaxRecords", //tag name "0", //default value (optional) DataType.INT); //data type param2.add(RequiredConstraint.REQUIRED); param2.add(RequiredConstraint.REQUIRED); param2.add(rc); paramDefs.put(param2.tagName(), param2); initDocument.parameters(paramDefs); System.out.println(rc); System.out.println("Param:"+param1.toInteger());*/
System.out.println(Build.BUILD_NO);
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filesorter/FilePropertySorter.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileSorterStrategy.java // public interface IFileSorterStrategy extends IPublisherStrategy{ // // /* // * Get the first file to process from a list of files. // */ // public File getFirstFile(File[] fileList); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/util/TraceLevel.java // public class TraceLevel { // /** // * Exception level (0) // */ // public static final int EXCEPTION = 0; // /** // * Error and warning messages (1) // */ // public static final int ERROR_WARN = 1; // /** // * Debugging information (descisions taken etc) // */ // public static final int DEBUG = 2; // /** // * TRACE level: method entry/exit // */ // public static final int TRACE = 3; // }
import java.util.Comparator; import java.util.List; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; import com.novell.nds.dirxml.driver.xds.EnumConstraint; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IFileSorterStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import info.vancauwenberge.filedriver.util.TraceLevel; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
possibleMethods.add(method.getName()); } } return possibleMethods; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getFirstFile(java.io.File[]) */ public File getFirstFile(File[] fileList) { if (fileList != null && fileList.length > 0) { trace.trace("getNextFile: found file(s)", TraceLevel.DEBUG); if (fileSortMethod != null && fileList.length>1){ //Sort the files List<File> list = Arrays.asList(fileList); Collections.sort(list, fileComparator); return (File) list.get(0); } else { return fileList[0]; } } return null; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/AbstractStrategy.java // public abstract class AbstractStrategy implements IStrategy{ // // public interface IStrategyParameters{ // public String getParameterName(); // public String getDefaultValue(); // public DataType getDataType(); // public Constraint[] getConstraints(); // } // // public static String getStringValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toString(); // } // // public static boolean getBoolValueFor(IStrategyParameters paramDef,Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toBoolean().booleanValue(); // } // // public static int getIntValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toInteger(); // } // // public static long getLongValueFor(IStrategyParameters paramDef, Map<String,Parameter> subParams){ // return subParams.get(paramDef.getParameterName()).toLong(); // } // // private <E extends Enum<?> & IStrategyParameters> Map<String,Parameter> getIDMParameters(Class<E> parameters){ // E[] values = parameters.getEnumConstants(); // Map<String,Parameter> result = new HashMap<String, Parameter>(values.length); // for (E aParameter : values) { // Parameter param = new Parameter(aParameter.getParameterName(), //tag name // aParameter.getDefaultValue(), //default value (optional) // aParameter.getDataType()); //data type // Constraint[] cons = aParameter.getConstraints(); // if (cons != null) // for (Constraint constraint: cons) { // param.add(constraint); // } // result.put(aParameter.getParameterName(), param); // } // return result; // // } // // // public Map<String,Parameter> getParameterDefinitions(){ // //The XDS.jar library automatically checks parameter // //data types for you. When a RequiredConstraint // //is added to a parameter, the library will check init documents // //to ensure the parameter is present and has a value. When you // //add RangeConstraints or EnumConstraints to a parameter, the // //library will check parameter values to see if they satisfy these // //constraints. // return getIDMParameters(getParametersEnum()); // } // // // // // public abstract <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileSorterStrategy.java // public interface IFileSorterStrategy extends IPublisherStrategy{ // // /* // * Get the first file to process from a list of files. // */ // public File getFirstFile(File[] fileList); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/util/TraceLevel.java // public class TraceLevel { // /** // * Exception level (0) // */ // public static final int EXCEPTION = 0; // /** // * Error and warning messages (1) // */ // public static final int ERROR_WARN = 1; // /** // * Debugging information (descisions taken etc) // */ // public static final int DEBUG = 2; // /** // * TRACE level: method entry/exit // */ // public static final int TRACE = 3; // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filesorter/FilePropertySorter.java import java.util.Comparator; import java.util.List; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; import com.novell.nds.dirxml.driver.xds.EnumConstraint; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IFileSorterStrategy; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import info.vancauwenberge.filedriver.util.TraceLevel; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; possibleMethods.add(method.getName()); } } return possibleMethods; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#getFirstFile(java.io.File[]) */ public File getFirstFile(File[] fileList) { if (fileList != null && fileList.length > 0) { trace.trace("getNextFile: found file(s)", TraceLevel.DEBUG); if (fileSortMethod != null && fileList.length>1){ //Sort the files List<File> list = Arrays.asList(fileList); Collections.sort(list, fileComparator); return (File) list.get(0); } else { return fileList[0]; } } return null; } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileSorterStrategy#init(com.novell.nds.dirxml.driver.Trace, java.util.Map) */
public void init(Trace trace, Map<String,Parameter> driverParams, IPublisher publisher) throws XDSParameterException {
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filereader/csv/CSVFileParser.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/filereader/RecordQueue.java // public class RecordQueue { // private LinkedList<Map<String, String>> list = new LinkedList<Map<String, String>>(); // private boolean isFinished = false; // private static final int MAXQUEUESIZE = 20; // private Exception exceptionToThrow = null; // // public void setFinished() { // synchronized (list) { // isFinished = true; // list.notifyAll(); // } // } // // public void addRecord(Map<String, String> record) { // synchronized (list) { // // Only add when we did not have any exception and are still running // if ((exceptionToThrow == null) && !isFinished) { // if (list.size() >= MAXQUEUESIZE) { // try { // System.out.println("..waiting before appending records to the queue."); // list.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // list.add(record); // } // list.notifyAll(); // } // } // // public Map<String, String> getNextRecord() throws Exception { // Map<String, String> result = null; // synchronized (list) { // // If 0, we either reached the end, we had an exception or still // // parsing and we need to wait // if (list.size() == 0) { // if (!isFinished && (exceptionToThrow == null)) { // try { // // wait until we get notified about an update // System.out.println("..waiting for next record to get added."); // list.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // if (list.size() == 0) { // if (exceptionToThrow != null) { // list.notifyAll(); // throw exceptionToThrow; // } // Assume finished. Only option left... // return null; // } else { // result = list.removeFirst(); // list.notifyAll(); // } // } else { // // size >0 // result = list.removeFirst(); // list.notifyAll(); // } // } // return result; // } // // /** // * // */ // public void setFinishedInError(Exception e) { // exceptionToThrow = e; // synchronized (list) { // list.notifyAll(); // } // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/util/TraceLevel.java // public class TraceLevel { // /** // * Exception level (0) // */ // public static final int EXCEPTION = 0; // /** // * Error and warning messages (1) // */ // public static final int ERROR_WARN = 1; // /** // * Debugging information (descisions taken etc) // */ // public static final int DEBUG = 2; // /** // * TRACE level: method entry/exit // */ // public static final int TRACE = 3; // }
import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import info.vancauwenberge.filedriver.filereader.RecordQueue; import info.vancauwenberge.filedriver.util.TraceLevel;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader.csv; public class CSVFileParser { private static final char TOKEN_COMMENT = '#'; private static final int LINE_BEGIN = 0; private static final int LINE_NORMAL = 1; private static final int LINE_COMMENT = 2; private static final int FIELD_BEGIN = 0; private static final int FIELD_QUOTED = 1; private static final int FIELD_NORMAL = 2; private static final int CHAR_NORMAL = 0; private static final int CHAR_ESCAPE = 1; // fields private boolean fileHeaderprocessed = false; private final Object fileHeaderprocessedLock = new Object(); private final boolean loadNodeNamesFromHeader; private final boolean skipEmptyLines; private int fieldStat = FIELD_BEGIN; private int charStat = CHAR_NORMAL; private int lineStat = LINE_BEGIN; private HashMap<String, String> thisRecord = new HashMap<String, String>(); private int fieldIndex = 0; private char token_seperator = ';'; private String[] currentRecordFields; // private String dataRecordTag; private String[] dataRecordFields; // private String headerRecordTag; private final String[] headerRecordFields;
// Path: shim/src/main/java/info/vancauwenberge/filedriver/filereader/RecordQueue.java // public class RecordQueue { // private LinkedList<Map<String, String>> list = new LinkedList<Map<String, String>>(); // private boolean isFinished = false; // private static final int MAXQUEUESIZE = 20; // private Exception exceptionToThrow = null; // // public void setFinished() { // synchronized (list) { // isFinished = true; // list.notifyAll(); // } // } // // public void addRecord(Map<String, String> record) { // synchronized (list) { // // Only add when we did not have any exception and are still running // if ((exceptionToThrow == null) && !isFinished) { // if (list.size() >= MAXQUEUESIZE) { // try { // System.out.println("..waiting before appending records to the queue."); // list.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // list.add(record); // } // list.notifyAll(); // } // } // // public Map<String, String> getNextRecord() throws Exception { // Map<String, String> result = null; // synchronized (list) { // // If 0, we either reached the end, we had an exception or still // // parsing and we need to wait // if (list.size() == 0) { // if (!isFinished && (exceptionToThrow == null)) { // try { // // wait until we get notified about an update // System.out.println("..waiting for next record to get added."); // list.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // if (list.size() == 0) { // if (exceptionToThrow != null) { // list.notifyAll(); // throw exceptionToThrow; // } // Assume finished. Only option left... // return null; // } else { // result = list.removeFirst(); // list.notifyAll(); // } // } else { // // size >0 // result = list.removeFirst(); // list.notifyAll(); // } // } // return result; // } // // /** // * // */ // public void setFinishedInError(Exception e) { // exceptionToThrow = e; // synchronized (list) { // list.notifyAll(); // } // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/util/TraceLevel.java // public class TraceLevel { // /** // * Exception level (0) // */ // public static final int EXCEPTION = 0; // /** // * Error and warning messages (1) // */ // public static final int ERROR_WARN = 1; // /** // * Debugging information (descisions taken etc) // */ // public static final int DEBUG = 2; // /** // * TRACE level: method entry/exit // */ // public static final int TRACE = 3; // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filereader/csv/CSVFileParser.java import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import info.vancauwenberge.filedriver.filereader.RecordQueue; import info.vancauwenberge.filedriver.util.TraceLevel; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader.csv; public class CSVFileParser { private static final char TOKEN_COMMENT = '#'; private static final int LINE_BEGIN = 0; private static final int LINE_NORMAL = 1; private static final int LINE_COMMENT = 2; private static final int FIELD_BEGIN = 0; private static final int FIELD_QUOTED = 1; private static final int FIELD_NORMAL = 2; private static final int CHAR_NORMAL = 0; private static final int CHAR_ESCAPE = 1; // fields private boolean fileHeaderprocessed = false; private final Object fileHeaderprocessedLock = new Object(); private final boolean loadNodeNamesFromHeader; private final boolean skipEmptyLines; private int fieldStat = FIELD_BEGIN; private int charStat = CHAR_NORMAL; private int lineStat = LINE_BEGIN; private HashMap<String, String> thisRecord = new HashMap<String, String>(); private int fieldIndex = 0; private char token_seperator = ';'; private String[] currentRecordFields; // private String dataRecordTag; private String[] dataRecordFields; // private String headerRecordTag; private final String[] headerRecordFields;
private RecordQueue queue;
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/query/QueryMatcher.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // }
import info.vancauwenberge.filedriver.api.IDriver; import java.util.List; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.XDSAssociationElement; import com.novell.nds.dirxml.driver.xds.XDSQueryDocument; import com.novell.nds.dirxml.driver.xds.XDSQueryElement; import com.novell.nds.dirxml.driver.xds.XDSSearchAttrElement;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.query; public abstract class QueryMatcher { @SuppressWarnings("unchecked")
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/query/QueryMatcher.java import info.vancauwenberge.filedriver.api.IDriver; import java.util.List; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.XDSAssociationElement; import com.novell.nds.dirxml.driver.xds.XDSQueryDocument; import com.novell.nds.dirxml.driver.xds.XDSQueryElement; import com.novell.nds.dirxml.driver.xds.XDSSearchAttrElement; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.query; public abstract class QueryMatcher { @SuppressWarnings("unchecked")
public static QueryMatcher getMatcher(Trace trace, XDSQueryDocument queryDoc, IDriver driver){
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisherImplStrategy.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // }
import com.novell.nds.dirxml.driver.xds.XDSResultDocument; import info.vancauwenberge.filedriver.api.IDriver; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.XmlCommandProcessor; import com.novell.nds.dirxml.driver.XmlDocument; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSClassDefElement; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import com.novell.nds.dirxml.driver.xds.XDSParseException;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filepublisher; /** * This is the implementation that the shim expects. * @author stefaanv * */ public interface IPublisherImplStrategy { /** * Common configuration options. Each publisher implementation should do somthing with this. */ static public final String PUB_HEARTBEAT_INTERVAL = "pub_heartbeatInterval"; /** * Delegation method from XDSPublisher * @param arg0 * @return */ public XmlDocument query(XmlDocument arg0); /** * Delegation method from XDSPublisher * @param arg0 * @return */ public XmlDocument start(XmlCommandProcessor arg0); /** * init this publisher implementation * @param trace * @param driverParams * @param driver * @param initXML * @return * @throws Exception */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IDriver.java // public interface IDriver { // public ISubscriberShim getSubscriber(); // /** // * Create a new XDS result document // * @return // */ // public XDSResultDocument newResultDoc(); // // /** // * Get all the driver parameters // * @return // */ // public Map<? extends String, ? extends Parameter> getDriverParams(); // // /** // * Append the source node to the given query doc // * @param result // */ // public void appendSourceInfo(WriteableDocument doc); // // /** // * Get the drivers RDN (=cn) // * @return // */ // public String getDriverInstanceName(); // // /** // * Get the driver's schema // * @return // */ // public Object getSchema(); // // /** // * Create a new command doc // * @return // */ // public XDSCommandDocument newCommandDoc(); // // /** // * Get the association value for the given record // * @param record // * @return // */ // public String getAssociationField(Map<String, String> record); // /** // * Get the source field for the given record // * @param record // * @return // */ // public String getSourceField(Map<String, String> record); // // /** // * Get a pre-configured ECMA script evaluator // * // */ // public EcmascriptBuilder getEcmaBuilder(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisherImplStrategy.java import com.novell.nds.dirxml.driver.xds.XDSResultDocument; import info.vancauwenberge.filedriver.api.IDriver; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.XmlCommandProcessor; import com.novell.nds.dirxml.driver.XmlDocument; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSClassDefElement; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import com.novell.nds.dirxml.driver.xds.XDSParseException; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filepublisher; /** * This is the implementation that the shim expects. * @author stefaanv * */ public interface IPublisherImplStrategy { /** * Common configuration options. Each publisher implementation should do somthing with this. */ static public final String PUB_HEARTBEAT_INTERVAL = "pub_heartbeatInterval"; /** * Delegation method from XDSPublisher * @param arg0 * @return */ public XmlDocument query(XmlDocument arg0); /** * Delegation method from XDSPublisher * @param arg0 * @return */ public XmlDocument start(XmlCommandProcessor arg0); /** * init this publisher implementation * @param trace * @param driverParams * @param driver * @param initXML * @return * @throws Exception */
public XmlDocument init(Trace trace, Map<String,Parameter> driverParams, IDriver driver, XmlDocument initXML) throws Exception;
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filereader/DummyFileReader.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileReadStrategy.java // public interface IFileReadStrategy extends IPublisherStrategy{ // /** // * Tells the reader to prepare for reading a given file. The previous file (if any) was processed completly. // * @param trace // * @param f // * @throws IOException // */ // public void openFile(File f) throws ReadException; // /** // * Reads one record from the file. Return null if no more records can be read from the file. // * @param trace // * @return a map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @throws IOException // */ // public Map<String,String> readRecord() throws ReadException; // /** // * Tells the reader that no more records will be read from this file (readRecord returned null). // * The reader should release all resources associated with the file. // * @throws IOException // */ // public void close() throws ReadException; // // // /** // * Get the actual schema used by the file reader. This can differ than the schema configured on the driver (eg: headers in the CSV file). // * @return // */ // public String[] getActualSchema(); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/ReadException.java // public class ReadException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public ReadException(final String message, final Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public ReadException(final Exception cause) { // super(cause); // } // // public ReadException(final String message) { // super(message); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // }
import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.IFileReadStrategy; import info.vancauwenberge.filedriver.exception.ReadException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader; public class DummyFileReader implements IFileReadStrategy{ BufferedReader br; /** * Get a Map of parameter definitions. Key=parameter name, value=Parameter object * @param * @return the map with parameter definitions */ public Map<String, Parameter> getParameterDefinitions(){ return new HashMap<String, Parameter>(0); } /** * Initialize this file reader on startup * @param trace * @param driverParams * @throws XDSParameterException */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileReadStrategy.java // public interface IFileReadStrategy extends IPublisherStrategy{ // /** // * Tells the reader to prepare for reading a given file. The previous file (if any) was processed completly. // * @param trace // * @param f // * @throws IOException // */ // public void openFile(File f) throws ReadException; // /** // * Reads one record from the file. Return null if no more records can be read from the file. // * @param trace // * @return a map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @throws IOException // */ // public Map<String,String> readRecord() throws ReadException; // /** // * Tells the reader that no more records will be read from this file (readRecord returned null). // * The reader should release all resources associated with the file. // * @throws IOException // */ // public void close() throws ReadException; // // // /** // * Get the actual schema used by the file reader. This can differ than the schema configured on the driver (eg: headers in the CSV file). // * @return // */ // public String[] getActualSchema(); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/ReadException.java // public class ReadException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public ReadException(final String message, final Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public ReadException(final Exception cause) { // super(cause); // } // // public ReadException(final String message) { // super(message); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filereader/DummyFileReader.java import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.IFileReadStrategy; import info.vancauwenberge.filedriver.exception.ReadException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader; public class DummyFileReader implements IFileReadStrategy{ BufferedReader br; /** * Get a Map of parameter definitions. Key=parameter name, value=Parameter object * @param * @return the map with parameter definitions */ public Map<String, Parameter> getParameterDefinitions(){ return new HashMap<String, Parameter>(0); } /** * Initialize this file reader on startup * @param trace * @param driverParams * @throws XDSParameterException */
public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws XDSParameterException{
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filereader/DummyFileReader.java
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileReadStrategy.java // public interface IFileReadStrategy extends IPublisherStrategy{ // /** // * Tells the reader to prepare for reading a given file. The previous file (if any) was processed completly. // * @param trace // * @param f // * @throws IOException // */ // public void openFile(File f) throws ReadException; // /** // * Reads one record from the file. Return null if no more records can be read from the file. // * @param trace // * @return a map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @throws IOException // */ // public Map<String,String> readRecord() throws ReadException; // /** // * Tells the reader that no more records will be read from this file (readRecord returned null). // * The reader should release all resources associated with the file. // * @throws IOException // */ // public void close() throws ReadException; // // // /** // * Get the actual schema used by the file reader. This can differ than the schema configured on the driver (eg: headers in the CSV file). // * @return // */ // public String[] getActualSchema(); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/ReadException.java // public class ReadException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public ReadException(final String message, final Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public ReadException(final Exception cause) { // super(cause); // } // // public ReadException(final String message) { // super(message); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // }
import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.IFileReadStrategy; import info.vancauwenberge.filedriver.exception.ReadException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map;
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader; public class DummyFileReader implements IFileReadStrategy{ BufferedReader br; /** * Get a Map of parameter definitions. Key=parameter name, value=Parameter object * @param * @return the map with parameter definitions */ public Map<String, Parameter> getParameterDefinitions(){ return new HashMap<String, Parameter>(0); } /** * Initialize this file reader on startup * @param trace * @param driverParams * @throws XDSParameterException */ public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws XDSParameterException{ } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileReader#openFile(com.novell.nds.dirxml.driver.Trace, java.io.File) */
// Path: shim/src/main/java/info/vancauwenberge/filedriver/api/IFileReadStrategy.java // public interface IFileReadStrategy extends IPublisherStrategy{ // /** // * Tells the reader to prepare for reading a given file. The previous file (if any) was processed completly. // * @param trace // * @param f // * @throws IOException // */ // public void openFile(File f) throws ReadException; // /** // * Reads one record from the file. Return null if no more records can be read from the file. // * @param trace // * @return a map of key/value pairs. The key is the fieldname (String), the value is the String value for that field. Value can be null. // * @throws IOException // */ // public Map<String,String> readRecord() throws ReadException; // /** // * Tells the reader that no more records will be read from this file (readRecord returned null). // * The reader should release all resources associated with the file. // * @throws IOException // */ // public void close() throws ReadException; // // // /** // * Get the actual schema used by the file reader. This can differ than the schema configured on the driver (eg: headers in the CSV file). // * @return // */ // public String[] getActualSchema(); // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/exception/ReadException.java // public class ReadException extends Exception { // /** // * // */ // private static final long serialVersionUID = 1L; // /** // * @param message // * @param cause // */ // public ReadException(final String message, final Exception cause) { // super(message,cause); // } // /** // * @param cause // */ // public ReadException(final Exception cause) { // super(cause); // } // // public ReadException(final String message) { // super(message); // } // } // // Path: shim/src/main/java/info/vancauwenberge/filedriver/filepublisher/IPublisher.java // public interface IPublisher { // // /** // * Get the folder where files are moved to for processing // * @return // */ // public String getWorkDir(); // // /** // * Get the current file in process (should be in workDir). // * Note: files are only moved to the workdir just prior to processing. If multiple files are found for processing, only // * the first one is moved to 'workdir' and processed. After this, the next file is moved and processed etc... // * @return // */ // public File getCurrentFile(); // // } // Path: shim/src/main/java/info/vancauwenberge/filedriver/filereader/DummyFileReader.java import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.IFileReadStrategy; import info.vancauwenberge.filedriver.exception.ReadException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader; public class DummyFileReader implements IFileReadStrategy{ BufferedReader br; /** * Get a Map of parameter definitions. Key=parameter name, value=Parameter object * @param * @return the map with parameter definitions */ public Map<String, Parameter> getParameterDefinitions(){ return new HashMap<String, Parameter>(0); } /** * Initialize this file reader on startup * @param trace * @param driverParams * @throws XDSParameterException */ public void init(Trace trace, Map<String, Parameter> driverParams, IPublisher publisher) throws XDSParameterException{ } /* (non-Javadoc) * @see info.vancauwenberge.filedriver.api.IFileReader#openFile(com.novell.nds.dirxml.driver.Trace, java.io.File) */
public void openFile(File f) throws ReadException{
pinussilvestrus/bncl
core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclTaskParser.java
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // }
import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.BpmnModelElementInstance; import org.camunda.bpm.model.bpmn.instance.BusinessRuleTask; import org.camunda.bpm.model.bpmn.instance.ManualTask; import org.camunda.bpm.model.bpmn.instance.ReceiveTask; import org.camunda.bpm.model.bpmn.instance.ScriptTask; import org.camunda.bpm.model.bpmn.instance.SendTask; import org.camunda.bpm.model.bpmn.instance.ServiceTask; import org.camunda.bpm.model.bpmn.instance.UserTask; import java.util.ArrayList; import java.util.List; import java.util.Map;
package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer */ public class BnclTaskParser extends BnclElementParser { private List<TaskElement> taskTypes = new ArrayList<>();
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // } // Path: core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclTaskParser.java import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.BpmnModelElementInstance; import org.camunda.bpm.model.bpmn.instance.BusinessRuleTask; import org.camunda.bpm.model.bpmn.instance.ManualTask; import org.camunda.bpm.model.bpmn.instance.ReceiveTask; import org.camunda.bpm.model.bpmn.instance.ScriptTask; import org.camunda.bpm.model.bpmn.instance.SendTask; import org.camunda.bpm.model.bpmn.instance.ServiceTask; import org.camunda.bpm.model.bpmn.instance.UserTask; import java.util.ArrayList; import java.util.List; import java.util.Map; package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer */ public class BnclTaskParser extends BnclElementParser { private List<TaskElement> taskTypes = new ArrayList<>();
public BnclTaskParser(BPMNModelBuilder builder) {
pinussilvestrus/bncl
web/src/test/java/de/niklaskiefer/bnclWeb/controller/MainControllerTest.java
// Path: web/src/main/java/de/niklaskiefer/bnclWeb/MainApplication.java // @SpringBootApplication // @Import(ThymeleafConfig.class) // public class MainApplication { // // // public static void main(String[] args) { // System.out.println("----Starting Demo Server-----"); // SpringApplication.run(MainApplication.class, args); // } // }
import de.niklaskiefer.bnclWeb.MainApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package de.niklaskiefer.bnclWeb.controller; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration
// Path: web/src/main/java/de/niklaskiefer/bnclWeb/MainApplication.java // @SpringBootApplication // @Import(ThymeleafConfig.class) // public class MainApplication { // // // public static void main(String[] args) { // System.out.println("----Starting Demo Server-----"); // SpringApplication.run(MainApplication.class, args); // } // } // Path: web/src/test/java/de/niklaskiefer/bnclWeb/controller/MainControllerTest.java import de.niklaskiefer.bnclWeb.MainApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; package de.niklaskiefer.bnclWeb.controller; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration
@ContextConfiguration(classes = MainApplication.class)
pinussilvestrus/bncl
core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclEventParser.java
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // }
import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.BpmnModelElementInstance; import org.camunda.bpm.model.bpmn.instance.CancelEventDefinition; import org.camunda.bpm.model.bpmn.instance.CompensateEventDefinition; import org.camunda.bpm.model.bpmn.instance.EndEvent; import org.camunda.bpm.model.bpmn.instance.ErrorEventDefinition; import org.camunda.bpm.model.bpmn.instance.EscalationEventDefinition; import org.camunda.bpm.model.bpmn.instance.IntermediateCatchEvent; import org.camunda.bpm.model.bpmn.instance.IntermediateThrowEvent; import org.camunda.bpm.model.bpmn.instance.MessageEventDefinition; import org.camunda.bpm.model.bpmn.instance.SignalEventDefinition; import org.camunda.bpm.model.bpmn.instance.StartEvent; import org.camunda.bpm.model.bpmn.instance.TerminateEventDefinition; import org.camunda.bpm.model.bpmn.instance.TimerEventDefinition; import java.util.ArrayList; import java.util.List; import java.util.Map;
package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer */ public class BnclEventParser extends BnclElementParser { private List<EventElement> eventTypes = new ArrayList<>();
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // } // Path: core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclEventParser.java import de.niklaskiefer.bnclCore.BPMNModelBuilder; import org.camunda.bpm.model.bpmn.instance.BpmnModelElementInstance; import org.camunda.bpm.model.bpmn.instance.CancelEventDefinition; import org.camunda.bpm.model.bpmn.instance.CompensateEventDefinition; import org.camunda.bpm.model.bpmn.instance.EndEvent; import org.camunda.bpm.model.bpmn.instance.ErrorEventDefinition; import org.camunda.bpm.model.bpmn.instance.EscalationEventDefinition; import org.camunda.bpm.model.bpmn.instance.IntermediateCatchEvent; import org.camunda.bpm.model.bpmn.instance.IntermediateThrowEvent; import org.camunda.bpm.model.bpmn.instance.MessageEventDefinition; import org.camunda.bpm.model.bpmn.instance.SignalEventDefinition; import org.camunda.bpm.model.bpmn.instance.StartEvent; import org.camunda.bpm.model.bpmn.instance.TerminateEventDefinition; import org.camunda.bpm.model.bpmn.instance.TimerEventDefinition; import java.util.ArrayList; import java.util.List; import java.util.Map; package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer */ public class BnclEventParser extends BnclElementParser { private List<EventElement> eventTypes = new ArrayList<>();
public BnclEventParser(BPMNModelBuilder builder) {
pinussilvestrus/bncl
core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclElementParser.java
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // }
import de.niklaskiefer.bnclCore.BPMNModelBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer structure of BnclElement: WITH STARTEVENT called [NAME] * * WITH is keyword for BnclElement */ public class BnclElementParser extends AbstractBnclParser { // attribute types protected List<AttributeElement> attributeTypes = new ArrayList<>(); private static final String NO_ID_EXCEPTION = "This element has no id! Please add a \'signed\' attribute";
// Path: core/src/main/java/de/niklaskiefer/bnclCore/BPMNModelBuilder.java // public class BPMNModelBuilder { // // private static final String CAMUNDA_NAMESPACE = "http://camunda.org/examples"; // // private BpmnModelInstance bpmnModelInstance; // private Process process; // private List<BpmnModelElementInstance> elements = new ArrayList<>(); // // public BPMNModelBuilder() { // String id = "pid-" + UUID.randomUUID().toString(); // bpmnModelInstance = Bpmn.createExecutableProcess(id) // .startEvent() // .userTask() // .endEvent() // .done(); // } // // // public Process createProcess() { // String id = "pid-" + UUID.randomUUID().toString(); // process = createElement(bpmnModelInstance.getDefinitions(), id, Process.class); // return process; // } // // public void createDefinitions() { // Definitions definitions = bpmnModelInstance.newInstance(Definitions.class); // definitions.setTargetNamespace(CAMUNDA_NAMESPACE); // bpmnModelInstance.setDefinitions(definitions); // } // // public <T extends EventDefinition> T createEventDefinition(BpmnModelElementInstance parentElement, Process process, Class<T> eventDefinitionClass) { // T element = bpmnModelInstance.newInstance(eventDefinitionClass); // parentElement.addChildElement(element); // elements.add(element); // return element; // } // // public SequenceFlow createSequenceFlow(Process process, String idFrom, String idTo) { // FlowNode from = null; // FlowNode to = null; // for (BpmnModelElementInstance element : elements) { // if (element.getAttributeValue("id").equals(idFrom)) { // from = (FlowNode) element; // } else if (element.getAttributeValue("id").equals(idTo)) { // to = (FlowNode) element; // } // } // // if (from != null && to != null) { // return createSequenceFlow(process, from, to); // } // // return null; // } // // public Gateway createGateway(Process process, Map<String, String> attributes, Class type) { // return (Gateway) createElement(process, type, attributes); // } // // public SequenceFlow createSequenceFlow(Process process, FlowNode from, FlowNode to) { // String identifier = from.getId() + "-" + to.getId(); // SequenceFlow sequenceFlow = createElement(process, identifier, SequenceFlow.class); // process.addChildElement(sequenceFlow); // sequenceFlow.setSource(from); // from.getOutgoing().add(sequenceFlow); // sequenceFlow.setTarget(to); // to.getIncoming().add(sequenceFlow); // return sequenceFlow; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, Class<T> elementClass, Map<String, String> attributes) { // T element = createElement(parentElement, "dump", elementClass); // for (Map.Entry<String, String> s : attributes.entrySet()) { // element.setAttributeValue(s.getKey(), s.getValue(), false); // } // return element; // } // // public <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) { // T element = bpmnModelInstance.newInstance(elementClass); // element.setAttributeValue("id", id, true); // parentElement.addChildElement(element); // elements.add(element); // save all elements for later referencing // return element; // } // // public BpmnModelInstance getModel() { // return bpmnModelInstance; // } // // // public Process getProcess() { // return process; // } // } // Path: core/src/main/java/de/niklaskiefer/bnclCore/parser/BnclElementParser.java import de.niklaskiefer.bnclCore.BPMNModelBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package de.niklaskiefer.bnclCore.parser; /** * @author Niklas Kiefer structure of BnclElement: WITH STARTEVENT called [NAME] * * WITH is keyword for BnclElement */ public class BnclElementParser extends AbstractBnclParser { // attribute types protected List<AttributeElement> attributeTypes = new ArrayList<>(); private static final String NO_ID_EXCEPTION = "This element has no id! Please add a \'signed\' attribute";
protected BPMNModelBuilder builder;
pinussilvestrus/bncl
web/src/test/java/de/niklaskiefer/bnclWeb/controller/ApiControllerTest.java
// Path: web/src/main/java/de/niklaskiefer/bnclWeb/MainApplication.java // @SpringBootApplication // @Import(ThymeleafConfig.class) // public class MainApplication { // // // public static void main(String[] args) { // System.out.println("----Starting Demo Server-----"); // SpringApplication.run(MainApplication.class, args); // } // }
import de.niklaskiefer.bnclWeb.MainApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package de.niklaskiefer.bnclWeb.controller; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration
// Path: web/src/main/java/de/niklaskiefer/bnclWeb/MainApplication.java // @SpringBootApplication // @Import(ThymeleafConfig.class) // public class MainApplication { // // // public static void main(String[] args) { // System.out.println("----Starting Demo Server-----"); // SpringApplication.run(MainApplication.class, args); // } // } // Path: web/src/test/java/de/niklaskiefer/bnclWeb/controller/ApiControllerTest.java import de.niklaskiefer.bnclWeb.MainApplication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; package de.niklaskiefer.bnclWeb.controller; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration
@ContextConfiguration(classes = MainApplication.class)
pinussilvestrus/bncl
core/src/test/java/de/niklaskiefer/bnclCore/MainApplicationTest.java
// Path: core/src/main/java/de/niklaskiefer/bnclCore/MainApplication.java // public class MainApplication { // // public static String testBncl = // "lets create a process with " + // "a signalstartevent signed startEvent1 called message incoming with " + // "an errorevent signed event1 called 3 Stunden vergangen with " + // "a scripttask signed usertask1 called dosomething with " + // "usertask signed usertask2 with " + // "inclusivegateway signed gateway1 with " + // "parallelgateway signed gateway2 with " + // "sequenceflow comesfrom startevent1 goesto event1 with " + // "sequenceflow comesfrom event1 goesto gateway1 with " + // "sequenceflow comesfrom gateway1 goesto usertask1 with " + // "sequenceflow comesfrom gateway1 goesto usertask2 with " + // "sequenceflow comesfrom usertask1 goesto gateway2 with " + // "sequenceflow comesfrom usertask2 goesto gateway2 with " + // "messagethrowevent signed endevent1 called terminated with " + // "sequenceflow comesfrom gateway2 goesto endevent1"; // // private static List<String> cliOptions = new ArrayList<>(); // private static Console console; // // public static void main(String[] args) { // startConsoleProgram(); // } // // private static void startConsoleProgram() { // initCLIOptions(); // // try { // // console = System.console(); // if (console != null) { // System.out.println("Welcome to the Bncl-Parser demo console program! Please chose an option: "); // printCLIOptions(); // String option = console.readLine("> "); // executeOption(option); // } else { // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFile(testBncl); // } // } catch (Exception ex) { // ex.printStackTrace(); // System.out.println("Oh, there was a problem in parsing Bncl!"); // } // } // // private static void executeOption(String option) throws Exception { // switch (option) { // case "1": simpleConverting(); break; // case "2": fileConverting(); break; // default: // System.out.println("No valid option, please try again!"); // break; // } // } // // private static void simpleConverting() throws Exception { // System.out.println("Input a Bncl-Statement: "); // String input = console.readLine("> "); // // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFile(input); // } // // private static void fileConverting() throws Exception { // System.out.println("Input a Bncl-file: "); // String fileName = console.readLine("> "); // // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFileFromFile(fileName); // } // // private static void printCLIOptions() { // for (String cliOption : cliOptions) { // System.out.println(cliOption); // } // } // // private static void initCLIOptions() { // cliOptions.add("1: Parse a single Bncl-statement"); // cliOptions.add("2: Parse a Bncl-file"); // } // }
import de.niklaskiefer.bnclCore.MainApplication; import org.junit.Test;
package de.niklaskiefer.bnclCore; /** * @author Niklas Kiefer */ public class MainApplicationTest { @Test public void testMain() {
// Path: core/src/main/java/de/niklaskiefer/bnclCore/MainApplication.java // public class MainApplication { // // public static String testBncl = // "lets create a process with " + // "a signalstartevent signed startEvent1 called message incoming with " + // "an errorevent signed event1 called 3 Stunden vergangen with " + // "a scripttask signed usertask1 called dosomething with " + // "usertask signed usertask2 with " + // "inclusivegateway signed gateway1 with " + // "parallelgateway signed gateway2 with " + // "sequenceflow comesfrom startevent1 goesto event1 with " + // "sequenceflow comesfrom event1 goesto gateway1 with " + // "sequenceflow comesfrom gateway1 goesto usertask1 with " + // "sequenceflow comesfrom gateway1 goesto usertask2 with " + // "sequenceflow comesfrom usertask1 goesto gateway2 with " + // "sequenceflow comesfrom usertask2 goesto gateway2 with " + // "messagethrowevent signed endevent1 called terminated with " + // "sequenceflow comesfrom gateway2 goesto endevent1"; // // private static List<String> cliOptions = new ArrayList<>(); // private static Console console; // // public static void main(String[] args) { // startConsoleProgram(); // } // // private static void startConsoleProgram() { // initCLIOptions(); // // try { // // console = System.console(); // if (console != null) { // System.out.println("Welcome to the Bncl-Parser demo console program! Please chose an option: "); // printCLIOptions(); // String option = console.readLine("> "); // executeOption(option); // } else { // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFile(testBncl); // } // } catch (Exception ex) { // ex.printStackTrace(); // System.out.println("Oh, there was a problem in parsing Bncl!"); // } // } // // private static void executeOption(String option) throws Exception { // switch (option) { // case "1": simpleConverting(); break; // case "2": fileConverting(); break; // default: // System.out.println("No valid option, please try again!"); // break; // } // } // // private static void simpleConverting() throws Exception { // System.out.println("Input a Bncl-Statement: "); // String input = console.readLine("> "); // // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFile(input); // } // // private static void fileConverting() throws Exception { // System.out.println("Input a Bncl-file: "); // String fileName = console.readLine("> "); // // BnclToXmlWriter writer = new BnclToXmlWriter(); // writer.createBPMNFileFromFile(fileName); // } // // private static void printCLIOptions() { // for (String cliOption : cliOptions) { // System.out.println(cliOption); // } // } // // private static void initCLIOptions() { // cliOptions.add("1: Parse a single Bncl-statement"); // cliOptions.add("2: Parse a Bncl-file"); // } // } // Path: core/src/test/java/de/niklaskiefer/bnclCore/MainApplicationTest.java import de.niklaskiefer.bnclCore.MainApplication; import org.junit.Test; package de.niklaskiefer.bnclCore; /** * @author Niklas Kiefer */ public class MainApplicationTest { @Test public void testMain() {
MainApplication.main(new String[]{});