code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.bulatnig.smpp.testutil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * SMSC stub implementation. * * @author Bulat Nigmatullin */ public class SimpleSmscStub implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SimpleSmscStub.class); public List<byte[]> input = new ArrayList<byte[]>(); private final int port; private volatile ServerSocket server; private volatile OutputStream out; private volatile boolean run = true; public SimpleSmscStub(int port) { this.port = port; } public void start() throws IOException, InterruptedException { Thread listener = new Thread(this); listener.start(); synchronized (this) { this.wait(); } } @Override public void run() { try { server = new ServerSocket(port); synchronized (this) { this.notify(); } Socket client = server.accept(); client.setSoTimeout(0); InputStream in = client.getInputStream(); out = client.getOutputStream(); byte[] bytes = new byte[1024]; do { int read = in.read(bytes); if (read < 0) break; byte[] pdu = new byte[read]; System.arraycopy(bytes, 0, pdu, 0, read); input.add(pdu); } while (run); client.close(); stop(); } catch (IOException e) { if (run) { logger.error("SMSC execution failed.", e); } } } public void write(byte[] bytes) throws IOException, InterruptedException { while (out == null) Thread.sleep(10); out.write(bytes); } public synchronized void stop() { if (run) { run = false; if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Java
package org.bulatnig.smpp.testutil; import org.bulatnig.smpp.pdu.CommandId; import org.bulatnig.smpp.pdu.impl.BindTransceiverResp; import org.bulatnig.smpp.pdu.impl.EnquireLinkResp; import org.bulatnig.smpp.pdu.impl.SubmitSmResp; import org.bulatnig.smpp.pdu.impl.UnbindResp; import org.bulatnig.smpp.util.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * SMSC stub implementation. * * @author Bulat Nigmatullin */ public class ComplexSmscStub implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ComplexSmscStub.class); public List<byte[]> input = new ArrayList<byte[]>(); private final int port; private volatile ServerSocket server; private volatile OutputStream out; private Thread listener; private Socket client; private volatile boolean run = true; public ComplexSmscStub(int port) { this.port = port; } public void start() throws IOException, InterruptedException { listener = new Thread(this); listener.start(); synchronized (this) { wait(); } } @Override public void run() { try { server = new ServerSocket(port); synchronized (this) { notify(); } client = server.accept(); client.setSoTimeout(0); InputStream in = client.getInputStream(); out = client.getOutputStream(); byte[] bytes = new byte[1024]; do { int read = in.read(bytes); if (read < 0) break; byte[] pdu = new byte[read]; System.arraycopy(bytes, 0, pdu, 0, read); input.add(pdu); ByteBuffer bb = new ByteBuffer().appendBytes(bytes, read); long commandId = bb.readInt(4); if (commandId < CommandId.GENERIC_NACK) { long seqNum = bb.readInt(12); if (CommandId.BIND_TRANSCEIVER == commandId) { BindTransceiverResp bindResp = new BindTransceiverResp(); bindResp.setSystemId(Long.toString(System.currentTimeMillis())); bindResp.setSequenceNumber(seqNum); out.write(bindResp.buffer().array()); } else if (CommandId.ENQUIRE_LINK == commandId) { EnquireLinkResp enquireLinkResp = new EnquireLinkResp(); enquireLinkResp.setSequenceNumber(seqNum); out.write(enquireLinkResp.buffer().array()); } else if (CommandId.SUBMIT_SM == commandId) { SubmitSmResp submitSmResp = new SubmitSmResp(); submitSmResp.setMessageId(Long.toString(System.currentTimeMillis())); submitSmResp.setSequenceNumber(seqNum); out.write(submitSmResp.buffer().array()); } else if (CommandId.UNBIND == commandId) { UnbindResp unbindResp = new UnbindResp(); unbindResp.setSequenceNumber(seqNum); out.write(unbindResp.buffer().array()); } } } while (run); client.close(); } catch (Exception e) { if (run) { logger.error("SMSC execution failed.", e); } } finally { stop(); } } public void write(byte[] bytes) throws IOException, InterruptedException { while (out == null) Thread.sleep(10); out.write(bytes); } public synchronized void stop() { if (run) { run = false; if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } if (client != null) { try { client.close(); } catch (IOException ignore) { // omit it } } listener.interrupt(); } } }
Java
package org.bulatnig.smpp.testutil; import org.bulatnig.smpp.pdu.Pdu; import org.bulatnig.smpp.pdu.impl.DefaultPduParser; import org.bulatnig.smpp.pdu.impl.DeliverSm; import org.bulatnig.smpp.util.ByteBuffer; /** * Useful class for parsing hex dumps. * * @author Bulat Nigmatullin */ public class HexStringParser { public static final void main(String[] args) throws Exception { String dump = "000000b300000005000000000fa79c1f000101373930363033373633323000000132353133233830343934393134000400000000000000006669643a31393038313937393334207375623a30303120646c7672643a303030207375626d697420646174653a3131303332313137343920646f6e6520646174653a3131303332313137353420737461743a45585049524544206572723a30303020746578743a0427000103001e000b3139303831393739333400"; DeliverSm deliverSm = (DeliverSm) parse(dump); System.out.println(new String(deliverSm.getShortMessage())); } private static Pdu parse(String hexString) throws Exception { byte[] array = new byte[hexString.length()/2]; for (int i = 0; i < array.length; i++) { array[i] = (byte) Integer.parseInt(hexString.substring(i*2, (i+1)*2), 16); } ByteBuffer bb = new ByteBuffer(array); return new DefaultPduParser().parse(bb); } }
Java
package org.bulatnig.smpp.testutil; import java.util.concurrent.atomic.AtomicInteger; /** * Generate unique port for each test. * * @author Bulat Nigmatullin */ public enum UniquePortGenerator { INSTANCE; /** * Values through 1 to 1024 reserved. So we are starting from 1025. */ private static final AtomicInteger port = new AtomicInteger(1025); public static int generate() { return port.getAndIncrement(); } }
Java
package org.bulatnig.smpp.util; import java.io.UnsupportedEncodingException; /** * Converts java types to byte array according to SMPP protocol. * Implemented, using java.nio.ByteBuffer as template. * You should remember, that all SMPP simple numeric types are unsigned, * but Java types are always signed. * <p/> * Not thread safe. * <p/> * Implementation notes: buffer may be read or write types. Append and remove operations should not be mixed * and should be called only on corresponding buffer type. * * @author Bulat Nigmatullin */ public class PositioningByteBuffer { /** * Default buffer capacity. It should be enough to contain SUBMIT_SM or DELIVER_SM with 140 bytes text. */ public static final int DEFAULT_CAPACITY = 250; /** * Byte buffer. */ private final byte[] buffer; /** * Buffer type: read or write. Affects array and length operations. */ private final boolean read; /** * Cursor position. Next write or read operation will start from this array element. */ private int position = 0; /** * Create buffer with default capacity. */ public PositioningByteBuffer() { this(DEFAULT_CAPACITY); } /** * Create buffer with given capacity. * * @param capacity buffer capacity */ public PositioningByteBuffer(int capacity) { buffer = new byte[capacity]; read = false; } /** * Create buffer based on provided array. * * @param b byte array */ public PositioningByteBuffer(byte[] b) { buffer = b; read = true; } /** * Возвращает массив байтов. * * @return массив байтов */ public byte[] array() { if (read) return buffer; else { byte[] result = new byte[position]; System.arraycopy(buffer, 0, result, 0, position); return result; } } /** * Возвращает длину массива. * * @return длина массива */ public int length() { if (read) return buffer.length; else return position; } /** * Добавляет байты в массив. * * @param bytes byte array * @return this buffer */ public PositioningByteBuffer appendBytes(byte[] bytes) { return appendBytes(bytes, bytes.length); } /** * Добавляет байты в массив. * * @param bytes byte array * @param length bytes length to add * @return this buffer */ public PositioningByteBuffer appendBytes(byte[] bytes, int length) { System.arraycopy(bytes, 0, buffer, position, length); position += length; return this; } /** * Добавляет переменную типа byte в массив. * Значение переменной должно быть в диапазоне от 0 до 255 включительно. * * @param value byte value to be appended * @return this buffer * @throws IllegalArgumentException задан неверный параметр */ public PositioningByteBuffer appendByte(int value) throws IllegalArgumentException { if (value >= 0 && value < 256) { buffer[position] = (byte) value; position++; } else throw new IllegalArgumentException("Byte value should be between 0 and 255."); return this; } /** * Добавляет переменную типа short в массив. * Значение переменной должно быть в диапазоне от 0 до 65535 включительно. * * @param value short value to be appended * @return this buffer * @throws IllegalArgumentException задан неверный параметр */ public PositioningByteBuffer appendShort(int value) throws IllegalArgumentException { if (value >= 0 && value < 65536) { buffer[position] = (byte) (value >>> 8); buffer[position + 1] = (byte) value; position += 2; } else throw new IllegalArgumentException("Short value should be between 0 and 65535."); return this; } /** * Добавляет переменную типа int в массив. * Значение переменной должно быть в диапазоне от 0 до 4294967295 включительно. * * @param value short-переменная * @return this buffer * @throws IllegalArgumentException задан неверный параметр */ public PositioningByteBuffer appendInt(long value) throws IllegalArgumentException { if (value >= 0 && value < 4294967296L) { buffer[position] = (byte) (value >>> 24); buffer[position + 1] = (byte) (value >>> 16); buffer[position + 2] = (byte) (value >>> 8); buffer[position + 3] = (byte) value; position += 4; } else throw new IllegalArgumentException("Short value should be between 0 and 4294967295."); return this; } /** * Добавляет строку C-Octet String в массив. * * @param cstring строка типа C-Octet (по протоколу SMPP), may be null * @return this buffer */ public PositioningByteBuffer appendCString(String cstring) { if (cstring != null && cstring.length() > 0) { try { appendBytes(cstring.getBytes("US-ASCII")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e); } } position++; // always append terminating ZERO return this; } /** * Append string using ASCII charset. * * @param string string value, may be null * @return this buffer */ public PositioningByteBuffer appendString(String string) { return appendString(string, "US-ASCII"); } /** * Append string using charset name. * Note: UTF-16(UCS2) uses Byte Order Mark at the head of string and * it may be unsupported by your Operator. So you should consider using * UTF-16BE or UTF-16LE instead of UTF-16. * * @param string encoded string, null allowed * @param charsetName encoding character set name * @return this buffer */ public PositioningByteBuffer appendString(String string, String charsetName) { if (string != null && string.length() > 0) { try { appendBytes(string.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Wrong charset name provided.", e); } } return this; } /** * Read one byte from byte buffer * * @return byte was read */ public int readByte() { return buffer[0] & 0xFF; } /** * Read short value from buffer * * @return short value */ public int readShort() { int result = 0; result |= buffer[0] & 0xFF; result <<= 8; result |= buffer[1] & 0xFF; return result; } /** * Read int value from buffer * * @return int value */ public long readInt() { return readInt(0); } /** * Read int value from buffer * * @param offset start reading from offset byte * @return int value */ public long readInt(int offset) { long result = 0; result |= buffer[offset] & 0xFF; result <<= 8; result |= buffer[offset + 1] & 0xFF; result <<= 8; result |= buffer[offset + 2] & 0xFF; result <<= 8; result |= buffer[offset + 3] & 0xFF; return result; } /** * Удаляет один byte из массива и возвращает его. * * @return удаленный byte */ public int removeByte() { int result = readByte(); position++; return result; } /** * Удаляет один short из массива и возвращает его. * * @return удаленный short */ public int removeShort() { int result = readShort(); position += 2; return result; } /** * Удаляет один int из массива и возвращает его. * * @return удаленные int */ public long removeInt() { long result = readInt(); position += 4; return result; } /** * Удаляет строку C-Octet String из массива и возращает строку. * * @return C-Octet String, may be null * @throws TerminatingNullNotFoundException * null character not found in the buffer */ public String removeCString() throws TerminatingNullNotFoundException { int zeroPos = -1; for (int i = position; i < buffer.length; i++) { if (buffer[i] == 0) { zeroPos = i; break; } } if (zeroPos > -1) { // found terminating ZERO String result = null; if (zeroPos > position) { try { result = new String(buffer, 0, zeroPos, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e); } } position = zeroPos + 1; return result; } else { throw new TerminatingNullNotFoundException(); } } /** * Remove Octet String from buffer and return it in ASCII encoding.. * * @param length string length * @return removed string */ public String removeString(int length) { return removeString(length, "US-ASCII"); } /** * Remove Octet string from buffer and return it in charsetName encoding. * <p/> * Note: Even if string length is 0, zero-length String object created and returned. * This behavior is differ from C-Octet String cause user know Octet String length * and may not call this method if String length is 0 and he need null. * * @param length string length * @param charsetName string charset name * @return removed string */ public String removeString(int length, String charsetName) { String result; try { result = new String(buffer, position, length, charsetName); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported charset name: " + charsetName, e); } position += length; return result; } /** * Remove bytes from buffer and return them. * * @param count count of bytes to remove * @return removed bytes */ public byte[] removeBytes(int count) { byte[] result = readBytes(count); position += count; return result; } /** * Возвращает строку отображающую содержимое массива. * * @return содержимое массива */ public String hexDump() { StringBuilder builder = new StringBuilder(); for (byte b : array()) { builder.append(Character.forDigit((b >> 4) & 0x0f, 16)); builder.append(Character.forDigit(b & 0x0f, 16)); } return builder.toString(); } /** * Read bytes. * * @param count count of bytes to read * @return readed bytes */ private byte[] readBytes(int count) { byte[] resBuf = new byte[count]; System.arraycopy(buffer, position, resBuf, 0, count); return resBuf; } }
Java
package org.bulatnig.smpp.util; import org.junit.Test; /** * ByteBuffer performance comparison. * * @author Bulat Nigmatullin */ public class ByteBufferPerf { @Test public void test() { for (int i = 0; i < 10; i++) { test0(); } } private void test0() { long start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { // byteBuffer(Integer.toString(i)); newByteBuffer(Integer.toString(i)); } long done = System.currentTimeMillis(); System.out.println("Done in " + (done - start) + " ms."); } private Object byteBuffer(String type) { ByteBuffer bb = new ByteBuffer(); bb.appendCString(type); bb.appendByte(1); bb.appendByte(2); bb.appendCString("79269240813"); bb.appendByte(3); bb.appendByte(4); bb.appendCString("7474#1234567"); bb.appendByte(5); bb.appendByte(6); bb.appendByte(7); bb.appendCString(null); bb.appendCString(null); bb.appendByte(8); bb.appendByte(9); bb.appendByte(10); bb.appendByte(11); bb.appendByte(12); bb.appendString("One two three four five."); return bb.array(); } private Object newByteBuffer(String type) { PositioningByteBuffer bb = new PositioningByteBuffer(); bb.appendCString(type); bb.appendByte(1); bb.appendByte(2); bb.appendCString("79269240813"); bb.appendByte(3); bb.appendByte(4); bb.appendCString("7474#1234567"); bb.appendByte(5); bb.appendByte(6); bb.appendByte(7); bb.appendCString(null); bb.appendCString(null); bb.appendByte(8); bb.appendByte(9); bb.appendByte(10); bb.appendByte(11); bb.appendByte(12); bb.appendString("One two three four five."); return bb.array(); } }
Java
package pl.polidea.coverflow; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; /** * This class is an adapter that provides base, abstract class for images * adapter. * */ public abstract class AbstractCoverFlowImageAdapter extends BaseAdapter { /** The Constant TAG. */ private static final String TAG = AbstractCoverFlowImageAdapter.class.getSimpleName(); /** The width. */ private float width = 0; /** The height. */ private float height = 0; /** The bitmap map. */ private final Map<Integer, WeakReference<Bitmap>> bitmapMap = new HashMap<Integer, WeakReference<Bitmap>>(); public AbstractCoverFlowImageAdapter() { super(); } /** * Set width for all pictures. * * @param width * picture height */ public synchronized void setWidth(final float width) { this.width = width; } /** * Set height for all pictures. * * @param height * picture height */ public synchronized void setHeight(final float height) { this.height = height; } @Override public final Bitmap getItem(final int position) { final WeakReference<Bitmap> weakBitmapReference = bitmapMap.get(position); if (weakBitmapReference != null) { final Bitmap bitmap = weakBitmapReference.get(); if (bitmap == null) { Log.v(TAG, "Empty bitmap reference at position: " + position + ":" + this); } else { Log.v(TAG, "Reusing bitmap item at position: " + position + ":" + this); return bitmap; } } Log.v(TAG, "Creating item at position: " + position + ":" + this); final Bitmap bitmap = createBitmap(position); bitmapMap.put(position, new WeakReference<Bitmap>(bitmap)); Log.v(TAG, "Created item at position: " + position + ":" + this); return bitmap; } /** * Creates new bitmap for the position specified. * * @param position * position * @return Bitmap created */ protected abstract Bitmap createBitmap(int position); /* * (non-Javadoc) * * @see android.widget.Adapter#getItemId(int) */ @Override public final synchronized long getItemId(final int position) { return position; } /* * (non-Javadoc) * * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public final synchronized ImageView getView(final int position, final View convertView, final ViewGroup parent) { ImageView imageView; if (convertView == null) { final Context context = parent.getContext(); Log.v(TAG, "Creating Image view at position: " + position + ":" + this); imageView = new ImageView(context); imageView.setLayoutParams(new CoverFlow.LayoutParams((int) width, (int) height)); } else { Log.v(TAG, "Reusing view at position: " + position + ":" + this); imageView = (ImageView) convertView; } imageView.setImageBitmap(getItem(position)); return imageView; } }
Java
/** * Provides implementation of cover flow. */ package pl.polidea.coverflow;
Java
package pl.polidea.coverflow; import android.R.color; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Shader.TileMode; /** * This adapter provides reflected images from linked adapter. * * @author potiuk * */ public class ReflectingImageAdapter extends AbstractCoverFlowImageAdapter { /** The linked adapter. */ private final AbstractCoverFlowImageAdapter linkedAdapter; /** * Gap between the image and its reflection. */ private float reflectionGap; /** The image reflection ratio. */ private float imageReflectionRatio; /** * Sets the width ratio. * * @param imageReflectionRatio * the new width ratio */ public void setWidthRatio(final float imageReflectionRatio) { this.imageReflectionRatio = imageReflectionRatio; } /** * Creates reflecting adapter. * * @param linkedAdapter * adapter that provides images to get reflections */ public ReflectingImageAdapter(final AbstractCoverFlowImageAdapter linkedAdapter) { super(); this.linkedAdapter = linkedAdapter; } /** * Sets the reflection gap. * * @param reflectionGap * the new reflection gap */ public void setReflectionGap(final float reflectionGap) { this.reflectionGap = reflectionGap; } /** * Gets the reflection gap. * * @return the reflection gap */ public float getReflectionGap() { return reflectionGap; } /* * (non-Javadoc) * * @see pl.polidea.coverflow.AbstractCoverFlowImageAdapter#createBitmap(int) */ @Override protected Bitmap createBitmap(final int position) { return createReflectedImages(linkedAdapter.getItem(position)); } /** * Creates the reflected images. * * @param originalImage * the original image * @return true, if successful */ public Bitmap createReflectedImages(final Bitmap originalImage) { final int width = originalImage.getWidth(); final int height = originalImage.getHeight(); final Matrix matrix = new Matrix(); matrix.preScale(1, -1); final Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, (int) (height * imageReflectionRatio), width, (int) (height - height * imageReflectionRatio), matrix, false); final Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (int) (height + height * imageReflectionRatio), Config.ARGB_8888); final Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); final Paint deafaultPaint = new Paint(); deafaultPaint.setColor(color.transparent); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); final Paint paint = new Paint(); final LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /* * (non-Javadoc) * * @see android.widget.Adapter#getCount() */ @Override public int getCount() { return linkedAdapter.getCount(); } }
Java
/** * Test activity. */ package pl.polidea.coverflow.testingactivity;
Java
package pl.polidea.coverflow.testingactivity; import pl.polidea.coverflow.CoverFlow; import pl.polidea.coverflow.R; import pl.polidea.coverflow.ReflectingImageAdapter; import pl.polidea.coverflow.ResourceImageAdapter; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.TextView; /** * The Class CoverFlowTestingActivity. */ public class CoverFlowTestingActivity extends Activity { private TextView textView; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(this.getResources() .getIdentifier("statusText", "id", "pl.polidea.coverflow")); // note resources below are taken using getIdentifier to allow importing // this library as library. final CoverFlow coverFlow1 = (CoverFlow) findViewById(this.getResources().getIdentifier("coverflow", "id", "pl.polidea.coverflow")); setupCoverFlow(coverFlow1, false); final CoverFlow reflectingCoverFlow = (CoverFlow) findViewById(this.getResources().getIdentifier( "coverflowReflect", "id", "pl.polidea.coverflow")); setupCoverFlow(reflectingCoverFlow, true); } /** * Setup cover flow. * * @param mCoverFlow * the m cover flow * @param reflect * the reflect */ private void setupCoverFlow(final CoverFlow mCoverFlow, final boolean reflect) { BaseAdapter coverImageAdapter; if (reflect) { coverImageAdapter = new ReflectingImageAdapter(new ResourceImageAdapter(this)); } else { coverImageAdapter = new ResourceImageAdapter(this); } mCoverFlow.setAdapter(coverImageAdapter); mCoverFlow.setSelection(2, true); setupListeners(mCoverFlow); } /** * Sets the up listeners. * * @param mCoverFlow * the new up listeners */ private void setupListeners(final CoverFlow mCoverFlow) { mCoverFlow.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView< ? > parent, final View view, final int position, final long id) { textView.setText("Item clicked! : " + id); } }); mCoverFlow.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(final AdapterView< ? > parent, final View view, final int position, final long id) { textView.setText("Item selected! : " + id); } @Override public void onNothingSelected(final AdapterView< ? > parent) { textView.setText("Nothing clicked!"); } }); } }
Java
package pl.polidea.coverflow; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.util.Log; /** * This class is an adapter that provides images from a fixed set of resource * ids. Bitmaps and ImageViews are kept as weak references so that they can be * cleared by garbage collection when not needed. * */ public class ResourceImageAdapter extends AbstractCoverFlowImageAdapter { /** The Constant TAG. */ private static final String TAG = ResourceImageAdapter.class.getSimpleName(); /** The Constant DEFAULT_LIST_SIZE. */ private static final int DEFAULT_LIST_SIZE = 20; /** The Constant IMAGE_RESOURCE_IDS. */ private static final List<Integer> IMAGE_RESOURCE_IDS = new ArrayList<Integer>(DEFAULT_LIST_SIZE); /** The Constant DEFAULT_RESOURCE_LIST. */ private static final int[] DEFAULT_RESOURCE_LIST = { R.drawable.image01, R.drawable.image02, R.drawable.image03, R.drawable.image04, R.drawable.image05 }; /** The bitmap map. */ private final Map<Integer, WeakReference<Bitmap>> bitmapMap = new HashMap<Integer, WeakReference<Bitmap>>(); private final Context context; /** * Creates the adapter with default set of resource images. * * @param context * context */ public ResourceImageAdapter(final Context context) { super(); this.context = context; setResources(DEFAULT_RESOURCE_LIST); } /** * Replaces resources with those specified. * * @param resourceIds * array of ids of resources. */ public final synchronized void setResources(final int[] resourceIds) { IMAGE_RESOURCE_IDS.clear(); for (final int resourceId : resourceIds) { IMAGE_RESOURCE_IDS.add(resourceId); } notifyDataSetChanged(); } /* * (non-Javadoc) * * @see android.widget.Adapter#getCount() */ @Override public synchronized int getCount() { return IMAGE_RESOURCE_IDS.size(); } /* * (non-Javadoc) * * @see pl.polidea.coverflow.AbstractCoverFlowImageAdapter#createBitmap(int) */ @Override protected Bitmap createBitmap(final int position) { Log.v(TAG, "creating item " + position); final Bitmap bitmap = ((BitmapDrawable) context.getResources().getDrawable(IMAGE_RESOURCE_IDS.get(position))) .getBitmap(); bitmapMap.put(position, new WeakReference<Bitmap>(bitmap)); return bitmap; } }
Java
/* * Copyright (C) 2010 Neil Davies * * 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. * * This code is base on the Android Gallery widget and was Created * by Neil Davies neild001 'at' gmail dot com to be a Coverflow widget * * @author Neil Davies */ package pl.polidea.coverflow; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Camera; import android.graphics.Matrix; import android.util.AttributeSet; import android.view.View; import android.view.animation.Transformation; import android.widget.Gallery; import android.widget.ImageView; import android.widget.SpinnerAdapter; /** * Cover Flow implementation. * */ public class CoverFlow extends Gallery { /** * Graphics Camera used for transforming the matrix of ImageViews. */ private final Camera mCamera = new Camera(); /** * The maximum angle the Child ImageView will be rotated by. */ private int mMaxRotationAngle = 60; /** * The maximum zoom on the centre Child. */ private int mMaxZoom = -120; /** * The Centre of the Coverflow. */ private int mCoveflowCenter; /** The image height. */ private float imageHeight; /** The image width. */ private float imageWidth; /** The reflection gap. */ private float reflectionGap; /** The with reflection. */ private boolean withReflection; /** The image reflection ratio. */ private float imageReflectionRatio; /** * Gets the image height. * * @return the image height */ public float getImageHeight() { return imageHeight; } /** * Sets the image height. * * @param imageHeight * the new image height */ public void setImageHeight(final float imageHeight) { this.imageHeight = imageHeight; } /** * Gets the image width. * * @return the image width */ public float getImageWidth() { return imageWidth; } /** * Sets the image width. * * @param imageWidth * the new image width */ public void setImageWidth(final float imageWidth) { this.imageWidth = imageWidth; } /** * Gets the reflection gap. * * @return the reflection gap */ public float getReflectionGap() { return reflectionGap; } /** * Sets the reflection gap. * * @param reflectionGap * the new reflection gap */ public void setReflectionGap(final float reflectionGap) { this.reflectionGap = reflectionGap; } /** * Checks if is with reflection. * * @return true, if is with reflection */ public boolean isWithReflection() { return withReflection; } /** * Sets the with reflection. * * @param withReflection * the new with reflection */ public void setWithReflection(final boolean withReflection) { this.withReflection = withReflection; } /** * Sets the image reflection ratio. * * @param imageReflectionRatio * the new image reflection ratio */ public void setImageReflectionRatio(final float imageReflectionRatio) { this.imageReflectionRatio = imageReflectionRatio; } /** * Gets the image reflection ratio. * * @return the image reflection ratio */ public float getImageReflectionRatio() { return imageReflectionRatio; } public CoverFlow(final Context context) { super(context); this.setStaticTransformationsEnabled(true); } public CoverFlow(final Context context, final AttributeSet attrs) { this(context, attrs, android.R.attr.galleryStyle); } public CoverFlow(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); this.setStaticTransformationsEnabled(true); } /** * Get the max rotational angle of the image. * * @return the mMaxRotationAngle */ public int getMaxRotationAngle() { return mMaxRotationAngle; } /** * Sets the. * * @param adapter * the new adapter */ @Override public void setAdapter(final SpinnerAdapter adapter) { if (!(adapter instanceof AbstractCoverFlowImageAdapter)) { throw new IllegalArgumentException("The adapter should derive from " + AbstractCoverFlowImageAdapter.class.getName()); } final AbstractCoverFlowImageAdapter coverAdapter = (AbstractCoverFlowImageAdapter) adapter; coverAdapter.setWidth(imageWidth); coverAdapter.setHeight(imageHeight); if (withReflection) { final ReflectingImageAdapter reflectAdapter = new ReflectingImageAdapter(coverAdapter); reflectAdapter.setReflectionGap(reflectionGap); reflectAdapter.setWidthRatio(imageReflectionRatio); reflectAdapter.setWidth(imageWidth); reflectAdapter.setHeight(imageHeight * (1 + imageReflectionRatio)); super.setAdapter(reflectAdapter); } else { super.setAdapter(adapter); } } /** * Set the max rotational angle of each image. * * @param maxRotationAngle * the mMaxRotationAngle to set */ public void setMaxRotationAngle(final int maxRotationAngle) { mMaxRotationAngle = maxRotationAngle; } /** * Get the Max zoom of the centre image. * * @return the mMaxZoom */ public int getMaxZoom() { return mMaxZoom; } /** * Set the max zoom of the centre image. * * @param maxZoom * the mMaxZoom to set */ public void setMaxZoom(final int maxZoom) { mMaxZoom = maxZoom; } /** * Get the Centre of the Coverflow. * * @return The centre of this Coverflow. */ private int getCenterOfCoverflow() { return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft(); } /** * Get the Centre of the View. * * @return The centre of the given view. */ private static int getCenterOfView(final View view) { return view.getLeft() + view.getWidth() / 2; } /** * {@inheritDoc} * * @see #setStaticTransformationsEnabled(boolean) */ @Override protected boolean getChildStaticTransformation(final View child, final Transformation t) { final int childCenter = getCenterOfView(child); final int childWidth = child.getWidth(); int rotationAngle = 0; t.clear(); t.setTransformationType(Transformation.TYPE_MATRIX); if (childCenter == mCoveflowCenter) { transformImageBitmap((ImageView) child, t, 0); } else { rotationAngle = (int) ((float) (mCoveflowCenter - childCenter) / childWidth * mMaxRotationAngle); if (Math.abs(rotationAngle) > mMaxRotationAngle) { rotationAngle = rotationAngle < 0 ? -mMaxRotationAngle : mMaxRotationAngle; } transformImageBitmap((ImageView) child, t, rotationAngle); } return true; } /** * This is called during layout when the size of this view has changed. If * you were just added to the view hierarchy, you're called with the old * values of 0. * * @param w * Current width of this view. * @param h * Current height of this view. * @param oldw * Old width of this view. * @param oldh * Old height of this view. */ @Override protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh) { mCoveflowCenter = getCenterOfCoverflow(); super.onSizeChanged(w, h, oldw, oldh); } /** * Transform the Image Bitmap by the Angle passed. * * @param imageView * ImageView the ImageView whose bitmap we want to rotate * @param t * transformation * @param rotationAngle * the Angle by which to rotate the Bitmap */ private void transformImageBitmap(final ImageView child, final Transformation t, final int rotationAngle) { mCamera.save(); final Matrix imageMatrix = t.getMatrix(); final int height = child.getLayoutParams().height; final int width = child.getLayoutParams().width; final int rotation = Math.abs(rotationAngle); mCamera.translate(0.0f, 0.0f, 100.0f); // As the angle of the view gets less, zoom in if (rotation < mMaxRotationAngle) { final float zoomAmount = (float) (mMaxZoom + rotation * 1.5); mCamera.translate(0.0f, 0.0f, zoomAmount); } mCamera.rotateY(rotationAngle); mCamera.getMatrix(imageMatrix); imageMatrix.preTranslate(-(width / 2.0f), -(height / 2.0f)); imageMatrix.postTranslate((width / 2.0f), (height / 2.0f)); mCamera.restore(); } /** * Parses the attributes. * * @param context * the context * @param attrs * the attrs */ private void parseAttributes(final Context context, final AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CoverFlow); try { imageWidth = a.getDimension(R.styleable.CoverFlow_imageWidth, 480); imageHeight = a.getDimension(R.styleable.CoverFlow_imageHeight, 320); withReflection = a.getBoolean(R.styleable.CoverFlow_withReflection, false); imageReflectionRatio = a.getFloat(R.styleable.CoverFlow_imageReflectionRatio, 0.2f); reflectionGap = a.getDimension(R.styleable.CoverFlow_reflectionGap, 4); setSpacing(-15); } finally { a.recycle(); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author DangThanh */ public class HashMD5 { public HashMD5() { } /*** * Hash MD5 for password * @param password * @return String */ public String hashMD5(String password) { byte[] hash; String temp = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); hash = md.digest(password.getBytes("UTF-8")); for (int i = 0; i < hash.length; i++) { temp += Byte.toString(hash[i]); } } catch (UnsupportedEncodingException ex) { Logger.getLogger(HashMD5.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(HashMD5.class.getName()).log(Level.SEVERE, null, ex); } return temp; } }
Java
package app.controller; import app.entity.Property; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.PropertyFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "propertyController") @SessionScoped public class PropertyController implements Serializable { private Property current; private DataModel items = null; @EJB private app.session.PropertyFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public PropertyController() { } public Property getSelected() { if (current == null) { current = new Property(); selectedItemIndex = -1; } return current; } private PropertyFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Property) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Property(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Property) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Property) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Property.class) public static class PropertyControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } PropertyController controller = (PropertyController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "propertyController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Property) { Property o = (Property) object; return getStringKey(o.getPropertyId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + PropertyController.class.getName()); } } } }
Java
package app.controller; import app.entity.Function; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.FunctionFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "functionController") @SessionScoped public class FunctionController implements Serializable { private Function current; private DataModel items = null; @EJB private app.session.FunctionFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public FunctionController() { } public Function getSelected() { if (current == null) { current = new Function(); selectedItemIndex = -1; } return current; } private FunctionFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Function) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Function(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Function) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Function) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Function.class) public static class FunctionControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } FunctionController controller = (FunctionController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "functionController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Function) { Function o = (Function) object; return getStringKey(o.getFunctionId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FunctionController.class.getName()); } } } }
Java
package app.controller; import app.entity.Functionrole; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.FunctionroleFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "functionroleController") @SessionScoped public class FunctionroleController implements Serializable { private Functionrole current; private DataModel items = null; @EJB private app.session.FunctionroleFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public FunctionroleController() { } public Functionrole getSelected() { if (current == null) { current = new Functionrole(); selectedItemIndex = -1; } return current; } private FunctionroleFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Functionrole) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Functionrole(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionroleCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Functionrole) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionroleUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Functionrole) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FunctionroleDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Functionrole.class) public static class FunctionroleControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } FunctionroleController controller = (FunctionroleController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "functionroleController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Functionrole) { Functionrole o = (Functionrole) object; return getStringKey(o.getFunctionroleid()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FunctionroleController.class.getName()); } } } }
Java
package app.controller; import app.entity.UserInformation; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.UserInformationFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "userInformationController") @SessionScoped public class UserInformationController implements Serializable { private UserInformation current; private DataModel items = null; @EJB private app.session.UserInformationFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public UserInformationController() { } public UserInformation getSelected() { if (current == null) { current = new UserInformation(); selectedItemIndex = -1; } return current; } private UserInformationFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (UserInformation) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new UserInformation(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserInformationCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (UserInformation) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserInformationUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (UserInformation) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UserInformationDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = UserInformation.class) public static class UserInformationControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } UserInformationController controller = (UserInformationController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "userInformationController"); return controller.ejbFacade.find(getKey(value)); } java.lang.String getKey(String value) { java.lang.String key; key = value; return key; } String getStringKey(java.lang.String value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof UserInformation) { UserInformation o = (UserInformation) object; return getStringKey(o.getUsername()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UserInformationController.class.getName()); } } } }
Java
package app.controller; import app.entity.Faq; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.FaqFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "faqController") @SessionScoped public class FaqController implements Serializable { private Faq current; private DataModel items = null; @EJB private app.session.FaqFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public FaqController() { } public Faq getSelected() { if (current == null) { current = new Faq(); selectedItemIndex = -1; } return current; } private FaqFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Faq) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Faq(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FaqCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Faq) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FaqUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Faq) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FaqDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Faq.class) public static class FaqControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } FaqController controller = (FaqController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "faqController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Faq) { Faq o = (Faq) object; return getStringKey(o.getFaqId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FaqController.class.getName()); } } } }
Java
package app.controller; import app.entity.Role; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.RoleFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "roleController") @SessionScoped public class RoleController implements Serializable { private Role current; private DataModel items = null; @EJB private app.session.RoleFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public RoleController() { } public Role getSelected() { if (current == null) { current = new Role(); selectedItemIndex = -1; } return current; } private RoleFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Role) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Role(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoleCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Role) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoleUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Role) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoleDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Role.class) public static class RoleControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } RoleController controller = (RoleController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "roleController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Role) { Role o = (Role) object; return getStringKey(o.getRoleId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + RoleController.class.getName()); } } } }
Java
package app.controller; import app.entity.PropertyType; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.PropertyTypeFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "propertyTypeController") @SessionScoped public class PropertyTypeController implements Serializable { private PropertyType current; private DataModel items = null; @EJB private app.session.PropertyTypeFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public PropertyTypeController() { } public PropertyType getSelected() { if (current == null) { current = new PropertyType(); selectedItemIndex = -1; } return current; } private PropertyTypeFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (PropertyType) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new PropertyType(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyTypeCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (PropertyType) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyTypeUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (PropertyType) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyTypeDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = PropertyType.class) public static class PropertyTypeControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } PropertyTypeController controller = (PropertyTypeController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "propertyTypeController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof PropertyType) { PropertyType o = (PropertyType) object; return getStringKey(o.getTypeId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + PropertyTypeController.class.getName()); } } } }
Java
package app.controller; import app.entity.Feedback; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.session.FeedbackFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "feedbackController") @SessionScoped public class FeedbackController implements Serializable { private Feedback current; private DataModel items = null; @EJB private app.session.FeedbackFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public FeedbackController() { } public Feedback getSelected() { if (current == null) { current = new Feedback(); selectedItemIndex = -1; } return current; } private FeedbackFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Feedback) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Feedback(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FeedbackCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Feedback) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FeedbackUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Feedback) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FeedbackDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Feedback.class) public static class FeedbackControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } FeedbackController controller = (FeedbackController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "feedbackController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Feedback) { Feedback o = (Feedback) object; return getStringKey(o.getFeedbackId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FeedbackController.class.getName()); } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.controller.util; import app.entity.Mail; import javax.mail.*; import javax.mail.internet.*; import java.util.*; /** * * @author Song Lam */ public class SendMail { public int sendMail(Mail m) { try { /* this.to = "dtbinhqb@gmail.com"; subject = "subject"; message = "message"; */ m.setSubject("Recover Password"); m.setFrom("Java.Mail.CA@gmail.com"); m.setSmtpServ("smtp.gmail.com"); Properties props = System.getProperties(); // -- Attaching to default Session, or we could start a new one -- props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", m.getSmtpServ()); props.put("mail.smtp.auth", "true"); Authenticator auth = new SendMail.SMTPAuthenticator(); Session session = Session.getInstance(props, auth); // -- Create a new message -- Message msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(m.getFrom())); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(m.getTo(), false)); msg.setSubject(m.getSubject()); msg.setText(m.getMessage()); // -- Set some other header information -- msg.setHeader("MyMail", "Mr. XYZ"); msg.setSentDate(new Date()); // -- Send the message -- Transport.send(msg); return 0; } catch (Exception ex) { ex.printStackTrace(); return -1; } } private class SMTPAuthenticator extends javax.mail.Authenticator { @Override public PasswordAuthentication getPasswordAuthentication() { String username = "sendmail.jsf@gmail.com"; // specify your email id here (sender's email id) String password = "sendmail.jsf"; // specify your password here return new PasswordAuthentication(username, password); } } }
Java
package app.controller.util; import app.entity.Role; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.model.SelectItem; public class JsfUtil { public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) { int size = selectOne ? entities.size() + 1 : entities.size(); SelectItem[] items = new SelectItem[size]; int i = 0; if (selectOne) { items[0] = new SelectItem("", "---"); i++; } for (Object x : entities) { String temp=""; if(x.toString().startsWith("app.entity.Role")){ Role rl = (Role)x; temp=rl.getRoleName(); } items[i++] = new SelectItem(x,temp); } return items; } public static void addErrorMessage(Exception ex, String defaultMsg) { String msg = ex.getLocalizedMessage(); if (msg != null && msg.length() > 0) { addErrorMessage(msg); } else { addErrorMessage(defaultMsg); } } public static void addErrorMessages(List<String> messages) { for (String message : messages) { addErrorMessage(message); } } public static void addErrorMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } public static void addSuccessMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg); } public static String getRequestParameter(String key) { return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key); } public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) { String theId = JsfUtil.getRequestParameter(requestParameterName); return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId); } }
Java
package app.controller.util; import javax.faces.model.DataModel; public abstract class PaginationHelper { private int pageSize; private int page; public PaginationHelper(int pageSize) { this.pageSize = pageSize; } public abstract int getItemsCount(); public abstract DataModel createPageDataModel(); public int getPageFirstItem() { return page * pageSize; } public int getPageLastItem() { int i = getPageFirstItem() + pageSize - 1; int count = getItemsCount() - 1; if (i > count) { i = count; } if (i < 0) { i = 0; } return i; } public boolean isHasNextPage() { return (page + 1) * pageSize + 1 <= getItemsCount(); } public void nextPage() { if (isHasNextPage()) { page++; } } public boolean isHasPreviousPage() { return page > 0; } public void previousPage() { if (isHasPreviousPage()) { page--; } } public int getPageSize() { return pageSize; } }
Java
package app.controller; import app.entity.Account; import app.controller.util.JsfUtil; import app.controller.util.PaginationHelper; import app.entity.Role; import app.entity.UserInformation; import app.session.AccountFacade; import app.session.UserInformationFacade; import com.sun.xml.ws.security.trust.elements.Encryption; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @ManagedBean(name = "accountController") @SessionScoped public class AccountController implements Serializable { private Account current; private Account loggedUser; public Account getLoggedUser() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest myRequest = (HttpServletRequest) context.getExternalContext().getRequest(); HttpSession session = myRequest.getSession(); loggedUser = (Account) session.getAttribute("user"); return loggedUser; } public void setLoggedUser(Account loggedUser) { this.loggedUser = loggedUser; } private DataModel items = null; @EJB private app.session.AccountFacade ejbFacade; UserInformationFacade userFacade = new UserInformationFacade(); private PaginationHelper pagination; private int selectedItemIndex; UserInformation user; private String temp; public String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } public UserInformation getUser() { return user; } public void setUser(UserInformation user) { this.user = user; } public AccountController() { user = new UserInformation(); } public Account getSelected() { if (current == null) { current = new Account(); selectedItemIndex = -1; } return current; } private AccountFacade getFacade() { return ejbFacade; } public String changePass(){ current.setUsername(getLoggedUser().getUsername()); if(ejbFacade.checkLogin(current) != null){ current.setPassword(temp); current.setRoleId(getLoggedUser().getRoleId()); try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccountUpdated")); return "index"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } JsfUtil.addErrorMessage( ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } public String checkLogin() { // current.setPassword(Encryption.encrypt(current.getPassword())); if (ejbFacade.checkLogin(current) != null) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest myRequest = (HttpServletRequest) context.getExternalContext().getRequest(); HttpSession session = myRequest.getSession(); current = ejbFacade.checkLogin(current); session.setAttribute("user", current); if (current.getRoleId().getRoleId() == 0) { return "Admin"; } else { String viewId = context.getViewRoot().getViewId(); if(viewId.equals("/login.xhtml")||viewId.equals("/register.xhtml")) return "/index"; return viewId; } } JsfUtil.addErrorMessage("Login Failure!"); return "/login"; } public String logOut() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest myRequest = (HttpServletRequest) context.getExternalContext().getRequest(); HttpSession session = myRequest.getSession(); session.removeAttribute("user"); return "/index"; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Account) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Account(); selectedItemIndex = -1; return "Create"; } public String create() { try { user.setUsername(current.getUsername()); current.setUserInformation(user); getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccountCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Account) getItems().getRowData(); user = current.getUserInformation(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public void register() { try { Role r = new Role(); r.setRoleId(Integer.parseInt(temp)); current.setRoleId(r); user.setUsername(current.getUsername()); user.setAvatar("aa"); current.setUserInformation(user); if(getFacade().register(current)){ JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccountCreated")); } else{ JsfUtil.addErrorMessage( ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccountUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Account) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccountDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Account.class) public static class AccountControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } AccountController controller = (AccountController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "accountController"); return controller.ejbFacade.find(getKey(value)); } java.lang.String getKey(String value) { java.lang.String key; key = value; return key; } String getStringKey(java.lang.String value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Account) { Account o = (Account) object; return getStringKey(o.getUsername()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AccountController.class.getName()); } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "functionrole", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Functionrole.findAll", query = "SELECT f FROM Functionrole f"), @NamedQuery(name = "Functionrole.findByFunctionroleid", query = "SELECT f FROM Functionrole f WHERE f.functionroleid = :functionroleid"), @NamedQuery(name = "Functionrole.findByDescription", query = "SELECT f FROM Functionrole f WHERE f.description = :description")}) public class Functionrole implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "functionroleid", nullable = false) private Integer functionroleid; @Size(max = 50) @Column(name = "description", length = 50) private String description; @JoinColumn(name = "role_id", referencedColumnName = "role_id", nullable = false) @ManyToOne(optional = false) private Role roleId; @JoinColumn(name = "functionid", referencedColumnName = "function_id", nullable = false) @ManyToOne(optional = false) private Function functionid; public Functionrole() { } public Functionrole(Integer functionroleid) { this.functionroleid = functionroleid; } public Integer getFunctionroleid() { return functionroleid; } public void setFunctionroleid(Integer functionroleid) { this.functionroleid = functionroleid; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Role getRoleId() { return roleId; } public void setRoleId(Role roleId) { this.roleId = roleId; } public Function getFunctionid() { return functionid; } public void setFunctionid(Function functionid) { this.functionid = functionid; } @Override public int hashCode() { int hash = 0; hash += (functionroleid != null ? functionroleid.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Functionrole)) { return false; } Functionrole other = (Functionrole) object; if ((this.functionroleid == null && other.functionroleid != null) || (this.functionroleid != null && !this.functionroleid.equals(other.functionroleid))) { return false; } return true; } @Override public String toString() { return "app.entity.Functionrole[ functionroleid=" + functionroleid + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "FAQ", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Faq.findAll", query = "SELECT f FROM Faq f"), @NamedQuery(name = "Faq.findByFaqId", query = "SELECT f FROM Faq f WHERE f.faqId = :faqId"), @NamedQuery(name = "Faq.findByUsername", query = "SELECT f FROM Faq f WHERE f.username = :username")}) public class Faq implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "faq_id", nullable = false) private Integer faqId; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 2147483647) @Column(name = "question", nullable = false, length = 2147483647) private String question; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 2147483647) @Column(name = "answer", nullable = false, length = 2147483647) private String answer; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "username", nullable = false, length = 50) private String username; public Faq() { } public Faq(Integer faqId) { this.faqId = faqId; } public Faq(Integer faqId, String question, String answer, String username) { this.faqId = faqId; this.question = question; this.answer = answer; this.username = username; } public Integer getFaqId() { return faqId; } public void setFaqId(Integer faqId) { this.faqId = faqId; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public int hashCode() { int hash = 0; hash += (faqId != null ? faqId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Faq)) { return false; } Faq other = (Faq) object; if ((this.faqId == null && other.faqId != null) || (this.faqId != null && !this.faqId.equals(other.faqId))) { return false; } return true; } @Override public String toString() { return "app.entity.Faq[ faqId=" + faqId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; /** * * @author Jerry */ public class Mail { String to; String from; String message; String subject; String smtpServ; public Mail(){ } public Mail(String to, String mess){ this.to=to; this.message=mess; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSmtpServ() { return smtpServ; } public void setSmtpServ(String smtpServ) { this.smtpServ = smtpServ; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "sysdiagrams", catalog = "mysweethome", schema = "dbo", uniqueConstraints = { @UniqueConstraint(columnNames = {"principal_id", "name"})}) @XmlRootElement @NamedQueries({ @NamedQuery(name = "Sysdiagrams.findAll", query = "SELECT s FROM Sysdiagrams s"), @NamedQuery(name = "Sysdiagrams.findByName", query = "SELECT s FROM Sysdiagrams s WHERE s.name = :name"), @NamedQuery(name = "Sysdiagrams.findByPrincipalId", query = "SELECT s FROM Sysdiagrams s WHERE s.principalId = :principalId"), @NamedQuery(name = "Sysdiagrams.findByDiagramId", query = "SELECT s FROM Sysdiagrams s WHERE s.diagramId = :diagramId"), @NamedQuery(name = "Sysdiagrams.findByVersion", query = "SELECT s FROM Sysdiagrams s WHERE s.version = :version")}) public class Sysdiagrams implements Serializable { private static final long serialVersionUID = 1L; @Basic(optional = false) @NotNull @Size(min = 1, max = 128) @Column(name = "name", nullable = false, length = 128) private String name; @Basic(optional = false) @NotNull @Column(name = "principal_id", nullable = false) private int principalId; @Id @Basic(optional = false) @NotNull @Column(name = "diagram_id", nullable = false) private Integer diagramId; @Column(name = "version") private Integer version; @Lob @Column(name = "definition") private byte[] definition; public Sysdiagrams() { } public Sysdiagrams(Integer diagramId) { this.diagramId = diagramId; } public Sysdiagrams(Integer diagramId, String name, int principalId) { this.diagramId = diagramId; this.name = name; this.principalId = principalId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrincipalId() { return principalId; } public void setPrincipalId(int principalId) { this.principalId = principalId; } public Integer getDiagramId() { return diagramId; } public void setDiagramId(Integer diagramId) { this.diagramId = diagramId; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public byte[] getDefinition() { return definition; } public void setDefinition(byte[] definition) { this.definition = definition; } @Override public int hashCode() { int hash = 0; hash += (diagramId != null ? diagramId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Sysdiagrams)) { return false; } Sysdiagrams other = (Sysdiagrams) object; if ((this.diagramId == null && other.diagramId != null) || (this.diagramId != null && !this.diagramId.equals(other.diagramId))) { return false; } return true; } @Override public String toString() { return "app.entity.Sysdiagrams[ diagramId=" + diagramId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Deviant */ @Entity @Table(name = "Account", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Account.findAll", query = "SELECT a FROM Account a"), @NamedQuery(name = "Account.checkLogin", query = "SELECT a FROM Account a WHERE a.username = :username and a.password = :password"), @NamedQuery(name = "Account.findByUsername", query = "SELECT a FROM Account a WHERE a.username = :username")}) public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "username", nullable = false, length = 50) private String username; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 1073741823) @Column(name = "password", nullable = false, length = 1073741823) private String password; @JoinColumn(name = "role_id", referencedColumnName = "role_id", nullable = false) @ManyToOne(optional = false) private Role roleId; @OneToMany(cascade = CascadeType.ALL, mappedBy = "username") private Collection<Feedback> feedbackCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "username") private Collection<Property> propertyCollection; @OneToOne(cascade = CascadeType.ALL, mappedBy = "account") private UserInformation userInformation; public Account() { } public Account(String username) { this.username = username; } public Account(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Role getRoleId() { return roleId; } public void setRoleId(Role roleId) { this.roleId = roleId; } @XmlTransient public Collection<Feedback> getFeedbackCollection() { return feedbackCollection; } public void setFeedbackCollection(Collection<Feedback> feedbackCollection) { this.feedbackCollection = feedbackCollection; } @XmlTransient public Collection<Property> getPropertyCollection() { return propertyCollection; } public void setPropertyCollection(Collection<Property> propertyCollection) { this.propertyCollection = propertyCollection; } public UserInformation getUserInformation() { return userInformation; } public void setUserInformation(UserInformation userInformation) { this.userInformation = userInformation; } @Override public int hashCode() { int hash = 0; hash += (username != null ? username.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Account)) { return false; } Account other = (Account) object; if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) { return false; } return true; } @Override public String toString() { return "app.entity.Account[ username=" + username + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "UserInformation", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "UserInformation.findAll", query = "SELECT u FROM UserInformation u"), @NamedQuery(name = "UserInformation.findByUsername", query = "SELECT u FROM UserInformation u WHERE u.username = :username"), @NamedQuery(name = "UserInformation.findByFullname", query = "SELECT u FROM UserInformation u WHERE u.fullname = :fullname"), @NamedQuery(name = "UserInformation.findByGender", query = "SELECT u FROM UserInformation u WHERE u.gender = :gender"), @NamedQuery(name = "UserInformation.findByAddress", query = "SELECT u FROM UserInformation u WHERE u.address = :address"), @NamedQuery(name = "UserInformation.findByEmail", query = "SELECT u FROM UserInformation u WHERE u.email = :email"), @NamedQuery(name = "UserInformation.findByPhone", query = "SELECT u FROM UserInformation u WHERE u.phone = :phone"), @NamedQuery(name = "UserInformation.findByBirthday", query = "SELECT u FROM UserInformation u WHERE u.birthday = :birthday"), @NamedQuery(name = "UserInformation.findByAvatar", query = "SELECT u FROM UserInformation u WHERE u.avatar = :avatar")}) public class UserInformation implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "username", nullable = false, length = 50) private String username; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "fullname", nullable = false, length = 50) private String fullname; @Basic(optional = false) @NotNull @Column(name = "gender", nullable = false) private boolean gender; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "address", nullable = false, length = 50) private String address; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "email", nullable = false, length = 50) private String email; // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation @Size(max = 20) @Column(name = "phone", length = 20) private String phone; @Basic(optional = false) @NotNull @Column(name = "birthday", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date birthday; @Size(max = 50) @Column(name = "avatar", length = 50) private String avatar; @JoinColumn(name = "username", referencedColumnName = "username", nullable = false, insertable = false, updatable = false) @OneToOne(optional = false) private Account account; public UserInformation() { } public UserInformation(String username) { this.username = username; } public UserInformation(String username, String fullname, boolean gender, String address, String email, Date birthday) { this.username = username; this.fullname = fullname; this.gender = gender; this.address = address; this.email = email; this.birthday = birthday; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public boolean getGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } @Override public int hashCode() { int hash = 0; hash += (username != null ? username.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UserInformation)) { return false; } UserInformation other = (UserInformation) object; if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) { return false; } return true; } @Override public String toString() { return "app.entity.UserInformation[ username=" + username + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Deviant */ @Entity @Table(name = "function", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Function.findAll", query = "SELECT f FROM Function f"), @NamedQuery(name = "Function.findByFunctionId", query = "SELECT f FROM Function f WHERE f.functionId = :functionId"), @NamedQuery(name = "Function.findByFunctionname", query = "SELECT f FROM Function f WHERE f.functionname = :functionname"), @NamedQuery(name = "Function.findByUrl", query = "SELECT f FROM Function f WHERE f.url = :url")}) public class Function implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "function_id", nullable = false) private Integer functionId; @Size(max = 50) @Column(name = "functionname", length = 50) private String functionname; @Size(max = 50) @Column(name = "url", length = 50) private String url; @OneToMany(cascade = CascadeType.ALL, mappedBy = "functionid") private Collection<Functionrole> functionroleCollection; public Function() { } public Function(Integer functionId) { this.functionId = functionId; } public Integer getFunctionId() { return functionId; } public void setFunctionId(Integer functionId) { this.functionId = functionId; } public String getFunctionname() { return functionname; } public void setFunctionname(String functionname) { this.functionname = functionname; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @XmlTransient public Collection<Functionrole> getFunctionroleCollection() { return functionroleCollection; } public void setFunctionroleCollection(Collection<Functionrole> functionroleCollection) { this.functionroleCollection = functionroleCollection; } @Override public int hashCode() { int hash = 0; hash += (functionId != null ? functionId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Function)) { return false; } Function other = (Function) object; if ((this.functionId == null && other.functionId != null) || (this.functionId != null && !this.functionId.equals(other.functionId))) { return false; } return true; } @Override public String toString() { return "app.entity.Function[ functionId=" + functionId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "Property", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p"), @NamedQuery(name = "Property.findByPropertyId", query = "SELECT p FROM Property p WHERE p.propertyId = :propertyId"), @NamedQuery(name = "Property.findByCountry", query = "SELECT p FROM Property p WHERE p.country = :country"), @NamedQuery(name = "Property.findByCity", query = "SELECT p FROM Property p WHERE p.city = :city"), @NamedQuery(name = "Property.findByDistrict", query = "SELECT p FROM Property p WHERE p.district = :district"), @NamedQuery(name = "Property.findByAddress", query = "SELECT p FROM Property p WHERE p.address = :address"), @NamedQuery(name = "Property.findByNoOfBedroom", query = "SELECT p FROM Property p WHERE p.noOfBedroom = :noOfBedroom"), @NamedQuery(name = "Property.findByNoOfBathroom", query = "SELECT p FROM Property p WHERE p.noOfBathroom = :noOfBathroom"), @NamedQuery(name = "Property.findByPrice", query = "SELECT p FROM Property p WHERE p.price = :price"), @NamedQuery(name = "Property.findByImage", query = "SELECT p FROM Property p WHERE p.image = :image"), @NamedQuery(name = "Property.findByDescription", query = "SELECT p FROM Property p WHERE p.description = :description"), @NamedQuery(name = "Property.findByIsUsed", query = "SELECT p FROM Property p WHERE p.isUsed = :isUsed"), @NamedQuery(name = "Property.findByStatus", query = "SELECT p FROM Property p WHERE p.status = :status"), @NamedQuery(name = "Property.findByModeOfPay", query = "SELECT p FROM Property p WHERE p.modeOfPay = :modeOfPay"), @NamedQuery(name = "Property.findByRent", query = "SELECT p FROM Property p WHERE p.rent = :rent"), @NamedQuery(name = "Property.findByDeposit", query = "SELECT p FROM Property p WHERE p.deposit = :deposit"), @NamedQuery(name = "Property.findByTypeHouse", query = "SELECT p FROM Property p WHERE p.typeHouse = :typeHouse"), @NamedQuery(name = "Property.findByModeOfTransport", query = "SELECT p FROM Property p WHERE p.modeOfTransport = :modeOfTransport"), @NamedQuery(name = "Property.findByIsfurniture", query = "SELECT p FROM Property p WHERE p.isfurniture = :isfurniture"), @NamedQuery(name = "Property.findByDatePost", query = "SELECT p FROM Property p WHERE p.datePost = :datePost")}) public class Property implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "property_id", nullable = false) private Integer propertyId; @Size(max = 30) @Column(name = "country", length = 30) private String country; @Size(max = 30) @Column(name = "city", length = 30) private String city; @Size(max = 30) @Column(name = "district", length = 30) private String district; @Size(max = 30) @Column(name = "address", length = 30) private String address; @Column(name = "no_Of_Bedroom") private Integer noOfBedroom; @Column(name = "no_Of_Bathroom") private Integer noOfBathroom; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "price", precision = 53) private Double price; @Size(max = 50) @Column(name = "image", length = 50) private String image; @Size(max = 50) @Column(name = "description", length = 50) private String description; @Basic(optional = false) @NotNull @Column(name = "isUsed", nullable = false) private boolean isUsed; @Basic(optional = false) @NotNull @Column(name = "status", nullable = false) private boolean status; @Size(max = 50) @Column(name = "mode_of_pay", length = 50) private String modeOfPay; @Column(name = "rent", precision = 53) private Double rent; @Column(name = "deposit", precision = 53) private Double deposit; @Size(max = 30) @Column(name = "type_house", length = 30) private String typeHouse; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "mode_of_transport", nullable = false, length = 50) private String modeOfTransport; @Basic(optional = false) @NotNull @Column(name = "isfurniture", nullable = false) private boolean isfurniture; @Basic(optional = false) @NotNull @Column(name = "date_post", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date datePost; @JoinColumn(name = "type_id", referencedColumnName = "type_id", nullable = false) @ManyToOne(optional = false) private PropertyType typeId; @JoinColumn(name = "username", referencedColumnName = "username", nullable = false) @ManyToOne(optional = false) private Account username; public Property() { } public Property(Integer propertyId) { this.propertyId = propertyId; } public Property(Integer propertyId, boolean isUsed, boolean status, String modeOfTransport, boolean isfurniture, Date datePost) { this.propertyId = propertyId; this.isUsed = isUsed; this.status = status; this.modeOfTransport = modeOfTransport; this.isfurniture = isfurniture; this.datePost = datePost; } public Integer getPropertyId() { return propertyId; } public void setPropertyId(Integer propertyId) { this.propertyId = propertyId; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getNoOfBedroom() { return noOfBedroom; } public void setNoOfBedroom(Integer noOfBedroom) { this.noOfBedroom = noOfBedroom; } public Integer getNoOfBathroom() { return noOfBathroom; } public void setNoOfBathroom(Integer noOfBathroom) { this.noOfBathroom = noOfBathroom; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getIsUsed() { return isUsed; } public void setIsUsed(boolean isUsed) { this.isUsed = isUsed; } public boolean getStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getModeOfPay() { return modeOfPay; } public void setModeOfPay(String modeOfPay) { this.modeOfPay = modeOfPay; } public Double getRent() { return rent; } public void setRent(Double rent) { this.rent = rent; } public Double getDeposit() { return deposit; } public void setDeposit(Double deposit) { this.deposit = deposit; } public String getTypeHouse() { return typeHouse; } public void setTypeHouse(String typeHouse) { this.typeHouse = typeHouse; } public String getModeOfTransport() { return modeOfTransport; } public void setModeOfTransport(String modeOfTransport) { this.modeOfTransport = modeOfTransport; } public boolean getIsfurniture() { return isfurniture; } public void setIsfurniture(boolean isfurniture) { this.isfurniture = isfurniture; } public Date getDatePost() { return datePost; } public void setDatePost(Date datePost) { this.datePost = datePost; } public PropertyType getTypeId() { return typeId; } public void setTypeId(PropertyType typeId) { this.typeId = typeId; } public Account getUsername() { return username; } public void setUsername(Account username) { this.username = username; } @Override public int hashCode() { int hash = 0; hash += (propertyId != null ? propertyId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Property)) { return false; } Property other = (Property) object; if ((this.propertyId == null && other.propertyId != null) || (this.propertyId != null && !this.propertyId.equals(other.propertyId))) { return false; } return true; } @Override public String toString() { return "app.entity.Property[ propertyId=" + propertyId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Deviant */ @Entity @Table(name = "Feedback", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Feedback.findAll", query = "SELECT f FROM Feedback f"), @NamedQuery(name = "Feedback.findByFeedbackId", query = "SELECT f FROM Feedback f WHERE f.feedbackId = :feedbackId"), @NamedQuery(name = "Feedback.findByStatus", query = "SELECT f FROM Feedback f WHERE f.status = :status")}) public class Feedback implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "feedback_id", nullable = false) private Integer feedbackId; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 2147483647) @Column(name = "contents", nullable = false, length = 2147483647) private String contents; @Basic(optional = false) @NotNull @Column(name = "status", nullable = false) private boolean status; @Lob @Size(max = 2147483647) @Column(name = "answer", length = 2147483647) private String answer; @JoinColumn(name = "username", referencedColumnName = "username", nullable = false) @ManyToOne(optional = false) private Account username; public Feedback() { } public Feedback(Integer feedbackId) { this.feedbackId = feedbackId; } public Feedback(Integer feedbackId, String contents, boolean status) { this.feedbackId = feedbackId; this.contents = contents; this.status = status; } public Integer getFeedbackId() { return feedbackId; } public void setFeedbackId(Integer feedbackId) { this.feedbackId = feedbackId; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public boolean getStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public Account getUsername() { return username; } public void setUsername(Account username) { this.username = username; } @Override public int hashCode() { int hash = 0; hash += (feedbackId != null ? feedbackId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Feedback)) { return false; } Feedback other = (Feedback) object; if ((this.feedbackId == null && other.feedbackId != null) || (this.feedbackId != null && !this.feedbackId.equals(other.feedbackId))) { return false; } return true; } @Override public String toString() { return "app.entity.Feedback[ feedbackId=" + feedbackId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Deviant */ @Entity @Table(name = "Role", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r"), @NamedQuery(name = "Role.findByRoleId", query = "SELECT r FROM Role r WHERE r.roleId = :roleId"), @NamedQuery(name = "Role.findByRoleName", query = "SELECT r FROM Role r WHERE r.roleName = :roleName"), @NamedQuery(name = "Role.findByDescription", query = "SELECT r FROM Role r WHERE r.description = :description")}) public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "role_id", nullable = false) private Integer roleId; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "roleName", nullable = false, length = 50) private String roleName; @Size(max = 50) @Column(name = "description", length = 50) private String description; @OneToMany(cascade = CascadeType.ALL, mappedBy = "roleId") private Collection<Account> accountCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "roleId") private Collection<Functionrole> functionroleCollection; public Role() { } public Role(Integer roleId) { this.roleId = roleId; } public Role(Integer roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @XmlTransient public Collection<Account> getAccountCollection() { return accountCollection; } public void setAccountCollection(Collection<Account> accountCollection) { this.accountCollection = accountCollection; } @XmlTransient public Collection<Functionrole> getFunctionroleCollection() { return functionroleCollection; } public void setFunctionroleCollection(Collection<Functionrole> functionroleCollection) { this.functionroleCollection = functionroleCollection; } @Override public int hashCode() { int hash = 0; hash += (roleId != null ? roleId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Role)) { return false; } Role other = (Role) object; if ((this.roleId == null && other.roleId != null) || (this.roleId != null && !this.roleId.equals(other.roleId))) { return false; } return true; } @Override public String toString() { return "app.entity.Role[ roleId=" + roleId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Deviant */ @Entity @Table(name = "Property_Type", catalog = "mysweethome", schema = "dbo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "PropertyType.findAll", query = "SELECT p FROM PropertyType p"), @NamedQuery(name = "PropertyType.findByTypeId", query = "SELECT p FROM PropertyType p WHERE p.typeId = :typeId"), @NamedQuery(name = "PropertyType.findByType", query = "SELECT p FROM PropertyType p WHERE p.type = :type"), @NamedQuery(name = "PropertyType.findByDescription", query = "SELECT p FROM PropertyType p WHERE p.description = :description")}) public class PropertyType implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "type_id", nullable = false) private Integer typeId; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "type", nullable = false, length = 50) private String type; @Size(max = 50) @Column(name = "description", length = 50) private String description; @OneToMany(cascade = CascadeType.ALL, mappedBy = "typeId") private Collection<Property> propertyCollection; public PropertyType() { } public PropertyType(Integer typeId) { this.typeId = typeId; } public PropertyType(Integer typeId, String type) { this.typeId = typeId; this.type = type; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @XmlTransient public Collection<Property> getPropertyCollection() { return propertyCollection; } public void setPropertyCollection(Collection<Property> propertyCollection) { this.propertyCollection = propertyCollection; } @Override public int hashCode() { int hash = 0; hash += (typeId != null ? typeId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PropertyType)) { return false; } PropertyType other = (PropertyType) object; if ((this.typeId == null && other.typeId != null) || (this.typeId != null && !this.typeId.equals(other.typeId))) { return false; } return true; } @Override public String toString() { return "app.entity.PropertyType[ typeId=" + typeId + " ]"; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Property; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class PropertyFacade extends AbstractFacade<Property> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public PropertyFacade() { super(Property.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Functionrole; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class FunctionroleFacade extends AbstractFacade<Functionrole> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FunctionroleFacade() { super(Functionrole.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Role; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class RoleFacade extends AbstractFacade<Role> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public RoleFacade() { super(Role.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import java.util.List; import javax.persistence.EntityManager; /** * * @author RubiLam */ public abstract class AbstractFacade<T> { private Class<T> entityClass; public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public void create(T entity) { getEntityManager().persist(entity); } public void edit(T entity) { getEntityManager().merge(entity); } public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public T find(Object id) { return getEntityManager().find(entityClass, id); } public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0]); q.setFirstResult(range[0]); return q.getResultList(); } public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Feedback; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class FeedbackFacade extends AbstractFacade<Feedback> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FeedbackFacade() { super(Feedback.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Faq; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class FaqFacade extends AbstractFacade<Faq> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FaqFacade() { super(Faq.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Account; import app.entity.UserInformation; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author RubiLam */ @Stateless public class UserInformationFacade extends AbstractFacade<UserInformation> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public UserInformationFacade() { super(UserInformation.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.PropertyType; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class PropertyTypeFacade extends AbstractFacade<PropertyType> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public PropertyTypeFacade() { super(PropertyType.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Account; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author RubiLam */ @Stateless public class AccountFacade extends AbstractFacade<Account> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public AccountFacade() { super(Account.class); } public Account checkLogin(Account acc){ Query qr = em.createNamedQuery("Account.checkLogin"); qr.setParameter("username", acc.getUsername()); qr.setParameter("password", acc.getPassword()); if(qr.getResultList().size()>0){ Account ac = (Account) qr.getResultList().get(0); return ac; } return null; } public boolean register(Account acc) { boolean f = false; try { //utx.begin(); //create(acc); //.commit(); Query qr = em.createNativeQuery("INSERT INTO Account(username,password,role_id)" + " values(?,?,?)"); qr.setParameter(1, acc.getUsername()); qr.setParameter(2, acc.getPassword()); qr.setParameter(3, acc.getRoleId().getRoleId()); if (qr.executeUpdate() == 1) { try { qr = em.createNativeQuery("INSERT INTO UserInformation(username,fullname,gender,address,email,phone,birthday,avatar)" + " values(?,?,?,?,?,?,?,?)"); qr.setParameter(1, acc.getUsername()); qr.setParameter(2, acc.getUserInformation().getFullname()); qr.setParameter(3, acc.getUserInformation().getGender()); qr.setParameter(4, acc.getUserInformation().getAddress()); qr.setParameter(5, acc.getUserInformation().getEmail()); qr.setParameter(6, acc.getUserInformation().getPhone()); qr.setParameter(7, acc.getUserInformation().getBirthday()); qr.setParameter(8, acc.getUserInformation().getAvatar()); if (qr.executeUpdate() == 1) { f = true; } } catch (Exception e) { f = false; } } } catch (Exception e) { f = false; } finally { return f; } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package app.session; import app.entity.Function; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author RubiLam */ @Stateless public class FunctionFacade extends AbstractFacade<Function> { @PersistenceContext(unitName = "MySweetHomesPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FunctionFacade() { super(Function.class); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller.util; /** * * @author Jerry */ import java.io.*; import javax.faces.application.FacesMessage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; public class FileUpload { private static final int BUFFER_SIZE = 6124; public void handleFileUpload(FileUploadEvent event) { ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext(); String p = extContext.getRealPath(event.getFile().getFileName()); String[] temp = p.split("build");//gfdeploy//Demo_Primefaces_JSF_Part2//Demo_Primefaces_JSF_Part2-war_war"); p = temp[0] + "web//resources//Images//imageAdmin//"; File result = new File(p + event.getFile().getFileName()); //"D:\APT\SEM 4\SV\babyshop-primefaces\Demo_Primefaces_JSF_Part2\Jellyfish.jpg" System.out.println(p); try { FileOutputStream fileOutputStream = new FileOutputStream(result); byte[] buffer = new byte[BUFFER_SIZE]; int bulk; InputStream inputStream = event.getFile().getInputstream(); while (true) { bulk = inputStream.read(buffer); if (bulk < 0) { break; } fileOutputStream.write(buffer, 0, bulk); fileOutputStream.flush(); } fileOutputStream.close(); inputStream.close(); FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (IOException e) { e.printStackTrace(); FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", ""); FacesContext.getCurrentInstance().addMessage(null, error); } } }
Java
package Interfaces; import java.rmi.Remote; import java.rmi.RemoteException; public interface WorkerInterface extends Remote { /** * This function does the task given. * @param task - the task to perform * @throws RemoteException */ void doTask(Task task) throws RemoteException; }
Java
/** * */ package Interfaces; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.Set; /** * @author Barak & Ron * */ public interface WorkerRegister extends Remote { /** * Through This function a worker registers in the server. * @param name The unique name of the new worker. * @param resources The resources the worker have. * @throws RemoteException */ void register(String name,Set<String> resources) throws RemoteException; }
Java
package Interfaces; import java.io.Serializable; import java.util.Set; public class Task implements Serializable { private static final long serialVersionUID = -4751120753565781651L; Set<String> requirements; int taskId; public Task(int taskId, Set<String> requirements) { this.taskId = taskId; this.requirements = requirements; } public Set<String> getRequirements() { return this.requirements; } public void execute() { // simulate some long running execution // sleep for a second System.out.println("Executing task " + this.taskId + " ..."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task " + this.taskId + " done."); } }
Java
package Master; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.net.Socket; import Interfaces.Task; /** * * This class tries to execute the clients' task on the appropriate machine * * Receives via the constructor the socket by which we communicate with the * client. * In order to decide on which machine (if exists) we will run the task, we * use a server method of the Master class - doTask. * */ public class ClientServiceThread extends Thread { private Socket socket; public ClientServiceThread(Socket socket){ this.socket=socket; } @Override public void run(){ try { ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); Task task = (Task)in.readObject(); PrintWriter out = new PrintWriter(socket.getOutputStream(),true); if(Master.doTask(task)) { out.println("OK"); } else { out.println("REJECT"); } socket.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } } }
Java
package Master; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import Interfaces.Task; import Interfaces.WorkerInterface; import Interfaces.WorkerRegister; public class Master implements WorkerRegister { /** * * This class encapsulates a worker. * * For a specific worker we save: * 1. offered resources * 2. the current number of jobs executed on it * 3. the computer hostname for sending instructions to the worker */ class Worker { Set<String> resources = new HashSet<String>(); // the current number of jobs executing on the worker int numJobs; public Worker(Set<String> resources) { this.resources.addAll(resources); this.numJobs=0; } public void increaseJobNum(){ numJobs++; } public void decreaseJobNum(){ numJobs--; } } // we identify a worker by a special string created by the UUID class private static Map<String,Worker> workersMap = new ConcurrentHashMap<String,Worker>(); /** * Checks if the specified worker is suitable for the execution of task * @param task the client sent for execution * @param worker to query * @return true if the worker has the resources the client specified in task */ private static boolean isWorkerSuitable(Task task, Worker worker) { for(String req : task.getRequirements()){ if(!worker.resources.contains(req)) { return false; } } return true; } /** * Searching for the worker that can run the task and has the minimal number * of jobs. * @param task the client sent * @return the tuple in workersMap that corresponds to the found worker, or * null if no suitable worker is found. */ private static Entry<String,Worker> findWorker(Task task) { Entry<String,Worker> chosenWorker = null; int minJobs=Integer.MAX_VALUE; // searching for the worker that can run the task and has the minimal // number of jobs for (Entry<String,Worker> workerTuple: workersMap.entrySet()) { Worker worker = workerTuple.getValue(); if( isWorkerSuitable(task, worker) && (minJobs > worker.numJobs) ) { minJobs = worker.numJobs; chosenWorker = workerTuple; } } return chosenWorker; } /** * This method tries to perform the task specified by the client. * We search for the appropriate worker (amongst all are signed ones), and * send him the task for execution * @param task the client sent * @return true if we found a suitable worker and we were able to run it */ public static boolean doTask(Task task){ // TODO maybe check if it should be a synchronized function Entry<String,Worker> chosenWorker = findWorker(task); if(chosenWorker == null) { return false; } Worker worker = chosenWorker.getValue(); String workerID = chosenWorker.getKey(); try { // getting the remote stub Registry registry = LocateRegistry.getRegistry(); WorkerInterface remoteWorker=(WorkerInterface)registry.lookup(workerID); // performing the task and increasing the number of jobs run by worker worker.increaseJobNum(); remoteWorker.doTask(task); // removing this completed job form the workers job count worker.decreaseJobNum(); } catch (Exception e){ workersMap.remove(workerID); return doTask(task); } return true; } @Override public void register(String name, Set<String> resources) throws RemoteException { workersMap.put(name, new Worker(resources)); } public static void main(String[] args) { // acquiring the security policy if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } // registering the workers try { String name = "Register"; WorkerRegister workerRegistrer = new Master(); WorkerRegister stub = (WorkerRegister) UnicastRemoteObject.exportObject(workerRegistrer , 0); Registry registry = LocateRegistry.getRegistry(); // installing a special remote object to the local rmiregistry, this // object is responsible for the registration of the workers registry.rebind(name, stub); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } ServerSocket srv=null; // acting as a server for the clients task requests try { int port = Integer.valueOf(args[0]); srv = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } while(true){ // TODO check if we really need to do a while true loop or is there some other way we need to operate try { Socket socket = srv.accept(); // for each connection from the client we open new thread to handle it ClientServiceThread cliThread = new ClientServiceThread(socket); cliThread.start(); } catch (Exception e) { e.printStackTrace(); } } } // main end }
Java
package Client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashSet; import java.util.Set; import Interfaces.Task; public class Client { public static void main (String args[]) throws InterruptedException{ Runnable r = new Runnable() { public void run() { Set<String> set=new HashSet<String>(); set.add("spong"); Task newTask=new Task(3,set); Socket socket=null; try { socket = new Socket("127.0.1.1", 10099); System.out.println("created socket"); ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream()); out.writeObject(newTask); System.out.println("Object sent to server"); System.out.println("reading response"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(in.readLine()); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ; new Thread(r).start(); Thread.sleep(500); Runnable r2 = new Runnable() { public void run() { Set<String> set=new HashSet<String>(); set.add("spong"); Task newTask=new Task(4,set); Socket socket=null; try { socket = new Socket("127.0.1.1", 10099); System.out.println("created socket"); ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream()); out.writeObject(newTask); System.out.println("Object sent to server"); System.out.println("reading response"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(in.readLine()); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ; new Thread(r2).start(); Thread.sleep(500); Runnable r3 = new Runnable() { public void run() { Set<String> set=new HashSet<String>(); set.add("spong"); Task newTask=new Task(5,set); Socket socket=null; try { socket = new Socket("127.0.1.1", 10099); System.out.println("created socket"); ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream()); out.writeObject(newTask); System.out.println("Object sent to server"); System.out.println("reading response"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(in.readLine()); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ; new Thread(r3).start(); } }
Java
package Worker; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import Interfaces.*; public class Worker implements WorkerInterface{ private static String uniqueID = UUID.randomUUID().toString(); @Override public void doTask(Task task) throws RemoteException{ task.execute(); } public static void main(String args[]) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } try { // installing a remote object for treating client jobs at the remote rmiregistry WorkerInterface worker= new Worker(); Registry registry = LocateRegistry.getRegistry(args[0]); WorkerInterface stub = (WorkerInterface) UnicastRemoteObject.exportObject(worker,0); registry.rebind(uniqueID, stub); // getting the remote stub for worker registration String name = "Register"; WorkerRegister regObj = (WorkerRegister) registry.lookup(name); Set<String> resources = new TreeSet<String>(); for(int i=1;i<args.length;i++) { resources.add(args[i]); } // registering to the master machine regObj.register(uniqueID,resources); } catch (Exception e) { System.exit(-1); } } }
Java
package rmiExample.client; import java.rmi.Remote; import java.rmi.RemoteException; public interface Compute extends Remote { <T> T executeTask(Task<T> t) throws RemoteException; }
Java
package rmiExample.client; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.math.BigDecimal; public class ComputePi { public static void main(String args[]) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } try { String name = "Compute"; Registry registry = LocateRegistry.getRegistry(args[0]); Compute comp = (Compute) registry.lookup(name); System.out.println("Got the stub"); Pi task = new Pi(Integer.parseInt(args[1])); BigDecimal pi = comp.executeTask(task); System.out.println(pi); } catch (Exception e) { System.err.println("ComputePi exception:"); e.printStackTrace(); } } }
Java
package rmiExample.client; public interface Task<T> { T execute(); }
Java
package rmiExample.client; import rmiExample.client.Task; import java.io.Serializable; import java.math.BigDecimal; public class Pi implements Task<BigDecimal>, Serializable { private static final long serialVersionUID = 227L; /** constants used in pi computation */ private static final BigDecimal FOUR = BigDecimal.valueOf(4); /** rounding mode to use during pi computation */ private static final int roundingMode = BigDecimal.ROUND_HALF_EVEN; /** digits of precision after the decimal point */ private final int digits; /** * Construct a task to calculate pi to the specified * precision. */ public Pi(int digits) { this.digits = digits; } /** * Calculate pi. */ public BigDecimal execute() { return computePi(digits); } /** * Compute the value of pi to the specified number of * digits after the decimal point. The value is * computed using Machin's formula: * * pi/4 = 4*arctan(1/5) - arctan(1/239) * * and a power series expansion of arctan(x) to * sufficient precision. */ public static BigDecimal computePi(int digits) { int scale = digits + 5; BigDecimal arctan1_5 = arctan(5, scale); BigDecimal arctan1_239 = arctan(239, scale); BigDecimal pi = arctan1_5.multiply(FOUR).subtract( arctan1_239).multiply(FOUR); return pi.setScale(digits, BigDecimal.ROUND_HALF_UP); } /** * Compute the value, in radians, of the arctangent of * the inverse of the supplied integer to the specified * number of digits after the decimal point. The value * is computed using the power series expansion for the * arc tangent: * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + * (x^9)/9 ... */ public static BigDecimal arctan(int inverseX, int scale) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, scale, roundingMode); result = numer; int i = 1; do { numer = numer.divide(invX2, scale, roundingMode); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode); if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } while (term.compareTo(BigDecimal.ZERO) != 0); return result; } }
Java
package rmiExample.server; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import rmiExample.client.Compute; import rmiExample.client.Task; public class ComputeEngine implements Compute { public ComputeEngine() { super(); } public <T> T executeTask(Task<T> t) throws RemoteException { System.out.println("Executing the task..."); System.out.println("a:"+a); a++; System.out.println("a:"+a); return t.execute(); } public static int a=0; public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } System.out.println("Security manager obtained"); try { String name = "Compute"; Compute engine = new ComputeEngine(); Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0); Registry registry = LocateRegistry.getRegistry(); System.out.println("The registry located"); registry.rebind(name, stub); System.out.println("ComputeEngine bound"); } catch (Exception e) { System.err.println("ComputeEngine exception:"); e.printStackTrace(); } } }
Java
package groupManagement; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Timer; import javax.jms.JMSException; import javax.jms.TopicSubscriber; import chat.LingvoChat; import topicHandlers.Control; import topicHandlers.Translate; public class ChatGroup { private HashSet<String> userNames; private String groupName; private String userName; private Timer aliveSender; private TopicSubscriber translate; private TopicSubscriber control; public ChatGroup(String groupName,String userName,String lang) { super(); this.userNames = new HashSet<String>(); this.groupName = groupName; this.userName=userName; //start the I'm alive sender Timer timer=new Timer(); timer.scheduleAtFixedRate(new AliveSender(groupName, userName, lang), 0, 10000); this.aliveSender=timer; this.translate=LingvoChat.initListner(groupName, new Translate(lang)); this.control=LingvoChat.initListner(groupName+"-control", new Control(groupName, this,userName,lang)); this.userNames.add(userName); User.addUserToGroup(userName, lang, this); LingvoChat.publishMsg(groupName+"-control", "join-" + lang + "-" + userName); } //clean up all of the timers and listeners. public void leaveGroup(){ this.aliveSender.cancel(); try { this.translate.close(); this.control.close(); } catch (JMSException e) { e.printStackTrace(); } for(String user : userNames){ User.removeUserFromGroup(user, this); } LingvoChat.publishMsg(groupName+"-control", "leave-" + userName); } public void addUser(String userName,String lang) { synchronized (userNames) { User.addUserToGroup(userName, lang, this); userNames.add(userName); } } public void removeUser(String userName){ synchronized (userNames) { if(userNames.contains(userName)){ userNames.remove(userName); User.removeUserFromGroup(userName, this); } } } public boolean doYouHaveThisUser(String userName){ synchronized (userNames) { return (userNames.contains(userName)); } } public void printStatus() { System.out.println("~~~" + this.groupName.substring(14) + "~~~"); synchronized (userNames) { for(String user : userNames){ User.printUser(user); } } System.out.println(""); } }
Java
package groupManagement; import java.util.TimerTask; import chat.LingvoChat; public class AliveSender extends TimerTask{ private String userName; private String topicName; private String lang; public AliveSender(String group,String userName,String lang) { this.topicName = group+"-control"; this.userName=userName; this.lang=lang; } @Override public void run() { //the I'm alive message is alive-<language>-<user name> LingvoChat.publishMsg(topicName,"alive-"+lang+ "-" + userName); } }
Java
package groupManagement; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Timer; public class User { private static HashMap<String, User> users=new HashMap<String, User>(); private String lang; private String name; private Set<ChatGroup> groups; private Timer timer; private User(String name,String lang){ this.lang=lang; this.name=name; this.groups=new HashSet<ChatGroup>(); this.timer=new Timer(); this.timer.schedule(new UserTimer(name), 30000); //change this synchronized (users) { users.put(name,this); } } private void resetTimer(){ this.timer.cancel(); this.timer=new Timer(); this.timer.schedule(new UserTimer(name), 30000); } public static void addUserToGroup(String user,String lang,ChatGroup group){ synchronized (users) { if(users.containsKey(user)){ User current=users.get(user); synchronized (current.groups) { if(!current.groups.contains(group)){ current.groups.add(group); } } current.resetTimer(); } else{ User current=new User(user,lang); synchronized (current.groups) { current.groups.add(group); } } } } public static void removeUserFromGroup(String user,ChatGroup group){ synchronized (users) { if(!users.containsKey(user)){ return ; //user not in records } else{ User current = users.get(user); synchronized (current.groups) { current.groups.remove(group); if(current.groups.isEmpty()){ current.timer.cancel(); users.remove(user); } } } } } public static void userImAlive(String name){ synchronized (users) { if(users.containsKey(name)){ users.get(name).resetTimer(); } } } public static void removeUser(String name){ Set<ChatGroup> groups = new HashSet<ChatGroup>(); synchronized (users) { if(!users.containsKey(name)){ return; } User current=users.get(name); current.timer.cancel(); synchronized (current.groups) { groups.addAll(current.groups); users.remove(name); } } for(ChatGroup group : groups){ group.removeUser(name); } } public static void printUser(String userName){ synchronized (users) { if(users.containsKey(userName)){ User current=users.get(userName); System.out.println("User name: " + current.name); System.out.println("User language: " + current.lang); } } } }
Java
package groupManagement; import java.util.TimerTask; //remove user if an I'm alive message was not received in 30 seconds. public class UserTimer extends TimerTask { private String userName; public UserTimer(String userName){ this.userName=userName; } @Override public void run() { User.removeUser(userName); } }
Java
package Logging; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Date; import java.util.Map; /** * Monitor class which allows logging server information into * a file. This class is a singleton, the instance can be received by * calling the static get method. */ public class Monitor { private FileWriter fw; private PrintWriter pw; private int ln = 0; private final String LogFilePath = "c://temp/log.txt"; private final boolean CAN_WRITE = true; public Monitor() { try { fw = new FileWriter(LogFilePath, true); pw = new PrintWriter(fw, true); if(CAN_WRITE) pw.println("====== Started at " + new Date() + " ======"); } catch (IOException e) { } } private static Monitor inst; public synchronized static Monitor get() { if (inst == null) { inst = new Monitor(); } return inst; } /** * Writes simple data to log. * * @param o * the object which initiated the logging * @param arr * the list of data to log */ public static void write(Object o, Object... arr) { get().writeImpl(o, arr); } /** * Writes exception data to log * * @param e * the exception to be logged */ public static void writeException(Exception e) { get().writeExp(e); } /** * Writes the exception stack trace to log * * @param e * the exception to be logged */ private void writeExp(Exception e) { if (pw == null || !CAN_WRITE) { return; } e.printStackTrace(pw); pw.flush(); } /** * Writes the data to the log * * @param o * the object which initialized the logging * @param arr * the data to log */ private void writeImpl(Object o, Object... arr) { if (pw == null || !CAN_WRITE) { return; } StringBuilder sb = new StringBuilder(100); ++ln; sb.append("(" + ln + ") "); if(o != null) { sb.append(o.getClass().getSimpleName()); } for (Object x : arr) { sb.append(" ").append(str(x)); } pw.println(sb.toString()); pw.flush(); } /** * Converts the received object to string depending on its type * * @param x * the object to convert * @return the string representation of that object */ private String str(Object x) { if (x instanceof Iterable<?>) { return strList((Iterable<?>) x); } if (x instanceof Object[]) { return Arrays.toString((Object[]) x); } if (x instanceof Map<?, ?>) { return strMap((Map<?, ?>) x); } return String.valueOf(x); } /** * Converts a map object to a printable string * * @param x * the map object * @return the string representation of the received object */ private String strMap(Map<?, ?> x) { StringBuilder sb = new StringBuilder("{"); int n = 0; for (Map.Entry<?, ?> e : x.entrySet()) { if (++n > 1) { sb.append(", "); } sb.append(str(e.getKey() + "=" + str(e.getValue()))); } sb.append("}"); return sb.toString(); } /** * Converts a iterable object to a printable string * * @param x * the iterable object * @return the string representation of the received object */ private String strList(Iterable<?> x) { StringBuilder sb = new StringBuilder("["); int n = 0; for (Object o : x) { if (++n > 1) { sb.append(", "); } sb.append(str(o)); } sb.append("]"); return sb.toString(); } }
Java
package chat; import groupManagement.ChatGroup; import groupManagement.User; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import javax.jms.JMSException; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.rowset.spi.SyncResolver; import topicHandlers.Translate; import Logging.Monitor; public class LingvoChat { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // for the communication with rest of the groups static Context jndiContext = null; static TopicConnectionFactory topicConnectionFactory = null; static TopicConnection topicConnection = null; static TopicSession topicSession = null; MessageListener controlListener; // Groups info private Map<String, ChatGroup> groups=new HashMap<String, ChatGroup>(); // user specific info private final String userName; private final String lang; private final static LinkedList<String> allowedLang = new LinkedList<String>( Arrays.asList(new String[]{"ENGLISH","SPANISH","FRENCH","GERMAN"}) ); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public LingvoChat(String username,String lang) { this.userName = username; this.lang = lang; } private void initMessaging() { try { jndiContext = new InitialContext(); topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup("TopicConnectionFactory"); topicConnection = topicConnectionFactory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); } catch (NamingException e) { System.out.println("Could not connect to JMS"); quit(); } catch (JMSException e) { System.out.println("Could not connect to JMS"); quit(); } } static public TopicSubscriber initListner(String topicName,MessageListener topicListener) { try { Topic topic = (Topic) jndiContext.lookup(topicName); TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(topicListener); topicConnection.start(); return topicSubscriber; } catch (NamingException e) { System.out.println("Could not connect to Topic"); } catch (JMSException e) { System.out.println("Could not connect to Topic"); } return null; } public static void publishMsg(String topicName,String message) { try { Topic topic = (Topic) jndiContext.lookup(topicName); TopicPublisher topicPublisher = topicSession.createPublisher(topic); TextMessage textMessage = topicSession.createTextMessage(); textMessage = topicSession.createTextMessage(message); topicPublisher.publish(textMessage); topicPublisher.close(); } catch (NamingException e) { System.out.println("Couldnt publish msg on topic, for more details - " + e.getMessage()); } catch (JMSException e) { System.out.println("Couldnt publish msg on topic, for more details - " + e.getMessage()); } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// private void join(String group) { Monitor.write(null, "Handling a join request for group:"+group); if( !groups.containsKey(group)){ synchronized (groups) { groups.put(group, new ChatGroup(group, userName, lang)); } try { Thread.sleep(10000); } catch (InterruptedException ignore) {} Monitor.write(this, "Added new group"); // printing the participants of the group groupStatus(group); } else { System.out.println("Already in group " + group.substring(14)); } } private void leave(String group) { Monitor.write(null, "Handling a leave request for group:"+group); synchronized (groups) { if(!groups.containsKey(group)){ System.out.println("Leave action failed - user not in group"); } else { groups.get(group).leaveGroup(); User.removeUserFromGroup(userName, groups.get(group)); groups.remove(group); System.out.println("ok"); } } } private void publish(String group,String message) { Monitor.write(null, "Handling a publish request for group:"+group+ " with the message:"+message); synchronized (groups) { if(!groups.containsKey(group)){ System.out.println("User not in group " + group.substring(14)); }else{ publishMsg(group, userName + Translate.SEPERATOR + lang + Translate.SEPERATOR + message); } } } private void groupStatus(String groupName) { Monitor.write(null, "Handling a groupStatuses request"); synchronized (groups) { ChatGroup group = groups.get(groupName); if(group==null){ System.out.println("Not in group " + groupName.substring(14)); } else{ group.printStatus(); } } } private void myGroups() { Monitor.write(null, "Handlinng a myGroups request"); synchronized (groups) { for (ChatGroup group : groups.values()) { group.printStatus(); } } } private void quit() { Monitor.write(null, "Handling a quit request"); synchronized (groups) { for(ChatGroup group : groups.values()){ group.leaveGroup(); } } System.exit(0); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// private boolean exeCommand(String commandLine) { // parse and find what command should we execute int commandEnding = commandLine.indexOf(" "); commandEnding = (commandEnding == -1)? commandLine.length(): commandEnding; // in upper case to make our comparison easier String command = commandLine.substring(0, commandEnding). toUpperCase(); String parameter = (commandEnding == commandLine.length())? command: commandLine.substring(commandEnding+1); if(command.equals("JOIN")) { join("dynamicTopics/" + parameter); } else if(command.equals("LEAVE")) { leave("dynamicTopics/" + parameter); } else if(command.equals("PUBLISHMSG")) { int paramDelim = parameter.indexOf(" "); publish("dynamicTopics/" + parameter.substring(0,paramDelim), parameter.substring(paramDelim+1)); } else if(command.equals("GROUPSTATUS")) { groupStatus("dynamicTopics/" + parameter); } else if(command.equals("MYGROUPS")) { myGroups(); } else if (command.equals("QUIT")) { quit(); return false; } System.out.print(">> "); return true; } public static void main(String[] args) throws IOException { // check that the parameters entered in the correct format if( args.length != 2) { System.out.println("Please insert parameters in the correct format:\n" + "<username> {English | Spanish | French | German}"); System.exit(0); } String enteredUsername = args[0]; // checking that the language is one of {English,Spanish,French,German} if(!allowedLang.contains(args[1].toUpperCase())) { System.out.println("Please insert a language to be one of the following:\n" + "{English,Spanish,French,German}"); System.exit(0); } String enteredLang = args[1]; Monitor.write(null, "Recieved the following parameters:\n" + "username:"+enteredUsername+"\n"+ "langauage:"+enteredLang); LingvoChat userInstance = new LingvoChat(enteredUsername,enteredLang); userInstance.initMessaging(); // waiting for instructions from the user BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print(">> "); while(userInstance.exeCommand(br.readLine())); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// }
Java
package topicHandlers; import groupManagement.ChatGroup; import groupManagement.User; import java.util.TimerTask; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import chat.LingvoChat; /** * This class is responsible for: * <ol> * <li>adding the user to a group: * <ol> * <li>If we are in the margin of 30 seconds we try to add if not exists * to personsInGroup and userInGroup * </ol> * </li> * </ol> * * <p>Received message types:</p> * <p>"Alive-"[username] - I'm alive message</p> * <p>"Joined-"[username] - join request, send back "Alive-"[username]</p> * <p>"Leave-"[username] - Leave request, delete user from group.</p> */ public class Control implements MessageListener{ private String group; private String userName; private String lang; private ChatGroup chatGroup; public Control(String group,ChatGroup chatGroup,String userName,String lang) { this.group=group; this.chatGroup=chatGroup; this.userName=userName; this.lang=lang; } @Override public void onMessage(Message message) { String msg = null; try { if (message instanceof TextMessage) { msg = ((TextMessage) message).getText(); } else { System.out.println("Message of wrong type: " + message.getClass().getName()); return ; } } catch (JMSException e) { System.out.println("JMSException in onMessage(): " + e.toString()); } catch (Throwable t) { System.out.println("Exception in onMessage():" + t.getMessage()); } parse(msg); } void parse(String msg){ // parse and find what command should we execute int commandEnding = msg.indexOf("-"); if(commandEnding==-1){ //unrecognised command. return; } String command=msg.substring(0,commandEnding); String parameter=msg.substring(commandEnding+1); if(command.equals("alive")) { alive(parameter); } else if(command.equals("join")) { join(parameter); } else if(command.equals("leave")) { leave(parameter); } } private void alive(String parameter) { String user,lang; int langEnding = parameter.indexOf("-"); if(langEnding==-1){ //unknown message return ; } lang=parameter.substring(0, langEnding); user=parameter.substring(langEnding+1); if(chatGroup.doYouHaveThisUser(user)==false){ //add user to group f missed him on join request. chatGroup.addUser(user, lang); } else{ User.userImAlive(user); } } private void join(String parameter) { alive(parameter); LingvoChat.publishMsg(group, "alive-"+lang+"-"+userName); } private void leave(String user) { if(chatGroup.doYouHaveThisUser(user)==true){ chatGroup.removeUser(user); } } }
Java
package topicHandlers; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; //WS is the translation web service import Logging.Monitor; import WS.GetResponse; import WS.Otms; import WS.OtmsSoap; import WS.Query; public class Translate implements MessageListener{ private OtmsSoap translator; private String myLang; //the received message should be in the form of <username><Seperator><userlang><seperator><message> //<seperator>=</sep/> public static final String SEPERATOR="</sep/>"; public Translate(String myLang) { this.myLang = myLang; Otms impl= new Otms(); this.translator=impl.getOtmsSoap(); } @Override public void onMessage(Message message) { String msg = null; try { if (message instanceof TextMessage) { msg = ((TextMessage) message).getText(); } else { System.out.println("Message of wrong type: " + message.getClass().getName()); return ; } } catch (JMSException e) { System.out.println("JMSException in onMessage(): " + e.toString()); } catch (Throwable t) { System.out.println("Exception in onMessage():" + t.getMessage()); } parse(msg); } private String useWS(String fromLang,String inputStr) { Query q = new Query(); q.setSourceLang(fromLang); q.setTargetLang(this.myLang); q.setMt(1); q.setSource(inputStr); GetResponse response = translator.otmsGet("mmDemo123", q); if (response.isSuccess()) { // get the first match String translation = response.getMatches().getMatch().get(0).getTranslation(); return translation; } else { return "Translation not found"; } } private void parse(String msg) { //get user name int endOfUserName=msg.indexOf(SEPERATOR); if(endOfUserName==-1) { badMessage(); return; } String userName=msg.substring(0, endOfUserName); msg=msg.substring(endOfUserName+SEPERATOR.length(), msg.length()); //get the message language int endOfLang=msg.indexOf(SEPERATOR); if (endOfLang==-1) { badMessage(); return; } String lang=msg.substring(0, endOfLang); //Translate message if necessary msg=msg.substring(endOfLang+SEPERATOR.length(), msg.length()); String outMessage=null; if(lang.equals(this.myLang)) //Message is in own language - no need to translate outMessage= msg; else outMessage=useWS(lang, msg); System.out.println("["+userName + ":] "+outMessage+"("+lang+": "+msg+")"); } private void badMessage() { //maybe add error message to the screen Monitor.write(this,"received bad message on topic"); } }
Java
/* * * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * */ package jms.pubsub.topic; /** * The SimpleTopicSubscriber class consists only of a main * method, which receives one or more messages from a topic using * asynchronous message delivery. It uses the message listener * TextListener. Run this program in conjunction with * SimpleTopicPublisher. * * Specify a topic name on the command line when you run the * program. To end the program, enter Q or q on the command line. */ import javax.jms.*; import javax.naming.*; import java.io.*; public class SimpleTopicSubscriber { /** * Main method. * * @param args * the topic used by the example */ public static void main(String[] args) { String topicName = "topic1"; //default Context jndiContext = null; TopicConnectionFactory topicConnectionFactory = null; TopicConnection topicConnection = null; TopicSession topicSession = null; Topic topic = null; TopicSubscriber topicSubscriber = null; TextListener topicListener = null; InputStreamReader inputStreamReader = null; char answer = '\0'; /* * Read topic name from command line and display it. */ if (args.length != 1) { System.out.println("Usage: java " + "SimpleTopicSubscriber <topic-name>"); System.exit(1); } topicName = new String(args[0]); System.out.println("Topic name is " + topicName); /* * Create a JNDI API InitialContext object if none exists yet. */ try { jndiContext = new InitialContext(); } catch (NamingException e) { System.out.println("Could not create JNDI API " + "context: " + e.toString()); e.printStackTrace(); System.exit(1); } /* * Look up connection factory and topic. If either does not exist, exit. */ try { topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup("TopicConnectionFactory"); topic = (Topic) jndiContext.lookup(topicName); } catch (NamingException e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create subscriber. Register message * listener (TextListener). Receive text messages from topic. When all * messages have been received, enter Q to quit. Close connection. */ try { topicConnection = topicConnectionFactory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); topicSubscriber = topicSession.createSubscriber(topic); topicListener = new TextListener(); topicSubscriber.setMessageListener(topicListener); //non durable: receive only messages that are published while they are active. topicConnection.start(); //Starts (or restarts) a connection's delivery of incoming messages. A call to start on a connection that has already been started is ignored. System.out.println("To end program, enter Q or q, " + "then <return>"); inputStreamReader = new InputStreamReader(System.in); while (!((answer == 'q') || (answer == 'Q'))) { try { answer = (char) inputStreamReader.read(); } catch (IOException e) { System.out.println("I/O exception: " + e.toString()); } } } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); } finally { if (topicConnection != null) { try { topicConnection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } }
Java
/* * * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * */ package jms.pubsub.topic; /** * The TextListener class implements the MessageListener * interface by defining an onMessage method that displays * the contents of a TextMessage. * * This class acts as the listener for the SimpleTopicSubscriber * class. */ import javax.jms.*; public class TextListener implements MessageListener { /** * Casts the message to a TextMessage and displays its text. * * @param message * the incoming message */ public void onMessage(Message message) { TextMessage msg = null; try { if (message instanceof TextMessage) { msg = (TextMessage) message; System.out.println("Reading message: " + msg.getText()); } else { System.out.println("Message of wrong type: " + message.getClass().getName()); } } catch (JMSException e) { System.out.println("JMSException in onMessage(): " + e.toString()); } catch (Throwable t) { System.out.println("Exception in onMessage():" + t.getMessage()); } } }
Java
/* * * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * */ package jms.pubsub.topic; import javax.jms.*; import javax.naming.*; /** * The SimpleTopicPublisher class consists only of a main method, * which publishes several messages to a topic. * * Run this program in conjunction with SimpleTopicSubscriber. * Specify a topic name on the command line when you run the * program. By default, the program sends one message. * Specify a number after the topic name to send that number * of messages. */ public class SimpleTopicPublisher { /** * Main method. * * @param args * the topic used by the example and, optionally, the number of * messages to send */ public static void main(String[] args) { String topicName = "topic1"; //default value Context jndiContext = null; TopicConnectionFactory topicConnectionFactory = null; TopicConnection topicConnection = null; TopicSession topicSession = null; Topic topic = null; TopicPublisher topicPublisher = null; TextMessage message = null; final int NUM_MSGS; if ((args.length < 1) || (args.length > 2)) { System.out.println("Usage: java " + "SimpleTopicPublisher <topic-name> " + "[<number-of-messages>]"); System.exit(1); } topicName = new String(args[0]); System.out.println("Topic name is " + topicName); if (args.length == 2) { NUM_MSGS = (new Integer(args[1])).intValue(); } else { NUM_MSGS = 1; } /* * Create a JNDI API InitialContext object if none exists yet. */ try { jndiContext = new InitialContext(); } catch (NamingException e) { System.out.println("Could not create JNDI API " + "context: " + e.toString()); e.printStackTrace(); System.exit(1); } /* * Look up connection factory and topic. If either does not exist, exit. */ try { topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup("TopicConnectionFactory"); topic = (Topic) jndiContext.lookup(topicName); //topicName needs to be defined in the jndi.properties file! } catch (NamingException e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create publisher and text message. Send * messages, varying text slightly. Finally, close connection. */ try { topicConnection = topicConnectionFactory.createTopicConnection(); //an active connection to a JMS Pub/Sub provider topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); //provides methods for creating TopicPublisher, TopicSubscriber //transacted - indicates whether the session is transacted //acknowledgeMode - indicates whether the consumer or the client will acknowledge any messages it receives; // ignored if the session is transacted. Legal values are Session.AUTO_ACKNOWLEDGE, // Session.CLIENT_ACKNOWLEDGE, and Session.DUPS_OK_ACKNOWLEDGE topicPublisher = topicSession.createPublisher(topic); message = topicSession.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Publishing message: " + message.getText()); topicPublisher.publish(message); } } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); e.printStackTrace(); } finally { if (topicConnection != null) { try { topicConnection.close(); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); e.printStackTrace(); } } } } }
Java
package listeners; import java.util.TimerTask; import javax.jms.Message; import javax.jms.MessageListener; /** * This class is responsible for: * <ol> * <li>adding the user to a group: * <ol> * <li>If we are in the margin of 30 seconds we try to add if not exists * to personsInGroup and userInGroup * </ol> * </li> * </ol> * * @author Ron Galay * message types: * "Alive-"<username> - I'm alive message * "Joined-"<username> - join request, send back "Alive-"<username> * "Leave-"<username> - Leave request, delete user from group. */ public class Control implements MessageListener{ private String group; public Control(String group) { this.group=group; } @Override public void onMessage(Message arg0) { // TODO Auto-generated method stub } }
Java
package listeners; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; //WS is the translation web service import WS.GetResponse; import WS.Otms; import WS.OtmsSoap; import WS.Query; // TODO get the message from onMessage and not from the constructor public class Translate implements MessageListener{ private OtmsSoap translator; private String myLang; //the received message should be in the form of <username><Seperator><userlang><seperator><message> //<seperator>=</sep/> public static final String SEPERATOR="</sep/>"; public Translate(String myLang) { this.myLang = myLang; Otms impl= new Otms(); this.translator=impl.getOtmsSoap(); } @Override public void onMessage(Message message) { String msg = null; try { if (message instanceof TextMessage) { msg = ((TextMessage) message).getText(); } else { System.out.println("Message of wrong type: " + message.getClass().getName()); return ; } } catch (JMSException e) { System.out.println("JMSException in onMessage(): " + e.toString()); } catch (Throwable t) { System.out.println("Exception in onMessage():" + t.getMessage()); } parse(msg); } private String useWS(String fromLang,String inputStr) { Query q = new Query(); q.setSourceLang(fromLang); q.setTargetLang(this.myLang); q.setMt(1); q.setSource(inputStr); GetResponse response = translator.otmsGet("mmDemo123", q); if (response.isSuccess()) { // get the first match String translation = response.getMatches().getMatch().get(0).getTranslation(); return translation; } else { return "Translation not found"; } } private void parse(String msg) { // TODO change to private later //get user name int endOfUserName=msg.indexOf(SEPERATOR); if(endOfUserName==-2) { badMessage(); return; } String userName=msg.substring(0, endOfUserName); msg=msg.substring(endOfUserName+SEPERATOR.length(), msg.length()); //get the message language int endOfLang=msg.indexOf(SEPERATOR); if (endOfLang==-2) { badMessage(); return; } String lang=msg.substring(0, endOfLang); //Translate message if necessary msg=msg.substring(endOfLang+SEPERATOR.length(), msg.length()); String outMessage=null; if(lang.equals(this.myLang)) //Message is in own language - no need to translate outMessage=this.myLang; else outMessage=useWS(lang, msg); System.out.println("["+userName + ":] "+outMessage+"("+lang+": "+msg+")"); } private void badMessage() { //maybe add error message to the screen } }
Java
package Logging; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Date; import java.util.Map; /** * Monitor class which allows logging server information into * a file. This class is a singleton, the instance can be received by * calling the static get method. */ public class Monitor { private FileWriter fw; private PrintWriter pw; private int ln = 0; private final String LogFilePath = "c://temp/log.txt"; private final boolean CAN_WRITE = true; public Monitor() { try { fw = new FileWriter(LogFilePath, true); pw = new PrintWriter(fw, true); if(CAN_WRITE) pw.println("====== Started at " + new Date() + " ======"); } catch (IOException e) { } } private static Monitor inst; public synchronized static Monitor get() { if (inst == null) { inst = new Monitor(); } return inst; } /** * Writes simple data to log. * * @param o * the object which initiated the logging * @param arr * the list of data to log */ public static void write(Object o, Object... arr) { get().writeImpl(o, arr); } /** * Writes exception data to log * * @param e * the exception to be logged */ public static void writeException(Exception e) { get().writeExp(e); } /** * Writes the exception stack trace to log * * @param e * the exception to be logged */ private void writeExp(Exception e) { if (pw == null || !CAN_WRITE) { return; } e.printStackTrace(pw); pw.flush(); } /** * Writes the data to the log * * @param o * the object which initialized the logging * @param arr * the data to log */ private void writeImpl(Object o, Object... arr) { if (pw == null || !CAN_WRITE) { return; } StringBuilder sb = new StringBuilder(100); ++ln; sb.append("(" + ln + ") "); if(o != null) { sb.append(o.getClass().getSimpleName()); } for (Object x : arr) { sb.append(" ").append(str(x)); } pw.println(sb.toString()); pw.flush(); } /** * Converts the received object to string depending on its type * * @param x * the object to convert * @return the string representation of that object */ private String str(Object x) { if (x instanceof Iterable<?>) { return strList((Iterable<?>) x); } if (x instanceof Object[]) { return Arrays.toString((Object[]) x); } if (x instanceof Map<?, ?>) { return strMap((Map<?, ?>) x); } return String.valueOf(x); } /** * Converts a map object to a printable string * * @param x * the map object * @return the string representation of the received object */ private String strMap(Map<?, ?> x) { StringBuilder sb = new StringBuilder("{"); int n = 0; for (Map.Entry<?, ?> e : x.entrySet()) { if (++n > 1) { sb.append(", "); } sb.append(str(e.getKey() + "=" + str(e.getValue()))); } sb.append("}"); return sb.toString(); } /** * Converts a iterable object to a printable string * * @param x * the iterable object * @return the string representation of the received object */ private String strList(Iterable<?> x) { StringBuilder sb = new StringBuilder("["); int n = 0; for (Object o : x) { if (++n > 1) { sb.append(", "); } sb.append(str(o)); } sb.append("]"); return sb.toString(); } }
Java
package chat; import java.util.Timer; public class chatUser { private String userName; // according to the exercise the username is unique private String lang; private Timer removeUser; chatUser(String name,String lang) { userName = name; this.lang = lang; } public String getName() { return userName; } public String getLang() { return lang; } @Override public int hashCode() { return userName.hashCode(); } @Override public boolean equals(Object obj) { return userName.equals(obj); } }
Java
package chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.jms.JMSException; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import listeners.Control; import listeners.Translate; import Logging.Monitor; public class LingvoChat { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * This class is responsible to send "I'm Alive" messages to each group we * participate in. * @author Ron Galay */ class aliveAction extends TimerTask { private String topicName; // the data is sent to topics named <group>Control public aliveAction(String topicName) { this.topicName = topicName; } @Override public void run() { //the I'm alive message is "Alive-" + the user name. publishMsq(topicName,"Alive-" + userName); } } /** * This class is responsible for: * <ol> * <li>removing a user from a group: * <ol> * <li>Traversing each group the user is in, and for each group we enter * a new entry to personsInGroup without the user.</li> * <li>Removing the user entry from userInGroup</li> * </ol> * </li> * </ol> * * @author Ron Galay */ class controlMessage extends TimerTask { private final String userName; public controlMessage(String userName) { this.userName = userName; } @Override public void run() { // TODO check if a dead-lock cannot be reached synchronized(userInGroups) { synchronized(usersInGroup) { // removing the user from all of his groups for(String group: userInGroups.get(userName)) { usersInGroup.get(group).remove(userName); } // removing the user entry from userInGroup userInGroups.remove(userName); } } } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // for the communication with rest of the groups Context jndiContext = null; TopicConnectionFactory topicConnectionFactory = null; TopicConnection topicConnection = null; TopicSession topicSession = null; MessageListener controlListener; // all access to the maps should be guarded by synchronized private Collection<TopicPublisher> publishToGroups = new LinkedList<TopicPublisher>(); private Map<String,Timer> aliveToGroup = new HashMap<String,Timer>(); private Map<String,Collection<chatUser>> usersInGroup = new HashMap<String,Collection<chatUser>>(); private Map<String,TopicSubscriber> //group,topic groupTopicSubscibers = new HashMap<String,TopicSubscriber>(); private Map<chatUser,Collection<String>> userInGroups = new HashMap<chatUser,Collection<String>>(); // user specific info private final String userName; private final String lang; private final static LinkedList<String> allowedLang = new LinkedList<String>( Arrays.asList(new String[]{"ENGLISH","SPANISH","FRENCH","GERMAN"}) ); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public LingvoChat(String username,String lang) { this.userName = username; this.lang = lang; } private void initMessaging() { try { jndiContext = new InitialContext(); topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup("TopicConnectionFactory"); topicConnection = topicConnectionFactory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); } catch (NamingException e) { // TODO Auto-generated catch block quit(); } catch (JMSException e) { // TODO Auto-generated catch block quit(); } } private void initListner(String control,MessageListener topicListener) { try { Topic topic = (Topic) jndiContext.lookup(control); TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(topicListener); //todo - save the topic subscriber to map - group to subscribers topicConnection.start(); synchronized (groupTopicSubscibers) { groupTopicSubscibers.put(control, topicSubscriber); } } catch (NamingException e) { // TODO Auto-generated catch block quit(); } catch (JMSException e) { // TODO Auto-generated catch block quit(); } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// private void publishMsq(String topicName,String message) { try { Topic topic = (Topic) jndiContext.lookup(topicName); TopicPublisher topicPublisher = topicSession.createPublisher(topic); TextMessage textMessage = topicSession.createTextMessage(); textMessage = topicSession.createTextMessage(message); topicPublisher.publish(textMessage); } catch (NamingException e) { // TODO Auto-generated catch block quit(); } catch (JMSException e) { // TODO Auto-generated catch block quit(); } } private void join(String group) { Monitor.write(null, "Handling a join request for group:"+group); if( !(userInGroups.containsKey(userName) && userInGroups.get(userName).contains(group)) ) { // sending the joined in message - "Joined-<username>" String topicName = group+"Control"; publishMsq(topicName, "Joined-" + userName); // receiving the "ack" messages from the participants of the group initListner(topicName, new Control(group)); // giving time for the "ack" messages to arrive - 30 seconds try { // TODO we might to busywait instead Thread.sleep(30000); } catch (InterruptedException ignore) {} // starting off the "I'm Alive" messaging" Timer controlTimer = new Timer(); controlTimer.scheduleAtFixedRate( new aliveAction(topicName), System.currentTimeMillis(), 10000); Monitor.write(this, "Started off the control messaging"); synchronized (aliveToGroup) { aliveToGroup.put(topicName, controlTimer); } // initializing the receiving of messages from the group initListner(group, new Translate(lang)); } // printing the participants of the group groupStatus(group); } private void leave(String group) { Monitor.write(null, "Handling a leave request for group:"+group); } private void publish(String group,String message) { Monitor.write(null, "Handling a publish request for group:"+group+ " with the message:"+message); } private void groupStatus(String groupName) { Monitor.write(null, "Handling a groupStatuses request"); synchronized (usersInGroup) { for(chatUser user : usersInGroup.get(groupName) ){ System.out.println("User:"+user.getName()+ " Speaks:"+user.getLang()); } } } private void myGroups() { Monitor.write(null, "Handlinng a myGroups request"); // TODO check if no dead lock can be reached synchronized (userInGroups) { for (String group : userInGroups.get(userName)) { groupStatus(group); } } } private void quit() { Monitor.write(null, "Handling a quit request"); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// private boolean exeCommand(String commandLine) { // parse and find what command should we execute int commandEnding = commandLine.indexOf(" "); commandEnding = (commandEnding == -1)? commandLine.length(): commandEnding; // in upper case to make our comparison easier String command = commandLine.substring(0, commandEnding). toUpperCase(); String parameter = (commandEnding == commandLine.length())? command: commandLine.substring(commandEnding+1); if(command.equals("JOIN")) { join(parameter); } else if(command.equals("LEAVE")) { leave(parameter); } else if(command.equals("PUBLISHMSG")) { int paramDelim = parameter.indexOf(" "); publish(parameter.substring(0,paramDelim), parameter.substring(paramDelim+1)); } else if(command.equals("GROUPSTATUS")) { groupStatus(parameter); } else if(command.equals("MYGROUPS")) { myGroups(); } else if (command.equals("QUIT")) { quit(); return false; } return true; } public static void main(String[] args) throws IOException { // check that the parameters entered in the correct format if( args.length != 2) { System.out.println("Please insert parameters in the correct format:\n" + "<username> {English | Spanish | French | German}"); System.exit(0); } String enteredUsername = args[0]; // checking that the language is one of {English,Spanish,French,German} if(!allowedLang.contains(args[1].toUpperCase())) { System.out.println("Please insert a language to be one of the following:\n" + "{English,Spanish,French,German}"); System.exit(0); } String enteredLang = args[1]; Monitor.write(null, "Recieved the following parameters:\n" + "username:"+enteredUsername+"\n"+ "langauage:"+enteredLang); LingvoChat userInstance = new LingvoChat(enteredUsername,enteredLang); userInstance.initMessaging(); // waiting for instructions from the user BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while(userInstance.exeCommand(br.readLine())); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// }
Java
import java.io.Serializable; //Stuff, that is common with server code class MessagesDescription { public final static int PLAYERS_NICKNAME = 1; public final static int LOGIN_SUCCESSFUL = 2; public final static int LOGIN_FAIL = 3; public final static int PLAYER_LEFT = 4; public final static int OUT_OF_GAME = 5; public final static int ADD_PLAYER_FAIL = 6; public final static int ADD_PLAYER_SUCCESS = 7; public final static int PLAYER_X_HAS_N_CARDS = 8; public final static int CARDS_OPEN = 9; public final static int NEW_GAME = 10; public final static int ASK_FOR_DECISION = 11; public final static int NEXT_PLAYER = 12; public final static int WINNER = 13; public final static int ENTERING_GAME = 14; public final static int PLAYERS_DECISION = 15; } class TWebMessage implements Serializable{ private static final long serialVersionUID = 4514049446113263469L; public static final int MAX_ARGS = 10; public int purpose; public int[] args; TWebMessage(){ args = new int[MAX_ARGS]; } } enum ECardSuit { NONE, HEART, DIAMOND, CLUB, SPADE } class TCard { public static final int JACK = 2; public static final int QUEEN = 3; public static final int KING = 4; public static final int ACE = 11; public ECardSuit suit; public int rank; public TCard(int rnk, ECardSuit sui){ rank = rnk; suit = sui; } public TCard(int digital){ rank = digital / 10; switch (rank % 10){ case 0: suit = ECardSuit.HEART; break; case 1: suit = ECardSuit.DIAMOND; break; case 2: suit = ECardSuit.CLUB; break; case 3: suit = ECardSuit.SPADE; break; } } public int Digitize(){ int res = rank * 10; switch (suit){ case HEART: break; case DIAMOND: res += 1; break; case CLUB: res += 2; break; case SPADE: res += 3; break; } return res; } }
Java
public class Main { public static void main(String[] args) { new TInterface(); } }
Java
import java.net.InetAddress; import java.net.UnknownHostException; import java.awt.event.*; import javax.swing.*; class TPlayer{ public JLabel nickname; public JLabel[] cards; TPlayer(TInterface p, int pos){ nickname = new JLabel(); p.add(nickname); nickname.setLocation(15, 40 + 110 * pos); nickname.setSize(100, 30); cards = new JLabel[6]; for (int i = 0; i < 6; ++i){ cards[i] = new JLabel(""); p.add(cards[i]); cards[i].setLocation(15 + 100 * i, 60 + 110 * pos); cards[i].setSize(100,100); } } } public class TInterface extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; TClient lowLevel; TPlayer[] playerLabels; JButton[] senders; JTextField[] textInput; JLabel lastLog; String myNickname; int mySeat; TInterface(){ super("21"); setSize(1000,1000); setLayout(null); playerLabels = new TPlayer[6]; for (int i = 0; i < 6; ++i) playerLabels[i] = new TPlayer(this, i); textInput = new JTextField[2]; for (int i = 0; i < 2; ++i){ textInput[i] = new JTextField(); textInput[i].setSize(100, 30); textInput[i].setLocation(15 + 150 * i, 15); add(textInput[i]); } textInput[0].setText("Address"); textInput[1].setText("Nickname"); senders = new JButton[4]; for (int i = 0; i < 4; ++i){ senders[i] = new JButton(); add(senders[i]); } senders[0].setText("Connect"); senders[0].addActionListener(this); senders[0].setActionCommand("Connect"); senders[0].setBounds(310,15,120,30); senders[1].setText("Enter"); senders[1].addActionListener(this); senders[1].setActionCommand("Enter"); senders[1].setBounds(650, 200,120,30); senders[2].setText("More"); senders[2].addActionListener(this); senders[2].setActionCommand("More"); senders[2].setBounds(650,250,120,30); senders[3].setText("Enough"); senders[3].addActionListener(this); senders[3].setActionCommand("Enough"); senders[3].setBounds(650,300,120,30); lastLog = new JLabel("Welcome to 21"); lastLog.setBounds(650, 100, 1000, 30); add(lastLog); lastLog.setVisible(true); add(lastLog); setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { String s = arg0.getActionCommand(); if (s.equals("Connect")){ myNickname = textInput[1].getText(); EstablishConnection(textInput[0].getText(), textInput[1].getText()); } if (s.equals("Enough")) lowLevel.SendDecision(0); if (s.equals("More")) lowLevel.SendDecision(1); if (s.equals("Enter")) lowLevel.SendEnterGame(); } void InterfaceModification(){ while (true){ TQuery current = lowLevel.Poll(); switch (current.primary.purpose){ case MessagesDescription.ADD_PLAYER_SUCCESS: System.out.print("You are added to game. Seat #"); System.out.println(current.primary.args[0]); mySeat = current.primary.args[0]; playerLabels[mySeat].nickname.setText(myNickname); senders[1].setVisible(false); break; case MessagesDescription.ADD_PLAYER_FAIL: System.out.println("No free seat. Try again later"); break; case MessagesDescription.ASK_FOR_DECISION: System.out.println("It's you turn"); lastLog.setText("It's your turn"); break; case MessagesDescription.CARDS_OPEN: System.out.print("Cards of player #"); System.out.print(current.primary.args[0]); for (int i = 1; i <= 6; ++i){ playerLabels[current.primary.args[0]].cards[i-1].setText(Integer.toString(current.primary.args[i] / 10)); System.out.print(' '); System.out.print(current.primary.args[i]); } System.out.print('\n'); break; case MessagesDescription.NEW_GAME: System.out.println("New game starts"); lastLog.setText("New game starts"); for (int i = 0; i < 6; ++i) for (int j = 0; j < 6; ++j) playerLabels[i].cards[j].setText(""); break; case MessagesDescription.NEXT_PLAYER: System.out.print("Next player #"); System.out.println(current.primary.args[0]); lastLog.setText("Next player is ".concat(playerLabels[current.primary.args[0]].nickname.getText())); break; case MessagesDescription.PLAYER_LEFT: System.out.print("Player left. #"); System.out.println(current.primary.args[0]); int leaver = current.primary.args[0]; playerLabels[leaver].nickname.setText(""); for (int i = 0; i < 6; ++i) playerLabels[leaver].cards[i].setText(""); break; case MessagesDescription.PLAYER_X_HAS_N_CARDS: System.out.print("Number of cards of player #"); System.out.print(current.primary.args[0]); System.out.print(' '); System.out.println(current.primary.args[1]); int number = current.primary.args[1]; for (int i = 0; i < number ; ++i){ playerLabels[current.primary.args[0]].cards[i].setText("N/A"); System.out.print(' '); System.out.print(current.primary.args[i]); } break; case MessagesDescription.PLAYERS_NICKNAME: System.out.print("New player. Greet #"); System.out.print(current.primary.args[0]); System.out.print(' '); System.out.println(current.secondary); playerLabels[current.primary.args[0]].nickname.setText(current.secondary); break; case MessagesDescription.WINNER: System.out.print("We have a winner! Gratz, #"); System.out.println(current.primary.args[0]); String winner = playerLabels[current.primary.args[0]].nickname.getText(); lastLog.setText("We have a winner! Gratz, ".concat(winner).concat("! Game will start over in seconds")); break; } } } class InterfaceThread extends Thread { TInterface child; InterfaceThread(String name, TInterface ch){ super(name); child = ch; } public void run(){ child.InterfaceModification(); } } void EstablishConnection(String address, String nickname){ lowLevel = new TClient(); try { lowLevel.Connect(InetAddress.getByName(address), 8840, nickname); } catch (UnknownHostException e) {e.printStackTrace();} new InterfaceThread("ITh", this).start(); textInput[0].setVisible(false); textInput[1].setVisible(false); senders[0].setVisible(false); } }
Java
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.*; class TQuery{ public TWebMessage primary; public String secondary; } class InputThread extends Thread{ TClient cl; InputThread(String name, TClient c){ super(name); cl = c; } public void run(){ cl.StartReceiveingMessages(); } } class OutputThread extends Thread { TClient cl; OutputThread(String name, TClient c){ super(); cl = c; } public void run(){ cl.StartSendingMessages(); } } public class TClient { private Socket sock; private AtomicBoolean isRunning; private BlockingQueue<TQuery> queries; private BlockingQueue<TWebMessage> outcoming; private ObjectInputStream in; private ObjectOutputStream out; public TQuery Poll(){ try { return queries.take(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public TClient(){ queries = new LinkedBlockingQueue<TQuery>(); outcoming = new LinkedBlockingQueue<TWebMessage>(); isRunning = new AtomicBoolean(true); } public void Connect(InetAddress addr, int port, String nickname){ try { sock = new Socket(addr, port); out = new ObjectOutputStream(sock.getOutputStream()); out.flush(); in = new ObjectInputStream(sock.getInputStream()); out.writeObject(nickname); } catch (IOException e) { e.printStackTrace(); } new InputThread("ITh",this).start(); new OutputThread("OTh", this).start(); } public void StartSendingMessages(){ while (isRunning.get()){ TWebMessage current; try { current = outcoming.take(); SendMessage(current); } catch (InterruptedException e) { e.printStackTrace(); } } } public void AddMessage(TWebMessage a){ outcoming.add(a); } public void StartReceiveingMessages(){ try { while (isRunning.get()){ TQuery input = new TQuery(); try { input.primary = (TWebMessage) in.readObject(); if (input.primary.purpose == MessagesDescription.PLAYERS_NICKNAME) input.secondary = (String) in.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (input.primary.purpose != -1) queries.add(input); } sock.close(); } catch (IOException e) { e.printStackTrace(); } } private void SendMessage(Serializable msg){ try { out.writeObject(msg); } catch (IOException e) { e.printStackTrace(); } } public void SendEnterGame(){ TWebMessage msg = new TWebMessage(); msg.purpose = MessagesDescription.ENTERING_GAME; AddMessage(msg); } public void SendDecision(int decision){ TWebMessage msg = new TWebMessage(); msg.purpose = MessagesDescription.PLAYERS_DECISION; msg.args[0] = decision; AddMessage(msg); } public void Disconnect(){ isRunning.set(false); } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.client; import com.dpdearing.sandbox.gpsemulator.common.LocationServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.maps.client.MapUIOptions; import com.google.gwt.maps.client.MapWidget; import com.google.gwt.maps.client.Maps; import com.google.gwt.maps.client.event.MapClickHandler; import com.google.gwt.maps.client.geom.LatLng; import com.google.gwt.maps.client.overlay.Marker; import com.google.gwt.maps.client.overlay.Overlay; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.TextBox; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GpsEmulator implements EntryPoint, MapClickHandler { /** * The default emulator port */ static private final int DEFAULT_PORT = 5554; static private final String SUCCESS_STYLE = "success"; static private final String ERROR_STYLE = "error"; /** * Create a remote service proxy to talk to the server-side Location service. */ private final LocationServiceAsync _service = LocationServiceAsync.Util.getInstance(); /** * The last marker placed on the map */ private Marker _lastMarker = null; /** * The textbox, button, and info label for configuring the port. */ private TextBox _text; private Button _button; private Label _info; /** * This is the entry point method. */ public void onModuleLoad() { /* * Asynchronously loads the Maps API. * * The first parameter should be a valid Maps API Key to deploy this * application on a public server, but a blank key will work for an * application served from localhost. */ Maps.loadMapsApi("", "2", false, new Runnable() { public void run() { // initialize the UI buildUi(); // initialize the default port new PortAsyncCallback(DEFAULT_PORT).execute(); } }); } /** * Initialize the UI */ private void buildUi() { // Create a textbox and set default port _text = new TextBox(); _text.setText(String.valueOf(DEFAULT_PORT)); // Create button to change default port _button = new Button("Change Emulator Port"); // Create the info/status label _info = new InlineLabel(); // register the button action _button.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { final int port = Integer.valueOf(_text.getText()); new PortAsyncCallback(port).execute(); } }); // Open a map centered on Cawker City, KS USA final LatLng cawkerCity = LatLng.newInstance(39.509, -98.434); final MapWidget map = new MapWidget(cawkerCity, 2); map.setSize("100%", "100%"); // Workaround for bug with click handler & setUItoDefaults() - see issue 260 final MapUIOptions opts = map.getDefaultUI(); opts.setDoubleClick(false); map.setUI(opts); // Register map click handler map.addMapClickHandler(this); // Create panel for textbox, button and info label final FlowPanel div = new FlowPanel(); div.add(_text); div.add(_button); div.add(_info); // Dock the map final DockLayoutPanel dock = new DockLayoutPanel(Unit.PX); dock.addNorth(map, 500); // Add the map dock to the div panel div.add(dock); RootLayoutPanel.get().add(div); } /** * Handle a map click event */ public void onClick(final MapClickEvent e) { final MapWidget sender = e.getSender(); final Overlay overlay = e.getOverlay(); final LatLng point = e.getLatLng(); if (overlay != null && overlay instanceof Marker) { // clear a marker that has been clicked on sender.removeOverlay(overlay); } else { // clear the last-placed marker ... if (_lastMarker != null && _lastMarker instanceof Marker) { sender.removeOverlay(_lastMarker); _lastMarker = null; } // ... and add the new marker final Marker mark = new Marker(point); _lastMarker = mark; sender.addOverlay(mark); // set the location new GeoFixAsyncCallback(point.getLatitude(), point.getLongitude()).execute(); } } /** * Asynchronous callback for setting the telnet port. */ private class PortAsyncCallback implements AsyncCallback<Void>, Command { private final int _port; /** * Constructor * * @param port the port */ public PortAsyncCallback(final int port) { _port = port; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { _info.addStyleDependentName(SUCCESS_STYLE); _info.setText("Connected to port " + _port); } /** * Oh no! */ public void onFailure(final Throwable caught) { _info.addStyleDependentName(ERROR_STYLE); _info.setText("Error making connection on port " + _port + ": " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear info message _info.setText(""); _info.removeStyleDependentName(ERROR_STYLE); _info.removeStyleDependentName(SUCCESS_STYLE); _service.setPort(_port, this); } } /** * Asynchronous callback for changing the emulator's location */ private class GeoFixAsyncCallback implements AsyncCallback<Void>, Command { private final double _latitude; private final double _longitude; /** * Constructor. * * @param latitude * latitude * @param longitude * longitude */ public GeoFixAsyncCallback(final double latitude, final double longitude) { _latitude = latitude; _longitude = longitude; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { _info.addStyleDependentName(SUCCESS_STYLE); _info.setText("geo fix " + _longitude + " " + _latitude); } /** * Oh no! */ public void onFailure(final Throwable caught) { _info.addStyleDependentName(ERROR_STYLE); _info.setText("Error setting location: " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear info message _info.setText(""); _info.removeStyleDependentName(ERROR_STYLE); _info.removeStyleDependentName(SUCCESS_STYLE); _service.setLocation(_latitude, _longitude, this); } } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.server; import java.io.IOException; import com.dpdearing.sandbox.gpsemulator.common.LocationService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import de.mud.telnet.TelnetWrapper; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class LocationServiceImpl extends RemoteServiceServlet implements LocationService { /** * The telnet wrapper. */ private TelnetWrapper _telnet; /** * Constructor. */ public LocationServiceImpl() { _telnet = new TelnetWrapper(); } /** * {@inheritDoc} */ public void setPort(final int port) throws IOException { // disconnect from any previous connection _telnet.disconnect(); // reconnect to the new port _telnet.connect("localhost", port); } /** * {@inheritDoc} */ public void setLocation(final double latitude, final double longitude) throws IOException { // telnet the geo fix location: longitude first! _telnet.send("geo fix " + longitude + " " + latitude); } }
Java
/** * Copyright (c) 2010 David Dearing */ package com.dpdearing.sandbox.gpsemulator.common; import java.io.IOException; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("location") public interface LocationService extends RemoteService { /** * Set the Telnet port * * @param port * the port number * @throws IOException */ void setPort(int port) throws IOException; /** * Set the geospatial location * * @param latitude * latitude * @param longitude * longitude * @throws IOException */ void setLocation(double latitude, double longitude) throws IOException; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import android.content.Context; import android.test.AndroidTestCase; import java.text.SimpleDateFormat; import java.util.Date; /** * Tests {@link DefaultTrackNameFactory} * * @author Matthew Simmons */ public class DefaultTrackNameFactoryTest extends AndroidTestCase { /** * A version of the factory which allows us to supply our own answer as to * whether a timestamp-based track name should be used. */ private static class MockDefaultTrackNameFactory extends DefaultTrackNameFactory { private final boolean useTimestamp; MockDefaultTrackNameFactory(Context context, boolean useTimestamp) { super(context); this.useTimestamp = useTimestamp; } @Override protected boolean useTimestampTrackName() { return useTimestamp; } } private static final long TIMESTAMP = 1288213406000L; public void testTimestampTrackName() { DefaultTrackNameFactory factory = new MockDefaultTrackNameFactory(getContext(), true); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); assertEquals(formatter.format(new Date(TIMESTAMP)), factory.newTrackName(1, TIMESTAMP)); } public void testIncrementingTrackName() { DefaultTrackNameFactory factory = new MockDefaultTrackNameFactory(getContext(), false); assertEquals("Track 1", factory.newTrackName(1, TIMESTAMP)); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.testing.mocking.AndroidMock.capture; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import static com.google.android.testing.mocking.AndroidMock.same; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.Context; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.test.AndroidTestCase; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import org.easymock.Capture; /** * Tests for {@link StatusAnnouncerTask}. * WARNING: I'm not responsible if your eyes start bleeding while reading this * code. You have been warned. It's still better than no test, though. * * @author Rodrigo Damazio */ public class StatusAnnouncerTaskTest extends AndroidTestCase { // Use something other than our hardcoded value private static final Locale DEFAULT_LOCALE = Locale.KOREAN; private static final String ANNOUNCEMENT = "I can haz cheeseburger?"; private Locale oldDefaultLocale; private StatusAnnouncerTask task; private StringUtils stringUtils; private StatusAnnouncerTask mockTask; private Capture<OnInitListener> initListenerCapture; private Capture<PhoneStateListener> phoneListenerCapture; private TextToSpeechDelegate ttsDelegate; private TextToSpeechInterface tts; /** * Mockable interface that we delegate TTS calls to. */ interface TextToSpeechInterface { int addEarcon(String earcon, String packagename, int resourceId); int addEarcon(String earcon, String filename); int addSpeech(String text, String packagename, int resourceId); int addSpeech(String text, String filename); boolean areDefaultsEnforced(); String getDefaultEngine(); Locale getLanguage(); int isLanguageAvailable(Locale loc); boolean isSpeaking(); int playEarcon(String earcon, int queueMode, HashMap<String, String> params); int playSilence(long durationInMs, int queueMode, HashMap<String, String> params); int setEngineByPackageName(String enginePackageName); int setLanguage(Locale loc); int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener); int setPitch(float pitch); int setSpeechRate(float speechRate); void shutdown(); int speak(String text, int queueMode, HashMap<String, String> params); int stop(); int synthesizeToFile(String text, HashMap<String, String> params, String filename); } /** * Subclass of {@link TextToSpeech} which delegates calls to the interface * above. * The logic here is stupid and the author is ashamed of having to write it * like this, but basically the issue is that TextToSpeech cannot be mocked * without running its constructor, its constructor runs async operations * which call other methods (and then if the methods are part of a mock we'd * have to set a behavior, but we can't 'cause the object hasn't been fully * built yet). * The logic is that calls made during the constructor (when tts is not yet * set) will go up to the original class, but after tts is set we'll forward * them all to the mock. */ private class TextToSpeechDelegate extends TextToSpeech implements TextToSpeechInterface { public TextToSpeechDelegate(Context context, OnInitListener listener) { super(context, listener); } @Override public int addEarcon(String earcon, String packagename, int resourceId) { if (tts == null) { return super.addEarcon(earcon, packagename, resourceId); } return tts.addEarcon(earcon, packagename, resourceId); } @Override public int addEarcon(String earcon, String filename) { if (tts == null) { return super.addEarcon(earcon, filename); } return tts.addEarcon(earcon, filename); } @Override public int addSpeech(String text, String packagename, int resourceId) { if (tts == null) { return super.addSpeech(text, packagename, resourceId); } return tts.addSpeech(text, packagename, resourceId); } @Override public int addSpeech(String text, String filename) { if (tts == null) { return super.addSpeech(text, filename); } return tts.addSpeech(text, filename); } @Override public Locale getLanguage() { if (tts == null) { return super.getLanguage(); } return tts.getLanguage(); } @Override public int isLanguageAvailable(Locale loc) { if (tts == null) { return super.isLanguageAvailable(loc); } return tts.isLanguageAvailable(loc); } @Override public boolean isSpeaking() { if (tts == null) { return super.isSpeaking(); } return tts.isSpeaking(); } @Override public int playEarcon(String earcon, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playEarcon(earcon, queueMode, params); } return tts.playEarcon(earcon, queueMode, params); } @Override public int playSilence(long durationInMs, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.playSilence(durationInMs, queueMode, params); } return tts.playSilence(durationInMs, queueMode, params); } @Override public int setLanguage(Locale loc) { if (tts == null) { return super.setLanguage(loc); } return tts.setLanguage(loc); } @Override public int setOnUtteranceCompletedListener( OnUtteranceCompletedListener listener) { if (tts == null) { return super.setOnUtteranceCompletedListener(listener); } return tts.setOnUtteranceCompletedListener(listener); } @Override public int setPitch(float pitch) { if (tts == null) { return super.setPitch(pitch); } return tts.setPitch(pitch); } @Override public int setSpeechRate(float speechRate) { if (tts == null) { return super.setSpeechRate(speechRate); } return tts.setSpeechRate(speechRate); } @Override public void shutdown() { if (tts == null) { super.shutdown(); return; } tts.shutdown(); } @Override public int speak( String text, int queueMode, HashMap<String, String> params) { if (tts == null) { return super.speak(text, queueMode, params); } return tts.speak(text, queueMode, params); } @Override public int stop() { if (tts == null) { return super.stop(); } return tts.stop(); } @Override public int synthesizeToFile(String text, HashMap<String, String> params, String filename) { if (tts == null) { return super.synthesizeToFile(text, params, filename); } return tts.synthesizeToFile(text, params, filename); } } @UsesMocks({ StatusAnnouncerTask.class, StringUtils.class, TrackRecordingService.class, }) @Override protected void setUp() throws Exception { super.setUp(); oldDefaultLocale = Locale.getDefault(); Locale.setDefault(DEFAULT_LOCALE); stringUtils = AndroidMock.createMock(StringUtils.class, getContext()); // Eww, the effort required just to mock TextToSpeech is insane final AtomicBoolean listenerCalled = new AtomicBoolean(); OnInitListener blockingListener = new OnInitListener() { @Override public void onInit(int status) { synchronized (this) { listenerCalled.set(true); notify(); } } }; ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener); // Wait for all async operations done in the constructor to finish. synchronized (blockingListener) { while (!listenerCalled.get()) { // Releases the synchronized lock until we're woken up. blockingListener.wait(); } } // Phew, done, now we can start forwarding calls tts = AndroidMock.createMock(TextToSpeechInterface.class); initListenerCapture = new Capture<OnInitListener>(); phoneListenerCapture = new Capture<PhoneStateListener>(); // Create a partial forwarding mock mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext(), stringUtils); task = new StatusAnnouncerTask(getContext(), stringUtils) { @Override protected TextToSpeech newTextToSpeech(Context ctx, OnInitListener onInitListener) { return mockTask.newTextToSpeech(ctx, onInitListener); } @Override protected String getAnnouncement(TripStatistics stats) { return mockTask.getAnnouncement(stats); } @Override protected void listenToPhoneState( PhoneStateListener listener, int events) { mockTask.listenToPhoneState(listener, events); } }; } @Override protected void tearDown() { Locale.setDefault(oldDefaultLocale); } public void testStart() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setLanguage(DEFAULT_LOCALE)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts, stringUtils); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts, stringUtils); } public void testStart_languageNotSupported() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); expect(tts.isLanguageAvailable(DEFAULT_LOCALE)) .andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED); expect(tts.setLanguage(Locale.ENGLISH)) .andReturn(TextToSpeech.LANG_AVAILABLE); expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE)) .andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts, stringUtils); ttsInitListener.onInit(TextToSpeech.SUCCESS); AndroidMock.verify(mockTask, tts, stringUtils); } public void testStart_notReady() { doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); assertNotNull(ttsInitListener); AndroidMock.replay(tts, stringUtils); ttsInitListener.onInit(TextToSpeech.ERROR); AndroidMock.verify(mockTask, tts, stringUtils); } public void testShutdown() { // First, start doStart(); AndroidMock.verify(mockTask); AndroidMock.reset(mockTask); // Then, shut down PhoneStateListener phoneListener = phoneListenerCapture.getValue(); mockTask.listenToPhoneState( same(phoneListener), eq(PhoneStateListener.LISTEN_NONE)); tts.shutdown(); AndroidMock.replay(mockTask, tts, stringUtils); task.shutdown(); AndroidMock.verify(mockTask, tts, stringUtils); } public void testRun() throws Exception { // Expect service data calls TripStatistics stats = new TripStatistics(); TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); expect(service.getTripStatistics()).andStubReturn(stats); // Expect announcement building call expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT); // Put task in "ready" state startTask(TextToSpeech.SUCCESS); // Expect actual announcement call expect(tts.speak( eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH), AndroidMock.<HashMap<String, String>>isNull())) .andReturn(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts, stringUtils, service); task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } public void testRun_notReady() throws Exception { TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); // Put task in "not ready" state startTask(TextToSpeech.ERROR); // Run the announcement AndroidMock.replay(tts, stringUtils, service); task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } public void testRun_duringCall() throws Exception { TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts, stringUtils, service); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null); task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } public void testRun_ringWhileSpeaking() throws Exception { TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(true); expect(tts.stop()).andReturn(TextToSpeech.SUCCESS); AndroidMock.replay(tts, stringUtils, service); // Update the state to ringing - this should stop the current announcement. PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); // Run the announcement - this should do nothing. task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } public void testRun_whileRinging() throws Exception { TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); startTask(TextToSpeech.SUCCESS); expect(tts.isSpeaking()).andStubReturn(false); // Run the announcement AndroidMock.replay(tts, stringUtils, service); PhoneStateListener phoneListener = phoneListenerCapture.getValue(); phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null); task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } public void testRun_noService() throws Exception { startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts, stringUtils); task.run(null); AndroidMock.verify(mockTask, tts, stringUtils); } public void testRun_noStats() throws Exception { // Expect service data calls TrackRecordingService service = AndroidMock.createMock(TrackRecordingService.class); expect(service.getTripStatistics()).andStubReturn(null); startTask(TextToSpeech.SUCCESS); // Run the announcement AndroidMock.replay(tts, stringUtils, service); task.run(service); AndroidMock.verify(mockTask, tts, stringUtils, service); } private void startTask(int state) { AndroidMock.resetToNice(tts, stringUtils); AndroidMock.replay(tts, stringUtils); doStart(); OnInitListener ttsInitListener = initListenerCapture.getValue(); ttsInitListener.onInit(state); AndroidMock.resetToDefault(tts, stringUtils); } private void doStart() { mockTask.listenToPhoneState(capture(phoneListenerCapture), eq(PhoneStateListener.LISTEN_CALL_STATE)); expect(mockTask.newTextToSpeech( same(getContext()), capture(initListenerCapture))) .andStubReturn(ttsDelegate); AndroidMock.replay(mockTask); task.start(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.util.ApiFeatures; import android.media.AudioManager; import android.speech.tts.TextToSpeech; import android.test.AndroidTestCase; /** * Tests for {@link StatusAnnouncerFactory}. * These tests require Donut+ to run. * * @author Rodrigo Damazio */ public class StatusAnnouncerFactoryTest extends AndroidTestCase { /** * Mock version of the {@link ApiFeatures} class. */ private class MockApiFeatures extends ApiFeatures { private boolean hasTts; public void setHasTextToSpeech(boolean hasTts) { this.hasTts = hasTts; } @Override public boolean hasTextToSpeech() { return hasTts; } } private MockApiFeatures apiFeatures; @Override protected void setUp() throws Exception { super.setUp(); apiFeatures = new MockApiFeatures(); } public void testCreate() { apiFeatures.setHasTextToSpeech(true); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); PeriodicTask task = factory.create(getContext()); assertTrue(task instanceof StatusAnnouncerTask); } public void testCreate_notAvailable() { apiFeatures.setHasTextToSpeech(false); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); PeriodicTask task = factory.create(getContext()); assertNull(task); } public void testGetVolumeStream() { apiFeatures.setHasTextToSpeech(true); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); assertEquals( TextToSpeech.Engine.DEFAULT_STREAM, factory.getVolumeStream()); } public void testGetVolumeStream_notAvailable() { apiFeatures.setHasTextToSpeech(false); StatusAnnouncerFactory factory = new StatusAnnouncerFactory(apiFeatures); assertEquals( AudioManager.USE_DEFAULT_STREAM_TYPE, factory.getVolumeStream()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.MyTracksConstants.RESUME_TRACK_EXTRA_NAME; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.os.IBinder; import android.test.RenamingDelegatingContext; import android.test.ServiceTestCase; import android.test.mock.MockContentResolver; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Tests for the MyTracks track recording service. * * @author Bartlomiej Niechwiej * * TODO: The original class, ServiceTestCase, has a few limitations, e.g. * it's not possible to properly shutdown the service, unless tearDown() * is called, which prevents from testing multiple scenarios in a single * test (see runFunctionTest for more details). */ public class TrackRecordingServiceTest extends ServiceTestCase<TrackRecordingService> { private Context context; private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; /* * In order to support starting and binding to the service in the same * unit test, we provide a workaround, as the original class doesn't allow * to bind after the service has been previously started. */ private boolean bound; private Intent serviceIntent; public TrackRecordingServiceTest() { super(TrackRecordingService.class); } /** * A context wrapper with the user provided {@link ContentResolver}. * * TODO: Move to test utils package. */ public static class MockContext extends ContextWrapper { private final ContentResolver contentResolver; public MockContext(ContentResolver contentResolver, Context base) { super(base); this.contentResolver = contentResolver; } @Override public ContentResolver getContentResolver() { return contentResolver; } } /** * A mock class that forces API level < 5 to make sure we can workaround a bug * in ServiceTestCase (throwing a NPE). * See http://code.google.com/p/android/issues/detail?id=12122 for more * details. */ private static class MockApiFeatures extends ApiFeatures { @Override protected int getApiLevel() { return 4; } } @Override protected IBinder bindService(Intent intent) { if (getService() != null) { if (bound) { throw new IllegalStateException( "Service: " + getService() + " is already bound"); } bound = true; serviceIntent = intent.cloneFilter(); return getService().onBind(intent); } else { return super.bindService(intent); } } @Override protected void shutdownService() { if (bound) { assertNotNull(getService()); getService().onUnbind(serviceIntent); bound = false; } super.shutdownService(); } @Override protected void setUp() throws Exception { super.setUp(); ApiFeatures.injectInstance(new MockApiFeatures()); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); sharedPreferences = context.getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); // Let's use default values. sharedPreferences.edit().clear().commit(); // Disable auto resume by default. updateAutoResumePrefs(0, -1); // No recording track. Editor editor = sharedPreferences.edit(); editor.putLong(context.getString(R.string.recording_track_key), -1); editor.commit(); } @SmallTest public void testStartable() { startService(createStartIntent()); assertNotNull(getService()); } @MediumTest public void testBindable() { IBinder service = bindService(createStartIntent()); assertNotNull(service); } @MediumTest public void testResumeAfterReboot_shouldResume() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123, System.currentTimeMillis(), true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We expect to resume the previous track. assertTrue(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(123, service.getRecordingTrackId()); } // TODO: shutdownService() has a bug and doesn't set mServiceCreated // to false, thus preventing from a second call to onCreate(). // Report the bug to Android team. Until then, the following tests // and checks must be commented out. // // TODO: If fixed, remove "disabled" prefix from the test name. @MediumTest public void disabledTestResumeAfterReboot_simulateReboot() throws Exception { updateAutoResumePrefs(0, 10); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Simulate recording a track. long id = service.startNewTrack(); assertTrue(service.isRecording()); assertEquals(id, service.getRecordingTrackId()); shutdownService(); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); assertTrue(getService().isRecording()); } @MediumTest public void testResumeAfterReboot_noRecordingTrack() throws Exception { // Insert a dummy track and mark it as recording track. createDummyTrack(123, System.currentTimeMillis(), false); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it was stopped. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_expiredTrack() throws Exception { // Insert a dummy track last updated 20 min ago. createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true); // Clear the number of attempts and set the timeout to 10 min. updateAutoResumePrefs(0, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because it has expired. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testResumeAfterReboot_tooManyAttempts() throws Exception { // Insert a dummy track. createDummyTrack(123, System.currentTimeMillis(), true); // Set the number of attempts to max. updateAutoResumePrefs( TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10); // Start the service in "resume" mode (simulates the on-reboot action). Intent startIntent = createStartIntent(); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); startService(startIntent); assertNotNull(getService()); // We don't expect to resume the previous track, because there were already // too many attempts. assertFalse(getService().isRecording()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_noTracks() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); // Test if we start in no-recording mode by default. assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_oldTracks() throws Exception { createDummyTrack(123, -1, false); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testRecording_orphanedRecordingTrack() throws Exception { // Just set recording track to a bogus value. setRecordingTrack(256); // Make sure that the service will not start recording and will clear // the bogus track. ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); } /** * Synchronous/waitable broadcast receiver to be used in testing. */ private class BlockingBroadcastReceiver extends BroadcastReceiver { private static final long MAX_WAIT_TIME_MS = 10000; private List<Intent> receivedIntents = new ArrayList<Intent>(); public List<Intent> getReceivedIntents() { return receivedIntents; } @Override public void onReceive(Context context, Intent intent) { Log.d("MyTracksTest", "Got broadcast: " + intent); synchronized (receivedIntents) { receivedIntents.add(intent); receivedIntents.notifyAll(); } } public boolean waitUntilReceived(int receiveCount) { long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS; synchronized (receivedIntents) { while (receivedIntents.size() < receiveCount) { try { // Wait releases synchronized lock until it returns receivedIntents.wait(500); } catch (InterruptedException e) { // Do nothing } if (System.currentTimeMillis() > deadline) { return false; } } } return true; } } @MediumTest public void testStartNewTrack_noRecording() throws Exception { // NOTICE: due to the way Android permissions work, if this fails, // uninstall the test apk then retry - the test must be installed *after* // My Tracks (go figure). // Reference: http://code.google.com/p/android/issues/detail?id=5521 BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver(); String startAction = context.getString(R.string.track_started_broadcast_action); context.registerReceiver(startReceiver, new IntentFilter(startAction)); List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); assertEquals(id, service.getRecordingTrackId()); // Verify that the start broadcast was received. assertTrue(startReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = startReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(startAction, broadcastIntent.getAction()); assertEquals(id, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1)); context.unregisterReceiver(startReceiver); } @MediumTest public void testStartNewTrack_alreadyRecording() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); try { service.startNewTrack(); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } assertEquals(123, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(123, service.getRecordingTrackId()); } @MediumTest public void testEndCurrentTrack_alreadyRecording() throws Exception { // See comment above if this fails randomly. BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver(); String stopAction = context.getString(R.string.track_stopped_broadcast_action); context.registerReceiver(stopReceiver, new IntentFilter(stopAction)); createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // End the current track. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(-1, service.getRecordingTrackId()); // Verify that the stop broadcast was received. assertTrue(stopReceiver.waitUntilReceived(1)); List<Intent> receivedIntents = stopReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent broadcastIntent = receivedIntents.get(0); assertEquals(stopAction, broadcastIntent.getAction()); assertEquals(123, broadcastIntent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), -1)); context.unregisterReceiver(stopReceiver); } @MediumTest public void testEndCurrentTrack_noRecording() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // End the current track. try { service.endCurrentTrack(); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } assertEquals(-1, sharedPreferences.getLong( context.getString(R.string.recording_track_key), 0)); assertEquals(-1, service.getRecordingTrackId()); } @MediumTest public void testIntegration_completeRecordingSession() throws Exception { List<Track> tracks = providerUtils.getAllTracks(); assertTrue(tracks.isEmpty()); fullRecordingSession(); } @MediumTest public void testDeleteAllTracks_noRecording() throws Exception { createDummyTrack(123, -1, false); assertEquals(1, providerUtils.getAllTracks().size()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Deleting all tracks should succeed. service.deleteAllTracks(); assertFalse(service.isRecording()); assertTrue(providerUtils.getAllTracks().isEmpty()); } @MediumTest public void testDeleteAllTracks_noTracks() throws Exception { assertTrue(providerUtils.getAllTracks().isEmpty()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Deleting all tracks should succeed. service.deleteAllTracks(); assertFalse(service.isRecording()); assertTrue(providerUtils.getAllTracks().isEmpty()); } @MediumTest public void testDeleteAllTracks_trackInProgress() throws Exception { createDummyTrack(123, -1, true); assertEquals(1, providerUtils.getAllTracks().size()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); // Since we have a track in progress, we expect to fail. try { service.deleteAllTracks(); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } assertTrue(service.isRecording()); assertEquals(1, providerUtils.getAllTracks().size()); } @MediumTest public void testHasRecorded_noTracks() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertFalse(service.hasRecorded()); } @MediumTest public void testHasRecorded_trackInProgress() throws Exception { createDummyTrack(123, -1, true); assertEquals(1, providerUtils.getAllTracks().size()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertTrue(service.hasRecorded()); } @MediumTest public void testHasRecorded_oldTracks() throws Exception { createDummyTrack(123, -1, false); assertEquals(1, providerUtils.getAllTracks().size()); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); assertTrue(service.hasRecorded()); } @MediumTest public void testInsertStatisticsMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertStatisticsMarker_validLocation() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.stats_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.statistics), wpt.getName()); assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType()); assertEquals(123, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNotNull(wpt.getStatistics()); // TODO check the rest of the params. // TODO: Check waypoint 2. } @MediumTest public void testInsertWaypointMarker_noRecordingTrack() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); try { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); fail("Expecting IllegalStateException"); } catch (IllegalStateException e) { // Expected. } } @MediumTest public void testInsertWaypointMarker_validWaypoint() throws Exception { createDummyTrack(123, -1, true); ITrackRecordingService service = bindAndGetService(createStartIntent()); assertTrue(service.isRecording()); assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER)); Waypoint wpt = providerUtils.getWaypoint(1); assertEquals(getContext().getString(R.string.waypoint_icon_url), wpt.getIcon()); assertEquals(getContext().getString(R.string.waypoint), wpt.getName()); assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType()); assertEquals(123, wpt.getTrackId()); assertEquals(0.0, wpt.getLength()); assertNotNull(wpt.getLocation()); assertNull(wpt.getStatistics()); } @MediumTest public void testWithProperties_noAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultAnnouncementFreq() throws Exception { functionalTest(R.string.announcement_frequency_key, 1); } @MediumTest public void testWithProperties_noMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMaxRecordingDist() throws Exception { functionalTest(R.string.max_recording_distance_key, 5); } @MediumTest public void testWithProperties_noMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingDist() throws Exception { functionalTest(R.string.min_recording_distance_key, 2); } @MediumTest public void testWithProperties_noSplitFreq() throws Exception { functionalTest(R.string.split_frequency_key, (Object) null); } @MediumTest public void testWithProperties_defaultSplitFreqByDist() throws Exception { functionalTest(R.string.split_frequency_key, 5); } @MediumTest public void testWithProperties_defaultSplitFreqByTime() throws Exception { functionalTest(R.string.split_frequency_key, -2); } @MediumTest public void testWithProperties_noMetricUnits() throws Exception { functionalTest(R.string.metric_units_key, (Object) null); } @MediumTest public void testWithProperties_metricUnitsEnabled() throws Exception { functionalTest(R.string.metric_units_key, true); } @MediumTest public void testWithProperties_metricUnitsDisabled() throws Exception { functionalTest(R.string.metric_units_key, false); } @MediumTest public void testWithProperties_noMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRecordingInterval() throws Exception { functionalTest(R.string.min_recording_interval_key, 3); } @MediumTest public void testWithProperties_noMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, (Object) null); } @MediumTest public void testWithProperties_defaultMinRequiredAccuracy() throws Exception { functionalTest(R.string.min_required_accuracy_key, 500); } @MediumTest public void testWithProperties_noSensorType() throws Exception { functionalTest(R.string.sensor_type_key, (Object) null); } @MediumTest public void testWithProperties_zephyrSensorType() throws Exception { functionalTest(R.string.sensor_type_key, context.getString(R.string.zephyr_sensor_type)); } private ITrackRecordingService bindAndGetService(Intent intent) { ITrackRecordingService service = ITrackRecordingService.Stub.asInterface( bindService(intent)); assertNotNull(service); return service; } private Track createDummyTrack(long id, long stopTime, boolean isRecording) { Track dummyTrack = new Track(); dummyTrack.setId(id); dummyTrack.setName("Dummy Track"); TripStatistics tripStatistics = new TripStatistics(); tripStatistics.setStopTime(stopTime); dummyTrack.setStatistics(tripStatistics); addTrack(dummyTrack, isRecording); return dummyTrack; } private void updateAutoResumePrefs(int attempts, int timeoutMins) { Editor editor = sharedPreferences.edit(); editor.putInt(context.getString( R.string.auto_resume_track_current_retry_key), attempts); editor.putInt(context.getString( R.string.auto_resume_track_timeout_key), timeoutMins); editor.commit(); } private Intent createStartIntent() { Intent startIntent = new Intent(); startIntent.setClass(context, TrackRecordingService.class); return startIntent; } private void addTrack(Track track, boolean isRecording) { assertTrue(track.getId() >= 0); providerUtils.insertTrack(track); assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); setRecordingTrack(isRecording ? track.getId() : -1); } private void setRecordingTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(context.getString(R.string.recording_track_key), id); editor.commit(); } // TODO: We support multiple values for readability, however this test's // base class doesn't properly shutdown the service, so it's not possible // to pass more than 1 value at a time. private void functionalTest(int resourceId, Object ...values) throws Exception { final String key = context.getString(resourceId); for (Object value : values) { // Remove all properties and set the property for the given key. Editor editor = sharedPreferences.edit(); editor.clear(); if (value instanceof String) { editor.putString(key, (String) value); } else if (value instanceof Long) { editor.putLong(key, (Long) value); } else if (value instanceof Integer) { editor.putInt(key, (Integer) value); } else if (value instanceof Boolean) { editor.putBoolean(key, (Boolean) value); } else if (value == null) { // Do nothing, as clear above has already removed this property. } editor.commit(); fullRecordingSession(); } } private void fullRecordingSession() throws Exception { ITrackRecordingService service = bindAndGetService(createStartIntent()); assertFalse(service.isRecording()); // Start a track. long id = service.startNewTrack(); assertTrue(id >= 0); assertTrue(service.isRecording()); Track track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); assertEquals(id, sharedPreferences.getLong( context.getString(R.string.recording_track_key), -1)); assertEquals(id, service.getRecordingTrackId()); // Insert a few points, markers and statistics. long startTime = System.currentTimeMillis(); for (int i = 0; i < 30; i++) { Location loc = new Location("gps"); loc.setLongitude(35.0f + i / 10.0f); loc.setLatitude(45.0f - i / 5.0f); loc.setAccuracy(5); loc.setSpeed(10); loc.setTime(startTime + i * 10000); loc.setBearing(3.0f); service.recordLocation(loc); if (i % 10 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } else if (i % 7 == 0) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER); } } // Stop the track. Validate if it has correct data. service.endCurrentTrack(); assertFalse(service.isRecording()); assertEquals(-1, service.getRecordingTrackId()); track = providerUtils.getTrack(id); assertNotNull(track); assertEquals(id, track.getId()); TripStatistics tripStatistics = track.getStatistics(); assertNotNull(tripStatistics); assertTrue(tripStatistics.getStartTime() > 0); assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime()); } }
Java
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.maps.mytracks.R; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class SensorManagerFactoryTest extends AndroidTestCase { private SharedPreferences sharedPreferences; @Override protected void setUp() throws Exception { super.setUp(); sharedPreferences = getContext().getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); // Let's use default values. sharedPreferences.edit().clear().commit(); } @SmallTest public void testDefaultSettings() throws Exception { assertNull(SensorManagerFactory.getSensorManager(getContext())); } @SmallTest public void testCreateZephyr() throws Exception { assertClassForName(ZephyrSensorManager.class, R.string.zephyr_sensor_type); } @SmallTest public void testCreateAnt() throws Exception { assertClassForName(AntDirectSensorManager.class, R.string.ant_sensor_type); } @SmallTest public void testCreateAntSRM() throws Exception { assertClassForName(AntSRMSensorManager.class, R.string.srm_ant_bridge_sensor_type); } private void assertClassForName(Class<?> c, int i) { sharedPreferences.edit() .putString(getContext().getString(R.string.sensor_type_key), getContext().getString(i)) .commit(); SensorManager sm = SensorManagerFactory.getSensorManager(getContext()); assertNotNull(sm); assertTrue(c.isInstance(sm)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntStartupMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0x12, }; AntStartupMessage message = new AntStartupMessage(rawMessage); assertEquals(0x12, message.getMessage()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import android.test.AndroidTestCase; public class AntChannelResponseMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, AntMesg.MESG_EVENT_ID, AntDefine.EVENT_RX_SEARCH_TIMEOUT }; AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId()); assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntChannelIdMessageTest extends AndroidTestCase { public void testParse() { byte[] rawMessage = { 0, // channel number 0x34, 0x12, // device number (byte) 0xaa, // device type id (byte) 0xbb, // transmission type }; AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); assertEquals(0, message.getChannelNumber()); assertEquals(0x1234, message.getDeviceNumber()); assertEquals((byte) 0xaa, message.getDeviceTypeId()); assertEquals((byte) 0xbb, message.getTransmissionType()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import android.test.AndroidTestCase; public class AntMessageTest extends AndroidTestCase { private static class TestAntMessage extends AntMessage { public static short decodeShort(byte low, byte high) { return AntMessage.decodeShort(low, high); } } public void testDecode() { assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12)); } }
Java
package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; import junit.framework.TestCase; public class ZephyrMessageParserTest extends TestCase { ZephyrMessageParser parser = new ZephyrMessageParser(); public void testIsValid() { byte[] buf = new byte[60]; assertFalse(parser.isValid(buf)); buf[0] = 0x02; assertFalse(parser.isValid(buf)); buf[59] = 0x03; assertTrue(parser.isValid(buf)); } public void testParseBuffer() { byte[] buf = new byte[60]; buf[12] = 50; Sensor.SensorDataSet sds = parser.parseBuffer(buf); assertTrue(sds.hasHeartRate()); assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING); assertEquals(50, sds.getHeartRate().getValue()); } public void testFindNextAlignment() { byte[] buf = new byte[60]; assertEquals(-1, parser.findNextAlignment(buf)); buf[10] = 0x03; buf[11] = 0x02; assertEquals(10, parser.findNextAlignment(buf)); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import android.test.AndroidTestCase; import android.test.MoreAsserts; public class AntSensorManagerTest extends AndroidTestCase { private class TestAntSensorManager extends AntSensorManager { public byte messageId; public byte[] messageData; public TestAntSensorManager() { super(null); } @Override protected void setupAntSensorChannels() {} @SuppressWarnings("deprecation") @Override public void handleMessage(byte[] rawMessage) { super.handleMessage(rawMessage); } @Override public boolean handleMessage(byte messageId, byte[] messageData) { this.messageId = messageId; this.messageData = messageData; return true; } } private final TestAntSensorManager sensorManager = new TestAntSensorManager(); public void testSimple() { byte[] rawMessage = { 0x03, // length 0x12, // message id 0x11, 0x22, 0x33, // body }; byte[] expectedBody = { 0x11, 0x22, 0x33 }; sensorManager.handleMessage(rawMessage); assertEquals((byte) 0x12, sensorManager.messageId); MoreAsserts.assertEquals(expectedBody, sensorManager.messageData); } public void testTooShort() { byte[] rawMessage = { 0x53, // length 0x12 // message id }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } public void testLengthWrong() { byte[] rawMessage = { 0x53, // length 0x12, // message id 0x34, // body }; sensorManager.handleMessage(rawMessage); assertEquals(0, sensorManager.messageId); assertNull(sensorManager.messageData); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import com.dsi.ant.AntMesg; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.SharedPreferences; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; public class AntDirectSensorManagerTest extends AndroidTestCase { private SharedPreferences sharedPreferences; private AntDirectSensorManager manager; public void setUp() { sharedPreferences = getContext().getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); // Let's use default values. sharedPreferences.edit().clear().commit(); manager = new AntDirectSensorManager(getContext()); } @SuppressWarnings("deprecation") @SmallTest public void testBroadcastData() { manager.setDeviceNumberHRM((short) 42); byte[] buff = new byte[11]; buff[0] = 9; buff[1] = AntMesg.MESG_BROADCAST_DATA_ID; buff[2] = 0; // HRM CHANNEL buff[10] = (byte) 220; manager.handleMessage(buff); Sensor.SensorDataSet sds = manager.getSensorDataSet(); assertNotNull(sds); assertTrue(sds.hasHeartRate()); assertEquals(Sensor.SensorState.SENDING, sds.getHeartRate().getState()); assertEquals(220, sds.getHeartRate().getValue()); assertFalse(sds.hasCadence()); assertFalse(sds.hasPower()); } @SuppressWarnings("deprecation") @SmallTest public void testChannelId() { byte[] buff = new byte[11]; buff[0] = 9; buff[1] = AntMesg.MESG_CHANNEL_ID_ID; buff[3] = 42; manager.handleMessage(buff); assertEquals(42, manager.getDeviceNumberHRM()); assertEquals(42, sharedPreferences.getInt( getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1)); assertNull(manager.getSensorDataSet()); } @SuppressWarnings("deprecation") @SmallTest public void testResponseEvent() { assertEquals(Sensor.SensorState.NONE, manager.getSensorState()); byte[] buff = new byte[5]; buff[0] = 3; // length buff[1] = AntMesg.MESG_RESPONSE_EVENT_ID; buff[2] = 0; // channel buff[3] = AntMesg.MESG_UNASSIGN_CHANNEL_ID; buff[4] = 0; // code manager.handleMessage(buff); assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState()); assertNull(manager.getSensorDataSet()); } // TODO: Test timeout too. }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType; import android.os.Parcel; import android.test.AndroidTestCase; /** * Tests for the WaypointCreationRequest class. * {@link WaypointCreationRequest} * * @author Sandor Dornbush */ public class WaypointCreationRequestTest extends AndroidTestCase { public void testTypeParceling() { WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER; Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertNull(copy.getName()); assertNull(copy.getDescription()); assertNull(copy.getIconUrl()); } public void testAllAttributesParceling() { WaypointCreationRequest original = new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png"); Parcel p = Parcel.obtain(); original.writeToParcel(p, 0); p.setDataPosition(0); WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p); assertEquals(original.getType(), copy.getType()); assertEquals("name", copy.getName()); assertEquals("description", copy.getDescription()); assertEquals("img.png", copy.getIconUrl()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * A unit test for {@link MyTracksProviderUtilsImpl}. * * @author Bartlomiej Niechwiej */ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { private Context context; private MyTracksProviderUtils providerUtils; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); } public void testLocationIterator_noPoints() { testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_customFactory() { final Location location = new Location("test_location"); final AtomicInteger counter = new AtomicInteger(); testIterator(1, 15, 4, false, new LocationFactory() { @Override public Location createLocation() { counter.incrementAndGet(); return location; } }); // Make sure we were called exactly as many times as we had track points. assertEquals(15, counter.get()); } public void testLocationIterator_nullFactory() { try { testIterator(1, 15, 4, false, null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } public void testLocationIterator_noBatchAscending() { testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_noBatchDescending() { testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchAscending() { testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_batchDescending() { testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } public void testLocationIterator_largeTrack() { testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); } private List<Location> testIterator(long trackId, int numPoints, int batchSize, boolean descending, LocationFactory locationFactory) { long lastPointId = initializeTrack(trackId, numPoints); ((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize); List<Location> locations = new ArrayList<Location>(numPoints); LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory); try { while (it.hasNext()) { Location loc = it.next(); assertNotNull(loc); locations.add(loc); // Make sure the IDs are returned in the right order. assertEquals(descending ? lastPointId - locations.size() + 1 : lastPointId - numPoints + locations.size(), it.getLocationId()); } assertEquals(numPoints, locations.size()); } finally { it.close(); } return locations; } private long initializeTrack(long id, int numPoints) { Track track = new Track(); track.setId(id); track.setName("Test: " + id); track.setNumberOfPoints(numPoints); providerUtils.insertTrack(track); track = providerUtils.getTrack(id); assertNotNull(track); Location[] locations = new Location[numPoints]; for (int i = 0; i < numPoints; ++i) { Location loc = new Location("test"); loc.setLatitude(37.0 + (double) i / 10000.0); loc.setLongitude(57.0 - (double) i / 10000.0); loc.setAccuracy((float) i / 100.0f); loc.setAltitude(i * 2.5); locations[i] = loc; } providerUtils.bulkInsertTrackPoints(locations, numPoints, id); // Load all inserted locations. long lastPointId = -1; int counter = 0; LocationIterator it = providerUtils.getLocationIterator(id, -1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); try { while (it.hasNext()) { it.next(); lastPointId = it.getLocationId(); counter++; } } finally { it.close(); } assertTrue(numPoints == 0 || lastPointId > 0); assertEquals(numPoints, track.getNumberOfPoints()); assertEquals(numPoints, counter); return lastPointId; } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.stats; import com.google.android.apps.mytracks.MyTracksConstants; import android.location.Location; import junit.framework.TestCase; /** * Test the the function of the TripStatisticsBuilder class. * * @author Sandor Dornbush */ public class TripStatisticsBuilderTest extends TestCase { private TripStatisticsBuilder builder = null; @Override protected void setUp() throws Exception { super.setUp(); builder = new TripStatisticsBuilder(System.currentTimeMillis()); } public void testAddLocationSimple() throws Exception { builder = new TripStatisticsBuilder(1000); TripStatistics stats = builder.getStatistics(); assertEquals(0.0, builder.getSmoothedElevation()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation()); assertEquals(0.0, stats.getMaxSpeed()); assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade()); assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade()); assertEquals(0.0, stats.getTotalElevationGain()); assertEquals(0, stats.getMovingTime()); assertEquals(0.0, stats.getTotalDistance()); for (int i = 0; i < 100; i++) { Location l = new Location("test"); l.setAccuracy(1.0f); l.setLongitude(45.0); // Going up by 5 meters each time. l.setAltitude(i); // Moving by .1% of a degree latitude. l.setLatitude(i * .001); l.setSpeed(11.1f); // Each time slice is 10 seconds. long time = 1000 + 10000 * i; l.setTime(time); boolean moving = builder.addLocation(l, time); assertEquals((i != 0), moving); stats = builder.getStatistics(); assertEquals(10000 * i, stats.getTotalTime()); assertEquals(10000 * i, stats.getMovingTime()); assertEquals(i, builder.getSmoothedElevation(), MyTracksConstants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(0.0, stats.getMinElevation()); assertEquals(i, stats.getMaxElevation(), MyTracksConstants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(i, stats.getTotalElevationGain(), MyTracksConstants.ELEVATION_SMOOTHING_FACTOR); if (i > MyTracksConstants.SPEED_SMOOTHING_FACTOR) { assertEquals(11.1f, stats.getMaxSpeed(), 0.1); } if ((i > MyTracksConstants.GRADE_SMOOTHING_FACTOR) && (i > MyTracksConstants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(0.009, stats.getMinGrade(), 0.0001); assertEquals(0.009, stats.getMaxGrade(), 0.0001); } // 1 degree = 111 km // 1 timeslice = 0.001 degree = 111 m assertEquals(111.0 * i, stats.getTotalDistance(), 100); } } /** * Test that elevation works if the user is stable. */ public void testElevationSimple() throws Exception { for (double elevation = 0; elevation < 1000; elevation += 10) { builder = new TripStatisticsBuilder(System.currentTimeMillis()); for (int j = 0; j < 100; j++) { assertEquals(0.0, builder.updateElevation(elevation)); assertEquals(elevation, builder.getSmoothedElevation()); TripStatistics data = builder.getStatistics(); assertEquals(elevation, data.getMinElevation()); assertEquals(elevation, data.getMaxElevation()); assertEquals(0.0, data.getTotalElevationGain()); } } } public void testElevationGain() throws Exception { for (double i = 0; i < 1000; i++) { double expectedGain; if (i < (MyTracksConstants.ELEVATION_SMOOTHING_FACTOR - 1)) { expectedGain = 0; } else if (i < MyTracksConstants.ELEVATION_SMOOTHING_FACTOR) { expectedGain = 0.5; } else { expectedGain = 1.0; } assertEquals(expectedGain, builder.updateElevation(i)); assertEquals(i, builder.getSmoothedElevation(), 20); TripStatistics data = builder.getStatistics(); assertEquals(0.0, data.getMinElevation(), 0.0); assertEquals(i, data.getMaxElevation(), MyTracksConstants.ELEVATION_SMOOTHING_FACTOR); assertEquals(i, data.getTotalElevationGain(), MyTracksConstants.ELEVATION_SMOOTHING_FACTOR); } } public void testGradeSimple() throws Exception { for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, 100); if ((i > MyTracksConstants.GRADE_SMOOTHING_FACTOR) && (i > MyTracksConstants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(1.0, builder.getStatistics().getMinGrade()); } } for (double i = 0; i < 1000; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(100, -100); if ((i > MyTracksConstants.GRADE_SMOOTHING_FACTOR) && (i > MyTracksConstants.ELEVATION_SMOOTHING_FACTOR)) { assertEquals(1.0, builder.getStatistics().getMaxGrade()); assertEquals(-1.0, builder.getStatistics().getMinGrade()); } } } public void testGradeIgnoreShort() throws Exception { for (double i = 0; i < 100; i++) { // The value of the elevation does not matter. This is just to fill the // buffer. builder.updateElevation(i); builder.updateGrade(1, 100); assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade()); assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade()); } } public void testUpdateSpeedIncludeZero() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 0.0, i, 4.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); } } public void testUpdateSpeedIngoreErrorCode() { builder.updateSpeed(12345000, 128.0, 12344000, 0.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeedIngoreLargeAcceleration() { builder.updateSpeed(12345000, 100.0, 12344000, 1.0); assertEquals(0.0, builder.getStatistics().getMaxSpeed()); assertEquals(1000, builder.getStatistics().getMovingTime()); } public void testUpdateSpeed() { for (int i = 0; i < 1000; i++) { builder.updateSpeed(i + 1000, 4.0, i, 4.0); assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime()); if (i > MyTracksConstants.SPEED_SMOOTHING_FACTOR) { assertEquals(4.0, builder.getStatistics().getMaxSpeed()); } } } }
Java
/* * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Test for the DoubleBuffer class. * * @author Sandor Dornbush */ public class DoubleBufferTest extends TestCase { /** * Tests that the constructor leaves the buffer in a valid state. */ public void testConstructor() { DoubleBuffer buffer = new DoubleBuffer(10); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Simple test with 10 of the same values. */ public void testBasic() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 9; i++) { buffer.setNext(1.0); assertFalse(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } buffer.setNext(1); assertTrue(buffer.isFull()); assertEquals(1.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(1.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests with 5 entries of -10 and 5 entries of 10. */ public void testSplit() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 5; i++) { buffer.setNext(-10); assertFalse(buffer.isFull()); assertEquals(-10.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(-10.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } for (int i = 1; i < 5; i++) { buffer.setNext(10); assertFalse(buffer.isFull()); double expectedAverage = ((i * 10.0) - 50.0) / (i + 5); assertEquals(buffer.toString(), expectedAverage, buffer.getAverage(), 0.01); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(expectedAverage, averageAndVariance[0]); } buffer.setNext(10); assertTrue(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(100.0, averageAndVariance[1]); } /** * Tests that reset leaves the buffer in a valid state. */ public void testReset() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 100; i++) { buffer.setNext(i); } assertTrue(buffer.isFull()); buffer.reset(); assertFalse(buffer.isFull()); assertEquals(0.0, buffer.getAverage()); double[] averageAndVariance = buffer.getAverageAndVariance(); assertEquals(0.0, averageAndVariance[0]); assertEquals(0.0, averageAndVariance[1]); } /** * Tests that if a lot of items are inserted the smoothing and looping works. */ public void testLoop() { DoubleBuffer buffer = new DoubleBuffer(10); for (int i = 0; i < 1000; i++) { buffer.setNext(i); assertEquals(i >= 9, buffer.isFull()); if (i > 10) { assertEquals(i - 4.5, buffer.getAverage()); } } } }
Java
/** * Copyright 2009 Google Inc. All Rights Reserved. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; import java.util.Random; /** * This class test the ExtremityMonitor class. * * @author Sandor Dornbush */ public class ExtremityMonitorTest extends TestCase { public ExtremityMonitorTest(String name) { super(name); } public void testInitialize() { ExtremityMonitor monitor = new ExtremityMonitor(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); } public void testSimple() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); assertFalse(monitor.update(1)); assertFalse(monitor.update(0.5)); } /** * Throws a bunch of random numbers between [0,1] at the monitor. */ public void testRandom() { ExtremityMonitor monitor = new ExtremityMonitor(); Random random = new Random(42); for (int i = 0; i < 1000; i++) { monitor.update(random.nextDouble()); } assertTrue(monitor.getMin() < 0.1); assertTrue(monitor.getMax() < 1.0); assertTrue(monitor.getMin() >= 0.0); assertTrue(monitor.getMax() > 0.9); } public void testReset() { ExtremityMonitor monitor = new ExtremityMonitor(); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); monitor.reset(); assertEquals(Double.POSITIVE_INFINITY, monitor.getMin()); assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax()); assertTrue(monitor.update(0)); assertTrue(monitor.update(1)); assertEquals(0.0, monitor.getMin()); assertEquals(1.0, monitor.getMax()); } }
Java