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
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/event/LayoutEvent.java
// Path: app/src/main/java/javax/microedition/lcdui/Event.java // public abstract class Event implements Runnable // { // // private static int count = 0; // // private int id = count++; // // // // public int getID() // // { // // return id; // // } // // /** // * Обработка события. // * Именно здесь нужно выполнять требуемые действия. // */ // public abstract void process(); // // /** // * Сдача события в утиль. // * // * Если предусмотрен пул событий, то здесь // * событие нужно обнулить и вернуть в пул. // */ // public abstract void recycle(); // // /** // * Обработать событие и сдать в утиль за один прием. // */ // public void run() // { // process(); // recycle(); // } // // /** // * Вызывается, когда событие вошло в очередь. // * Здесь можно увеличить счетчик таких событий в очереди. // */ // public abstract void enterQueue(); // // /** // * Вызывается, когда событие покинуло очередь. // * Здесь можно уменьшить счетчик таких событий в очереди. // */ // public abstract void leaveQueue(); // // /** // * Проверить, можно ли поместить это событие в очередь // * сразу за некоторым другим событием. // * // * @param event событие, после которого нас могут поместить в очередь // * @return true, если мы на это согласны // */ // public abstract boolean placeableAfter(Event event); // } // // Path: app/src/main/java/javax/microedition/util/ArrayStack.java // public class ArrayStack<E> // { // public static final int DELTA = 100; // // protected Object[] data; // protected int index; // // public ArrayStack() // { // clear(); // } // // public void push(E value) // { // if(index >= data.length - 1) // { // Object[] temp = new Object[data.length + DELTA]; // System.arraycopy(data, 0, temp, 0, data.length); // data = temp; // } // // data[++index] = value; // } // // public E pop() // { // if(index < 0) // { // return null; // } // // // if(index + (DELTA << 1) <= data.length - 1) // // { // // Object[] temp = new Object[data.length - DELTA]; // // System.arraycopy(data, 0, temp, 0, temp.length); // // data = temp; // // } // // return (E)data[index--]; // } // // public void clear() // { // data = new Object[0]; // index = -1; // } // // public boolean empty() // { // return index < 0; // } // }
import javax.microedition.lcdui.Event; import javax.microedition.util.ArrayStack; import android.view.View; import android.view.ViewGroup;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.event; public class LayoutEvent extends Event {
// Path: app/src/main/java/javax/microedition/lcdui/Event.java // public abstract class Event implements Runnable // { // // private static int count = 0; // // private int id = count++; // // // // public int getID() // // { // // return id; // // } // // /** // * Обработка события. // * Именно здесь нужно выполнять требуемые действия. // */ // public abstract void process(); // // /** // * Сдача события в утиль. // * // * Если предусмотрен пул событий, то здесь // * событие нужно обнулить и вернуть в пул. // */ // public abstract void recycle(); // // /** // * Обработать событие и сдать в утиль за один прием. // */ // public void run() // { // process(); // recycle(); // } // // /** // * Вызывается, когда событие вошло в очередь. // * Здесь можно увеличить счетчик таких событий в очереди. // */ // public abstract void enterQueue(); // // /** // * Вызывается, когда событие покинуло очередь. // * Здесь можно уменьшить счетчик таких событий в очереди. // */ // public abstract void leaveQueue(); // // /** // * Проверить, можно ли поместить это событие в очередь // * сразу за некоторым другим событием. // * // * @param event событие, после которого нас могут поместить в очередь // * @return true, если мы на это согласны // */ // public abstract boolean placeableAfter(Event event); // } // // Path: app/src/main/java/javax/microedition/util/ArrayStack.java // public class ArrayStack<E> // { // public static final int DELTA = 100; // // protected Object[] data; // protected int index; // // public ArrayStack() // { // clear(); // } // // public void push(E value) // { // if(index >= data.length - 1) // { // Object[] temp = new Object[data.length + DELTA]; // System.arraycopy(data, 0, temp, 0, data.length); // data = temp; // } // // data[++index] = value; // } // // public E pop() // { // if(index < 0) // { // return null; // } // // // if(index + (DELTA << 1) <= data.length - 1) // // { // // Object[] temp = new Object[data.length - DELTA]; // // System.arraycopy(data, 0, temp, 0, temp.length); // // data = temp; // // } // // return (E)data[index--]; // } // // public void clear() // { // data = new Object[0]; // index = -1; // } // // public boolean empty() // { // return index < 0; // } // } // Path: app/src/main/java/javax/microedition/lcdui/event/LayoutEvent.java import javax.microedition.lcdui.Event; import javax.microedition.util.ArrayStack; import android.view.View; import android.view.ViewGroup; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.event; public class LayoutEvent extends Event {
private static ArrayStack<LayoutEvent> recycled = new ArrayStack();
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/shell/MyClassLoader.java
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import dalvik.system.DexClassLoader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.FileNotFoundException; import filelog.Log;
package javax.microedition.shell; public class MyClassLoader extends DexClassLoader { private static final String tag = MyClassLoader.class.getName(); private File resFolder; public MyClassLoader(String paths, String tmpDir, String libs, ClassLoader parent, String resDir) { super(paths, tmpDir, libs, parent); this.resFolder = new File(resDir); } @Override public InputStream getResourceAsStream(String resName) { System.err.println("CUSTOM GET RES CALLED WITH PATH: " + resName);
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/javax/microedition/shell/MyClassLoader.java import dalvik.system.DexClassLoader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.FileNotFoundException; import filelog.Log; package javax.microedition.shell; public class MyClassLoader extends DexClassLoader { private static final String tag = MyClassLoader.class.getName(); private File resFolder; public MyClassLoader(String paths, String tmpDir, String libs, ClassLoader parent, String resDir) { super(paths, tmpDir, libs, parent); this.resFolder = new File(resDir); } @Override public InputStream getResourceAsStream(String resName) { System.err.println("CUSTOM GET RES CALLED WITH PATH: " + resName);
Log.d(tag, "CUSTOM GET RES CALLED WITH PATH: " + resName);
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/List.java
// Path: app/src/main/java/javax/microedition/lcdui/list/CompoundListAdapter.java // public class CompoundListAdapter extends CompoundAdapter implements ListAdapter // { // protected int listType; // protected int viewResourceID; // protected ItemSelector selector; // // public CompoundListAdapter(Context context, ItemSelector selector, int type) // { // super(context); // // this.listType = type; // this.selector = selector; // // switch(type) // { // case Choice.IMPLICIT: // viewResourceID = layout.simple_list_item_1; // break; // // case Choice.EXCLUSIVE: // viewResourceID = layout.simple_list_item_single_choice; // break; // // case Choice.MULTIPLE: // viewResourceID = layout.simple_list_item_multiple_choice; // break; // // default: // throw new IllegalArgumentException("list type " + type + " is not supported"); // } // // if(type != Choice.IMPLICIT && selector == null) // { // throw new IllegalArgumentException("ItemSelector is requered for this list type"); // } // } // // public View getView(int position, View convertView, ViewGroup parent) // { // convertView = getView(position, convertView, parent, viewResourceID, true); // // if(listType != Choice.IMPLICIT && convertView instanceof CompoundButton) // { // ((CompoundButton)convertView).setChecked(selector.isSelected(position)); // } // // return convertView; // } // // public boolean areAllItemsEnabled() // { // return true; // } // // public boolean isEnabled(int position) // { // return true; // } // } // // Path: app/src/main/java/javax/microedition/lcdui/list/ItemSelector.java // public interface ItemSelector // { // public boolean isSelected(int elementNum); // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.microedition.lcdui.list.CompoundListAdapter; import javax.microedition.lcdui.list.ItemSelector; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.ListView;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class List extends Screen implements Choice, ItemSelector { public static final Command SELECT_COMMAND = new Command("", Command.SCREEN, 0); private ArrayList<String> strings = new ArrayList(); private ArrayList<Image> images = new ArrayList(); private final ArrayList<Boolean> selected = new ArrayList(); private ListView list;
// Path: app/src/main/java/javax/microedition/lcdui/list/CompoundListAdapter.java // public class CompoundListAdapter extends CompoundAdapter implements ListAdapter // { // protected int listType; // protected int viewResourceID; // protected ItemSelector selector; // // public CompoundListAdapter(Context context, ItemSelector selector, int type) // { // super(context); // // this.listType = type; // this.selector = selector; // // switch(type) // { // case Choice.IMPLICIT: // viewResourceID = layout.simple_list_item_1; // break; // // case Choice.EXCLUSIVE: // viewResourceID = layout.simple_list_item_single_choice; // break; // // case Choice.MULTIPLE: // viewResourceID = layout.simple_list_item_multiple_choice; // break; // // default: // throw new IllegalArgumentException("list type " + type + " is not supported"); // } // // if(type != Choice.IMPLICIT && selector == null) // { // throw new IllegalArgumentException("ItemSelector is requered for this list type"); // } // } // // public View getView(int position, View convertView, ViewGroup parent) // { // convertView = getView(position, convertView, parent, viewResourceID, true); // // if(listType != Choice.IMPLICIT && convertView instanceof CompoundButton) // { // ((CompoundButton)convertView).setChecked(selector.isSelected(position)); // } // // return convertView; // } // // public boolean areAllItemsEnabled() // { // return true; // } // // public boolean isEnabled(int position) // { // return true; // } // } // // Path: app/src/main/java/javax/microedition/lcdui/list/ItemSelector.java // public interface ItemSelector // { // public boolean isSelected(int elementNum); // } // Path: app/src/main/java/javax/microedition/lcdui/List.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.microedition.lcdui.list.CompoundListAdapter; import javax.microedition.lcdui.list.ItemSelector; import android.content.Context; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class List extends Screen implements Choice, ItemSelector { public static final Command SELECT_COMMAND = new Command("", Command.SCREEN, 0); private ArrayList<String> strings = new ArrayList(); private ArrayList<Image> images = new ArrayList(); private final ArrayList<Boolean> selected = new ArrayList(); private ListView list;
private CompoundListAdapter adapter;
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/Font.java
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // }
import javax.microedition.util.ContextHolder; import android.graphics.Paint; import android.graphics.Typeface; import android.util.TypedValue;
{ case SIZE_SMALL: sizes[0] = value; break; case SIZE_MEDIUM: sizes[1] = value; break; case SIZE_LARGE: sizes[2] = value; break; default: return; } for(int i = 0; i < fonts.length; i++) { fonts[i] = null; } } private Paint paint; private int face, style, size; public Font(Typeface face, int style, float size, boolean underline) { if(applyDimensions) {
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // } // Path: app/src/main/java/javax/microedition/lcdui/Font.java import javax.microedition.util.ContextHolder; import android.graphics.Paint; import android.graphics.Typeface; import android.util.TypedValue; { case SIZE_SMALL: sizes[0] = value; break; case SIZE_MEDIUM: sizes[1] = value; break; case SIZE_LARGE: sizes[2] = value; break; default: return; } for(int i = 0; i < fonts.length; i++) { fonts[i] = null; } } private Paint paint; private int face, style, size; public Font(Typeface face, int style, float size, boolean underline) { if(applyDimensions) {
size = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, ContextHolder.getContext().getResources().getDisplayMetrics());
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/rms/RecordStore.java
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // }
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.microedition.util.ContextHolder; import android.content.Context;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.rms; public class RecordStore { private static final String INDEX_SUFFIX = ".idx"; private static final String RECORD_SUFFIX = ".dat"; private static final String SEPARATOR = "-"; private String recordStoreName; private int nextRecordID; private ArrayList<Integer> ids; private static String getFileNamePrefix(String recordStoreName) { return recordStoreName + SEPARATOR + Integer.toHexString(recordStoreName.hashCode()).toUpperCase(); } private String getIndexFileName() { return getFileNamePrefix(recordStoreName) + INDEX_SUFFIX; } private String getRecordFileName(int id) { return getFileNamePrefix(recordStoreName) + SEPARATOR + id + RECORD_SUFFIX; } private RecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException { this.recordStoreName = recordStoreName; try {
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // } // Path: app/src/main/java/javax/microedition/rms/RecordStore.java import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.microedition.util.ContextHolder; import android.content.Context; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.rms; public class RecordStore { private static final String INDEX_SUFFIX = ".idx"; private static final String RECORD_SUFFIX = ".dat"; private static final String SEPARATOR = "-"; private String recordStoreName; private int nextRecordID; private ArrayList<Integer> ids; private static String getFileNamePrefix(String recordStoreName) { return recordStoreName + SEPARATOR + Integer.toHexString(recordStoreName.hashCode()).toUpperCase(); } private String getIndexFileName() { return getFileNamePrefix(recordStoreName) + INDEX_SUFFIX; } private String getRecordFileName(int id) { return getFileNamePrefix(recordStoreName) + SEPARATOR + id + RECORD_SUFFIX; } private RecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException { this.recordStoreName = recordStoreName; try {
DataInputStream dis = new DataInputStream(ContextHolder.getContext().openFileInput(getIndexFileName()));
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/list/CompoundListAdapter.java
// Path: app/src/main/java/javax/microedition/lcdui/Choice.java // public interface Choice // { // public static final int EXCLUSIVE = 1; // public static final int MULTIPLE = 2; // public static final int IMPLICIT = 3; // public static final int POPUP = 4; // // public static final int TEXT_WRAP_DEFAULT = 0; // public static final int TEXT_WRAP_ON = 1; // public static final int TEXT_WRAP_OFF = 2; // // public int append(String stringPart, Image imagePart); // public void delete(int elementNum); // public void deleteAll(); // public Image getImage(int elementNum); // public int getSelectedFlags(boolean[] selectedArray_return); // public int getSelectedIndex(); // public String getString(int elementNum); // public void insert(int elementNum, String stringPart, Image imagePart); // public boolean isSelected(int elementNum); // public void set(int elementNum, String stringPart, Image imagePart); // public void setSelectedFlags(boolean[] selectedArray); // public void setSelectedIndex(int elementNum, boolean selected); // public int size(); // }
import javax.microedition.lcdui.Choice; import android.R.layout; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ListAdapter;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.list; public class CompoundListAdapter extends CompoundAdapter implements ListAdapter { protected int listType; protected int viewResourceID; protected ItemSelector selector; public CompoundListAdapter(Context context, ItemSelector selector, int type) { super(context); this.listType = type; this.selector = selector; switch(type) {
// Path: app/src/main/java/javax/microedition/lcdui/Choice.java // public interface Choice // { // public static final int EXCLUSIVE = 1; // public static final int MULTIPLE = 2; // public static final int IMPLICIT = 3; // public static final int POPUP = 4; // // public static final int TEXT_WRAP_DEFAULT = 0; // public static final int TEXT_WRAP_ON = 1; // public static final int TEXT_WRAP_OFF = 2; // // public int append(String stringPart, Image imagePart); // public void delete(int elementNum); // public void deleteAll(); // public Image getImage(int elementNum); // public int getSelectedFlags(boolean[] selectedArray_return); // public int getSelectedIndex(); // public String getString(int elementNum); // public void insert(int elementNum, String stringPart, Image imagePart); // public boolean isSelected(int elementNum); // public void set(int elementNum, String stringPart, Image imagePart); // public void setSelectedFlags(boolean[] selectedArray); // public void setSelectedIndex(int elementNum, boolean selected); // public int size(); // } // Path: app/src/main/java/javax/microedition/lcdui/list/CompoundListAdapter.java import javax.microedition.lcdui.Choice; import android.R.layout; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ListAdapter; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.list; public class CompoundListAdapter extends CompoundAdapter implements ListAdapter { protected int listType; protected int viewResourceID; protected ItemSelector selector; public CompoundListAdapter(Context context, ItemSelector selector, int type) { super(context); this.listType = type; this.selector = selector; switch(type) {
case Choice.IMPLICIT:
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/Connector.java // public class Connector // { // public static final int READ = 1; // public static final int READ_WRITE = 3; // public static final int WRITE = 2; // // private static HashMap<String, ConnectionProvider> providers; // // static // { // registerConnectionProvider("file", new FileSystemRegistry()); // registerConnectionProvider("http", new HttpConnectionProvider()); // registerConnectionProvider("btl2cap", new BTL2CAPConnectionProvider()); // } // // public static void registerConnectionProvider(String protocol, ConnectionProvider provider) // { // if(providers == null) // { // providers = new HashMap(); // } // // providers.put(protocol.toLowerCase(), provider); // } // // public static Connection open(String name) throws IOException // { // return open(name, READ_WRITE); // } // // public static Connection open(String name, int mode) throws IOException // { // if(providers == null || providers.isEmpty()) // { // throw new ConnectionNotFoundException("no registered connection providers"); // } // // int index = name.indexOf("://"); // // if(index >= 0) // { // String protocol = name.substring(0, index).toLowerCase(); // ConnectionProvider provider = providers.get(protocol); // // if(provider != null) // { // return provider.open(name.substring(index + 3), mode); // } // else // { // throw new ConnectionNotFoundException("'" + protocol + "' connections are not supported"); // } // } // else // { // throw new IllegalArgumentException("malformed URL: " + name); // } // } // // public static InputStream openInputStream(String name) throws IOException // { // Connection conn = open(name, READ); // // if(conn instanceof StreamConnection) // { // return new ImmediateInputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // // public static OutputStream openOutputStream(String name) throws IOException // { // Connection conn = open(name, WRITE); // // if(conn instanceof StreamConnection) // { // return new ImmediateOutputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // }
import java.io.File; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import javax.microedition.io.Connector; import android.os.Environment;
} else if(name.startsWith(EXTERNAL_DISK)) { name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); } return "/" + name; } public static String androidFileToMIDP(String name) { if(name.startsWith("/")) { name = name.substring(1); } String sdcard = getExternalStoragePath(); if(name.startsWith(sdcard)) { name = EXTERNAL_DISK + name.substring(sdcard.length()); } else { name = INTERNAL_DISK + name; } return "/" + name; }
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/Connector.java // public class Connector // { // public static final int READ = 1; // public static final int READ_WRITE = 3; // public static final int WRITE = 2; // // private static HashMap<String, ConnectionProvider> providers; // // static // { // registerConnectionProvider("file", new FileSystemRegistry()); // registerConnectionProvider("http", new HttpConnectionProvider()); // registerConnectionProvider("btl2cap", new BTL2CAPConnectionProvider()); // } // // public static void registerConnectionProvider(String protocol, ConnectionProvider provider) // { // if(providers == null) // { // providers = new HashMap(); // } // // providers.put(protocol.toLowerCase(), provider); // } // // public static Connection open(String name) throws IOException // { // return open(name, READ_WRITE); // } // // public static Connection open(String name, int mode) throws IOException // { // if(providers == null || providers.isEmpty()) // { // throw new ConnectionNotFoundException("no registered connection providers"); // } // // int index = name.indexOf("://"); // // if(index >= 0) // { // String protocol = name.substring(0, index).toLowerCase(); // ConnectionProvider provider = providers.get(protocol); // // if(provider != null) // { // return provider.open(name.substring(index + 3), mode); // } // else // { // throw new ConnectionNotFoundException("'" + protocol + "' connections are not supported"); // } // } // else // { // throw new IllegalArgumentException("malformed URL: " + name); // } // } // // public static InputStream openInputStream(String name) throws IOException // { // Connection conn = open(name, READ); // // if(conn instanceof StreamConnection) // { // return new ImmediateInputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // // public static OutputStream openOutputStream(String name) throws IOException // { // Connection conn = open(name, WRITE); // // if(conn instanceof StreamConnection) // { // return new ImmediateOutputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // } // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java import java.io.File; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import javax.microedition.io.Connector; import android.os.Environment; } else if(name.startsWith(EXTERNAL_DISK)) { name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); } return "/" + name; } public static String androidFileToMIDP(String name) { if(name.startsWith("/")) { name = name.substring(1); } String sdcard = getExternalStoragePath(); if(name.startsWith(sdcard)) { name = EXTERNAL_DISK + name.substring(sdcard.length()); } else { name = INTERNAL_DISK + name; } return "/" + name; }
public Connection open(String name, int mode)
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/Connector.java // public class Connector // { // public static final int READ = 1; // public static final int READ_WRITE = 3; // public static final int WRITE = 2; // // private static HashMap<String, ConnectionProvider> providers; // // static // { // registerConnectionProvider("file", new FileSystemRegistry()); // registerConnectionProvider("http", new HttpConnectionProvider()); // registerConnectionProvider("btl2cap", new BTL2CAPConnectionProvider()); // } // // public static void registerConnectionProvider(String protocol, ConnectionProvider provider) // { // if(providers == null) // { // providers = new HashMap(); // } // // providers.put(protocol.toLowerCase(), provider); // } // // public static Connection open(String name) throws IOException // { // return open(name, READ_WRITE); // } // // public static Connection open(String name, int mode) throws IOException // { // if(providers == null || providers.isEmpty()) // { // throw new ConnectionNotFoundException("no registered connection providers"); // } // // int index = name.indexOf("://"); // // if(index >= 0) // { // String protocol = name.substring(0, index).toLowerCase(); // ConnectionProvider provider = providers.get(protocol); // // if(provider != null) // { // return provider.open(name.substring(index + 3), mode); // } // else // { // throw new ConnectionNotFoundException("'" + protocol + "' connections are not supported"); // } // } // else // { // throw new IllegalArgumentException("malformed URL: " + name); // } // } // // public static InputStream openInputStream(String name) throws IOException // { // Connection conn = open(name, READ); // // if(conn instanceof StreamConnection) // { // return new ImmediateInputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // // public static OutputStream openOutputStream(String name) throws IOException // { // Connection conn = open(name, WRITE); // // if(conn instanceof StreamConnection) // { // return new ImmediateOutputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // }
import java.io.File; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import javax.microedition.io.Connector; import android.os.Environment;
{ name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); } return "/" + name; } public static String androidFileToMIDP(String name) { if(name.startsWith("/")) { name = name.substring(1); } String sdcard = getExternalStoragePath(); if(name.startsWith(sdcard)) { name = EXTERNAL_DISK + name.substring(sdcard.length()); } else { name = INTERNAL_DISK + name; } return "/" + name; } public Connection open(String name, int mode) {
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/Connector.java // public class Connector // { // public static final int READ = 1; // public static final int READ_WRITE = 3; // public static final int WRITE = 2; // // private static HashMap<String, ConnectionProvider> providers; // // static // { // registerConnectionProvider("file", new FileSystemRegistry()); // registerConnectionProvider("http", new HttpConnectionProvider()); // registerConnectionProvider("btl2cap", new BTL2CAPConnectionProvider()); // } // // public static void registerConnectionProvider(String protocol, ConnectionProvider provider) // { // if(providers == null) // { // providers = new HashMap(); // } // // providers.put(protocol.toLowerCase(), provider); // } // // public static Connection open(String name) throws IOException // { // return open(name, READ_WRITE); // } // // public static Connection open(String name, int mode) throws IOException // { // if(providers == null || providers.isEmpty()) // { // throw new ConnectionNotFoundException("no registered connection providers"); // } // // int index = name.indexOf("://"); // // if(index >= 0) // { // String protocol = name.substring(0, index).toLowerCase(); // ConnectionProvider provider = providers.get(protocol); // // if(provider != null) // { // return provider.open(name.substring(index + 3), mode); // } // else // { // throw new ConnectionNotFoundException("'" + protocol + "' connections are not supported"); // } // } // else // { // throw new IllegalArgumentException("malformed URL: " + name); // } // } // // public static InputStream openInputStream(String name) throws IOException // { // Connection conn = open(name, READ); // // if(conn instanceof StreamConnection) // { // return new ImmediateInputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // // public static OutputStream openOutputStream(String name) throws IOException // { // Connection conn = open(name, WRITE); // // if(conn instanceof StreamConnection) // { // return new ImmediateOutputStream((StreamConnection)conn); // } // else // { // throw new IOException("cannot open stream on a non-stream connection"); // } // } // } // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java import java.io.File; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import javax.microedition.io.Connector; import android.os.Environment; { name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); } return "/" + name; } public static String androidFileToMIDP(String name) { if(name.startsWith("/")) { name = name.substring(1); } String sdcard = getExternalStoragePath(); if(name.startsWith(sdcard)) { name = EXTERNAL_DISK + name.substring(sdcard.length()); } else { name = INTERNAL_DISK + name; } return "/" + name; } public Connection open(String name, int mode) {
return new FileConnection(new File(midpFileToAndroid(name)), (mode & Connector.WRITE) != 0 ? FileConnection.READ_WRITE : FileConnection.READ);
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/Screen.java
// Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // }
import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.text.TextUtils.TruncateAt; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public abstract class Screen extends Displayable { private static final int TICKER_NO_ACTION = 0; private static final int TICKER_SHOW = 1; private static final int TICKER_HIDE = 2; private Ticker ticker; private LinearLayout layout; private TextView marquee; private int tickermode;
// Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // } // Path: app/src/main/java/javax/microedition/lcdui/Screen.java import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.text.TextUtils.TruncateAt; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public abstract class Screen extends Displayable { private static final int TICKER_NO_ACTION = 0; private static final int TICKER_SHOW = 1; private static final int TICKER_HIDE = 2; private Ticker ticker; private LinearLayout layout; private TextView marquee; private int tickermode;
private SimpleEvent msgSetTicker = new SimpleEvent()
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/StringItem.java
// Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // }
import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.view.View; import android.widget.TextView;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class StringItem extends Item { private String text; private TextView textview;
// Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // } // Path: app/src/main/java/javax/microedition/lcdui/StringItem.java import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.view.View; import android.widget.TextView; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class StringItem extends Item { private String text; private TextView textview;
private SimpleEvent msgSetText = new SimpleEvent()
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/media/DataSource.java
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // }
import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import javax.microedition.util.ContextHolder; import android.content.res.AssetFileDescriptor; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.media; public class DataSource { protected String locator; protected File file; protected FileInputStream stream; protected AssetFileDescriptor asset; protected FileDescriptor descriptor; protected long offset; protected long length; public DataSource(String locator) { this.locator = locator; } public DataSource(File file) { this.file = file; } public void open() throws IOException { if(descriptor == null) { if(locator != null && !locator.contains("://")) { if(locator.startsWith("/")) { locator = locator.substring(1); }
// Path: app/src/main/java/javax/microedition/util/ContextHolder.java // public class ContextHolder { // // private static final String tag = "ContextHolder"; // // private static MainActivity context; // private static ArrayList<ActivityResultListener> resultListeners = new ArrayList<ActivityResultListener>(); // private static LayoutInflater inflater; // // public static void setContext(MainActivity cx) { // context = cx; // inflater = LayoutInflater.from(cx); // } // // public static Context getContext() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getContext()"); // } // return context; // } // // public static LayoutInflater getInflater() { // return inflater; // } // // public static InputStream getResourceAsStream(String filename) { // if (filename.startsWith("/")) { // filename = filename.substring(1); // } // // try { // return getContext().getAssets().open(filename); // } catch (IOException e) { // Log.d(tag, "getResourceAsStream err: " + e.getMessage()); // return null; // } // } // // public static File getCacheDir() { // if (Environment.MEDIA_MOUNTED.equals(Environment // .getExternalStorageState())) { // return getContext().getExternalCacheDir(); // } else { // return getContext().getCacheDir(); // } // } // // public static int getRequestCode(String requestString) { // return requestString.hashCode() & 0x7FFFFFFF; // } // // public static MainActivity getActivity() { // if (context == null) { // throw new IllegalStateException( // "call setContext() before calling getActivity()"); // } // return context; // } // // public static void addActivityResultListener(ActivityResultListener listener) { // if (!resultListeners.contains(listener)) { // resultListeners.add(listener); // } // } // // public static void removeActivityResultListener( // ActivityResultListener listener) { // resultListeners.remove(listener); // } // // public static void notifyOnActivityResult(int requestCode, int resultCode, // Intent data) { // for (ActivityResultListener listener : resultListeners) { // listener.onActivityResult(requestCode, resultCode, data); // } // } // } // Path: app/src/main/java/javax/microedition/media/DataSource.java import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import javax.microedition.util.ContextHolder; import android.content.res.AssetFileDescriptor; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.media; public class DataSource { protected String locator; protected File file; protected FileInputStream stream; protected AssetFileDescriptor asset; protected FileDescriptor descriptor; protected long offset; protected long length; public DataSource(String locator) { this.locator = locator; } public DataSource(File file) { this.file = file; } public void open() throws IOException { if(descriptor == null) { if(locator != null && !locator.contains("://")) { if(locator.startsWith("/")) { locator = locator.substring(1); }
asset = ContextHolder.getContext().getAssets().openFd(locator);
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/Item.java
// Path: app/src/main/java/javax/microedition/lcdui/event/CommandActionEvent.java // public class CommandActionEvent extends Event // { // private static ArrayStack<CommandActionEvent> recycled = new ArrayStack(); // // private CommandListener listener; // private ItemCommandListener itemlistener; // // private Command command; // private Displayable displayable; // private Item item; // // private CommandActionEvent() // { // } // // public static Event getInstance(CommandListener listener, Command command, Displayable displayable) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.listener = listener; // instance.command = command; // instance.displayable = displayable; // // return instance; // } // // public static Event getInstance(ItemCommandListener itemlistener, Command command, Item item) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.itemlistener = itemlistener; // instance.command = command; // instance.item = item; // // return instance; // } // // public void process() // { // if(listener != null) // { // listener.commandAction(command, displayable); // } // else if(itemlistener != null) // { // itemlistener.commandAction(command, item); // } // } // // public void recycle() // { // listener = null; // itemlistener = null; // // command = null; // displayable = null; // item = null; // // recycled.push(this); // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // // // public String toString() // // { // // if(listener != null) // // { // // return "сommandAction(" + command + ", " + displayable + ")"; // // } // // else if(itemlistener != null) // // { // // return "сommandAction(" + command + ", " + item + ")"; // // } // // else // // { // // return "сommandAction(" + command + ")"; // // } // // } // } // // Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // }
import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import javax.microedition.lcdui.event.CommandActionEvent; import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.util.TypedValue; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem;
public static final int LAYOUT_TOP = 16; public static final int LAYOUT_BOTTOM = 32; public static final int LAYOUT_VCENTER = 48; public static final int LAYOUT_NEWLINE_BEFORE = 256; public static final int LAYOUT_NEWLINE_AFTER = 512; public static final int LAYOUT_SHRINK = 1024; public static final int LAYOUT_EXPAND = 2048; public static final int LAYOUT_VSHRINK = 4096; public static final int LAYOUT_VEXPAND = 8192; public static final int LAYOUT_2 = 16384; private static final float BORDER_PADDING = 7; private static final float BORDER_RADIUS = 4; private static final int LABEL_NO_ACTION = 0; private static final int LABEL_SHOW = 1; private static final int LABEL_HIDE = 2; private LinearLayout layout; private View contentview; private String label; private TextView labelview; private int labelmode; private Form owner; private ArrayList<Command> commands = new ArrayList(); private ItemCommandListener listener = null;
// Path: app/src/main/java/javax/microedition/lcdui/event/CommandActionEvent.java // public class CommandActionEvent extends Event // { // private static ArrayStack<CommandActionEvent> recycled = new ArrayStack(); // // private CommandListener listener; // private ItemCommandListener itemlistener; // // private Command command; // private Displayable displayable; // private Item item; // // private CommandActionEvent() // { // } // // public static Event getInstance(CommandListener listener, Command command, Displayable displayable) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.listener = listener; // instance.command = command; // instance.displayable = displayable; // // return instance; // } // // public static Event getInstance(ItemCommandListener itemlistener, Command command, Item item) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.itemlistener = itemlistener; // instance.command = command; // instance.item = item; // // return instance; // } // // public void process() // { // if(listener != null) // { // listener.commandAction(command, displayable); // } // else if(itemlistener != null) // { // itemlistener.commandAction(command, item); // } // } // // public void recycle() // { // listener = null; // itemlistener = null; // // command = null; // displayable = null; // item = null; // // recycled.push(this); // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // // // public String toString() // // { // // if(listener != null) // // { // // return "сommandAction(" + command + ", " + displayable + ")"; // // } // // else if(itemlistener != null) // // { // // return "сommandAction(" + command + ", " + item + ")"; // // } // // else // // { // // return "сommandAction(" + command + ")"; // // } // // } // } // // Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // } // Path: app/src/main/java/javax/microedition/lcdui/Item.java import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import javax.microedition.lcdui.event.CommandActionEvent; import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.util.TypedValue; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; public static final int LAYOUT_TOP = 16; public static final int LAYOUT_BOTTOM = 32; public static final int LAYOUT_VCENTER = 48; public static final int LAYOUT_NEWLINE_BEFORE = 256; public static final int LAYOUT_NEWLINE_AFTER = 512; public static final int LAYOUT_SHRINK = 1024; public static final int LAYOUT_EXPAND = 2048; public static final int LAYOUT_VSHRINK = 4096; public static final int LAYOUT_VEXPAND = 8192; public static final int LAYOUT_2 = 16384; private static final float BORDER_PADDING = 7; private static final float BORDER_RADIUS = 4; private static final int LABEL_NO_ACTION = 0; private static final int LABEL_SHOW = 1; private static final int LABEL_HIDE = 2; private LinearLayout layout; private View contentview; private String label; private TextView labelview; private int labelmode; private Form owner; private ArrayList<Command> commands = new ArrayList(); private ItemCommandListener listener = null;
private SimpleEvent msgSetContextMenuListener = new SimpleEvent()
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/Item.java
// Path: app/src/main/java/javax/microedition/lcdui/event/CommandActionEvent.java // public class CommandActionEvent extends Event // { // private static ArrayStack<CommandActionEvent> recycled = new ArrayStack(); // // private CommandListener listener; // private ItemCommandListener itemlistener; // // private Command command; // private Displayable displayable; // private Item item; // // private CommandActionEvent() // { // } // // public static Event getInstance(CommandListener listener, Command command, Displayable displayable) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.listener = listener; // instance.command = command; // instance.displayable = displayable; // // return instance; // } // // public static Event getInstance(ItemCommandListener itemlistener, Command command, Item item) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.itemlistener = itemlistener; // instance.command = command; // instance.item = item; // // return instance; // } // // public void process() // { // if(listener != null) // { // listener.commandAction(command, displayable); // } // else if(itemlistener != null) // { // itemlistener.commandAction(command, item); // } // } // // public void recycle() // { // listener = null; // itemlistener = null; // // command = null; // displayable = null; // item = null; // // recycled.push(this); // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // // // public String toString() // // { // // if(listener != null) // // { // // return "сommandAction(" + command + ", " + displayable + ")"; // // } // // else if(itemlistener != null) // // { // // return "сommandAction(" + command + ", " + item + ")"; // // } // // else // // { // // return "сommandAction(" + command + ")"; // // } // // } // } // // Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // }
import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import javax.microedition.lcdui.event.CommandActionEvent; import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.util.TypedValue; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem;
{ ViewHandler.postEvent(msgSetContextMenuListener); } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.clear(); for(Command cmd : commands) { menu.add(Menu.NONE, cmd.hashCode(), cmd.getPriority(), cmd.getLabel()); } } public boolean contextMenuItemSelected(MenuItem item) { if(listener == null) { return false; } int id = item.getItemId(); for(Command cmd : commands) { if(cmd.hashCode() == id) { if(owner != null) {
// Path: app/src/main/java/javax/microedition/lcdui/event/CommandActionEvent.java // public class CommandActionEvent extends Event // { // private static ArrayStack<CommandActionEvent> recycled = new ArrayStack(); // // private CommandListener listener; // private ItemCommandListener itemlistener; // // private Command command; // private Displayable displayable; // private Item item; // // private CommandActionEvent() // { // } // // public static Event getInstance(CommandListener listener, Command command, Displayable displayable) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.listener = listener; // instance.command = command; // instance.displayable = displayable; // // return instance; // } // // public static Event getInstance(ItemCommandListener itemlistener, Command command, Item item) // { // CommandActionEvent instance = recycled.pop(); // // if(instance == null) // { // instance = new CommandActionEvent(); // } // // instance.itemlistener = itemlistener; // instance.command = command; // instance.item = item; // // return instance; // } // // public void process() // { // if(listener != null) // { // listener.commandAction(command, displayable); // } // else if(itemlistener != null) // { // itemlistener.commandAction(command, item); // } // } // // public void recycle() // { // listener = null; // itemlistener = null; // // command = null; // displayable = null; // item = null; // // recycled.push(this); // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // // // public String toString() // // { // // if(listener != null) // // { // // return "сommandAction(" + command + ", " + displayable + ")"; // // } // // else if(itemlistener != null) // // { // // return "сommandAction(" + command + ", " + item + ")"; // // } // // else // // { // // return "сommandAction(" + command + ")"; // // } // // } // } // // Path: app/src/main/java/javax/microedition/lcdui/event/SimpleEvent.java // public abstract class SimpleEvent extends Event // { // public void recycle() // { // } // // public void enterQueue() // { // } // // public void leaveQueue() // { // } // // public boolean placeableAfter(Event event) // { // return true; // } // } // Path: app/src/main/java/javax/microedition/lcdui/Item.java import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import javax.microedition.lcdui.event.CommandActionEvent; import javax.microedition.lcdui.event.SimpleEvent; import android.content.Context; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.util.TypedValue; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; { ViewHandler.postEvent(msgSetContextMenuListener); } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.clear(); for(Command cmd : commands) { menu.add(Menu.NONE, cmd.hashCode(), cmd.getPriority(), cmd.getLabel()); } } public boolean contextMenuItemSelected(MenuItem item) { if(listener == null) { return false; } int id = item.getItemId(); for(Command cmd : commands) { if(cmd.hashCode() == id) { if(owner != null) {
owner.postEvent(CommandActionEvent.getInstance(listener, cmd, this));
NaikSoftware/J2meLoader
app/src/main/java/ua/naiksoftware/j2meloader/JarClassLoader.java
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import java.util.HashMap; import java.util.jar.JarFile; import java.util.Enumeration; import java.util.jar.JarEntry; import java.io.IOException; import java.io.InputStream; import filelog.Log;
/** * * Не используется в программе! */ package ua.naiksoftware.j2meloader; public class JarClassLoader extends ClassLoader { private final static String tag = "JarClassLoader"; private final HashMap<String, Class<?>> cache = new HashMap<String, Class<?>>(); private final String jarFileName; private final String packageName; private static final String WARNING = "Warning : No jar file found. Packet unmarshalling won't be possible. Please verify your classpath"; public JarClassLoader(String jarFileName, String packageName) {
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/ua/naiksoftware/j2meloader/JarClassLoader.java import java.util.HashMap; import java.util.jar.JarFile; import java.util.Enumeration; import java.util.jar.JarEntry; import java.io.IOException; import java.io.InputStream; import filelog.Log; /** * * Не используется в программе! */ package ua.naiksoftware.j2meloader; public class JarClassLoader extends ClassLoader { private final static String tag = "JarClassLoader"; private final HashMap<String, Class<?>> cache = new HashMap<String, Class<?>>(); private final String jarFileName; private final String packageName; private static final String WARNING = "Warning : No jar file found. Packet unmarshalling won't be possible. Please verify your classpath"; public JarClassLoader(String jarFileName, String packageName) {
Log.d(tag, ".......JarClassLoader.......");
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/ChoiceGroup.java
// Path: app/src/main/java/javax/microedition/lcdui/list/CompoundSpinnerAdapter.java // public class CompoundSpinnerAdapter extends CompoundAdapter implements SpinnerAdapter // { // public CompoundSpinnerAdapter(Context context) // { // super(context); // } // // public View getView(int position, View convertView, ViewGroup parent) // { // return getView(position, convertView, parent, android.R.layout.simple_spinner_item, false); // } // // public View getDropDownView(int position, View convertView, ViewGroup parent) // { // return getView(position, convertView, parent, android.R.layout.simple_spinner_dropdown_item, true); // } // }
import android.widget.RadioGroup; import android.widget.Spinner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.microedition.lcdui.list.CompoundSpinnerAdapter; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.RadioButton;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class ChoiceGroup extends Item implements Choice { private ArrayList<String> strings = new ArrayList(); private ArrayList<Image> images = new ArrayList(); private ArrayList<CompoundButton> buttons = new ArrayList(); private final ArrayList<Boolean> selected = new ArrayList(); private Spinner spinner;
// Path: app/src/main/java/javax/microedition/lcdui/list/CompoundSpinnerAdapter.java // public class CompoundSpinnerAdapter extends CompoundAdapter implements SpinnerAdapter // { // public CompoundSpinnerAdapter(Context context) // { // super(context); // } // // public View getView(int position, View convertView, ViewGroup parent) // { // return getView(position, convertView, parent, android.R.layout.simple_spinner_item, false); // } // // public View getDropDownView(int position, View convertView, ViewGroup parent) // { // return getView(position, convertView, parent, android.R.layout.simple_spinner_dropdown_item, true); // } // } // Path: app/src/main/java/javax/microedition/lcdui/ChoiceGroup.java import android.widget.RadioGroup; import android.widget.Spinner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.microedition.lcdui.list.CompoundSpinnerAdapter; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.RadioButton; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui; public class ChoiceGroup extends Item implements Choice { private ArrayList<String> strings = new ArrayList(); private ArrayList<Image> images = new ArrayList(); private ArrayList<CompoundButton> buttons = new ArrayList(); private final ArrayList<Boolean> selected = new ArrayList(); private Spinner spinner;
private CompoundSpinnerAdapter adapter;
NaikSoftware/J2meLoader
app/src/main/java/ua/naiksoftware/util/FileUtils.java
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import java.io.*; import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import filelog.Log;
while ((zipEntry = zip.getNextEntry()) != null) { //long free = folderToUnzip.getFreeSpace(); fileName = zipEntry.getName(); final File outputFile = new File(folderToUnzip, fileName); outputFile.getParentFile().mkdirs(); //Log.d("Unzip", "Zip entry: " + fileName + ", extract to: " + outputFile.getPath()); if (fileName.endsWith("/")) { //Log.d("Unzip", fileName+ " is directory"); outputFile.mkdirs(); continue; } else { outputFile.createNewFile(); //if (zipEntry.getSize() == outputFile.length()) { // continue; //} //free = free - zipEntry.getSize() + outputFile.length(); //if (free < MIN_LOCAL_MEMORY) { // error // return false; //} fos = new FileOutputStream(outputFile, false); byte[] bytes = new byte[2048]; int c; try { while ((c = zip.read(bytes)) != -1) { fos.write(bytes, 0, c); } fos.flush(); fos.close(); } catch (IOException e) {
// Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/ua/naiksoftware/util/FileUtils.java import java.io.*; import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import filelog.Log; while ((zipEntry = zip.getNextEntry()) != null) { //long free = folderToUnzip.getFreeSpace(); fileName = zipEntry.getName(); final File outputFile = new File(folderToUnzip, fileName); outputFile.getParentFile().mkdirs(); //Log.d("Unzip", "Zip entry: " + fileName + ", extract to: " + outputFile.getPath()); if (fileName.endsWith("/")) { //Log.d("Unzip", fileName+ " is directory"); outputFile.mkdirs(); continue; } else { outputFile.createNewFile(); //if (zipEntry.getSize() == outputFile.length()) { // continue; //} //free = free - zipEntry.getSize() + outputFile.length(); //if (free < MIN_LOCAL_MEMORY) { // error // return false; //} fos = new FileOutputStream(outputFile, false); byte[] bytes = new byte[2048]; int c; try { while ((c = zip.read(bytes)) != -1) { fos.write(bytes, 0, c); } fos.flush(); fos.close(); } catch (IOException e) {
Log.d("Unzip", "IOErr in readFromStream (zip.read(bytes)): " + e.getMessage());
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/lcdui/event/RunnableEvent.java
// Path: app/src/main/java/javax/microedition/lcdui/Event.java // public abstract class Event implements Runnable // { // // private static int count = 0; // // private int id = count++; // // // // public int getID() // // { // // return id; // // } // // /** // * Обработка события. // * Именно здесь нужно выполнять требуемые действия. // */ // public abstract void process(); // // /** // * Сдача события в утиль. // * // * Если предусмотрен пул событий, то здесь // * событие нужно обнулить и вернуть в пул. // */ // public abstract void recycle(); // // /** // * Обработать событие и сдать в утиль за один прием. // */ // public void run() // { // process(); // recycle(); // } // // /** // * Вызывается, когда событие вошло в очередь. // * Здесь можно увеличить счетчик таких событий в очереди. // */ // public abstract void enterQueue(); // // /** // * Вызывается, когда событие покинуло очередь. // * Здесь можно уменьшить счетчик таких событий в очереди. // */ // public abstract void leaveQueue(); // // /** // * Проверить, можно ли поместить это событие в очередь // * сразу за некоторым другим событием. // * // * @param event событие, после которого нас могут поместить в очередь // * @return true, если мы на это согласны // */ // public abstract boolean placeableAfter(Event event); // } // // Path: app/src/main/java/javax/microedition/util/ArrayStack.java // public class ArrayStack<E> // { // public static final int DELTA = 100; // // protected Object[] data; // protected int index; // // public ArrayStack() // { // clear(); // } // // public void push(E value) // { // if(index >= data.length - 1) // { // Object[] temp = new Object[data.length + DELTA]; // System.arraycopy(data, 0, temp, 0, data.length); // data = temp; // } // // data[++index] = value; // } // // public E pop() // { // if(index < 0) // { // return null; // } // // // if(index + (DELTA << 1) <= data.length - 1) // // { // // Object[] temp = new Object[data.length - DELTA]; // // System.arraycopy(data, 0, temp, 0, temp.length); // // data = temp; // // } // // return (E)data[index--]; // } // // public void clear() // { // data = new Object[0]; // index = -1; // } // // public boolean empty() // { // return index < 0; // } // }
import javax.microedition.lcdui.Event; import javax.microedition.util.ArrayStack;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.event; public class RunnableEvent extends Event {
// Path: app/src/main/java/javax/microedition/lcdui/Event.java // public abstract class Event implements Runnable // { // // private static int count = 0; // // private int id = count++; // // // // public int getID() // // { // // return id; // // } // // /** // * Обработка события. // * Именно здесь нужно выполнять требуемые действия. // */ // public abstract void process(); // // /** // * Сдача события в утиль. // * // * Если предусмотрен пул событий, то здесь // * событие нужно обнулить и вернуть в пул. // */ // public abstract void recycle(); // // /** // * Обработать событие и сдать в утиль за один прием. // */ // public void run() // { // process(); // recycle(); // } // // /** // * Вызывается, когда событие вошло в очередь. // * Здесь можно увеличить счетчик таких событий в очереди. // */ // public abstract void enterQueue(); // // /** // * Вызывается, когда событие покинуло очередь. // * Здесь можно уменьшить счетчик таких событий в очереди. // */ // public abstract void leaveQueue(); // // /** // * Проверить, можно ли поместить это событие в очередь // * сразу за некоторым другим событием. // * // * @param event событие, после которого нас могут поместить в очередь // * @return true, если мы на это согласны // */ // public abstract boolean placeableAfter(Event event); // } // // Path: app/src/main/java/javax/microedition/util/ArrayStack.java // public class ArrayStack<E> // { // public static final int DELTA = 100; // // protected Object[] data; // protected int index; // // public ArrayStack() // { // clear(); // } // // public void push(E value) // { // if(index >= data.length - 1) // { // Object[] temp = new Object[data.length + DELTA]; // System.arraycopy(data, 0, temp, 0, data.length); // data = temp; // } // // data[++index] = value; // } // // public E pop() // { // if(index < 0) // { // return null; // } // // // if(index + (DELTA << 1) <= data.length - 1) // // { // // Object[] temp = new Object[data.length - DELTA]; // // System.arraycopy(data, 0, temp, 0, temp.length); // // data = temp; // // } // // return (E)data[index--]; // } // // public void clear() // { // data = new Object[0]; // index = -1; // } // // public boolean empty() // { // return index < 0; // } // } // Path: app/src/main/java/javax/microedition/lcdui/event/RunnableEvent.java import javax.microedition.lcdui.Event; import javax.microedition.util.ArrayStack; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.lcdui.event; public class RunnableEvent extends Event {
private static ArrayStack<RunnableEvent> recycled = new ArrayStack();
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/io/Connector.java
// Path: app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java // public class BTL2CAPConnectionProvider implements ConnectionProvider // { // public Connection open(String name, int mode) throws IOException // { // if(name.startsWith("localhost:")) // { // String[] params = name.substring(10).split(";"); // name = null; // // for(int i = 1; i < params.length; i++) // { // if(params[i].startsWith("name=")) // { // name = params[i].substring(5); // break; // } // } // // if(name == null) // { // name = "MicroBTL2CAP"; // } // // return new L2CAPConnectionNotifier(BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(name, BTUtils.parseUUID(params[0]))); // } // else // { // String[] params = name.split(";")[0].split(":"); // // BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(BTUtils.validateBluetoothAddress(params[0])); // BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BTUtils.parseUUID(params[1])); // // return new L2CAPConnection(socket); // } // } // } // // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java // public class FileSystemRegistry implements ConnectionProvider // { // public static final String INTERNAL_DISK = "c:/"; // public static final String EXTERNAL_DISK = "e:/"; // // private static Vector roots = new Vector(); // // public static Enumeration listRoots() // { // synchronized(roots) // { // roots.removeAllElements(); // roots.addElement(INTERNAL_DISK); // // String state = Environment.getExternalStorageState(); // // if(Environment.MEDIA_MOUNTED.equals(state) || // Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) // { // roots.addElement(EXTERNAL_DISK); // } // // return roots.elements(); // } // } // // public static String getExternalStoragePath() // { // String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath(); // // if(sdcard.startsWith("/")) // { // sdcard = sdcard.substring(1); // } // // if(!sdcard.endsWith("/")) // { // sdcard += "/"; // } // // return sdcard; // } // // public static String midpFileToAndroid(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // if(name.startsWith(INTERNAL_DISK)) // { // name = name.substring(INTERNAL_DISK.length()); // } // else if(name.startsWith(EXTERNAL_DISK)) // { // name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); // } // // return "/" + name; // } // // public static String androidFileToMIDP(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // String sdcard = getExternalStoragePath(); // // if(name.startsWith(sdcard)) // { // name = EXTERNAL_DISK + name.substring(sdcard.length()); // } // else // { // name = INTERNAL_DISK + name; // } // // return "/" + name; // } // // public Connection open(String name, int mode) // { // return new FileConnection(new File(midpFileToAndroid(name)), (mode & Connector.WRITE) != 0 ? FileConnection.READ_WRITE : FileConnection.READ); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import javax.bluetooth.BTL2CAPConnectionProvider; import javax.microedition.io.file.FileSystemRegistry;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.io; public class Connector { public static final int READ = 1; public static final int READ_WRITE = 3; public static final int WRITE = 2; private static HashMap<String, ConnectionProvider> providers; static {
// Path: app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java // public class BTL2CAPConnectionProvider implements ConnectionProvider // { // public Connection open(String name, int mode) throws IOException // { // if(name.startsWith("localhost:")) // { // String[] params = name.substring(10).split(";"); // name = null; // // for(int i = 1; i < params.length; i++) // { // if(params[i].startsWith("name=")) // { // name = params[i].substring(5); // break; // } // } // // if(name == null) // { // name = "MicroBTL2CAP"; // } // // return new L2CAPConnectionNotifier(BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(name, BTUtils.parseUUID(params[0]))); // } // else // { // String[] params = name.split(";")[0].split(":"); // // BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(BTUtils.validateBluetoothAddress(params[0])); // BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BTUtils.parseUUID(params[1])); // // return new L2CAPConnection(socket); // } // } // } // // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java // public class FileSystemRegistry implements ConnectionProvider // { // public static final String INTERNAL_DISK = "c:/"; // public static final String EXTERNAL_DISK = "e:/"; // // private static Vector roots = new Vector(); // // public static Enumeration listRoots() // { // synchronized(roots) // { // roots.removeAllElements(); // roots.addElement(INTERNAL_DISK); // // String state = Environment.getExternalStorageState(); // // if(Environment.MEDIA_MOUNTED.equals(state) || // Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) // { // roots.addElement(EXTERNAL_DISK); // } // // return roots.elements(); // } // } // // public static String getExternalStoragePath() // { // String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath(); // // if(sdcard.startsWith("/")) // { // sdcard = sdcard.substring(1); // } // // if(!sdcard.endsWith("/")) // { // sdcard += "/"; // } // // return sdcard; // } // // public static String midpFileToAndroid(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // if(name.startsWith(INTERNAL_DISK)) // { // name = name.substring(INTERNAL_DISK.length()); // } // else if(name.startsWith(EXTERNAL_DISK)) // { // name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); // } // // return "/" + name; // } // // public static String androidFileToMIDP(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // String sdcard = getExternalStoragePath(); // // if(name.startsWith(sdcard)) // { // name = EXTERNAL_DISK + name.substring(sdcard.length()); // } // else // { // name = INTERNAL_DISK + name; // } // // return "/" + name; // } // // public Connection open(String name, int mode) // { // return new FileConnection(new File(midpFileToAndroid(name)), (mode & Connector.WRITE) != 0 ? FileConnection.READ_WRITE : FileConnection.READ); // } // } // Path: app/src/main/java/javax/microedition/io/Connector.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import javax.bluetooth.BTL2CAPConnectionProvider; import javax.microedition.io.file.FileSystemRegistry; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.io; public class Connector { public static final int READ = 1; public static final int READ_WRITE = 3; public static final int WRITE = 2; private static HashMap<String, ConnectionProvider> providers; static {
registerConnectionProvider("file", new FileSystemRegistry());
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/io/Connector.java
// Path: app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java // public class BTL2CAPConnectionProvider implements ConnectionProvider // { // public Connection open(String name, int mode) throws IOException // { // if(name.startsWith("localhost:")) // { // String[] params = name.substring(10).split(";"); // name = null; // // for(int i = 1; i < params.length; i++) // { // if(params[i].startsWith("name=")) // { // name = params[i].substring(5); // break; // } // } // // if(name == null) // { // name = "MicroBTL2CAP"; // } // // return new L2CAPConnectionNotifier(BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(name, BTUtils.parseUUID(params[0]))); // } // else // { // String[] params = name.split(";")[0].split(":"); // // BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(BTUtils.validateBluetoothAddress(params[0])); // BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BTUtils.parseUUID(params[1])); // // return new L2CAPConnection(socket); // } // } // } // // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java // public class FileSystemRegistry implements ConnectionProvider // { // public static final String INTERNAL_DISK = "c:/"; // public static final String EXTERNAL_DISK = "e:/"; // // private static Vector roots = new Vector(); // // public static Enumeration listRoots() // { // synchronized(roots) // { // roots.removeAllElements(); // roots.addElement(INTERNAL_DISK); // // String state = Environment.getExternalStorageState(); // // if(Environment.MEDIA_MOUNTED.equals(state) || // Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) // { // roots.addElement(EXTERNAL_DISK); // } // // return roots.elements(); // } // } // // public static String getExternalStoragePath() // { // String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath(); // // if(sdcard.startsWith("/")) // { // sdcard = sdcard.substring(1); // } // // if(!sdcard.endsWith("/")) // { // sdcard += "/"; // } // // return sdcard; // } // // public static String midpFileToAndroid(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // if(name.startsWith(INTERNAL_DISK)) // { // name = name.substring(INTERNAL_DISK.length()); // } // else if(name.startsWith(EXTERNAL_DISK)) // { // name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); // } // // return "/" + name; // } // // public static String androidFileToMIDP(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // String sdcard = getExternalStoragePath(); // // if(name.startsWith(sdcard)) // { // name = EXTERNAL_DISK + name.substring(sdcard.length()); // } // else // { // name = INTERNAL_DISK + name; // } // // return "/" + name; // } // // public Connection open(String name, int mode) // { // return new FileConnection(new File(midpFileToAndroid(name)), (mode & Connector.WRITE) != 0 ? FileConnection.READ_WRITE : FileConnection.READ); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import javax.bluetooth.BTL2CAPConnectionProvider; import javax.microedition.io.file.FileSystemRegistry;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.io; public class Connector { public static final int READ = 1; public static final int READ_WRITE = 3; public static final int WRITE = 2; private static HashMap<String, ConnectionProvider> providers; static { registerConnectionProvider("file", new FileSystemRegistry()); registerConnectionProvider("http", new HttpConnectionProvider());
// Path: app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java // public class BTL2CAPConnectionProvider implements ConnectionProvider // { // public Connection open(String name, int mode) throws IOException // { // if(name.startsWith("localhost:")) // { // String[] params = name.substring(10).split(";"); // name = null; // // for(int i = 1; i < params.length; i++) // { // if(params[i].startsWith("name=")) // { // name = params[i].substring(5); // break; // } // } // // if(name == null) // { // name = "MicroBTL2CAP"; // } // // return new L2CAPConnectionNotifier(BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(name, BTUtils.parseUUID(params[0]))); // } // else // { // String[] params = name.split(";")[0].split(":"); // // BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(BTUtils.validateBluetoothAddress(params[0])); // BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BTUtils.parseUUID(params[1])); // // return new L2CAPConnection(socket); // } // } // } // // Path: app/src/main/java/javax/microedition/io/file/FileSystemRegistry.java // public class FileSystemRegistry implements ConnectionProvider // { // public static final String INTERNAL_DISK = "c:/"; // public static final String EXTERNAL_DISK = "e:/"; // // private static Vector roots = new Vector(); // // public static Enumeration listRoots() // { // synchronized(roots) // { // roots.removeAllElements(); // roots.addElement(INTERNAL_DISK); // // String state = Environment.getExternalStorageState(); // // if(Environment.MEDIA_MOUNTED.equals(state) || // Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) // { // roots.addElement(EXTERNAL_DISK); // } // // return roots.elements(); // } // } // // public static String getExternalStoragePath() // { // String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath(); // // if(sdcard.startsWith("/")) // { // sdcard = sdcard.substring(1); // } // // if(!sdcard.endsWith("/")) // { // sdcard += "/"; // } // // return sdcard; // } // // public static String midpFileToAndroid(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // if(name.startsWith(INTERNAL_DISK)) // { // name = name.substring(INTERNAL_DISK.length()); // } // else if(name.startsWith(EXTERNAL_DISK)) // { // name = getExternalStoragePath() + name.substring(EXTERNAL_DISK.length()); // } // // return "/" + name; // } // // public static String androidFileToMIDP(String name) // { // if(name.startsWith("/")) // { // name = name.substring(1); // } // // String sdcard = getExternalStoragePath(); // // if(name.startsWith(sdcard)) // { // name = EXTERNAL_DISK + name.substring(sdcard.length()); // } // else // { // name = INTERNAL_DISK + name; // } // // return "/" + name; // } // // public Connection open(String name, int mode) // { // return new FileConnection(new File(midpFileToAndroid(name)), (mode & Connector.WRITE) != 0 ? FileConnection.READ_WRITE : FileConnection.READ); // } // } // Path: app/src/main/java/javax/microedition/io/Connector.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import javax.bluetooth.BTL2CAPConnectionProvider; import javax.microedition.io.file.FileSystemRegistry; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.io; public class Connector { public static final int READ = 1; public static final int READ_WRITE = 3; public static final int WRITE = 2; private static HashMap<String, ConnectionProvider> providers; static { registerConnectionProvider("file", new FileSystemRegistry()); registerConnectionProvider("http", new HttpConnectionProvider());
registerConnectionProvider("btl2cap", new BTL2CAPConnectionProvider());
NaikSoftware/J2meLoader
app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log;
} /** * Per the navigation drawer design guidelines, updates the action bar to * show the global app 'context', rather than just what's in the current * screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.open_jar); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } /** * Callbacks interface that all activities using this fragment must * implement. */ public static interface SelectedCallback { /** * Called when clicked on file */ void onSelected(String path); } private void readFolder(String folderStr) {
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log; } /** * Per the navigation drawer design guidelines, updates the action bar to * show the global app 'context', rather than just what's in the current * screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.open_jar); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } /** * Callbacks interface that all activities using this fragment must * implement. */ public static interface SelectedCallback { /** * Called when clicked on file */ void onSelected(String path); } private void readFolder(String folderStr) {
Log.d(tag, "read : " + folderStr);
NaikSoftware/J2meLoader
app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log;
private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.open_jar); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } /** * Callbacks interface that all activities using this fragment must * implement. */ public static interface SelectedCallback { /** * Called when clicked on file */ void onSelected(String path); } private void readFolder(String folderStr) { Log.d(tag, "read : " + folderStr); String[] lsOutputDet;// Детальная информация String[] names; String error; try { java.lang.Process proc = new ProcessBuilder().command("ls", "-l", "-a", folderStr + "/").start();
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log; private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.open_jar); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } /** * Callbacks interface that all activities using this fragment must * implement. */ public static interface SelectedCallback { /** * Called when clicked on file */ void onSelected(String path); } private void readFolder(String folderStr) { Log.d(tag, "read : " + folderStr); String[] lsOutputDet;// Детальная информация String[] names; String error; try { java.lang.Process proc = new ProcessBuilder().command("ls", "-l", "-a", folderStr + "/").start();
lsOutputDet = ProcessUtils.readFromProcess(proc, false).split("\n");
NaikSoftware/J2meLoader
app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // }
import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log;
subheader.toString(), FSItem.Type.Folder)); } else {// если файл String ext = getExtension(names[j]);// get extension from name if (!mapExt.containsKey(ext)) { continue; // пропускаем все ненужные файлы } int iconId = mapExt.get(ext); subheader.append(arr[4]).append(' ').append(arr[5]);// date file subheader.append(' ').append(calcSize(Long.parseLong(arr[3]))); listFile.add(new FSItem(iconId, names[j], subheader.toString(), FSItem.Type.File)); } } Collections.sort(listFolder, comparator); Collections.sort(listFile, comparator); items.addAll(listFolder.subList(0, listFolder.size())); items.addAll(listFile.subList(0, listFile.size())); mDrawerListView.setAdapter(new FileListAdapter(getActionBar() .getThemedContext(), items)); fullPath.setText(currPath); } /* * calc file size in b, Kb or Mb */ private String calcSize(long length) { if (length < 1024) { return String.valueOf(length).concat(" b"); } else if (length < 1048576) {
// Path: app/src/main/java/ua/naiksoftware/util/ProcessUtils.java // public class ProcessUtils { // // public static String readFromProcess(java.lang.Process process, boolean err) { // StringBuilder result = new StringBuilder(); // String line; // BufferedReader br = new BufferedReader(new InputStreamReader(err ? process.getErrorStream() : process.getInputStream())); // try { // while ((line = br.readLine()) != null) { // result.append(line).append("\n"); // } // } catch (IOException e) { // //Log.e("Main", "read From Process", e); // } // return result.toString(); // } // } // // Path: app/src/main/java/ua/naiksoftware/util/MathUtils.java // public class MathUtils { // // /** // * // * @param sourceNum // * @return rounded to two decimal places // */ // public static float round(float sourceNum) { // int temp = (int) (sourceNum / 0.01f); // return temp / 100f; // } // } // // Path: app/src/main/java/filelog/Log.java // public class Log { // // private static final String token = " : "; // private static final long MAX_LEN = 300 * 1024;//50 Kb // // public static void d(String tag, String message) { // try { // boolean noClear; // File file = new File(Environment.getExternalStorageDirectory(), "log_j2meloader.txt"); // if (file.length() > MAX_LEN) { // noClear = false; // } else { // noClear = true; // } // FileWriter fw = new FileWriter(file, noClear); // String msg = "\n" + new Date().toLocaleString() + token + tag + token + message; // fw.write(msg); // fw.flush(); // fw.close(); // //Log.d("L", msg); // } catch (IOException e) { // android.util.Log.e("L", "err in logging", e); // } // } // } // Path: app/src/main/java/ua/naiksoftware/j2meloader/NavigationDrawerFragment.java import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import android.widget.TextView; import ua.naiksoftware.util.ProcessUtils; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Collections; import ua.naiksoftware.util.MathUtils; import filelog.Log; subheader.toString(), FSItem.Type.Folder)); } else {// если файл String ext = getExtension(names[j]);// get extension from name if (!mapExt.containsKey(ext)) { continue; // пропускаем все ненужные файлы } int iconId = mapExt.get(ext); subheader.append(arr[4]).append(' ').append(arr[5]);// date file subheader.append(' ').append(calcSize(Long.parseLong(arr[3]))); listFile.add(new FSItem(iconId, names[j], subheader.toString(), FSItem.Type.File)); } } Collections.sort(listFolder, comparator); Collections.sort(listFile, comparator); items.addAll(listFolder.subList(0, listFolder.size())); items.addAll(listFile.subList(0, listFile.size())); mDrawerListView.setAdapter(new FileListAdapter(getActionBar() .getThemedContext(), items)); fullPath.setText(currPath); } /* * calc file size in b, Kb or Mb */ private String calcSize(long length) { if (length < 1024) { return String.valueOf(length).concat(" b"); } else if (length < 1048576) {
return String.valueOf(MathUtils.round((float) length / 1024f))
NaikSoftware/J2meLoader
app/src/main/java/javax/microedition/media/control/VideoControl.java
// Path: app/src/main/java/javax/microedition/media/MediaException.java // public class MediaException extends Exception // { // public MediaException(Exception e) // { // super(e); // } // // public MediaException(String message) // { // super(message); // } // }
import javax.microedition.media.Control; import javax.microedition.media.MediaException;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.media.control; public interface VideoControl extends Control { public static final int USE_DIRECT_VIDEO = 1; public Object initDisplayMode(int mode, Object arg); public void setDisplayLocation(int x, int y);
// Path: app/src/main/java/javax/microedition/media/MediaException.java // public class MediaException extends Exception // { // public MediaException(Exception e) // { // super(e); // } // // public MediaException(String message) // { // super(message); // } // } // Path: app/src/main/java/javax/microedition/media/control/VideoControl.java import javax.microedition.media.Control; import javax.microedition.media.MediaException; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.microedition.media.control; public interface VideoControl extends Control { public static final int USE_DIRECT_VIDEO = 1; public Object initDisplayMode(int mode, Object arg); public void setDisplayLocation(int x, int y);
public void setDisplaySize(int width, int height) throws MediaException;
NaikSoftware/J2meLoader
app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // }
import java.io.IOException; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket;
/* * Copyright 2012 Kulikov Dmitriy * * 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 javax.bluetooth; public class BTL2CAPConnectionProvider implements ConnectionProvider {
// Path: app/src/main/java/javax/microedition/io/Connection.java // public interface Connection // { // public void close() throws IOException; // } // // Path: app/src/main/java/javax/microedition/io/ConnectionProvider.java // public interface ConnectionProvider // { // public Connection open(String name, int mode) throws IOException; // } // Path: app/src/main/java/javax/bluetooth/BTL2CAPConnectionProvider.java import java.io.IOException; import javax.microedition.io.Connection; import javax.microedition.io.ConnectionProvider; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; /* * Copyright 2012 Kulikov Dmitriy * * 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 javax.bluetooth; public class BTL2CAPConnectionProvider implements ConnectionProvider {
public Connection open(String name, int mode) throws IOException
ianturton/geotools-cookbook
modules/styling/src/main/java/org/ianturton/cookbook/styling/TwoAttributes.java
// Path: modules/output/src/main/java/org/ianturton/cookbook/output/SaveMapAsImage.java // public class SaveMapAsImage { // // private JMapFrame frame; // private MapContent mapContent; // // public static void main(String[] args) throws IOException { // File file = null; // if (args.length == 0) { // // display a data store file chooser dialog for shapefiles // file = JFileDataStoreChooser.showOpenFile("shp", null); // if (file == null) { // return; // } // } else { // file = new File(args[0]); // if (!file.exists()) { // System.err.println(file + " doesn't exist"); // return; // } // } // new SaveMapAsImage(file); // } // // public SaveMapAsImage(File file) throws IOException { // // FileDataStore store = FileDataStoreFinder.getDataStore(file); // SimpleFeatureSource featureSource = store.getFeatureSource(); // // // Create a map content and add our shapefile to it // mapContent = new MapContent(); // mapContent.setTitle("GeoTools Mapping"); // Style style = SLD.createSimpleStyle(featureSource.getSchema()); // Layer layer = new FeatureLayer(featureSource, style); // mapContent.addLayer(layer); // frame = new JMapFrame(mapContent); // frame.enableStatusBar(true); // frame.enableToolBar(true); // JToolBar toolBar = frame.getToolBar(); // toolBar.addSeparator(); // SaveAction save = new SaveAction("Save"); // toolBar.add(save); // frame.initComponents(); // frame.setSize(1000, 500); // frame.setVisible(true); // } // // public SaveMapAsImage() { // // TODO Auto-generated constructor stub // } // // public void drawMapToImage(File outputFile) { // this.drawMapToImage(outputFile, "image/png"); // } // // public void drawMapToImage(File outputFile, String outputType) { // JMapPane mapPane = frame.getMapPane(); // this.drawMapToImage(outputFile, outputType, mapPane); // } // // public void drawMapToImage(File outputFile, String outputType, // JMapPane mapPane) { // ImageOutputStream outputImageFile = null; // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = new FileOutputStream(outputFile); // outputImageFile = ImageIO.createImageOutputStream(fileOutputStream); // RenderedImage bufferedImage = mapPane.getBaseImage(); // ImageIO.write(bufferedImage, outputType, outputImageFile); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // try { // if (outputImageFile != null) { // outputImageFile.flush(); // outputImageFile.close(); // fileOutputStream.flush(); // fileOutputStream.close(); // } // } catch (IOException e) {// don't care now // } // } // } // // private class SaveAction extends AbstractAction { // /** // * Private SaveAction // */ // private static final long serialVersionUID = 3071568727121984649L; // // public SaveAction(String text) { // super(text); // } // // @Override // public void actionPerformed(ActionEvent arg0) { // String[] writers = ImageIO.getWriterFormatNames(); // // String format = (String) JOptionPane.showInputDialog(frame, // "Choose output format:", "Customized Dialog", // JOptionPane.PLAIN_MESSAGE, null, writers, "png"); // drawMapToImage(new File("ian." + format), format); // // } // // } // }
import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import javax.swing.JToolBar; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.styling.SLD; import org.geotools.styling.Style; import org.geotools.swing.JMapFrame; import org.ianturton.cookbook.output.SaveMapAsImage; import org.opengis.feature.simple.SimpleFeatureType;
package org.ianturton.cookbook.styling; public class TwoAttributes { private File infile; private File outFile;
// Path: modules/output/src/main/java/org/ianturton/cookbook/output/SaveMapAsImage.java // public class SaveMapAsImage { // // private JMapFrame frame; // private MapContent mapContent; // // public static void main(String[] args) throws IOException { // File file = null; // if (args.length == 0) { // // display a data store file chooser dialog for shapefiles // file = JFileDataStoreChooser.showOpenFile("shp", null); // if (file == null) { // return; // } // } else { // file = new File(args[0]); // if (!file.exists()) { // System.err.println(file + " doesn't exist"); // return; // } // } // new SaveMapAsImage(file); // } // // public SaveMapAsImage(File file) throws IOException { // // FileDataStore store = FileDataStoreFinder.getDataStore(file); // SimpleFeatureSource featureSource = store.getFeatureSource(); // // // Create a map content and add our shapefile to it // mapContent = new MapContent(); // mapContent.setTitle("GeoTools Mapping"); // Style style = SLD.createSimpleStyle(featureSource.getSchema()); // Layer layer = new FeatureLayer(featureSource, style); // mapContent.addLayer(layer); // frame = new JMapFrame(mapContent); // frame.enableStatusBar(true); // frame.enableToolBar(true); // JToolBar toolBar = frame.getToolBar(); // toolBar.addSeparator(); // SaveAction save = new SaveAction("Save"); // toolBar.add(save); // frame.initComponents(); // frame.setSize(1000, 500); // frame.setVisible(true); // } // // public SaveMapAsImage() { // // TODO Auto-generated constructor stub // } // // public void drawMapToImage(File outputFile) { // this.drawMapToImage(outputFile, "image/png"); // } // // public void drawMapToImage(File outputFile, String outputType) { // JMapPane mapPane = frame.getMapPane(); // this.drawMapToImage(outputFile, outputType, mapPane); // } // // public void drawMapToImage(File outputFile, String outputType, // JMapPane mapPane) { // ImageOutputStream outputImageFile = null; // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = new FileOutputStream(outputFile); // outputImageFile = ImageIO.createImageOutputStream(fileOutputStream); // RenderedImage bufferedImage = mapPane.getBaseImage(); // ImageIO.write(bufferedImage, outputType, outputImageFile); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // try { // if (outputImageFile != null) { // outputImageFile.flush(); // outputImageFile.close(); // fileOutputStream.flush(); // fileOutputStream.close(); // } // } catch (IOException e) {// don't care now // } // } // } // // private class SaveAction extends AbstractAction { // /** // * Private SaveAction // */ // private static final long serialVersionUID = 3071568727121984649L; // // public SaveAction(String text) { // super(text); // } // // @Override // public void actionPerformed(ActionEvent arg0) { // String[] writers = ImageIO.getWriterFormatNames(); // // String format = (String) JOptionPane.showInputDialog(frame, // "Choose output format:", "Customized Dialog", // JOptionPane.PLAIN_MESSAGE, null, writers, "png"); // drawMapToImage(new File("ian." + format), format); // // } // // } // } // Path: modules/styling/src/main/java/org/ianturton/cookbook/styling/TwoAttributes.java import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import javax.swing.JToolBar; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.styling.SLD; import org.geotools.styling.Style; import org.geotools.swing.JMapFrame; import org.ianturton.cookbook.output.SaveMapAsImage; import org.opengis.feature.simple.SimpleFeatureType; package org.ianturton.cookbook.styling; public class TwoAttributes { private File infile; private File outFile;
SaveMapAsImage saver = new SaveMapAsImage();
asLody/TurboDex
project/example/app/src/main/java/com/tbd/example/MyApplication.java
// Path: project/turbodex/turbodex/src/main/java/com/lody/turbodex/TurboDex.java // public class TurboDex { // // static { // System.loadLibrary("turbo-dex"); // } // // static native void nativeEnableTurboDex(); // // static native void nativeDisableTurboDex(); // // public static boolean enableTurboDex() { // if (isArtMode()) { // try { // nativeEnableTurboDex(); // return true; // } catch (Throwable e) { // e.printStackTrace(); // } // } // return false; // } // // public static void disableTurboDex() { // try { // nativeDisableTurboDex(); // } catch (Throwable e) { // e.printStackTrace(); // } // } // // // /** // * In current version, only enable TBD at ART mode. // * // * @return current Environment is ART mode // */ // private static boolean isArtMode() { // return System.getProperty("java.vm.version", "").startsWith("2"); // } // }
import android.app.Application; import android.content.Context; import com.lody.turbodex.TurboDex; import dalvik.system.DexClassLoader;
package com.tbd.example; /** * @author Lody * @version 1.0 */ public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) {
// Path: project/turbodex/turbodex/src/main/java/com/lody/turbodex/TurboDex.java // public class TurboDex { // // static { // System.loadLibrary("turbo-dex"); // } // // static native void nativeEnableTurboDex(); // // static native void nativeDisableTurboDex(); // // public static boolean enableTurboDex() { // if (isArtMode()) { // try { // nativeEnableTurboDex(); // return true; // } catch (Throwable e) { // e.printStackTrace(); // } // } // return false; // } // // public static void disableTurboDex() { // try { // nativeDisableTurboDex(); // } catch (Throwable e) { // e.printStackTrace(); // } // } // // // /** // * In current version, only enable TBD at ART mode. // * // * @return current Environment is ART mode // */ // private static boolean isArtMode() { // return System.getProperty("java.vm.version", "").startsWith("2"); // } // } // Path: project/example/app/src/main/java/com/tbd/example/MyApplication.java import android.app.Application; import android.content.Context; import com.lody.turbodex.TurboDex; import dalvik.system.DexClassLoader; package com.tbd.example; /** * @author Lody * @version 1.0 */ public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) {
TurboDex.enableTurboDex();
asLody/TurboDex
project/turbodex/app/src/main/java/com/tbd/app/Application.java
// Path: project/turbodex/turbodex/src/main/java/com/lody/turbodex/TurboDex.java // public class TurboDex { // // static { // System.loadLibrary("turbo-dex"); // } // // static native void nativeEnableTurboDex(); // // static native void nativeDisableTurboDex(); // // public static boolean enableTurboDex() { // if (isArtMode()) { // try { // nativeEnableTurboDex(); // return true; // } catch (Throwable e) { // e.printStackTrace(); // } // } // return false; // } // // public static void disableTurboDex() { // try { // nativeDisableTurboDex(); // } catch (Throwable e) { // e.printStackTrace(); // } // } // // // /** // * In current version, only enable TBD at ART mode. // * // * @return current Environment is ART mode // */ // private static boolean isArtMode() { // return System.getProperty("java.vm.version", "").startsWith("2"); // } // }
import android.content.Context; import com.lody.turbodex.TurboDex;
package com.tbd.app; /** * Created by qiujuer * on 16/4/22. */ public class Application extends android.app.Application { @Override protected void attachBaseContext(Context base) {
// Path: project/turbodex/turbodex/src/main/java/com/lody/turbodex/TurboDex.java // public class TurboDex { // // static { // System.loadLibrary("turbo-dex"); // } // // static native void nativeEnableTurboDex(); // // static native void nativeDisableTurboDex(); // // public static boolean enableTurboDex() { // if (isArtMode()) { // try { // nativeEnableTurboDex(); // return true; // } catch (Throwable e) { // e.printStackTrace(); // } // } // return false; // } // // public static void disableTurboDex() { // try { // nativeDisableTurboDex(); // } catch (Throwable e) { // e.printStackTrace(); // } // } // // // /** // * In current version, only enable TBD at ART mode. // * // * @return current Environment is ART mode // */ // private static boolean isArtMode() { // return System.getProperty("java.vm.version", "").startsWith("2"); // } // } // Path: project/turbodex/app/src/main/java/com/tbd/app/Application.java import android.content.Context; import com.lody.turbodex.TurboDex; package com.tbd.app; /** * Created by qiujuer * on 16/4/22. */ public class Application extends android.app.Application { @Override protected void attachBaseContext(Context base) {
TurboDex.enableTurboDex();
programus/java-experiments
refs/JavaTraining/src/com/ibm/javabasic/research/_00_ref/e3/TestPrint.java
// Path: refs/JavaTraining/src/com/ibm/javabasic/research/_00_ref/User.java // public class User { // // private String name; // // public User() { // } // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String toString() { // return "Name(" + this.name + ")"; // } // }
import com.ibm.javabasic.research._00_ref.User;
package com.ibm.javabasic.research._00_ref.e3; public class TestPrint { public static void main(String[] arg) { // What's the output? And why?
// Path: refs/JavaTraining/src/com/ibm/javabasic/research/_00_ref/User.java // public class User { // // private String name; // // public User() { // } // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String toString() { // return "Name(" + this.name + ")"; // } // } // Path: refs/JavaTraining/src/com/ibm/javabasic/research/_00_ref/e3/TestPrint.java import com.ibm.javabasic.research._00_ref.User; package com.ibm.javabasic.research._00_ref.e3; public class TestPrint { public static void main(String[] arg) { // What's the output? And why?
User a = new User("AAA");
Maximuspayne/NavyCraft2-Lite
src/com/maximuspayne/navycraft/NavyCraft_EntityListener.java
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // }
import org.bukkit.Location; import org.bukkit.entity.Egg; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.plugin.Plugin; import com.maximuspayne.navycraft.plugins.PermissionInterface;
} } } } NavyCraft.shotTNTList.remove(ent.getUniqueId()); } else structureUpdate(event.getLocation(), null); } } } public Craft structureUpdate(Location loc, Player causer) { Craft testcraft = Craft.getCraft(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if( testcraft != null ) { CraftMover cm = new CraftMover(testcraft, plugin); cm.structureUpdate(causer,false); return testcraft; } return null; } @EventHandler(priority = EventPriority.HIGH) public void onCreatureSpawn(CreatureSpawnEvent event) {
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // } // Path: src/com/maximuspayne/navycraft/NavyCraft_EntityListener.java import org.bukkit.Location; import org.bukkit.entity.Egg; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.plugin.Plugin; import com.maximuspayne.navycraft.plugins.PermissionInterface; } } } } NavyCraft.shotTNTList.remove(ent.getUniqueId()); } else structureUpdate(event.getLocation(), null); } } } public Craft structureUpdate(Location loc, Player causer) { Craft testcraft = Craft.getCraft(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if( testcraft != null ) { CraftMover cm = new CraftMover(testcraft, plugin); cm.structureUpdate(causer,false); return testcraft; } return null; } @EventHandler(priority = EventPriority.HIGH) public void onCreatureSpawn(CreatureSpawnEvent event) {
if( PermissionInterface.CheckEnabledWorld(event.getEntity().getLocation()) )
Maximuspayne/NavyCraft2-Lite
src/com/maximuspayne/navycraft/MoveCraft_EntityListener.java
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // }
import org.bukkit.Location; import org.bukkit.entity.Egg; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.plugin.Plugin; import com.maximuspayne.navycraft.plugins.PermissionInterface;
} } } } NavyCraft.shotTNTList.remove(ent.getUniqueId()); } else structureUpdate(event.getLocation(), null); } } } public Craft structureUpdate(Location loc, Player causer) { Craft testcraft = Craft.getCraft(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if( testcraft != null ) { CraftMover cm = new CraftMover(testcraft, plugin); cm.structureUpdate(causer,false); return testcraft; } return null; } @EventHandler(priority = EventPriority.HIGH) public void onCreatureSpawn(CreatureSpawnEvent event) {
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // } // Path: src/com/maximuspayne/navycraft/MoveCraft_EntityListener.java import org.bukkit.Location; import org.bukkit.entity.Egg; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.plugin.Plugin; import com.maximuspayne.navycraft.plugins.PermissionInterface; } } } } NavyCraft.shotTNTList.remove(ent.getUniqueId()); } else structureUpdate(event.getLocation(), null); } } } public Craft structureUpdate(Location loc, Player causer) { Craft testcraft = Craft.getCraft(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); if( testcraft != null ) { CraftMover cm = new CraftMover(testcraft, plugin); cm.structureUpdate(causer,false); return testcraft; } return null; } @EventHandler(priority = EventPriority.HIGH) public void onCreatureSpawn(CreatureSpawnEvent event) {
if( PermissionInterface.CheckEnabledWorld(event.getEntity().getLocation()) )
Maximuspayne/NavyCraft2-Lite
src/com/maximuspayne/navycraft/CraftType.java
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // }
import java.io.*; import java.util.ArrayList; import org.bukkit.entity.Player; import com.maximuspayne.navycraft.plugins.PermissionInterface;
if(NavyCraft.instance.ConfigSetting("ForbiddenBlocks") != "null") { bob = NavyCraft.instance.ConfigSetting("ForbiddenBlocks").split(","); juan = new short[bob.length]; for(int i = 0; i < bob.length; i++) { try { juan[i] = Short.parseShort(bob[i]); } catch (Exception ex){ } } if(juan != null && juan.length > 0 && juan[0] != 0) forbiddenBlocks = juan; } } public static CraftType getCraftType(String name) { for (CraftType type : craftTypes) { if (type.name.equalsIgnoreCase(name)) return type; } return null; } public String getCommand() { return "/" + name.toLowerCase(); } public Boolean canUse(Player player){
// Path: src/com/maximuspayne/navycraft/plugins/PermissionInterface.java // public class PermissionInterface { // public static NavyCraft plugin; // //public static PermissionInfo Permissions = null; // // public static void setupPermissions(NavyCraft p) { // plugin = p; // PluginManager pm = NavyCraft.instance.getServer().getPluginManager(); // if(pm != null) { // pm.addPermission(new Permission("navycraft.periscope.use")); // pm.addPermission(new Permission("navycraft.aa-gun.use")); // pm.addPermission(new Permission("navycraft.periscope.create")); // pm.addPermission(new Permission("navycraft.aa-gun.create")); // // for (CraftType type : CraftType.craftTypes) // { // pm.addPermission(new Permission("navycraft." + type.name + ".release")); // pm.addPermission(new Permission("navycraft." + type.name + ".info")); // pm.addPermission(new Permission("navycraft." + type.name + ".takeover")); // pm.addPermission(new Permission("navycraft." + type.name + ".start")); // pm.addPermission(new Permission("navycraft." + type.name + ".create")); // pm.addPermission(new Permission("navycraft." + type.name + ".sink")); // pm.addPermission(new Permission("navycraft." + type.name + ".remove")); // } // } // } // // // // public static boolean CheckPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckQuietPerm(Player player, String command) { // command = command.replace(" ", "."); // NavyCraft.instance.DebugMessage("Checking if " + player.getName() + " can " + command, 3); // // // if( player.hasPermission(command) || player.isOp() ) // { // NavyCraft.instance.DebugMessage("Player has permissions: " + command, 3); // NavyCraft.instance.DebugMessage("Player isop: " + // player.isOp(), 3); // return true; // } else // { // //player.sendMessage("You do not have permission to perform " + command); // return false; // } // } // // public static boolean CheckEnabledWorld(Location loc) { // if(!plugin.ConfigSetting("EnabledWorlds").equalsIgnoreCase("null")) { // String[] worlds = NavyCraft.instance.ConfigSetting("EnabledWorlds").split(","); // for(int i = 0; i < worlds.length; i++) { // if( loc.getWorld().getName().equalsIgnoreCase(worlds[i]) ) // { // return true; // } // // } // return false; // } // return true; // } // } // Path: src/com/maximuspayne/navycraft/CraftType.java import java.io.*; import java.util.ArrayList; import org.bukkit.entity.Player; import com.maximuspayne.navycraft.plugins.PermissionInterface; if(NavyCraft.instance.ConfigSetting("ForbiddenBlocks") != "null") { bob = NavyCraft.instance.ConfigSetting("ForbiddenBlocks").split(","); juan = new short[bob.length]; for(int i = 0; i < bob.length; i++) { try { juan[i] = Short.parseShort(bob[i]); } catch (Exception ex){ } } if(juan != null && juan.length > 0 && juan[0] != 0) forbiddenBlocks = juan; } } public static CraftType getCraftType(String name) { for (CraftType type : craftTypes) { if (type.name.equalsIgnoreCase(name)) return type; } return null; } public String getCommand() { return "/" + name.toLowerCase(); } public Boolean canUse(Player player){
if(PermissionInterface.CheckPerm(player, "navycraft." + name.toLowerCase()))
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/test/java/enterprisegeeks/action/AuthActionTest.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.MessageUtil; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.MockitoAnnotations; import util.PrivateUtil;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; /** * AuthActionのテスト * mockおよびリフレクションによる方法 */ public class AuthActionTest { @Mock(name="message")
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // } // Path: try_java_ee7-web/src/test/java/enterprisegeeks/action/AuthActionTest.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.MessageUtil; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.MockitoAnnotations; import util.PrivateUtil; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; /** * AuthActionのテスト * mockおよびリフレクションによる方法 */ public class AuthActionTest { @Mock(name="message")
private MessageUtil message;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/test/java/enterprisegeeks/action/AuthActionTest.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.MessageUtil; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.MockitoAnnotations; import util.PrivateUtil;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; /** * AuthActionのテスト * mockおよびリフレクションによる方法 */ public class AuthActionTest { @Mock(name="message") private MessageUtil message; @Mock(name="service")
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // } // Path: try_java_ee7-web/src/test/java/enterprisegeeks/action/AuthActionTest.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.MessageUtil; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.MockitoAnnotations; import util.PrivateUtil; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; /** * AuthActionのテスト * mockおよびリフレクションによる方法 */ public class AuthActionTest { @Mock(name="message") private MessageUtil message; @Mock(name="service")
private Service service;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject
private Auth auth;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject
private Service service;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject
private MessageUtil message;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject private MessageUtil message; /** 初期画面からログインする */ public String enter() {
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject private MessageUtil message; /** 初期画面からログインする */ public String enter() {
Account account = auth.getAccount();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject private MessageUtil message; /** 初期画面からログインする */ public String enter() { Account account = auth.getAccount();
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/Gravater.java // public class Gravater { // // private static String hex(byte[] array) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < array.length; ++i) { // sb.append(Integer.toHexString((array[i] // & 0xFF) | 0x100).substring(1, 3)); // } // return sb.toString(); // } // // public static String md5Hex(String message) { // try { // MessageDigest md // = MessageDigest.getInstance("MD5"); // return hex(md.digest(message.getBytes("CP1252"))); // } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { // return null; // } // } // // public static void main(String[] args) { // // // System.out.println(Gravater.md5Hex("[email protected]")); // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/util/MessageUtil.java // @ApplicationScoped // public class MessageUtil { // // public void addMessage(String cliendId, String messageId) { // FacesContext fc = FacesContext.getCurrentInstance(); // String message = fc.getApplication().getResourceBundle(fc, "msg") // .getString(messageId); // fc.addMessage(cliendId, new FacesMessage(message)); // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/action/AuthAction.java import enterprisegeeks.entity.Account; import enterprisegeeks.model.Auth; import enterprisegeeks.service.Service; import enterprisegeeks.util.Gravater; import enterprisegeeks.util.MessageUtil; import java.util.ResourceBundle; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.action; @RequestScoped @Named @Transactional public class AuthAction { @Inject private Auth auth; @Inject private Service service; @Inject private MessageUtil message; /** 初期画面からログインする */ public String enter() { Account account = auth.getAccount();
account.setGravaterHash(Gravater.md5Hex(account.getEmail()));
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Message.java // @XmlRootElement // public class Message { // // private String key; // private String message; // // public Message(){} // // public static Message of(String key, String message) { // Message m = new Message(); // m.key = key; // m.message = message; // return m; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // }
import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.dto.Message; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * */ @ApplicationScoped public class ResponseUtil{ @Inject @MessageResource private ResourceBundle messages; /* * バリデーションエラー時に通知するレスポンスを作成する。 */ public Response buildValidErrorResponce(String key, String messageKey) { String message = messages.getString(messageKey); return Response.status(400).type(MediaType.APPLICATION_JSON)
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Message.java // @XmlRootElement // public class Message { // // private String key; // private String message; // // public Message(){} // // public static Message of(String key, String message) { // Message m = new Message(); // m.key = key; // m.message = message; // return m; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.dto.Message; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * */ @ApplicationScoped public class ResponseUtil{ @Inject @MessageResource private ResourceBundle messages; /* * バリデーションエラー時に通知するレスポンスを作成する。 */ public Response buildValidErrorResponce(String key, String messageKey) { String message = messages.getString(messageKey); return Response.status(400).type(MediaType.APPLICATION_JSON)
.entity(new Message[]{Message.of(key, message)}).build();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/model/ChatRoom.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.Dependent; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * ChatRoom viewで使用するデータ構造 */ @Dependent public class ChatRoom implements Serializable{ /** チャットルーム一覧 */
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/ChatRoom.java import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.Dependent; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * ChatRoom viewで使用するデータ構造 */ @Dependent public class ChatRoom implements Serializable{ /** チャットルーム一覧 */
private List<Room> rooms = new ArrayList<>();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/model/ChatRoom.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.Dependent; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * ChatRoom viewで使用するデータ構造 */ @Dependent public class ChatRoom implements Serializable{ /** チャットルーム一覧 */ private List<Room> rooms = new ArrayList<>(); /** 現在選択されているチャットルームのチャット一覧 */
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/ChatRoom.java import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.Dependent; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * ChatRoom viewで使用するデータ構造 */ @Dependent public class ChatRoom implements Serializable{ /** チャットルーム一覧 */ private List<Room> rooms = new ArrayList<>(); /** 現在選択されているチャットルームのチャット一覧 */
private List<Chat> chats = new ArrayList<>();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/listener/LoginListener.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // }
import enterprisegeeks.model.Auth; import javax.enterprise.context.RequestScoped; import javax.faces.application.ConfigurableNavigationHandler; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.listener; /** *ログイン済みかどうかを判定し、遷移先を決定する。 */ @RequestScoped @Named("loginListener") public class LoginListener{ @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java // @SessionScoped // @Named // public class Auth implements Serializable{ // // private boolean loggedIn; // // private Room selected; // // private Account account = new Account(); // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // public Room getSelected() { // return selected; // } // // public void setSelected(Room selected) { // this.selected = selected; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/listener/LoginListener.java import enterprisegeeks.model.Auth; import javax.enterprise.context.RequestScoped; import javax.faces.application.ConfigurableNavigationHandler; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.listener; /** *ログイン済みかどうかを判定し、遷移先を決定する。 */ @RequestScoped @Named("loginListener") public class LoginListener{ @Inject
private Auth auth;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject
private Service service;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject
private ResponseUtil util;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject private ResponseUtil util; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject private ResponseUtil util; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Token join(@Valid Account account) {
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject private ResponseUtil util; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/ResponseUtil.java // @ApplicationScoped // public class ResponseUtil{ // // @Inject // @MessageResource // private ResourceBundle messages; // // /* // * バリデーションエラー時に通知するレスポンスを作成する。 // */ // public Response buildValidErrorResponce(String key, String messageKey) { // // String message = messages.getString(messageKey); // // return Response.status(400).type(MediaType.APPLICATION_JSON) // .entity(new Message[]{Message.of(key, message)}).build(); // // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Token.java // public class Token { // // private String token; // // public Token(){} // public Token(String token) { // this.token = token; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/JoinResource.java import enterprisegeeks.entity.Account; import enterprisegeeks.rest.ResponseUtil; import enterprisegeeks.rest.dto.Token; import enterprisegeeks.service.Service; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("join") @RequestScoped @Transactional public class JoinResource { @Inject private Service service; @Inject private ResponseUtil util; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Token join(@Valid Account account) {
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/BeanValidationExceptionMapper.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Message.java // @XmlRootElement // public class Message { // // private String key; // private String message; // // public Message(){} // // public static Message of(String key, String message) { // Message m = new Message(); // m.key = key; // m.message = message; // return m; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // }
import enterprisegeeks.rest.dto.Message; import java.util.List; import java.util.stream.Collectors; import javax.json.JsonStructure; import javax.validation.ConstraintViolationException; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * Bean Validationの例外に対するマッピング。 * * エラーメッセージをレスポンスに設定する。 */ @Provider // 特定の例外に対して、処理を行う。Providerアノテーションで自動判別される。 public class BeanValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { @Override @Produces(MediaType.APPLICATION_JSON) public Response toResponse(ConstraintViolationException exception) { // メソッドの戻り値が List<SomeObject> の場合は、List形式のデータを返しても動作する。 // が、Responseを返す場合は、entity()にlistを渡すと、ジェネリクスが解消できないので、 // 正常に動かない。 // 方法1. List<SomeObject>型のフィールドを持つクラスを別途作り、そのクラスで返す。 // 方法2. 配列で返す。 //Message[] list = // exception.getConstraintViolations().stream() // .map(v -> Message.of(last(v.getPropertyPath().toString()), v.getMessage())) // .toArray(Message[]::new); // 方法3 genericEntity
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Message.java // @XmlRootElement // public class Message { // // private String key; // private String message; // // public Message(){} // // public static Message of(String key, String message) { // Message m = new Message(); // m.key = key; // m.message = message; // return m; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/BeanValidationExceptionMapper.java import enterprisegeeks.rest.dto.Message; import java.util.List; import java.util.stream.Collectors; import javax.json.JsonStructure; import javax.validation.ConstraintViolationException; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * Bean Validationの例外に対するマッピング。 * * エラーメッセージをレスポンスに設定する。 */ @Provider // 特定の例外に対して、処理を行う。Providerアノテーションで自動判別される。 public class BeanValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { @Override @Produces(MediaType.APPLICATION_JSON) public Response toResponse(ConstraintViolationException exception) { // メソッドの戻り値が List<SomeObject> の場合は、List形式のデータを返しても動作する。 // が、Responseを返す場合は、entity()にlistを渡すと、ジェネリクスが解消できないので、 // 正常に動かない。 // 方法1. List<SomeObject>型のフィールドを持つクラスを別途作り、そのクラスで返す。 // 方法2. 配列で返す。 //Message[] list = // exception.getConstraintViolations().stream() // .map(v -> Message.of(last(v.getPropertyPath().toString()), v.getMessage())) // .toArray(Message[]::new); // 方法3 genericEntity
List<Message> list =
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/test/java/enterprisegeeks/service/ServiceTest.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // }
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import enterprisegeeks.entity.Room; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import util.PrivateUtil;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * Serviceのテスト * EntityManagerへの依存性を自力で解消する方法 */ public class ServiceTest { @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } private Service target; private EntityManager em; private EntityTransaction tx; @Before public void setUp() throws Exception{ em = Persistence.createEntityManagerFactory("stand_alone").createEntityManager(); target = new ServiceImpl();
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // } // Path: try_java_ee7-web/src/test/java/enterprisegeeks/service/ServiceTest.java import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import enterprisegeeks.entity.Room; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import util.PrivateUtil; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * Serviceのテスト * EntityManagerへの依存性を自力で解消する方法 */ public class ServiceTest { @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } private Service target; private EntityManager em; private EntityTransaction tx; @Before public void setUp() throws Exception{ em = Persistence.createEntityManagerFactory("stand_alone").createEntityManager(); target = new ServiceImpl();
PrivateUtil.setField(target, "em", em);
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/test/java/enterprisegeeks/service/ServiceTest.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // }
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import enterprisegeeks.entity.Room; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import util.PrivateUtil;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * Serviceのテスト * EntityManagerへの依存性を自力で解消する方法 */ public class ServiceTest { @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } private Service target; private EntityManager em; private EntityTransaction tx; @Before public void setUp() throws Exception{ em = Persistence.createEntityManagerFactory("stand_alone").createEntityManager(); target = new ServiceImpl(); PrivateUtil.setField(target, "em", em); tx = em.getTransaction(); tx.begin(); } @After public void tearDown() { tx.rollback(); em.close(); } @Test public void testRegisterAccount() throws Exception{ // prepare
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // // Path: try_java_ee7-web/src/test/java/util/PrivateUtil.java // public class PrivateUtil { // public static void setField(Object instance, String name, Object obj) { // // try { // Field f = instance.getClass().getDeclaredField(name); // f.setAccessible(true); // f.set(instance, obj); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // public static <T> T getFiled(Object obj, String name, Class<T> clazz) { // try { // Field f = obj.getClass().getDeclaredField(name); // f.setAccessible(true); // return (T)f.get(obj); // } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { // throw new RuntimeException(e); // } // } // } // Path: try_java_ee7-web/src/test/java/enterprisegeeks/service/ServiceTest.java import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import enterprisegeeks.entity.Room; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import util.PrivateUtil; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * Serviceのテスト * EntityManagerへの依存性を自力で解消する方法 */ public class ServiceTest { @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } private Service target; private EntityManager em; private EntityTransaction tx; @Before public void setUp() throws Exception{ em = Persistence.createEntityManagerFactory("stand_alone").createEntityManager(); target = new ServiceImpl(); PrivateUtil.setField(target, "em", em); tx = em.getTransaction(); tx.begin(); } @After public void tearDown() { tx.rollback(); em.close(); } @Test public void testRegisterAccount() throws Exception{ // prepare
Room room = new Room();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // }
import javax.enterprise.context.RequestScoped; import enterprisegeeks.entity.Account;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.dto; /** * 認証済み情報 */ @RequestScoped public class Authed {
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java import javax.enterprise.context.RequestScoped; import enterprisegeeks.entity.Account; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.dto; /** * 認証済み情報 */ @RequestScoped public class Authed {
private Account account;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/bot/NotifyBot.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/NewChat.java // public class NewChat { // // @NotNull(message = "{required}") // public long roomId; // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // public String content; // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.Service; import enterprisegeeks.util.ScheduledExecutor; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.enterprise.concurrent.LastExecution; import javax.enterprise.concurrent.ManagedScheduledExecutorService; import javax.enterprise.concurrent.Trigger; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.bot; /* * チャット用Bot EJB番 */ @Singleton @Startup public class NotifyBot { @Inject @ScheduledExecutor private ManagedScheduledExecutorService scheduler; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/NewChat.java // public class NewChat { // // @NotNull(message = "{required}") // public long roomId; // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // public String content; // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/bot/NotifyBot.java import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.Service; import enterprisegeeks.util.ScheduledExecutor; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.enterprise.concurrent.LastExecution; import javax.enterprise.concurrent.ManagedScheduledExecutorService; import javax.enterprise.concurrent.Trigger; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.bot; /* * チャット用Bot EJB番 */ @Singleton @Startup public class NotifyBot { @Inject @ScheduledExecutor private ManagedScheduledExecutorService scheduler; @Inject
private Service service;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/bot/NotifyBot.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/NewChat.java // public class NewChat { // // @NotNull(message = "{required}") // public long roomId; // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // public String content; // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.Service; import enterprisegeeks.util.ScheduledExecutor; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.enterprise.concurrent.LastExecution; import javax.enterprise.concurrent.ManagedScheduledExecutorService; import javax.enterprise.concurrent.Trigger; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType;
* @return 次回の実行時刻 */ @Override public Date getNextRunTime(LastExecution le, Date date) { if (le == null) { // 初回実行時 Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, 1); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MILLISECOND, 0); logger.fine(() -> "bot first execution at " + cal.getTime()); return cal.getTime(); } // 前回実行時の1時間後 Date next = new Date(le.getScheduledStart().getTime() + 3600 * 1000); logger.fine(() -> "bot next execution at " + next); return next; } @Override public boolean skipRun(LastExecution le, Date date) { return false; } }; Runnable command = () -> { String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")); roomIds.forEach(roomId -> {
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/NewChat.java // public class NewChat { // // @NotNull(message = "{required}") // public long roomId; // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // public String content; // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/bot/NotifyBot.java import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.Service; import enterprisegeeks.util.ScheduledExecutor; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.enterprise.concurrent.LastExecution; import javax.enterprise.concurrent.ManagedScheduledExecutorService; import javax.enterprise.concurrent.Trigger; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; * @return 次回の実行時刻 */ @Override public Date getNextRunTime(LastExecution le, Date date) { if (le == null) { // 初回実行時 Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, 1); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MILLISECOND, 0); logger.fine(() -> "bot first execution at " + cal.getTime()); return cal.getTime(); } // 前回実行時の1時間後 Date next = new Date(le.getScheduledStart().getTime() + 3600 * 1000); logger.fine(() -> "bot next execution at " + next); return next; } @Override public boolean skipRun(LastExecution le, Date date) { return false; } }; Runnable command = () -> { String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")); roomIds.forEach(roomId -> {
NewChat nc = new NewChat();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject
private Service service;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject private Service service; @Inject @MessageResource private ResourceBundle message; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject private Service service; @Inject @MessageResource private ResourceBundle message; @Inject
private Authed authed;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // }
import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject private Service service; @Inject @MessageResource private ResourceBundle message; @Inject private Authed authed; @AroundInvoke public Object invoke(InvocationContext ic) throws Exception{ if (req == null) { forbidden(); } String token = req.getHeader("authorization"); if (token == null) { forbidden(); }
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/dto/Authed.java // @RequestScoped // public class Authed { // // private Account account; // // public Account getAccount() { // return account; // } // // public void setAccount(Account account) { // this.account = account; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java // public interface Service{ // // // public boolean registerAccount(Account accout); // // public Account findAccountByName(String name); // // /** ログイン用トークン発行 */ // public String publishToken(Account account); // // /** チャットルーム一覧 */ // public List<Room> allRooms(); // // /** チャットルームのチャット一覧を取得 */ // public List<Chat> findChatByRoom(Room room, Timestamp from); // // public void addChat(Chat chat); // // public Account getAccountByToken(String token); // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/rest/WithAuthInterceptor.java import enterprisegeeks.rest.anotation.MessageResource; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.entity.Account; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.service.Service; import java.io.Serializable; import java.util.ResourceBundle; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.persistence.EntityNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest; /** * * 認証チェックインターセプター */ @Interceptor @Dependent @WithAuth @Transactional public class WithAuthInterceptor implements Serializable{ @Inject private HttpServletRequest req; @Inject private Service service; @Inject @MessageResource private ResourceBundle message; @Inject private Authed authed; @AroundInvoke public Object invoke(InvocationContext ic) throws Exception{ if (req == null) { forbidden(); } String token = req.getHeader("authorization"); if (token == null) { forbidden(); }
Account account = null;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Room; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * 認証済みアカウント */ @SessionScoped @Named public class Auth implements Serializable{ private boolean loggedIn;
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Room; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * 認証済みアカウント */ @SessionScoped @Named public class Auth implements Serializable{ private boolean loggedIn;
private Room selected;
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Room; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * 認証済みアカウント */ @SessionScoped @Named public class Auth implements Serializable{ private boolean loggedIn; private Room selected;
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/model/Auth.java import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Room; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.model; /** * 認証済みアカウント */ @SessionScoped @Named public class Auth implements Serializable{ private boolean loggedIn; private Room selected;
private Account account = new Account();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.sql.Timestamp; import java.util.List;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * 永続層周りの機能を提供 */ public interface Service{ public boolean registerAccount(Account accout); public Account findAccountByName(String name); /** ログイン用トークン発行 */ public String publishToken(Account account); /** チャットルーム一覧 */
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.sql.Timestamp; import java.util.List; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * 永続層周りの機能を提供 */ public interface Service{ public boolean registerAccount(Account accout); public Account findAccountByName(String name); /** ログイン用トークン発行 */ public String publishToken(Account account); /** チャットルーム一覧 */
public List<Room> allRooms();
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // }
import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.sql.Timestamp; import java.util.List;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * 永続層周りの機能を提供 */ public interface Service{ public boolean registerAccount(Account accout); public Account findAccountByName(String name); /** ログイン用トークン発行 */ public String publishToken(Account account); /** チャットルーム一覧 */ public List<Room> allRooms(); /** チャットルームのチャット一覧を取得 */
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Account.java // @Vetoed //CDI対象外 // @Entity // @NamedQueries({ // @NamedQuery(name = "Account.nameOrEmali", query = "select a from Account a where a.name = :name or a.email = :email") // , @NamedQuery(name = "Account.byToken", query="select a from Account a where a.token = :token")} // ) // @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "email"})) // public class Account implements Serializable{ // // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // 未入力の場合、空文字になるため。 // @Id // @Column(length = 40) // private String name; // // @Email(message = "{email.invalid}") // @NotNull(message = "{required}") // @Size(message = "{required}", min = 1) // @Column(length = 200, nullable = false) // private String email; // // @Column(length = 32, nullable = true ) // private String gravaterHash; // // @Column(length = 40, nullable = true ) // private String token; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getGravaterHash() { // return gravaterHash; // } // // public void setGravaterHash(String gravaterHash) { // this.gravaterHash = gravaterHash; // } // // public String getGravatar() { // return "https://www.gravatar.com/avatar/" + gravaterHash; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Chat.java // @Vetoed //CDI対象外 // @Entity // public class Chat implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // ID自動生成 // private long id; // // /** チャットを行ったチャットルーム */ // @ManyToOne // 多対1関連 // private Room room; // // /** 発言者 */ // @ManyToOne // private Account speaker; // // /** 内容 */ // @Column(length = 200, nullable = false) // private String content; // // /** 投稿時刻 */ // @Column(nullable = false) // private Timestamp posted; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public Room getRoom() { // return room; // } // // public void setRoom(Room room) { // this.room = room; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public Account getSpeaker() { // return speaker; // } // // public void setSpeaker(Account speaker) { // this.speaker = speaker; // } // // public Timestamp getPosted() { // return posted; // } // // public void setPosted(Timestamp posted) { // this.posted = posted; // } // // // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/entity/Room.java // @Vetoed //CDI対象外 // @XmlRootElement // @Entity // @NamedQueries(@NamedQuery(name = "Room.all", query = "select r from Room r order by r.id")) // public class Room implements Serializable { // // /** id(自動生成) */ // @Id // @GeneratedValue // private long id; // // /** 部屋名 */ // @Column(nullable = false, length = 40, unique = true) // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/Service.java import enterprisegeeks.entity.Account; import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import java.sql.Timestamp; import java.util.List; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * 永続層周りの機能を提供 */ public interface Service{ public boolean registerAccount(Account accout); public Account findAccountByName(String name); /** ログイン用トークン発行 */ public String publishToken(Account account); /** チャットルーム一覧 */ public List<Room> allRooms(); /** チャットルームのチャット一覧を取得 */
public List<Chat> findChatByRoom(Room room, Timestamp from);
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/service/ChatNotifier.java
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/websocket/Signal.java // public enum Signal { // UPDATE // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/websocket/WsClient.java // @ClientEndpoint(encoders = SignalEncoder.class) // public class WsClient { // // private Session session; // // @OnOpen // public void onOpen(Session session) { // this.session = session; // } // // @OnClose // public void onClose(Session session) { // } // // @OnMessage // public void onMessage(String message) throws IOException, EncodeException { // } // // public void notifyUpdate(){ // try { // // session.getBasicRemote().sendObject(Signal.UPDATE); // } catch(IOException | EncodeException e) { // throw new WebApplicationException(e); // } // } // }
import enterprisegeeks.websocket.ChatNotifyEndPoint; import enterprisegeeks.websocket.Signal; import enterprisegeeks.websocket.WsClient; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.ws.rs.WebApplicationException;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * チャット更新通知 */ @Dependent public class ChatNotifier implements Serializable { @Inject @ChatNotifyEndPoint private String wsURI; @Inject
// Path: try_java_ee7-web/src/main/java/enterprisegeeks/websocket/Signal.java // public enum Signal { // UPDATE // } // // Path: try_java_ee7-web/src/main/java/enterprisegeeks/websocket/WsClient.java // @ClientEndpoint(encoders = SignalEncoder.class) // public class WsClient { // // private Session session; // // @OnOpen // public void onOpen(Session session) { // this.session = session; // } // // @OnClose // public void onClose(Session session) { // } // // @OnMessage // public void onMessage(String message) throws IOException, EncodeException { // } // // public void notifyUpdate(){ // try { // // session.getBasicRemote().sendObject(Signal.UPDATE); // } catch(IOException | EncodeException e) { // throw new WebApplicationException(e); // } // } // } // Path: try_java_ee7-web/src/main/java/enterprisegeeks/service/ChatNotifier.java import enterprisegeeks.websocket.ChatNotifyEndPoint; import enterprisegeeks.websocket.Signal; import enterprisegeeks.websocket.WsClient; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.ws.rs.WebApplicationException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.service; /** * チャット更新通知 */ @Dependent public class ChatNotifier implements Serializable { @Inject @ChatNotifyEndPoint private String wsURI; @Inject
private Event<Signal> event;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/enums/Access.java
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public class Access { public static final int GOD_MODE = -1; public static final int ROOT = 0; public static final int MANAGER = 1; public static final int CO_MANAGER = 2; public static final int LEADER = 3; public static final int CO_LEADER = 4; public static final int ELITE = 5; public static final int ELDER = 6; public static final int MEMBER = 7; public static final int PRE_MEMBER = 8; public static final int NO_LOGIN = 9; public static final int USER = 10; public static final int GUEST = 11; public static final Map<Integer, String> inverseMap = new HashMap<>(); static { System.out.println("Loading Access..."); for (Field field : Access.class.getDeclaredFields()) { if (field.getType().isAssignableFrom(Integer.TYPE)) { try { inverseMap.put((Integer) field.get(null), field.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } public static String getLocalized(int access) { if (inverseMap.containsKey(access)) {
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/enums/Access.java import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public class Access { public static final int GOD_MODE = -1; public static final int ROOT = 0; public static final int MANAGER = 1; public static final int CO_MANAGER = 2; public static final int LEADER = 3; public static final int CO_LEADER = 4; public static final int ELITE = 5; public static final int ELDER = 6; public static final int MEMBER = 7; public static final int PRE_MEMBER = 8; public static final int NO_LOGIN = 9; public static final int USER = 10; public static final int GUEST = 11; public static final Map<Integer, String> inverseMap = new HashMap<>(); static { System.out.println("Loading Access..."); for (Field field : Access.class.getDeclaredFields()) { if (field.getType().isAssignableFrom(Integer.TYPE)) { try { inverseMap.put((Integer) field.get(null), field.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } public static String getLocalized(int access) { if (inverseMap.containsKey(access)) {
return lang("ACCESS_" + inverseMap.get(access));
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/config/Settings.java
// Path: src/main/java/love/sola/netsupport/sql/TableConfig.java // public class TableConfig extends SQLCore { // // public static final String KEY_SYS = "sys"; // // public static Settings getSettings() { // try (Connection conn = ds.getConnection()) { // Statement st = conn.createStatement(); // ResultSet rs = st.executeQuery("SELECT * FROM settings WHERE type='" + KEY_SYS + "'"); // if (rs.next()) { // return gson.fromJson(rs.getString("data"), Settings.class); // } // } catch (SQLException e) { // } // return null; // } // // public static int saveSettings(Settings obj) { // try (Connection conn = ds.getConnection()) { // PreparedStatement ps = conn.prepareStatement("UPDATE settings SET data=? WHERE type=?"); // ps.setString(1, gson.toJson(obj)); // ps.setString(2, KEY_SYS); // return ps.executeUpdate(); // } catch (SQLException e) { // } // return -1; // } // // }
import love.sola.netsupport.sql.TableConfig;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.config; /** * @author Sola {@literal <[email protected]>} */ public class Settings { public static final int MAX_DESC_LENGTH = 255; public static Settings I; static {
// Path: src/main/java/love/sola/netsupport/sql/TableConfig.java // public class TableConfig extends SQLCore { // // public static final String KEY_SYS = "sys"; // // public static Settings getSettings() { // try (Connection conn = ds.getConnection()) { // Statement st = conn.createStatement(); // ResultSet rs = st.executeQuery("SELECT * FROM settings WHERE type='" + KEY_SYS + "'"); // if (rs.next()) { // return gson.fromJson(rs.getString("data"), Settings.class); // } // } catch (SQLException e) { // } // return null; // } // // public static int saveSettings(Settings obj) { // try (Connection conn = ds.getConnection()) { // PreparedStatement ps = conn.prepareStatement("UPDATE settings SET data=? WHERE type=?"); // ps.setString(1, gson.toJson(obj)); // ps.setString(2, KEY_SYS); // return ps.executeUpdate(); // } catch (SQLException e) { // } // return -1; // } // // } // Path: src/main/java/love/sola/netsupport/config/Settings.java import love.sola.netsupport.sql.TableConfig; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.config; /** * @author Sola {@literal <[email protected]>} */ public class Settings { public static final int MAX_DESC_LENGTH = 255; public static Settings I; static {
I = TableConfig.getSettings();
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/API.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/API.java import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url
public int access = Access.GOD_MODE; //operator's permission
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/API.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url public int access = Access.GOD_MODE; //operator's permission
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/API.java import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url public int access = Access.GOD_MODE; //operator's permission
public Command authorize = null; //session check
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/API.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url public int access = Access.GOD_MODE; //operator's permission public Command authorize = null; //session check
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/API.java import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public abstract class API { public String url = null; //url public int access = Access.GOD_MODE; //operator's permission public Command authorize = null; //session check
protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/session/MapSessionRepository.java
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // }
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.commons.lang3.Validate; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import love.sola.netsupport.config.Settings;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright 2002-2015 the original author or authors. * * 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 love.sola.netsupport.session; /** * @author Sola {@literal <[email protected]>} */ public class MapSessionRepository { private final LoadingCache<String, MapSession> sessions; public MapSessionRepository() { this(CacheBuilder.newBuilder() .concurrencyLevel(4) .maximumSize(65535)
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // } // Path: src/main/java/love/sola/netsupport/session/MapSessionRepository.java import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.commons.lang3.Validate; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import love.sola.netsupport.config.Settings; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright 2002-2015 the original author or authors. * * 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 love.sola.netsupport.session; /** * @author Sola {@literal <[email protected]>} */ public class MapSessionRepository { private final LoadingCache<String, MapSession> sessions; public MapSessionRepository() { this(CacheBuilder.newBuilder() .concurrencyLevel(4) .maximumSize(65535)
.expireAfterAccess(Settings.I.User_Session_Max_Inactive, TimeUnit.SECONDS)
ZSCNetSupportDept/WechatTicketSystem
src/test/java/love/sola/netsupport/util/GsonTest.java
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import org.junit.Test; import java.util.Date; import love.sola.netsupport.enums.ISP;
package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class GsonTest { @Test public void testJsonDate() { Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime()))
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // Path: src/test/java/love/sola/netsupport/util/GsonTest.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import org.junit.Test; import java.util.Date; import love.sola.netsupport.enums.ISP; package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class GsonTest { @Test public void testJsonDate() { Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime()))
.registerTypeAdapter(ISP.class, (JsonDeserializer<ISP>) (json, typeOfT, context) -> ISP.fromId(json.getAsJsonPrimitive().getAsInt()))
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/util/ParseUtil.java
// Path: src/main/java/love/sola/netsupport/enums/Status.java // public class Status { // // public static final int UNCHECKED = 0; // public static final int ARRANGED = 1; // public static final int PUTOFF = 2; // public static final int REPORTED = 4; // public static final int ISP_HANDLED = 7; // public static final int SOLVED = 9; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Status..."); // for (Field field : Status.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int status) { // if (inverseMap.containsKey(status)) { // return lang("STATUS_" + inverseMap.get(status)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/pojo/Ticket.java // @Entity // @Table(name = "tickets") // @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) // public class Ticket { // // public static final String PROPERTY_USER = "user"; // public static final String PROPERTY_STATUS = "status"; // public static final String PROPERTY_SUBMIT_TIME = "submitTime"; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @ManyToOne(optional = false) // @JoinColumn(name = TableTicket.COLUMN_SID) // private User user; // private String description; // @Column(name = TableTicket.COLUMN_SUBMIT_TIME, insertable = false, updatable = false) // private Date submitTime; // private String remark; // private Date updateTime; // @ManyToOne // @JoinColumn(name = TableTicket.COLUMN_OPSID) // private Operator operator; // private Integer status; // // public Ticket() { // } // // public Ticket(User user, String description, Date submitTime, String remark, Date updateTime, Operator operator, Integer status) { // this.user = user; // this.description = description; // this.submitTime = submitTime; // this.remark = remark; // this.updateTime = updateTime; // this.operator = operator; // this.status = status; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Operator getOperator() { // return operator; // } // // public void setOperator(Operator operator) { // this.operator = operator; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // @Override // public String toString() { // return "Ticket{" + // "id=" + id + // ", user=" + user + // ", description='" + description + '\'' + // ", submitTime=" + submitTime + // ", remark='" + remark + '\'' + // ", updateTime=" + updateTime + // ", operator=" + operator + // ", status=" + status + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import static love.sola.netsupport.config.Lang.lang; import java.text.SimpleDateFormat; import love.sola.netsupport.enums.Status; import love.sola.netsupport.pojo.Ticket;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class ParseUtil { public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm EEE");
// Path: src/main/java/love/sola/netsupport/enums/Status.java // public class Status { // // public static final int UNCHECKED = 0; // public static final int ARRANGED = 1; // public static final int PUTOFF = 2; // public static final int REPORTED = 4; // public static final int ISP_HANDLED = 7; // public static final int SOLVED = 9; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Status..."); // for (Field field : Status.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int status) { // if (inverseMap.containsKey(status)) { // return lang("STATUS_" + inverseMap.get(status)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/pojo/Ticket.java // @Entity // @Table(name = "tickets") // @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) // public class Ticket { // // public static final String PROPERTY_USER = "user"; // public static final String PROPERTY_STATUS = "status"; // public static final String PROPERTY_SUBMIT_TIME = "submitTime"; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @ManyToOne(optional = false) // @JoinColumn(name = TableTicket.COLUMN_SID) // private User user; // private String description; // @Column(name = TableTicket.COLUMN_SUBMIT_TIME, insertable = false, updatable = false) // private Date submitTime; // private String remark; // private Date updateTime; // @ManyToOne // @JoinColumn(name = TableTicket.COLUMN_OPSID) // private Operator operator; // private Integer status; // // public Ticket() { // } // // public Ticket(User user, String description, Date submitTime, String remark, Date updateTime, Operator operator, Integer status) { // this.user = user; // this.description = description; // this.submitTime = submitTime; // this.remark = remark; // this.updateTime = updateTime; // this.operator = operator; // this.status = status; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Operator getOperator() { // return operator; // } // // public void setOperator(Operator operator) { // this.operator = operator; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // @Override // public String toString() { // return "Ticket{" + // "id=" + id + // ", user=" + user + // ", description='" + description + '\'' + // ", submitTime=" + submitTime + // ", remark='" + remark + '\'' + // ", updateTime=" + updateTime + // ", operator=" + operator + // ", status=" + status + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/util/ParseUtil.java import static love.sola.netsupport.config.Lang.lang; import java.text.SimpleDateFormat; import love.sola.netsupport.enums.Status; import love.sola.netsupport.pojo.Ticket; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class ParseUtil { public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm EEE");
public static String parseTicket(Ticket t) {
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/util/ParseUtil.java
// Path: src/main/java/love/sola/netsupport/enums/Status.java // public class Status { // // public static final int UNCHECKED = 0; // public static final int ARRANGED = 1; // public static final int PUTOFF = 2; // public static final int REPORTED = 4; // public static final int ISP_HANDLED = 7; // public static final int SOLVED = 9; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Status..."); // for (Field field : Status.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int status) { // if (inverseMap.containsKey(status)) { // return lang("STATUS_" + inverseMap.get(status)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/pojo/Ticket.java // @Entity // @Table(name = "tickets") // @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) // public class Ticket { // // public static final String PROPERTY_USER = "user"; // public static final String PROPERTY_STATUS = "status"; // public static final String PROPERTY_SUBMIT_TIME = "submitTime"; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @ManyToOne(optional = false) // @JoinColumn(name = TableTicket.COLUMN_SID) // private User user; // private String description; // @Column(name = TableTicket.COLUMN_SUBMIT_TIME, insertable = false, updatable = false) // private Date submitTime; // private String remark; // private Date updateTime; // @ManyToOne // @JoinColumn(name = TableTicket.COLUMN_OPSID) // private Operator operator; // private Integer status; // // public Ticket() { // } // // public Ticket(User user, String description, Date submitTime, String remark, Date updateTime, Operator operator, Integer status) { // this.user = user; // this.description = description; // this.submitTime = submitTime; // this.remark = remark; // this.updateTime = updateTime; // this.operator = operator; // this.status = status; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Operator getOperator() { // return operator; // } // // public void setOperator(Operator operator) { // this.operator = operator; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // @Override // public String toString() { // return "Ticket{" + // "id=" + id + // ", user=" + user + // ", description='" + description + '\'' + // ", submitTime=" + submitTime + // ", remark='" + remark + '\'' + // ", updateTime=" + updateTime + // ", operator=" + operator + // ", status=" + status + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import static love.sola.netsupport.config.Lang.lang; import java.text.SimpleDateFormat; import love.sola.netsupport.enums.Status; import love.sola.netsupport.pojo.Ticket;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class ParseUtil { public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm EEE"); public static String parseTicket(Ticket t) { StringBuilder sb = new StringBuilder()
// Path: src/main/java/love/sola/netsupport/enums/Status.java // public class Status { // // public static final int UNCHECKED = 0; // public static final int ARRANGED = 1; // public static final int PUTOFF = 2; // public static final int REPORTED = 4; // public static final int ISP_HANDLED = 7; // public static final int SOLVED = 9; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Status..."); // for (Field field : Status.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int status) { // if (inverseMap.containsKey(status)) { // return lang("STATUS_" + inverseMap.get(status)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/pojo/Ticket.java // @Entity // @Table(name = "tickets") // @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) // public class Ticket { // // public static final String PROPERTY_USER = "user"; // public static final String PROPERTY_STATUS = "status"; // public static final String PROPERTY_SUBMIT_TIME = "submitTime"; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @ManyToOne(optional = false) // @JoinColumn(name = TableTicket.COLUMN_SID) // private User user; // private String description; // @Column(name = TableTicket.COLUMN_SUBMIT_TIME, insertable = false, updatable = false) // private Date submitTime; // private String remark; // private Date updateTime; // @ManyToOne // @JoinColumn(name = TableTicket.COLUMN_OPSID) // private Operator operator; // private Integer status; // // public Ticket() { // } // // public Ticket(User user, String description, Date submitTime, String remark, Date updateTime, Operator operator, Integer status) { // this.user = user; // this.description = description; // this.submitTime = submitTime; // this.remark = remark; // this.updateTime = updateTime; // this.operator = operator; // this.status = status; // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // public Operator getOperator() { // return operator; // } // // public void setOperator(Operator operator) { // this.operator = operator; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // @Override // public String toString() { // return "Ticket{" + // "id=" + id + // ", user=" + user + // ", description='" + description + '\'' + // ", submitTime=" + submitTime + // ", remark='" + remark + '\'' + // ", updateTime=" + updateTime + // ", operator=" + operator + // ", status=" + status + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/util/ParseUtil.java import static love.sola.netsupport.config.Lang.lang; import java.text.SimpleDateFormat; import love.sola.netsupport.enums.Status; import love.sola.netsupport.pojo.Ticket; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.util; /** * @author Sola {@literal <[email protected]>} */ public class ParseUtil { public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm EEE"); public static String parseTicket(Ticket t) { StringBuilder sb = new StringBuilder()
.append(lang("Ticket_Info_Id")).append(t.getId()).append("\n")
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/sql/TableUser.java
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/pojo/User.java // @Entity // @Table(name = "users") // public class User { // // //System Accounts // public static User OFFICIAL_CHINA_UNICOM_XH; // public static User OFFICIAL_CHINA_MOBILE_XH; // public static User OFFICIAL_CHINA_MOBILE_FX; // // public static final String PROPERTY_NAME = "name"; // public static final String PROPERTY_WECHAT = "wechatId"; // public static final String PROPERTY_BLOCK = "block"; // // @Id // @Column(name = "id", updatable = false, nullable = false) // private Long id; // @Column(name = "name", updatable = false, nullable = false) // private String name; // @Convert(converter = ISPConverter.class) // private ISP isp; // @Column(name = "netaccount") // private String netAccount; // @Expose(serialize = false) // @Column(name = "wechat") // private String wechatId; // private Integer block; // private Integer room; // private Long phone; // // public User() { // } // // public User(Long id, String name, ISP isp, String netAccount, String wechatId, Integer block, Integer room, Long phone) { // this.id = id; // this.name = name; // this.isp = isp; // this.netAccount = netAccount; // this.wechatId = wechatId; // this.block = block; // this.room = room; // this.phone = phone; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ISP getIsp() { // return isp; // } // // public void setIsp(ISP isp) { // this.isp = isp; // } // // public String getNetAccount() { // return netAccount; // } // // public void setNetAccount(String netAccount) { // this.netAccount = netAccount; // } // // public String getWechatId() { // return wechatId; // } // // public void setWechatId(String wechatId) { // this.wechatId = wechatId; // } // // public Integer getBlock() { // return block; // } // // public void setBlock(Integer block) { // this.block = block; // } // // public Integer getRoom() { // return room; // } // // public void setRoom(Integer room) { // this.room = room; // } // // public Long getPhone() { // return phone; // } // // public void setPhone(Long phone) { // this.phone = phone; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", isp=" + isp + // ", netAccount='" + netAccount + '\'' + // ", wechatId='" + wechatId + '\'' + // ", block=" + block + // ", room=" + room + // ", phone=" + phone + // '}'; // } // }
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import love.sola.netsupport.config.Settings; import love.sola.netsupport.pojo.User;
try { User u = cache.get(wechat); return u == NULL_USER ? null : u; } catch (ExecutionException e) { e.printStackTrace(); return null; } } public static int update(User user) { try (Session s = sf.openSession()) { s.beginTransaction(); s.update(user); s.getTransaction().commit(); cache.put(user.getWechatId(), user); return 1; } } protected static void init() { try (Session s = SQLCore.sf.openSession()) { User.OFFICIAL_CHINA_UNICOM_XH = s.get(User.class, 100104L); User.OFFICIAL_CHINA_MOBILE_XH = s.get(User.class, 100864L); User.OFFICIAL_CHINA_MOBILE_FX = s.get(User.class, 100865L); } } private static LoadingCache<String, User> cache = CacheBuilder.newBuilder() .concurrencyLevel(4) .maximumSize(4096)
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // } // // Path: src/main/java/love/sola/netsupport/pojo/User.java // @Entity // @Table(name = "users") // public class User { // // //System Accounts // public static User OFFICIAL_CHINA_UNICOM_XH; // public static User OFFICIAL_CHINA_MOBILE_XH; // public static User OFFICIAL_CHINA_MOBILE_FX; // // public static final String PROPERTY_NAME = "name"; // public static final String PROPERTY_WECHAT = "wechatId"; // public static final String PROPERTY_BLOCK = "block"; // // @Id // @Column(name = "id", updatable = false, nullable = false) // private Long id; // @Column(name = "name", updatable = false, nullable = false) // private String name; // @Convert(converter = ISPConverter.class) // private ISP isp; // @Column(name = "netaccount") // private String netAccount; // @Expose(serialize = false) // @Column(name = "wechat") // private String wechatId; // private Integer block; // private Integer room; // private Long phone; // // public User() { // } // // public User(Long id, String name, ISP isp, String netAccount, String wechatId, Integer block, Integer room, Long phone) { // this.id = id; // this.name = name; // this.isp = isp; // this.netAccount = netAccount; // this.wechatId = wechatId; // this.block = block; // this.room = room; // this.phone = phone; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ISP getIsp() { // return isp; // } // // public void setIsp(ISP isp) { // this.isp = isp; // } // // public String getNetAccount() { // return netAccount; // } // // public void setNetAccount(String netAccount) { // this.netAccount = netAccount; // } // // public String getWechatId() { // return wechatId; // } // // public void setWechatId(String wechatId) { // this.wechatId = wechatId; // } // // public Integer getBlock() { // return block; // } // // public void setBlock(Integer block) { // this.block = block; // } // // public Integer getRoom() { // return room; // } // // public void setRoom(Integer room) { // this.room = room; // } // // public Long getPhone() { // return phone; // } // // public void setPhone(Long phone) { // this.phone = phone; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", isp=" + isp + // ", netAccount='" + netAccount + '\'' + // ", wechatId='" + wechatId + '\'' + // ", block=" + block + // ", room=" + room + // ", phone=" + phone + // '}'; // } // } // Path: src/main/java/love/sola/netsupport/sql/TableUser.java import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import love.sola.netsupport.config.Settings; import love.sola.netsupport.pojo.User; try { User u = cache.get(wechat); return u == NULL_USER ? null : u; } catch (ExecutionException e) { e.printStackTrace(); return null; } } public static int update(User user) { try (Session s = sf.openSession()) { s.beginTransaction(); s.update(user); s.getTransaction().commit(); cache.put(user.getWechatId(), user); return 1; } } protected static void init() { try (Session s = SQLCore.sf.openSession()) { User.OFFICIAL_CHINA_UNICOM_XH = s.get(User.class, 100104L); User.OFFICIAL_CHINA_MOBILE_XH = s.get(User.class, 100864L); User.OFFICIAL_CHINA_MOBILE_FX = s.get(User.class, 100865L); } } private static LoadingCache<String, User> cache = CacheBuilder.newBuilder() .concurrencyLevel(4) .maximumSize(4096)
.expireAfterAccess(Settings.I.User_Wechat_Cache_Expire_Time, TimeUnit.SECONDS)
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/pojo/User.java
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/ISPConverter.java // @Converter // public class ISPConverter implements AttributeConverter<ISP, Integer> { // // @Override // public Integer convertToDatabaseColumn(ISP attribute) { // if (attribute == null) { // return null; // } // return attribute.id; // } // // @Override // public ISP convertToEntityAttribute(Integer dbData) { // if (dbData == null) { // return null; // } // return ISP.fromId(dbData); // } // // }
import com.google.gson.annotations.Expose; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.enums.ISPConverter;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.pojo; /** * @author Sola {@literal <[email protected]>} */ @Entity @Table(name = "users") public class User { //System Accounts public static User OFFICIAL_CHINA_UNICOM_XH; public static User OFFICIAL_CHINA_MOBILE_XH; public static User OFFICIAL_CHINA_MOBILE_FX; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_WECHAT = "wechatId"; public static final String PROPERTY_BLOCK = "block"; @Id @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", updatable = false, nullable = false) private String name;
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/ISPConverter.java // @Converter // public class ISPConverter implements AttributeConverter<ISP, Integer> { // // @Override // public Integer convertToDatabaseColumn(ISP attribute) { // if (attribute == null) { // return null; // } // return attribute.id; // } // // @Override // public ISP convertToEntityAttribute(Integer dbData) { // if (dbData == null) { // return null; // } // return ISP.fromId(dbData); // } // // } // Path: src/main/java/love/sola/netsupport/pojo/User.java import com.google.gson.annotations.Expose; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.enums.ISPConverter; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.pojo; /** * @author Sola {@literal <[email protected]>} */ @Entity @Table(name = "users") public class User { //System Accounts public static User OFFICIAL_CHINA_UNICOM_XH; public static User OFFICIAL_CHINA_MOBILE_XH; public static User OFFICIAL_CHINA_MOBILE_FX; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_WECHAT = "wechatId"; public static final String PROPERTY_BLOCK = "block"; @Id @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", updatable = false, nullable = false) private String name;
@Convert(converter = ISPConverter.class)
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/pojo/User.java
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/ISPConverter.java // @Converter // public class ISPConverter implements AttributeConverter<ISP, Integer> { // // @Override // public Integer convertToDatabaseColumn(ISP attribute) { // if (attribute == null) { // return null; // } // return attribute.id; // } // // @Override // public ISP convertToEntityAttribute(Integer dbData) { // if (dbData == null) { // return null; // } // return ISP.fromId(dbData); // } // // }
import com.google.gson.annotations.Expose; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.enums.ISPConverter;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.pojo; /** * @author Sola {@literal <[email protected]>} */ @Entity @Table(name = "users") public class User { //System Accounts public static User OFFICIAL_CHINA_UNICOM_XH; public static User OFFICIAL_CHINA_MOBILE_XH; public static User OFFICIAL_CHINA_MOBILE_FX; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_WECHAT = "wechatId"; public static final String PROPERTY_BLOCK = "block"; @Id @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", updatable = false, nullable = false) private String name; @Convert(converter = ISPConverter.class)
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/ISPConverter.java // @Converter // public class ISPConverter implements AttributeConverter<ISP, Integer> { // // @Override // public Integer convertToDatabaseColumn(ISP attribute) { // if (attribute == null) { // return null; // } // return attribute.id; // } // // @Override // public ISP convertToEntityAttribute(Integer dbData) { // if (dbData == null) { // return null; // } // return ISP.fromId(dbData); // } // // } // Path: src/main/java/love/sola/netsupport/pojo/User.java import com.google.gson.annotations.Expose; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.enums.ISPConverter; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.pojo; /** * @author Sola {@literal <[email protected]>} */ @Entity @Table(name = "users") public class User { //System Accounts public static User OFFICIAL_CHINA_UNICOM_XH; public static User OFFICIAL_CHINA_MOBILE_XH; public static User OFFICIAL_CHINA_MOBILE_FX; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_WECHAT = "wechatId"; public static final String PROPERTY_BLOCK = "block"; @Id @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", updatable = false, nullable = false) private String name; @Convert(converter = ISPConverter.class)
private ISP isp;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/CheckSession.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // }
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession";
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // Path: src/main/java/love/sola/netsupport/api/CheckSession.java import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession";
access = Access.GUEST;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/CheckSession.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // }
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession"; access = Access.GUEST; authorize = null; } @Override
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // Path: src/main/java/love/sola/netsupport/api/CheckSession.java import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession"; access = Access.GUEST; authorize = null; } @Override
protected Object process(HttpServletRequest req, WxSession session) throws Exception {
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/CheckSession.java
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // }
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession"; access = Access.GUEST; authorize = null; } @Override protected Object process(HttpServletRequest req, WxSession session) throws Exception { String more = req.getParameter("more"); Map<String, Object> result = new HashMap<>();
// Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Attribute.java // public class Attribute { // // public static final String AUTHORIZED = "authorized"; // public static final String WECHAT = "wechat"; // public static final String OPERATOR = "operator"; // public static final String USER = "user"; // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // Path: src/main/java/love/sola/netsupport/api/CheckSession.java import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.enums.Access; import love.sola.netsupport.enums.Attribute; import love.sola.netsupport.session.WxSession; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class CheckSession extends API { public CheckSession() { url = "/checksession"; access = Access.GUEST; authorize = null; } @Override protected Object process(HttpServletRequest req, WxSession session) throws Exception { String more = req.getParameter("more"); Map<String, Object> result = new HashMap<>();
result.put(Attribute.AUTHORIZED, session.getAttribute(Attribute.AUTHORIZED));
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/sql/TableOperator.java
// Path: src/main/java/love/sola/netsupport/pojo/Operator.java // @Entity // @Table(name = "operators") // public class Operator { // // public static final String PROPERTY_WECHAT = "wechat"; // // //System Accounts // public static Operator USER_SELF; // public static Operator ADMIN; // // @Id // @Column(name = "id", nullable = false, insertable = false, updatable = false) // private Integer id; // @Column(name = "name", nullable = false, insertable = false, updatable = false) // private String name; // @Column(name = "access", nullable = false, insertable = false, updatable = false) // private Integer access; // @Column(name = "wechat", insertable = false, updatable = false) // @Expose(serialize = false) // private String wechat; // private Integer block; // private Integer week; // @Expose(serialize = false) // private String password; // // public Operator(Integer id, String name, Integer access, String wechat, Integer block, Integer week, String password) { // this.id = id; // this.name = name; // this.access = access; // this.wechat = wechat; // this.block = block; // this.week = week; // this.password = password; // } // // public Operator() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAccess() { // return access; // } // // public void setAccess(Integer access) { // this.access = access; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public Integer getBlock() { // return block; // } // // public void setBlock(Integer block) { // this.block = block; // } // // public Integer getWeek() { // return week; // } // // public void setWeek(Integer week) { // this.week = week; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public String toString() { // return "Operator{" + // "id=" + id + // ", name='" + name + '\'' + // ", access=" + access + // ", wechat='" + wechat + '\'' + // ", block=" + block + // ", week=" + week + // '}'; // } // }
import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import love.sola.netsupport.pojo.Operator;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.sql; /** * @author Sola {@literal <[email protected]>} */ public class TableOperator extends SQLCore { public static boolean has(String wechat) { try (Session s = SQLCore.sf.openSession()) {
// Path: src/main/java/love/sola/netsupport/pojo/Operator.java // @Entity // @Table(name = "operators") // public class Operator { // // public static final String PROPERTY_WECHAT = "wechat"; // // //System Accounts // public static Operator USER_SELF; // public static Operator ADMIN; // // @Id // @Column(name = "id", nullable = false, insertable = false, updatable = false) // private Integer id; // @Column(name = "name", nullable = false, insertable = false, updatable = false) // private String name; // @Column(name = "access", nullable = false, insertable = false, updatable = false) // private Integer access; // @Column(name = "wechat", insertable = false, updatable = false) // @Expose(serialize = false) // private String wechat; // private Integer block; // private Integer week; // @Expose(serialize = false) // private String password; // // public Operator(Integer id, String name, Integer access, String wechat, Integer block, Integer week, String password) { // this.id = id; // this.name = name; // this.access = access; // this.wechat = wechat; // this.block = block; // this.week = week; // this.password = password; // } // // public Operator() { // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAccess() { // return access; // } // // public void setAccess(Integer access) { // this.access = access; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public Integer getBlock() { // return block; // } // // public void setBlock(Integer block) { // this.block = block; // } // // public Integer getWeek() { // return week; // } // // public void setWeek(Integer week) { // this.week = week; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public String toString() { // return "Operator{" + // "id=" + id + // ", name='" + name + '\'' + // ", access=" + access + // ", wechat='" + wechat + '\'' + // ", block=" + block + // ", week=" + week + // '}'; // } // } // Path: src/main/java/love/sola/netsupport/sql/TableOperator.java import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import love.sola.netsupport.pojo.Operator; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.sql; /** * @author Sola {@literal <[email protected]>} */ public class TableOperator extends SQLCore { public static boolean has(String wechat) { try (Session s = SQLCore.sf.openSession()) {
return (long) s.createCriteria(Operator.class)
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/Error.java
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import static love.sola.netsupport.config.Lang.lang;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class Error { public static final Error ALREADY_SUBMITTED = new Error(1); public static final Object OK = new Object(); public static final Error PARAMETER_REQUIRED = new Error(-1); public static final Error ILLEGAL_PARAMETER = new Error(-2); // public static final Error REQUEST_FAILED = new Error(-3); REMOVED public static final Error LENGTH_LIMIT_EXCEEDED = new Error(-4); public static final Error INVALID_PARAMETER = new Error(-5); public static final Error USER_NOT_FOUND = new Error(-11); public static final Error TICKET_NOT_FOUND = new Error(-12); public static final Error OPERATOR_NOT_FOUND = new Error(-13); public static final Error UNAUTHORIZED = new Error(-20); public static final Error WRONG_PASSWORD = new Error(-22); public static final Error PERMISSION_DENIED = new Error(-24); public static final Error INTERNAL_ERROR = new Error(-90); public static final Error DATABASE_ERROR = new Error(-91); public int errCode; public String errMsg; private Error(int code) {
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/api/Error.java import static love.sola.netsupport.config.Lang.lang; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api; /** * @author Sola {@literal <[email protected]>} */ public class Error { public static final Error ALREADY_SUBMITTED = new Error(1); public static final Object OK = new Object(); public static final Error PARAMETER_REQUIRED = new Error(-1); public static final Error ILLEGAL_PARAMETER = new Error(-2); // public static final Error REQUEST_FAILED = new Error(-3); REMOVED public static final Error LENGTH_LIMIT_EXCEEDED = new Error(-4); public static final Error INVALID_PARAMETER = new Error(-5); public static final Error USER_NOT_FOUND = new Error(-11); public static final Error TICKET_NOT_FOUND = new Error(-12); public static final Error OPERATOR_NOT_FOUND = new Error(-13); public static final Error UNAUTHORIZED = new Error(-20); public static final Error WRONG_PASSWORD = new Error(-22); public static final Error PERMISSION_DENIED = new Error(-24); public static final Error INTERNAL_ERROR = new Error(-90); public static final Error DATABASE_ERROR = new Error(-91); public int errCode; public String errMsg; private Error(int code) {
this(code, lang("ERR_" + code));
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/sql/TableConfig.java
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import love.sola.netsupport.config.Settings;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.sql; /** * @author Sola {@literal <[email protected]>} */ public class TableConfig extends SQLCore { public static final String KEY_SYS = "sys";
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // } // Path: src/main/java/love/sola/netsupport/sql/TableConfig.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import love.sola.netsupport.config.Settings; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.sql; /** * @author Sola {@literal <[email protected]>} */ public class TableConfig extends SQLCore { public static final String KEY_SYS = "sys";
public static Settings getSettings() {
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/sql/SQLCore.java
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.proxy.HibernateProxy; import org.hibernate.service.ServiceRegistry; import java.io.IOException; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.wechat.Command;
public static DataSource ds; public static SessionFactory sf; public static ServiceRegistry sr; public static Gson gson = new GsonBuilder() .addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.serialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .addDeserializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.deserialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime()))
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/sql/SQLCore.java import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.proxy.HibernateProxy; import org.hibernate.service.ServiceRegistry; import java.io.IOException; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.wechat.Command; public static DataSource ds; public static SessionFactory sf; public static ServiceRegistry sr; public static Gson gson = new GsonBuilder() .addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.serialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .addDeserializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.deserialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime()))
.registerTypeAdapter(ISP.class, (JsonDeserializer<ISP>) (json, typeOfT, context) -> ISP.fromId(json.getAsJsonPrimitive().getAsInt()))
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/sql/SQLCore.java
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.proxy.HibernateProxy; import org.hibernate.service.ServiceRegistry; import java.io.IOException; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.wechat.Command;
public static ServiceRegistry sr; public static Gson gson = new GsonBuilder() .addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.serialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .addDeserializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.deserialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime())) .registerTypeAdapter(ISP.class, (JsonDeserializer<ISP>) (json, typeOfT, context) -> ISP.fromId(json.getAsJsonPrimitive().getAsInt())) .registerTypeAdapter(ISP.class, (JsonSerializer<ISP>) (src, typeOfSrc, context) -> new JsonPrimitive(src.id))
// Path: src/main/java/love/sola/netsupport/enums/ISP.java // public enum ISP { // // TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), // UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), // CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), // OTHER(4, ".*"), // ; // // private static final Map<String, ISP> NAME_MAP = new HashMap<>(); // private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); // // static { // for (ISP type : values()) { // if (type.name != null) { // NAME_MAP.put(type.name.toLowerCase(), type); // } // if (type.id > 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final int id; // public final String name; // public final String accountRegex; // // ISP(int id, String accountRegex) { // this.id = id; // this.name = lang("ISP_" + name()); // this.accountRegex = accountRegex; // } // // public static ISP fromName(String name) { // if (name == null) { // return null; // } // return NAME_MAP.get(name.toLowerCase()); // } // // public static ISP fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name; // } // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/sql/SQLCore.java import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.proxy.HibernateProxy; import org.hibernate.service.ServiceRegistry; import java.io.IOException; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import love.sola.netsupport.enums.ISP; import love.sola.netsupport.wechat.Command; public static ServiceRegistry sr; public static Gson gson = new GsonBuilder() .addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.serialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .addDeserializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); return expose != null && !expose.deserialize(); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getTime())) .registerTypeAdapter(ISP.class, (JsonDeserializer<ISP>) (json, typeOfT, context) -> ISP.fromId(json.getAsJsonPrimitive().getAsInt())) .registerTypeAdapter(ISP.class, (JsonSerializer<ISP>) (src, typeOfSrc, context) -> new JsonPrimitive(src.id))
.registerTypeAdapter(Command.class, (JsonDeserializer<Command>) (json, typeOfT, context) -> Command.fromId(json.getAsJsonPrimitive().getAsInt()))
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/wechat/matcher/CheckSpamMatcher.java
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // }
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.TimeUnit; import love.sola.netsupport.config.Settings; import me.chanjar.weixin.mp.api.WxMpMessageMatcher; import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.wechat.matcher; /** * @author Sola {@literal <[email protected]>} */ public class CheckSpamMatcher implements WxMpMessageMatcher { private class ValueLoader extends CacheLoader<String, Long> { @Override public Long load(String key) throws Exception {
// Path: src/main/java/love/sola/netsupport/config/Settings.java // public class Settings { // // public static final int MAX_DESC_LENGTH = 255; // // public static Settings I; // // static { // I = TableConfig.getSettings(); // } // // public String Wechat_AppId; // public String Wechat_Secret; // public String Wechat_Token; // public String Wechat_AesKey; // // public int Check_Spam_Cache_Expire_Time; // public int Check_Spam_Interval; // // public int User_Session_Max_Inactive; // public int User_Wechat_Cache_Expire_Time; // // //No arg constructor for Yaml.loadAs // public Settings() { // I = this; // } // // @Override // public String toString() { // return "Settings{" + // "Wechat_AppId='" + Wechat_AppId + '\'' + // ", Wechat_Secret='" + Wechat_Secret + '\'' + // ", Wechat_Token='" + Wechat_Token + '\'' + // ", Wechat_AesKey='" + Wechat_AesKey + '\'' + // ", Check_Spam_Cache_Expire_Time=" + Check_Spam_Cache_Expire_Time + // ", Check_Spam_Interval=" + Check_Spam_Interval + // ", User_Session_Max_Inactive=" + User_Session_Max_Inactive + // ", User_Wechat_Cache_Expire_Time=" + User_Wechat_Cache_Expire_Time + // '}'; // } // } // Path: src/main/java/love/sola/netsupport/wechat/matcher/CheckSpamMatcher.java import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.TimeUnit; import love.sola.netsupport.config.Settings; import me.chanjar.weixin.mp.api.WxMpMessageMatcher; import me.chanjar.weixin.mp.bean.WxMpXmlMessage; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.wechat.matcher; /** * @author Sola {@literal <[email protected]>} */ public class CheckSpamMatcher implements WxMpMessageMatcher { private class ValueLoader extends CacheLoader<String, Long> { @Override public Long load(String key) throws Exception {
return System.currentTimeMillis() + Settings.I.Check_Spam_Interval;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/enums/ISP.java
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public enum ISP { TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), OTHER(4, ".*"), ; private static final Map<String, ISP> NAME_MAP = new HashMap<>(); private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); static { for (ISP type : values()) { if (type.name != null) { NAME_MAP.put(type.name.toLowerCase(), type); } if (type.id > 0) { ID_MAP.put(type.id, type); } } } public final int id; public final String name; public final String accountRegex; ISP(int id, String accountRegex) { this.id = id;
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/enums/ISP.java import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public enum ISP { TELECOM(1, "^1[3|4|5|6|7|8|9][0-9]{9}$"), UNICOM(2, "^\\w+([-+.]\\w+)*@16900\\.gd"), CHINAMOBILE(3, "^1[3|4|5|6|7|8|9][0-9]{9}@139\\.gd$"), OTHER(4, ".*"), ; private static final Map<String, ISP> NAME_MAP = new HashMap<>(); private static final Map<Integer, ISP> ID_MAP = new HashMap<>(); static { for (ISP type : values()) { if (type.name != null) { NAME_MAP.put(type.name.toLowerCase(), type); } if (type.id > 0) { ID_MAP.put(type.id, type); } } } public final int id; public final String name; public final String accountRegex; ISP(int id, String accountRegex) { this.id = id;
this.name = lang("ISP_" + name());
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/enums/Status.java
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public class Status { public static final int UNCHECKED = 0; public static final int ARRANGED = 1; public static final int PUTOFF = 2; public static final int REPORTED = 4; public static final int ISP_HANDLED = 7; public static final int SOLVED = 9; public static final Map<Integer, String> inverseMap = new HashMap<>(); static { System.out.println("Loading Status..."); for (Field field : Status.class.getDeclaredFields()) { if (field.getType().isAssignableFrom(Integer.TYPE)) { try { inverseMap.put((Integer) field.get(null), field.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } public static String getLocalized(int status) { if (inverseMap.containsKey(status)) {
// Path: src/main/java/love/sola/netsupport/config/Lang.java // public static String lang(String key) { // String value = messages.get(key); // return value == null ? "!!" + key + "!!" : value; // } // Path: src/main/java/love/sola/netsupport/enums/Status.java import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import static love.sola.netsupport.config.Lang.lang; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.enums; /** * @author Sola {@literal <[email protected]>} */ public class Status { public static final int UNCHECKED = 0; public static final int ARRANGED = 1; public static final int PUTOFF = 2; public static final int REPORTED = 4; public static final int ISP_HANDLED = 7; public static final int SOLVED = 9; public static final Map<Integer, String> inverseMap = new HashMap<>(); static { System.out.println("Loading Status..."); for (Field field : Status.class.getDeclaredFields()) { if (field.getType().isAssignableFrom(Integer.TYPE)) { try { inverseMap.put((Integer) field.get(null), field.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } public static String getLocalized(int status) { if (inverseMap.containsKey(status)) {
return lang("STATUS_" + inverseMap.get(status));
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/root/DashBoard.java
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard";
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/root/DashBoard.java import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard";
access = Access.ROOT;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/root/DashBoard.java
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard"; access = Access.ROOT;
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/root/DashBoard.java import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard"; access = Access.ROOT;
authorize = Command.LOGIN;
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/api/root/DashBoard.java
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // }
import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard"; access = Access.ROOT; authorize = Command.LOGIN; } @Override
// Path: src/main/java/love/sola/netsupport/api/API.java // public abstract class API { // // public String url = null; //url // public int access = Access.GOD_MODE; //operator's permission // public Command authorize = null; //session check // // protected abstract Object process(HttpServletRequest req, WxSession session) throws Exception; // // @Override // public String toString() { // return getClass().getSimpleName() + "{" + // "url='" + url + '\'' + // ", access=" + Access.inverseMap.get(access) + // ", authorize=" + authorize + // '}'; // } // // public static String getParameterWithDefault(String obj, String def) { // return obj == null ? def : obj; // } // // public static Date getParameterAsDate(String obj, Date def) { // return obj == null ? def : new Date(Long.valueOf(obj)); // } // // public static Date getToday() { // return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); // } // // public static Date getDay(Date date) { // return DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // } // // } // // Path: src/main/java/love/sola/netsupport/enums/Access.java // public class Access { // // public static final int GOD_MODE = -1; // public static final int ROOT = 0; // public static final int MANAGER = 1; // public static final int CO_MANAGER = 2; // public static final int LEADER = 3; // public static final int CO_LEADER = 4; // public static final int ELITE = 5; // public static final int ELDER = 6; // public static final int MEMBER = 7; // public static final int PRE_MEMBER = 8; // public static final int NO_LOGIN = 9; // public static final int USER = 10; // public static final int GUEST = 11; // // public static final Map<Integer, String> inverseMap = new HashMap<>(); // // static { // System.out.println("Loading Access..."); // for (Field field : Access.class.getDeclaredFields()) { // if (field.getType().isAssignableFrom(Integer.TYPE)) { // try { // inverseMap.put((Integer) field.get(null), field.getName()); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // public static String getLocalized(int access) { // if (inverseMap.containsKey(access)) { // return lang("ACCESS_" + inverseMap.get(access)); // } // return null; // } // // } // // Path: src/main/java/love/sola/netsupport/session/WechatSession.java // public class WechatSession { // // private static MapSessionRepository repository; // // static { // repository = new MapSessionRepository(); // } // // public static WxSession get(String id) { // return repository.getSession(id); // } // // public static WxSession create() { // return repository.createSession(); // } // // public static Collection<? extends WxSession> list() { // return repository.asMap().values(); // } // // } // // Path: src/main/java/love/sola/netsupport/session/WxSession.java // public interface WxSession { // // String getId(); // // <T> T getAttribute(String name); // // Set<String> getAttributeNames(); // // void setAttribute(String name, Object value); // // void removeAttribute(String name); // // void invalidate(); // // } // // Path: src/main/java/love/sola/netsupport/wechat/Command.java // public enum Command { // // REGISTER(0, RegisterHandler.class), // QUERY(1, QueryHandler.class), // SUBMIT(2, SubmitHandler.class), // CANCEL(3, CancelHandler.class), // PROFILE(4, ProfileHandler.class), // LOGIN(10, LoginHandler.class), // OPERATOR_INFO(11, OperatorInfoHandler.class), // SIGN(12, SignHandler.class), //FIXME // ; // // private static final Map<Integer, Command> ID_MAP = new HashMap<>(); // // static { // for (Command type : values()) { // if (type.id >= 0) { // ID_MAP.put(type.id, type); // } // } // } // // public final String regex; // public final Class<? extends WxMpMessageHandler> handler; // public final int id; // // Command(int id, Class<? extends WxMpMessageHandler> handler) { // this.id = id; // this.regex = lang("REGEX_" + name()); // this.handler = handler; // } // // public static Command fromId(int id) { // return ID_MAP.get(id); // } // // @Override // public String toString() { // return name(); // } // // } // Path: src/main/java/love/sola/netsupport/api/root/DashBoard.java import java.util.Set; import javax.servlet.http.HttpServletRequest; import love.sola.netsupport.api.API; import love.sola.netsupport.enums.Access; import love.sola.netsupport.session.WechatSession; import love.sola.netsupport.session.WxSession; import love.sola.netsupport.wechat.Command; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.api.root; /** * @author Sola {@literal <[email protected]>} */ public class DashBoard extends API { public DashBoard() { url = "/root/dashboard"; access = Access.ROOT; authorize = Command.LOGIN; } @Override
protected Object process(HttpServletRequest req, WxSession session) throws Exception {
ZSCNetSupportDept/WechatTicketSystem
src/main/java/love/sola/netsupport/wechat/matcher/RegisterMatcher.java
// Path: src/main/java/love/sola/netsupport/sql/TableUser.java // @SuppressWarnings("Duplicates") // public class TableUser extends SQLCore { // // public static final String COLUMN_ID = "id"; // public static final String COLUMN_NAME = "name"; // public static final String COLUMN_ISP = "isp"; // public static final String COLUMN_NET_ACCOUNT = "netaccount"; // public static final String COLUMN_WECHAT = "wechat"; // public static final String COLUMN_BLOCK = "block"; // public static final String COLUMN_ROOM = "room"; // public static final String COLUMN_PHONE = "phone"; // // public static User getById(long id) { // try (Session s = sf.openSession()) { // return s.get(User.class, id); // } // } // // public static User getByName(String name) { // try (Session s = sf.openSession()) { // return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_NAME, name)).uniqueResult(); // } // } // // public static User getByWechat(String wechat) { // try { // User u = cache.get(wechat); // return u == NULL_USER ? null : u; // } catch (ExecutionException e) { // e.printStackTrace(); // return null; // } // } // // public static int update(User user) { // try (Session s = sf.openSession()) { // s.beginTransaction(); // s.update(user); // s.getTransaction().commit(); // cache.put(user.getWechatId(), user); // return 1; // } // } // // protected static void init() { // try (Session s = SQLCore.sf.openSession()) { // User.OFFICIAL_CHINA_UNICOM_XH = s.get(User.class, 100104L); // User.OFFICIAL_CHINA_MOBILE_XH = s.get(User.class, 100864L); // User.OFFICIAL_CHINA_MOBILE_FX = s.get(User.class, 100865L); // } // } // // private static LoadingCache<String, User> cache = CacheBuilder.newBuilder() // .concurrencyLevel(4) // .maximumSize(4096) // .expireAfterAccess(Settings.I.User_Wechat_Cache_Expire_Time, TimeUnit.SECONDS) // .build(new ValueLoader()); // // private static class ValueLoader extends CacheLoader<String, User> { // @Override // public User load(String key) throws Exception { // User u = TableUser.getByWechat0(key); // return u == null ? NULL_USER : u; // } // } // // private static final User NULL_USER = new User(); // // public static void flushCache() { // cache.invalidateAll(); // } // // private static User getByWechat0(String wechat) { // try (Session s = sf.openSession()) { // return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_WECHAT, wechat)).uniqueResult(); // } // } // // }
import love.sola.netsupport.sql.TableUser; import me.chanjar.weixin.mp.api.WxMpMessageMatcher; import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
/* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.wechat.matcher; /** * @author Sola {@literal <[email protected]>} */ public class RegisterMatcher implements WxMpMessageMatcher { @Override public boolean match(WxMpXmlMessage message) {
// Path: src/main/java/love/sola/netsupport/sql/TableUser.java // @SuppressWarnings("Duplicates") // public class TableUser extends SQLCore { // // public static final String COLUMN_ID = "id"; // public static final String COLUMN_NAME = "name"; // public static final String COLUMN_ISP = "isp"; // public static final String COLUMN_NET_ACCOUNT = "netaccount"; // public static final String COLUMN_WECHAT = "wechat"; // public static final String COLUMN_BLOCK = "block"; // public static final String COLUMN_ROOM = "room"; // public static final String COLUMN_PHONE = "phone"; // // public static User getById(long id) { // try (Session s = sf.openSession()) { // return s.get(User.class, id); // } // } // // public static User getByName(String name) { // try (Session s = sf.openSession()) { // return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_NAME, name)).uniqueResult(); // } // } // // public static User getByWechat(String wechat) { // try { // User u = cache.get(wechat); // return u == NULL_USER ? null : u; // } catch (ExecutionException e) { // e.printStackTrace(); // return null; // } // } // // public static int update(User user) { // try (Session s = sf.openSession()) { // s.beginTransaction(); // s.update(user); // s.getTransaction().commit(); // cache.put(user.getWechatId(), user); // return 1; // } // } // // protected static void init() { // try (Session s = SQLCore.sf.openSession()) { // User.OFFICIAL_CHINA_UNICOM_XH = s.get(User.class, 100104L); // User.OFFICIAL_CHINA_MOBILE_XH = s.get(User.class, 100864L); // User.OFFICIAL_CHINA_MOBILE_FX = s.get(User.class, 100865L); // } // } // // private static LoadingCache<String, User> cache = CacheBuilder.newBuilder() // .concurrencyLevel(4) // .maximumSize(4096) // .expireAfterAccess(Settings.I.User_Wechat_Cache_Expire_Time, TimeUnit.SECONDS) // .build(new ValueLoader()); // // private static class ValueLoader extends CacheLoader<String, User> { // @Override // public User load(String key) throws Exception { // User u = TableUser.getByWechat0(key); // return u == null ? NULL_USER : u; // } // } // // private static final User NULL_USER = new User(); // // public static void flushCache() { // cache.invalidateAll(); // } // // private static User getByWechat0(String wechat) { // try (Session s = sf.openSession()) { // return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_WECHAT, wechat)).uniqueResult(); // } // } // // } // Path: src/main/java/love/sola/netsupport/wechat/matcher/RegisterMatcher.java import love.sola.netsupport.sql.TableUser; import me.chanjar.weixin.mp.api.WxMpMessageMatcher; import me.chanjar.weixin.mp.bean.WxMpXmlMessage; /* * This file is part of WechatTicketSystem. * * WechatTicketSystem is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WechatTicketSystem 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>. */ package love.sola.netsupport.wechat.matcher; /** * @author Sola {@literal <[email protected]>} */ public class RegisterMatcher implements WxMpMessageMatcher { @Override public boolean match(WxMpXmlMessage message) {
return TableUser.getByWechat(message.getFromUserName()) == null;
Ellzord/JALSE
src/test/java/jalse/attributes/AttributesTest.java
// Path: src/main/java/jalse/entities/Entity.java // public interface Entity extends EntityContainer, Identifiable, AttributeContainer, Taggable, ActionScheduler<Entity> { // // /** // * Adds a listener for the entity. // * // * @param listener // * Listener to add. // * // * @return {@code true} if container did not already contain this listener. // * @throws NullPointerException // * if listener is null. // * // * @see ListenerSet#add(Object) // * // */ // boolean addEntityTypeListener(EntityTypeListener listener); // // /** // * Convenience method for wrapping the entity to a different type. // * // * @param type // * Entity type to wrap to. // * @return The wrapped entity. // * // * @see Entities#asType(Entity, Class) // */ // default <T extends Entity> T asType(final Class<T> type) { // return Entities.asType(this, type); // } // // /** // * Gets the parent container. // * // * @return The parent container or null if not found. // */ // EntityContainer getContainer(); // // /** // * Gets all the entity listeners. // * // * @return All the entity listeners. // */ // Set<? extends EntityTypeListener> getEntityTypeListeners(); // // /** // * Gets the types this entity has been marked as. // * // * @return Marked types. // * // * @see #streamMarkedAsTypes() // */ // default Set<Class<? extends Entity>> getMarkedAsTypes() { // return streamMarkedAsTypes().collect(Collectors.toSet()); // } // // /** // * This is a convenience method for getting the container (optional). // * // * @return Optional containing the container or else empty optional if the entity is not alive. // */ // default Optional<EntityContainer> getOptContainer() { // return Optional.ofNullable(getContainer()); // } // // /** // * Checks whether there is an associated container. // * // * @return Whether there was a container. // */ // default boolean hasContainer() { // return getContainer() != null; // } // // /** // * Checks whether the container contains a particular listener. // * // * @param listener // * The EntityListener to check for. // * @return Whether the container contains the given EntityListener. // */ // default boolean hasEntityTypeListener(final EntityTypeListener listener) { // return getEntityTypeListeners().contains(listener); // } // // /** // * Checks if the entity is alive. // * // * @return Whether the entity is alive. // */ // boolean isAlive(); // // /** // * Checks whether the entity has the associated type. // * // * @param type // * Entity type to check. // * @return Whether the entity was previously associated to the type. // */ // boolean isMarkedAsType(Class<? extends Entity> type); // // /** // * Kills the entity. // * // * @return Whether the entity was alive. // */ // boolean kill(); // // /** // * Adds the specified type to the entity. If any of the ancestry of this type are not associated // * to this entity they will also be added. // * // * @param type // * Entity type to add. // * @return Whether the type was not associated to the entity. // */ // boolean markAsType(Class<? extends Entity> type); // // /** // * Removes a entity listener. // * // * @param listener // * Listener to remove. // * // * @return {@code true} if the listener was removed. // * @throws NullPointerException // * if listener is null. // * // * @see ListenerSet#remove(Object) // * // */ // boolean removeEntityTypeListener(EntityTypeListener listener); // // /** // * Removes all listeners for entities. // */ // void removeEntityTypeListeners(); // // /** // * Streams the types this entity has been marked as. // * // * @return Stream of marked types. // * // */ // Stream<Class<? extends Entity>> streamMarkedAsTypes(); // // /** // * Transfers this entity to the specified destination container. // * // * @param destination // * Target container. // * @return Whether the entity was transferred. // * // */ // boolean transfer(EntityContainer destination); // // /** // * Removes all the types from the entity. // */ // void unmarkAsAllTypes(); // // /** // * Removes the specified type from the entity. If this type is the ancestor of any other types // * associated to the entity they will be removed. // * // * @param type // * Entity type to remove. // * @return Whether the entity was previously associated to the type (or its any of its // * children). // */ // boolean unmarkAsType(Class<? extends Entity> type); // }
import org.junit.After; import org.junit.Assert; import org.junit.Test; import jalse.entities.Entity;
package jalse.attributes; public class AttributesTest { AttributeType<?> attributeType; @After public void after() { attributeType = null; } @Test public void attributeTypeTest() { Assert.assertEquals(new AttributeType<Boolean>() {}, Attributes.BOOLEAN_TYPE); Assert.assertEquals(new AttributeType<Integer>() {}, Attributes.INTEGER_TYPE); Assert.assertEquals(new AttributeType<String>() {}, Attributes.STRING_TYPE); Assert.assertEquals(new AttributeType<Double>() {}, Attributes.DOUBLE_TYPE); Assert.assertEquals(new AttributeType<Character>() {}, Attributes.CHARACTER_TYPE); Assert.assertEquals(new AttributeType<Long>() {}, Attributes.LONG_TYPE); Assert.assertEquals(new AttributeType<Byte>() {}, Attributes.BYTE_TYPE); Assert.assertEquals(new AttributeType<Float>() {}, Attributes.FLOAT_TYPE); Assert.assertEquals(new AttributeType<Short>() {}, Attributes.SHORT_TYPE); Assert.assertEquals(new AttributeType<Object>() {}, Attributes.OBJECT_TYPE);
// Path: src/main/java/jalse/entities/Entity.java // public interface Entity extends EntityContainer, Identifiable, AttributeContainer, Taggable, ActionScheduler<Entity> { // // /** // * Adds a listener for the entity. // * // * @param listener // * Listener to add. // * // * @return {@code true} if container did not already contain this listener. // * @throws NullPointerException // * if listener is null. // * // * @see ListenerSet#add(Object) // * // */ // boolean addEntityTypeListener(EntityTypeListener listener); // // /** // * Convenience method for wrapping the entity to a different type. // * // * @param type // * Entity type to wrap to. // * @return The wrapped entity. // * // * @see Entities#asType(Entity, Class) // */ // default <T extends Entity> T asType(final Class<T> type) { // return Entities.asType(this, type); // } // // /** // * Gets the parent container. // * // * @return The parent container or null if not found. // */ // EntityContainer getContainer(); // // /** // * Gets all the entity listeners. // * // * @return All the entity listeners. // */ // Set<? extends EntityTypeListener> getEntityTypeListeners(); // // /** // * Gets the types this entity has been marked as. // * // * @return Marked types. // * // * @see #streamMarkedAsTypes() // */ // default Set<Class<? extends Entity>> getMarkedAsTypes() { // return streamMarkedAsTypes().collect(Collectors.toSet()); // } // // /** // * This is a convenience method for getting the container (optional). // * // * @return Optional containing the container or else empty optional if the entity is not alive. // */ // default Optional<EntityContainer> getOptContainer() { // return Optional.ofNullable(getContainer()); // } // // /** // * Checks whether there is an associated container. // * // * @return Whether there was a container. // */ // default boolean hasContainer() { // return getContainer() != null; // } // // /** // * Checks whether the container contains a particular listener. // * // * @param listener // * The EntityListener to check for. // * @return Whether the container contains the given EntityListener. // */ // default boolean hasEntityTypeListener(final EntityTypeListener listener) { // return getEntityTypeListeners().contains(listener); // } // // /** // * Checks if the entity is alive. // * // * @return Whether the entity is alive. // */ // boolean isAlive(); // // /** // * Checks whether the entity has the associated type. // * // * @param type // * Entity type to check. // * @return Whether the entity was previously associated to the type. // */ // boolean isMarkedAsType(Class<? extends Entity> type); // // /** // * Kills the entity. // * // * @return Whether the entity was alive. // */ // boolean kill(); // // /** // * Adds the specified type to the entity. If any of the ancestry of this type are not associated // * to this entity they will also be added. // * // * @param type // * Entity type to add. // * @return Whether the type was not associated to the entity. // */ // boolean markAsType(Class<? extends Entity> type); // // /** // * Removes a entity listener. // * // * @param listener // * Listener to remove. // * // * @return {@code true} if the listener was removed. // * @throws NullPointerException // * if listener is null. // * // * @see ListenerSet#remove(Object) // * // */ // boolean removeEntityTypeListener(EntityTypeListener listener); // // /** // * Removes all listeners for entities. // */ // void removeEntityTypeListeners(); // // /** // * Streams the types this entity has been marked as. // * // * @return Stream of marked types. // * // */ // Stream<Class<? extends Entity>> streamMarkedAsTypes(); // // /** // * Transfers this entity to the specified destination container. // * // * @param destination // * Target container. // * @return Whether the entity was transferred. // * // */ // boolean transfer(EntityContainer destination); // // /** // * Removes all the types from the entity. // */ // void unmarkAsAllTypes(); // // /** // * Removes the specified type from the entity. If this type is the ancestor of any other types // * associated to the entity they will be removed. // * // * @param type // * Entity type to remove. // * @return Whether the entity was previously associated to the type (or its any of its // * children). // */ // boolean unmarkAsType(Class<? extends Entity> type); // } // Path: src/test/java/jalse/attributes/AttributesTest.java import org.junit.After; import org.junit.Assert; import org.junit.Test; import jalse.entities.Entity; package jalse.attributes; public class AttributesTest { AttributeType<?> attributeType; @After public void after() { attributeType = null; } @Test public void attributeTypeTest() { Assert.assertEquals(new AttributeType<Boolean>() {}, Attributes.BOOLEAN_TYPE); Assert.assertEquals(new AttributeType<Integer>() {}, Attributes.INTEGER_TYPE); Assert.assertEquals(new AttributeType<String>() {}, Attributes.STRING_TYPE); Assert.assertEquals(new AttributeType<Double>() {}, Attributes.DOUBLE_TYPE); Assert.assertEquals(new AttributeType<Character>() {}, Attributes.CHARACTER_TYPE); Assert.assertEquals(new AttributeType<Long>() {}, Attributes.LONG_TYPE); Assert.assertEquals(new AttributeType<Byte>() {}, Attributes.BYTE_TYPE); Assert.assertEquals(new AttributeType<Float>() {}, Attributes.FLOAT_TYPE); Assert.assertEquals(new AttributeType<Short>() {}, Attributes.SHORT_TYPE); Assert.assertEquals(new AttributeType<Object>() {}, Attributes.OBJECT_TYPE);
Assert.assertEquals(new AttributeType<Entity>() {}, Attributes.newTypeOf(Entity.class));
Ellzord/JALSE
src/main/java/jalse/entities/Entities.java
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // }
import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; import jalse.attributes.AttributeListener; import jalse.attributes.NamedAttributeType; import jalse.entities.EntityVisitor.EntityVisitResult;
* @return Whether the descendant is equal or descended from the ancestor type. */ public static boolean isOrSubtype(final Class<? extends Entity> descendant, final Class<? extends Entity> ancestor) { return ancestor.isAssignableFrom(descendant); } /** * Checks if the specified type is a descendant from the specified ancestor type. * * @param descendant * Descendant type. * @param ancestor * Ancestor type. * @return Whether the descendant is descended from the ancestor type. */ public static boolean isSubtype(final Class<? extends Entity> descendant, final Class<? extends Entity> ancestor) { return !ancestor.equals(descendant) && ancestor.isAssignableFrom(descendant); } /** * Creates an recursive entity listener for named attribute type and the supplied attribute * listener supplier with Integer.MAX_VALUE recursion limit. * * @param namedType * Named attribute type being listened for by supplier's listeners. * @param supplier * Supplier of the attribute listener to be added to created entities. * @return Recursive attribute listener for named type and supplier. */
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // } // Path: src/main/java/jalse/entities/Entities.java import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; import jalse.attributes.AttributeListener; import jalse.attributes.NamedAttributeType; import jalse.entities.EntityVisitor.EntityVisitResult; * @return Whether the descendant is equal or descended from the ancestor type. */ public static boolean isOrSubtype(final Class<? extends Entity> descendant, final Class<? extends Entity> ancestor) { return ancestor.isAssignableFrom(descendant); } /** * Checks if the specified type is a descendant from the specified ancestor type. * * @param descendant * Descendant type. * @param ancestor * Ancestor type. * @return Whether the descendant is descended from the ancestor type. */ public static boolean isSubtype(final Class<? extends Entity> descendant, final Class<? extends Entity> ancestor) { return !ancestor.equals(descendant) && ancestor.isAssignableFrom(descendant); } /** * Creates an recursive entity listener for named attribute type and the supplied attribute * listener supplier with Integer.MAX_VALUE recursion limit. * * @param namedType * Named attribute type being listened for by supplier's listeners. * @param supplier * Supplier of the attribute listener to be added to created entities. * @return Recursive attribute listener for named type and supplier. */
public static <T> EntityListener newRecursiveAttributeListener(final NamedAttributeType<T> namedType,
Ellzord/JALSE
src/main/java/jalse/attributes/DefaultAttributeContainer.java
// Path: src/main/java/jalse/misc/ListenerSet.java // public class ListenerSet<T> extends LinkedHashSet<T>implements InvocationHandler { // // private static final long serialVersionUID = 1437345792255852480L; // // private final T proxy; // // /** // * Creates a new instance of listener set for the supplied listener type. // * // * @param clazz // * Listener type to store. // */ // public ListenerSet(final Class<? super T> clazz) { // this(clazz, null); // } // // /** // * Creates a new instance of listener set for the supplied listener type. // * // * @param clazz // * Listener type to store. // * @param listeners // * Starting listeners. // */ // @SuppressWarnings("unchecked") // public ListenerSet(final Class<? super T> clazz, final Set<? extends T> listeners) { // proxy = (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz }, this); // if (listeners != null) { // addAll(listeners); // } // } // // @Override // public boolean add(final T e) { // return super.add(Objects.requireNonNull(e)); // } // // /** // * Gets the group proxy for easy invocation of methods upon the group. // * // * @return Listener group proxy. // */ // public T getProxy() { // return proxy; // } // // @Override // public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { // for (final T t : this) { // method.invoke(t, args); // } // return null; // } // // @Override // public boolean remove(final Object o) { // return super.remove(Objects.requireNonNull(o)); // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Stream; import jalse.misc.ListenerSet;
} /** * Sets an attribute value. * * @param name * Attribute name. * @param type * Attribute type. * @param value * Value to set. * @return This builder. */ public <T> Builder setAttribute(final String name, final AttributeType<T> type, final T value) { return setAttribute(new NamedAttributeType<>(name, type), value); } /** * Sets the delegate attribute container. * * @param builderDelegateContainer * Delegate container to set. * @return This builder. */ public Builder setDelegateContainer(final AttributeContainer builderDelegateContainer) { this.builderDelegateContainer = Objects.requireNonNull(builderDelegateContainer); return this; } }
// Path: src/main/java/jalse/misc/ListenerSet.java // public class ListenerSet<T> extends LinkedHashSet<T>implements InvocationHandler { // // private static final long serialVersionUID = 1437345792255852480L; // // private final T proxy; // // /** // * Creates a new instance of listener set for the supplied listener type. // * // * @param clazz // * Listener type to store. // */ // public ListenerSet(final Class<? super T> clazz) { // this(clazz, null); // } // // /** // * Creates a new instance of listener set for the supplied listener type. // * // * @param clazz // * Listener type to store. // * @param listeners // * Starting listeners. // */ // @SuppressWarnings("unchecked") // public ListenerSet(final Class<? super T> clazz, final Set<? extends T> listeners) { // proxy = (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz }, this); // if (listeners != null) { // addAll(listeners); // } // } // // @Override // public boolean add(final T e) { // return super.add(Objects.requireNonNull(e)); // } // // /** // * Gets the group proxy for easy invocation of methods upon the group. // * // * @return Listener group proxy. // */ // public T getProxy() { // return proxy; // } // // @Override // public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { // for (final T t : this) { // method.invoke(t, args); // } // return null; // } // // @Override // public boolean remove(final Object o) { // return super.remove(Objects.requireNonNull(o)); // } // } // Path: src/main/java/jalse/attributes/DefaultAttributeContainer.java import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Stream; import jalse.misc.ListenerSet; } /** * Sets an attribute value. * * @param name * Attribute name. * @param type * Attribute type. * @param value * Value to set. * @return This builder. */ public <T> Builder setAttribute(final String name, final AttributeType<T> type, final T value) { return setAttribute(new NamedAttributeType<>(name, type), value); } /** * Sets the delegate attribute container. * * @param builderDelegateContainer * Delegate container to set. * @return This builder. */ public Builder setDelegateContainer(final AttributeContainer builderDelegateContainer) { this.builderDelegateContainer = Objects.requireNonNull(builderDelegateContainer); return this; } }
private final Map<NamedAttributeType<?>, ListenerSet<?>> listeners;
Ellzord/JALSE
src/test/java/jalse/entities/EntityContainerTest.java
// Path: src/main/java/jalse/entities/Entities.java // public static <T extends Entity> T asType(final Entity entity, final Class<T> type) { // return getProxyFactory().proxyOfEntity(entity, type); // }
import static jalse.entities.Entities.asType; import java.util.HashSet; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import org.junit.After; import org.junit.Assert; import org.junit.Test;
Assert.assertFalse(container.hasEntity(new UUID(0, 100))); Optional<Entity> optEntity = container.getOptEntity(new UUID(0, 100)); Assert.assertFalse(optEntity.isPresent()); optEntity = container.getOptEntity(new UUID(0, 0)); Assert.assertTrue(optEntity.isPresent()); } @After public void after() { container = null; } @Test public void entityClassTest() { container = new DefaultEntityContainer(); container.newEntity(); container.newEntity(new UUID(0, 0)); container.newEntity(TestEntity.class); container.newEntity(new UUID(0, 1), TestEntity.class); final HashSet<DefaultEntity> entities = (HashSet<DefaultEntity>) container .getEntitiesOfType(DefaultEntity.class); for (final Entity entity : entities) { Assert.assertEquals(DefaultEntity.class, entity.getClass()); } final Stream<DefaultEntity> entityStream = container.streamEntitiesOfType(DefaultEntity.class); entityStream.forEach(e -> Assert.assertEquals(DefaultEntity.class, e.getClass()));
// Path: src/main/java/jalse/entities/Entities.java // public static <T extends Entity> T asType(final Entity entity, final Class<T> type) { // return getProxyFactory().proxyOfEntity(entity, type); // } // Path: src/test/java/jalse/entities/EntityContainerTest.java import static jalse.entities.Entities.asType; import java.util.HashSet; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import org.junit.After; import org.junit.Assert; import org.junit.Test; Assert.assertFalse(container.hasEntity(new UUID(0, 100))); Optional<Entity> optEntity = container.getOptEntity(new UUID(0, 100)); Assert.assertFalse(optEntity.isPresent()); optEntity = container.getOptEntity(new UUID(0, 0)); Assert.assertTrue(optEntity.isPresent()); } @After public void after() { container = null; } @Test public void entityClassTest() { container = new DefaultEntityContainer(); container.newEntity(); container.newEntity(new UUID(0, 0)); container.newEntity(TestEntity.class); container.newEntity(new UUID(0, 1), TestEntity.class); final HashSet<DefaultEntity> entities = (HashSet<DefaultEntity>) container .getEntitiesOfType(DefaultEntity.class); for (final Entity entity : entities) { Assert.assertEquals(DefaultEntity.class, entity.getClass()); } final Stream<DefaultEntity> entityStream = container.streamEntitiesOfType(DefaultEntity.class); entityStream.forEach(e -> Assert.assertEquals(DefaultEntity.class, e.getClass()));
final Class<? extends TestEntity> type = asType(container.getEntity(new UUID(0, 0)), TestEntity.class)
Ellzord/JALSE
src/main/java/jalse/entities/RecursiveAttributeListener.java
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // }
import java.util.Objects; import java.util.function.Supplier; import jalse.attributes.AttributeListener; import jalse.attributes.NamedAttributeType;
package jalse.entities; class RecursiveAttributeListener<T> implements EntityListener { private final Supplier<AttributeListener<T>> supplier;
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // } // Path: src/main/java/jalse/entities/RecursiveAttributeListener.java import java.util.Objects; import java.util.function.Supplier; import jalse.attributes.AttributeListener; import jalse.attributes.NamedAttributeType; package jalse.entities; class RecursiveAttributeListener<T> implements EntityListener { private final Supplier<AttributeListener<T>> supplier;
private final NamedAttributeType<T> namedType;
Ellzord/JALSE
src/test/java/jalse/entities/EntitiesTest.java
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // }
import java.util.Objects; import org.junit.Assert; import org.junit.Test; import jalse.attributes.AttributeListener; import jalse.attributes.Attributes; import jalse.attributes.NamedAttributeType;
package jalse.entities; public class EntitiesTest { private EntitiesTest() {} public static class RecursiveAttributeListenerTest { private class TestAttributeListener implements AttributeListener<Integer> {} @Test public void createRecursiveAttributeListenerTest() { final EntityListener listener = Entities .newRecursiveAttributeListener(Attributes.newNamedIntegerType("Test"), TestAttributeListener::new); final EntityListener depthLimitedListener = Entities.newRecursiveAttributeListener( Attributes.newNamedIntegerType("Test"), TestAttributeListener::new, 3); Assert.assertTrue(Objects.nonNull(listener)); Assert.assertTrue(Objects.nonNull(depthLimitedListener)); } @Test public void recursionTest() {
// Path: src/main/java/jalse/attributes/NamedAttributeType.java // public final class NamedAttributeType<T> { // // private final String name; // private final AttributeType<T> type; // // /** // * Creates a new named attribute type. // * // * @param name // * Attribute type name. // * @param type // * Attribute type. // */ // public NamedAttributeType(final String name, final AttributeType<T> type) { // this.name = requireNotEmpty(name); // this.type = Objects.requireNonNull(type); // } // // @Override // public boolean equals(final Object obj) { // if (obj == this) { // return true; // } // // if (!(obj instanceof NamedAttributeType<?>)) { // return false; // } // // final NamedAttributeType<?> other = (NamedAttributeType<?>) obj; // return name.equals(other.name) && type.equals(other.type); // } // // /** // * Gets the attribute type name. // * // * @return Name. // */ // public String getName() { // return name; // } // // /** // * Gets the attribute type. // * // * @return Attribute type. // */ // public AttributeType<T> getType() { // return type; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + name.hashCode(); // result = prime * result + type.hashCode(); // return result; // } // // @Override // public String toString() { // return "NamedAttributeType [" + name + ":" + type.getValueType().getTypeName() + "]"; // } // } // Path: src/test/java/jalse/entities/EntitiesTest.java import java.util.Objects; import org.junit.Assert; import org.junit.Test; import jalse.attributes.AttributeListener; import jalse.attributes.Attributes; import jalse.attributes.NamedAttributeType; package jalse.entities; public class EntitiesTest { private EntitiesTest() {} public static class RecursiveAttributeListenerTest { private class TestAttributeListener implements AttributeListener<Integer> {} @Test public void createRecursiveAttributeListenerTest() { final EntityListener listener = Entities .newRecursiveAttributeListener(Attributes.newNamedIntegerType("Test"), TestAttributeListener::new); final EntityListener depthLimitedListener = Entities.newRecursiveAttributeListener( Attributes.newNamedIntegerType("Test"), TestAttributeListener::new, 3); Assert.assertTrue(Objects.nonNull(listener)); Assert.assertTrue(Objects.nonNull(depthLimitedListener)); } @Test public void recursionTest() {
final NamedAttributeType<Integer> testType = Attributes.newNamedIntegerType("Test");
jakobadam/rdp
src/net/propero/rdp/applet/RdpApplet.java
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // }
import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber;
/* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents();
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // } // Path: src/net/propero/rdp/applet/RdpApplet.java import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber; /* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents();
Common.underApplet = true;
jakobadam/rdp
src/net/propero/rdp/applet/RdpApplet.java
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // }
import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber;
/* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true;
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // } // Path: src/net/propero/rdp/applet/RdpApplet.java import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber; /* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true;
publishEvent(RdpEvent.INIT, id);
jakobadam/rdp
src/net/propero/rdp/applet/RdpApplet.java
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // }
import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber;
/* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true; publishEvent(RdpEvent.INIT, id); } private void subscribeToRdpEvents(){
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // } // Path: src/net/propero/rdp/applet/RdpApplet.java import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber; /* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true; publishEvent(RdpEvent.INIT, id); } private void subscribeToRdpEvents(){
RdpEventPublisher.subscribe(new RdpEventSubscriber(){
jakobadam/rdp
src/net/propero/rdp/applet/RdpApplet.java
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // }
import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber;
/* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true; publishEvent(RdpEvent.INIT, id); } private void subscribeToRdpEvents(){
// Path: src/net/propero/rdp/Common.java // public class Common { // // public static boolean underApplet = false; // // public static Rdp5 rdp; // // public static Secure secure; // // public static MCS mcs; // // public static RdesktopFrame frame; // // /** // * Quit the application // */ // public static void exit() { // Rdesktop.exit(0, rdp, frame, true); // } // } // // Path: src/net/propero/rdp/RdpEvent.java // public enum RdpEvent { // INIT("init"), // DESTROY("destroy"); // // private String name; // // RdpEvent(String name) { // this.name = name; // } // // public String toString() { // return name; // } // } // // Path: src/net/propero/rdp/RdpEventPublisher.java // public class RdpEventPublisher { // // static Logger logger = Logger.getLogger(RdpEventPublisher.class); // // private static List<RdpEventSubscriber> subscribers = new ArrayList<RdpEventSubscriber>(); // // public static void subscribe(RdpEventSubscriber listener){ // subscribers.add(listener); // } // // public static void publish(RdpEvent e, String txt){ // publish(e, txt, null); // } // // public static void publish(RdpEvent e, String txt, Exception ex){ // logger.info("publish: " + e + " " + txt + (ex != null ? " " + ex : "")); // // switch(e){ // case DESTROY: // for(RdpEventSubscriber s : subscribers){s.destroy(txt);} // break; // default: // System.err.println("WTF?"); // } // } // } // // Path: src/net/propero/rdp/RdpEventSubscriber.java // public interface RdpEventSubscriber { // // public void destroy(String s); // // } // Path: src/net/propero/rdp/applet/RdpApplet.java import java.io.File; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.StringTokenizer; import net.propero.rdp.Common; import net.propero.rdp.RdpEvent; import net.propero.rdp.RdpEventPublisher; import net.propero.rdp.RdpEventSubscriber; /* RdpApplet.java * Component: ProperJavaRDP * * Revision: $Revision: 13 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 14:14:45 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide an applet interface to ProperJavaRDP * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.applet; public class RdpApplet extends Applet2 { private String id; public void start() { System.out.println("new applet"); id = getRequiredParameter("id"); subscribeToRdpEvents(); Common.underApplet = true; publishEvent(RdpEvent.INIT, id); } private void subscribeToRdpEvents(){
RdpEventPublisher.subscribe(new RdpEventSubscriber(){
jakobadam/rdp
src/net/propero/rdp/Common.java
// Path: src/net/propero/rdp/rdp5/Rdp5.java // public class Rdp5 extends Rdp { // // private VChannels channels; // // /** // * Initialise the RDP5 communications layer, with specified virtual channels // * // * @param channels // * Virtual channels for RDP layer // */ // public Rdp5(VChannels channels) { // super(channels); // this.channels = channels; // } // // /** // * Process an RDP5 packet // * // * @param s // * Packet to be processed // * @param e // * True if packet is encrypted // * @throws RdesktopException // * @throws OrderException // * @throws CryptoException // */ // public void rdp5_process(RdpPacket_Localised s, boolean e) // throws RdesktopException, OrderException, CryptoException { // rdp5_process(s, e, false); // } // // /** // * Process an RDP5 packet // * // * @param s // * Packet to be processed // * @param encryption // * True if packet is encrypted // * @param shortform // * True if packet is of the "short" form // * @throws RdesktopException // * @throws OrderException // * @throws CryptoException // */ // public void rdp5_process(RdpPacket_Localised s, boolean encryption, // boolean shortform) throws RdesktopException, OrderException, // CryptoException { // logger.debug("Processing RDP 5 order"); // // int length, count; // int type; // int next; // // if (encryption) { // s.incrementPosition(shortform ? 6 : 7 /* XXX HACK */); /* signature */ // byte[] data = new byte[s.size() - s.getPosition()]; // s.copyToByteArray(data, 0, s.getPosition(), data.length); // byte[] packet = SecureLayer.decrypt(data); // } // // // printf("RDP5 data:\n"); // // hexdump(s->p, s->end - s->p); // // while (s.getPosition() < s.getEnd()) { // type = s.get8(); // length = s.getLittleEndian16(); // /* next_packet = */next = s.getPosition() + length; // logger.debug("RDP5: type = " + type); // switch (type) { // case 0: /* orders */ // count = s.getLittleEndian16(); // orders.processOrders(s, next, count); // break; // case 1: /* bitmap update (???) */ // s.incrementPosition(2); /* part length */ // processBitmapUpdates(s); // break; // case 2: /* palette */ // s.incrementPosition(2); // processPalette(s); // break; // case 3: /* probably an palette with offset 3. Weird */ // break; // case 5: // process_null_system_pointer_pdu(s); // break; // case 6: // default pointer // break; // case 9: // process_colour_pointer_pdu(s); // break; // case 10: // process_cached_pointer_pdu(s); // break; // default: // logger.warn("Unimplemented RDP5 opcode " + type); // } // // s.setPosition(next); // } // } // // /** // * Process an RDP5 packet from a virtual channel // * // * @param s // * Packet to be processed // * @param channelno // * Channel on which packet was received // */ // void rdp5_process_channel(RdpPacket_Localised s, int channelno) { // VChannel channel = channels.find_channel_by_channelno(channelno); // if (channel != null) { // try { // channel.process(s); // } catch (Exception e) { // } // } // } // // }
import net.propero.rdp.rdp5.Rdp5;
/* Common.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide a static interface to individual network layers * and UI components * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; public class Common { public static boolean underApplet = false;
// Path: src/net/propero/rdp/rdp5/Rdp5.java // public class Rdp5 extends Rdp { // // private VChannels channels; // // /** // * Initialise the RDP5 communications layer, with specified virtual channels // * // * @param channels // * Virtual channels for RDP layer // */ // public Rdp5(VChannels channels) { // super(channels); // this.channels = channels; // } // // /** // * Process an RDP5 packet // * // * @param s // * Packet to be processed // * @param e // * True if packet is encrypted // * @throws RdesktopException // * @throws OrderException // * @throws CryptoException // */ // public void rdp5_process(RdpPacket_Localised s, boolean e) // throws RdesktopException, OrderException, CryptoException { // rdp5_process(s, e, false); // } // // /** // * Process an RDP5 packet // * // * @param s // * Packet to be processed // * @param encryption // * True if packet is encrypted // * @param shortform // * True if packet is of the "short" form // * @throws RdesktopException // * @throws OrderException // * @throws CryptoException // */ // public void rdp5_process(RdpPacket_Localised s, boolean encryption, // boolean shortform) throws RdesktopException, OrderException, // CryptoException { // logger.debug("Processing RDP 5 order"); // // int length, count; // int type; // int next; // // if (encryption) { // s.incrementPosition(shortform ? 6 : 7 /* XXX HACK */); /* signature */ // byte[] data = new byte[s.size() - s.getPosition()]; // s.copyToByteArray(data, 0, s.getPosition(), data.length); // byte[] packet = SecureLayer.decrypt(data); // } // // // printf("RDP5 data:\n"); // // hexdump(s->p, s->end - s->p); // // while (s.getPosition() < s.getEnd()) { // type = s.get8(); // length = s.getLittleEndian16(); // /* next_packet = */next = s.getPosition() + length; // logger.debug("RDP5: type = " + type); // switch (type) { // case 0: /* orders */ // count = s.getLittleEndian16(); // orders.processOrders(s, next, count); // break; // case 1: /* bitmap update (???) */ // s.incrementPosition(2); /* part length */ // processBitmapUpdates(s); // break; // case 2: /* palette */ // s.incrementPosition(2); // processPalette(s); // break; // case 3: /* probably an palette with offset 3. Weird */ // break; // case 5: // process_null_system_pointer_pdu(s); // break; // case 6: // default pointer // break; // case 9: // process_colour_pointer_pdu(s); // break; // case 10: // process_cached_pointer_pdu(s); // break; // default: // logger.warn("Unimplemented RDP5 opcode " + type); // } // // s.setPosition(next); // } // } // // /** // * Process an RDP5 packet from a virtual channel // * // * @param s // * Packet to be processed // * @param channelno // * Channel on which packet was received // */ // void rdp5_process_channel(RdpPacket_Localised s, int channelno) { // VChannel channel = channels.find_channel_by_channelno(channelno); // if (channel != null) { // try { // channel.process(s); // } catch (Exception e) { // } // } // } // // } // Path: src/net/propero/rdp/Common.java import net.propero.rdp.rdp5.Rdp5; /* Common.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Provide a static interface to individual network layers * and UI components * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; public class Common { public static boolean underApplet = false;
public static Rdp5 rdp;
jakobadam/rdp
src/net/propero/rdp/rdp5/cliprdr/ImageSelection.java
// Path: src1.4/net/propero/rdp/Utilities_Localised.java // public class Utilities_Localised extends Utilities { // // public static DataFlavor imageFlavor = DataFlavor.imageFlavor; // // public static String strReplaceAll(String in, String find, String replace) { // return in.replaceAll(find, replace); // } // // public static String[] split(String in, String splitWith) { // return in.split(splitWith); // } // // }
import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import net.propero.rdp.Utilities_Localised; import java.awt.Image;
/* ImageSelection.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.rdp5.cliprdr; public class ImageSelection implements Transferable { // the Image object which will be housed by the ImageSelection private Image image; public ImageSelection(Image image) { this.image = image; } // Returns the supported flavors of our implementation public DataFlavor[] getTransferDataFlavors() {
// Path: src1.4/net/propero/rdp/Utilities_Localised.java // public class Utilities_Localised extends Utilities { // // public static DataFlavor imageFlavor = DataFlavor.imageFlavor; // // public static String strReplaceAll(String in, String find, String replace) { // return in.replaceAll(find, replace); // } // // public static String[] split(String in, String splitWith) { // return in.split(splitWith); // } // // } // Path: src/net/propero/rdp/rdp5/cliprdr/ImageSelection.java import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import net.propero.rdp.Utilities_Localised; import java.awt.Image; /* ImageSelection.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp.rdp5.cliprdr; public class ImageSelection implements Transferable { // the Image object which will be housed by the ImageSelection private Image image; public ImageSelection(Image image) { this.image = image; } // Returns the supported flavors of our implementation public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { Utilities_Localised.imageFlavor };
jakobadam/rdp
src/net/propero/rdp/ISO.java
// Path: src/net/propero/rdp/crypto/CryptoException.java // public class CryptoException extends Exception { // private static final long serialVersionUID = -5302220269148556116L; // // public CryptoException() { // super(); // } // // /** // * @param reason // * the reason why the exception was thrown. // */ // public CryptoException(String reason) { // super(reason); // } // }
import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import net.propero.rdp.crypto.CryptoException; import org.apache.log4j.Logger; import java.io.BufferedInputStream;
/* ISO.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: ISO layer of communication * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; public abstract class ISO { static Logger logger = Logger.getLogger(ISO.class); private HexDump dump = null; protected Socket rdpsock = null; private DataInputStream in = null; private DataOutputStream out = null; /* this for the ISO Layer */ private static final int CONNECTION_REQUEST = 0xE0; private static final int CONNECTION_CONFIRM = 0xD0; private static final int DISCONNECT_REQUEST = 0x80; private static final int DATA_TRANSFER = 0xF0; private static final int ERROR = 0x70; private static final int PROTOCOL_VERSION = 0x03; private static final int EOT = 0x80; /** * Construct ISO object, initialises hex dump */ public ISO() { dump = new HexDump(); } /** * Initialise an ISO PDU * * @param length * Desired length of PDU * @return Packet configured as ISO PDU, ready to write at higher level */ public RdpPacket_Localised init(int length) { RdpPacket_Localised data = new RdpPacket_Localised(length + 7);// getMemory(length+7); data.incrementPosition(7); data.setStart(data.getPosition()); return data; } /* * protected Socket negotiateSSL(Socket sock) throws Exception{ return sock; } */ /** * Create a socket for this ISO object * * @param host * Address of server * @param port * Port on which to connect socket * @throws IOException */ protected void doSocketConnect(InetAddress host, int port) throws IOException { this.rdpsock = new Socket(host, port); } /** * Connect to a server * * @param host * Address of server * @param port * Port to connect to on server * @throws IOException * @throws RdesktopException * @throws OrderException * @throws CryptoException */ public void connect(InetAddress host, int port) throws IOException,
// Path: src/net/propero/rdp/crypto/CryptoException.java // public class CryptoException extends Exception { // private static final long serialVersionUID = -5302220269148556116L; // // public CryptoException() { // super(); // } // // /** // * @param reason // * the reason why the exception was thrown. // */ // public CryptoException(String reason) { // super(reason); // } // } // Path: src/net/propero/rdp/ISO.java import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import net.propero.rdp.crypto.CryptoException; import org.apache.log4j.Logger; import java.io.BufferedInputStream; /* ISO.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: ISO layer of communication * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; public abstract class ISO { static Logger logger = Logger.getLogger(ISO.class); private HexDump dump = null; protected Socket rdpsock = null; private DataInputStream in = null; private DataOutputStream out = null; /* this for the ISO Layer */ private static final int CONNECTION_REQUEST = 0xE0; private static final int CONNECTION_CONFIRM = 0xD0; private static final int DISCONNECT_REQUEST = 0x80; private static final int DATA_TRANSFER = 0xF0; private static final int ERROR = 0x70; private static final int PROTOCOL_VERSION = 0x03; private static final int EOT = 0x80; /** * Construct ISO object, initialises hex dump */ public ISO() { dump = new HexDump(); } /** * Initialise an ISO PDU * * @param length * Desired length of PDU * @return Packet configured as ISO PDU, ready to write at higher level */ public RdpPacket_Localised init(int length) { RdpPacket_Localised data = new RdpPacket_Localised(length + 7);// getMemory(length+7); data.incrementPosition(7); data.setStart(data.getPosition()); return data; } /* * protected Socket negotiateSSL(Socket sock) throws Exception{ return sock; } */ /** * Create a socket for this ISO object * * @param host * Address of server * @param port * Port on which to connect socket * @throws IOException */ protected void doSocketConnect(InetAddress host, int port) throws IOException { this.rdpsock = new Socket(host, port); } /** * Connect to a server * * @param host * Address of server * @param port * Port to connect to on server * @throws IOException * @throws RdesktopException * @throws OrderException * @throws CryptoException */ public void connect(InetAddress host, int port) throws IOException,
RdesktopException, OrderException, CryptoException {