Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
code
stringlengths
3
1.18M
language
stringclasses
1 value
public class HundredIntegers { public static void main (String[] args) { for (int i = 1; i<=100; i++) { System.out.println(i); } } }
Java
public class HundredIntegers { public static void main (String[] args) { for (int i = 1; i<=100; i++) { System.out.println(i); } } }
Java
package Entity; public interface IOperatoerDTO { int getoprId(); void setoprId(int Id); String getoprNavn(); void setoprNavn(String Navn); String getini(); void setini(String In); String getcpr(); void setcpr(String cp); String getpassword(); void setpassword(String passwd); }
Java
package Entity; public class OperatoerDTO implements IOperatoerDTO { int oprId; String oprNavn; String ini; String cpr; String password; public OperatoerDTO() //Default Constructor { this.oprId = 0; this.oprNavn = ""; this.ini = ""; this.cpr = ""; this.password = ""; } public OperatoerDTO (int oId, String oNavn, String i, String cr, String pwd) //created constructor { this.oprId = oId; this.oprNavn = oNavn; this.ini = i; this.cpr = cr; this.password = pwd; } public int getoprId(){ return oprId;} //return must be oprId not 0; public void setoprId(int Id){ oprId = Id; } public String getoprNavn(){ return oprNavn; } public void setoprNavn(String Navn){ oprNavn = Navn; } public String getini(){ return ini; } public void setini(String In){ ini = In; } public String getcpr(){ return cpr; } public void setcpr(String cp){ cpr = cp; } public String getpassword(){ return password; } public void setpassword(String passwd){ password = passwd; } }//corrected setters and getters
Java
package Controller; import Entity.OperatoerDTO; /* public class ChangePassword implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public String passwordGenerator(String passwd){ return passwd; } public String opChangePasswd(int Id) { return null; } */
Java
package Controller; import java.util.ArrayList; import Entity.OperatoerDTO; public class OperatoerDAO implements IOperatoerDAO{ OperatoerDTO opr = new OperatoerDTO(); private ArrayList<OperatoerDTO> oDTO = new ArrayList<OperatoerDTO>();; //added an arraylist of type OperatoerDTO public OperatoerDAO() { } public OperatoerDTO getOperatoer(int oprId) throws DALException{ return opr; } public ArrayList<OperatoerDTO> getOperatoerList() throws DALException { return oDTO; } public void createOperatoer(OperatoerDTO opr) throws DALException{ oDTO.add(opr); } public void updateOperatoer(OperatoerDTO opr) throws DALException{} }
Java
package Controller; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator{ private Pattern pattern; private Matcher matcher; private static String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; public PasswordValidator(){ pattern = Pattern.compile(PASSWORD_PATTERN); } /* * Validate password with regular expression * @param password password for validation * @return true valid password, false invalid password */ public boolean validate(String password){ matcher = pattern.matcher(password); return matcher.matches(); } }
Java
package Controller; import Entity.OperatoerDTO; /* public class LoginTjeck implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public int loginUser(String passwd, int id) { return 0; } }*/
Java
package Controller; import Entity.OperatoerDTO; /* public class Afvejning implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public double beregningNetto(double Tara, double Brutto) { return 0.0; } }*/
Java
package Controller; import Entity.OperatoerDTO; import java.util.ArrayList; public interface IOperatoerDAO { //int loginUser(String passwd, int id); OperatoerDTO getOperatoer(int oprId) throws DALException; ArrayList<OperatoerDTO> getOperatoerList() throws DALException; void createOperatoer(OperatoerDTO opr) throws DALException; void updateOperatoer(OperatoerDTO opr) throws DALException; // String passwordGenerator(String passwd); // String opchangepasswd(int Id); //double beregningNetto(double Tara, double Brutto); public class DALException extends Exception //added exception class { public DALException() { super( " findes ikke."); } } }
Java
package Boundary; import Entity.OperatoerDTO; import Controller.IOperatoerDAO.DALException; import Controller.OperatoerDAO; import Controller.PasswordValidator; import java.util.Scanner; public class Graenseflade { OperatoerDTO opr = new OperatoerDTO(); OperatoerDAO dao = new OperatoerDAO(); PasswordValidator pv = new PasswordValidator(); boolean go = true; public Graenseflade() //added user options { while(go){ System.out.println("1. Login"); System.out.println("2. Change Password"); System.out.println("3. Exit"); System.out.println("Enter your choice"); Scanner sc = new Scanner(System.in); //user input String choice = sc.next(); switch(choice) //checking admin login { case "1": Scanner user = new Scanner(System.in); System.out.println("Enter ID:"); String uname = user.next(); System.out.println("Enter password:"); String pwd = user.next(); if((uname.equals("BOB")) && (pwd.equals("DGMNZ123"))) { System.out.println("Login Successful"); System.out.println(); System.out.println("Select you choice"); System.out.println("1. Create Operator"); System.out.println("2. Udpate Operator"); System.out.println("3. Delete Operator"); } //Scanner s = new Scanner(System.in); //user input String ch = sc.next(); switch(ch) //Admin entering operator data { case "1": Scanner admin = new Scanner(System.in); System.out.println("Enter ID"); int ID = admin.nextInt(); opr.setoprId(ID); System.out.println("Enter Name"); String name = admin.next(); opr.setoprNavn(name); System.out.println("Enter CPR"); String cpr = admin.next(); opr.setcpr(cpr); System.out.println("Enter Password"); /* must contains one digit from 0-9 must contains one lowercase characters must contains one uppercase characters must contains one special symbols in the list "@#$%" match anything with previous condition checking length at least 6 characters and maximum of 20 */ String pass = admin.next(); while((pv.validate(pass)) == false) { System.out.println("Enter a new Password"); pass = admin.next(); } opr.setpassword(pass); try { //try catch for createOperatoer dao.createOperatoer(opr); } catch (DALException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case "3": System.exit(0);; } System.out.println("Id: " + opr.getoprId() + "\nName: " + opr.getoprNavn() + "\nCPR: " + opr.getcpr() + "\nPassword: " + opr.getpassword()); System.out.println(); } } //Login interface /* if(Id == 10 && passwd == "02304it") { int Id = sysadminInt(); } */ //Operatorinterface //Sysadmininterface /* private int sysadminInt() { return 0; } */ //vægtdetaljerinterface }
Java
import Boundary.Graenseflade; public class Main { public static void main(String[] args) { Graenseflade g = new Graenseflade(); } }
Java
/* * Copyright (C) 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.googlecode.tesseract.android; import android.graphics.Bitmap; import android.graphics.Rect; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.ReadFile; import java.io.File; /** * Java interface for the Tesseract OCR engine. Does not implement all available * JNI methods, but does implement enough to be useful. Comments are adapted * from original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class TessBaseAPI { /** * Used by the native implementation of the class. */ private int mNativeData; static { System.loadLibrary("lept"); System.loadLibrary("tess"); nativeClassInit(); } /** Fully automatic page segmentation. */ public static final int PSM_AUTO = 0; /** Assume a single column of text of variable sizes. */ public static final int PSM_SINGLE_COLUMN = 1; /** Assume a single uniform block of text. (Default) */ public static final int PSM_SINGLE_BLOCK = 2; /** Treat the image as a single text line. */ public static final int PSM_SINGLE_LINE = 3; /** Treat the image as a single word. */ public static final int PSM_SINGLE_WORD = 4; /** Treat the image as a single character. */ public static final int PSM_SINGLE_CHAR = 5; /** Default accuracy versus speed mode. */ public static final int AVS_FASTEST = 0; /** Slowest and most accurate mode. */ public static final int AVS_MOST_ACCURATE = 100; /** Whitelist of characters to recognize. */ public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist"; /** Blacklist of characters to not recognize. */ public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist"; /** Accuracy versus speed setting. */ public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed"; /** * Constructs an instance of TessBaseAPI. */ public TessBaseAPI() { nativeConstruct(); } /** * Called by the GC to clean up the native data that we set up when we * construct the object. */ @Override protected void finalize() throws Throwable { try { nativeFinalize(); } finally { super.finalize(); } } /** * Initializes the Tesseract engine with a specified language model. Returns * <code>true</code> on success. * <p> * Instances are now mostly thread-safe and totally independent, but some * global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable * on some of the Params in classify and textord. If you do, then the effect * will be to change it for all your instances. * <p> * The datapath must be the name of the parent directory of tessdata and * must end in / . Any name after the last / will be stripped. The language * is (usually) an ISO 639-3 string or <code>null</code> will default to eng. * It is entirely safe (and eventually will be efficient too) to call Init * multiple times on the same instance to change language, or just to reset * the classifier. * <p> * <b>WARNING:</b> On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * <p> * If you have a rare need to set a Variable that controls initialization * for a second call to Init you should explicitly call End() and then use * SetVariable before Init. This is only a very rare use case, since there * are very few uses that require any parameters to be set before Init. * * @param datapath the parent directory of tessdata ending in a forward * slash * @param language (optional) an ISO 639-3 string representing the language * @return <code>true</code> on success */ public boolean init(String datapath, String language) { if (datapath == null) throw new IllegalArgumentException("Data path must not be null!"); if (!datapath.endsWith(File.separator)) datapath += File.separator; File tessdata = new File(datapath + "tessdata"); if (!tessdata.exists() || !tessdata.isDirectory()) throw new IllegalArgumentException("Data path must contain subfolder tessdata!"); return nativeInit(datapath, language); } /** * Frees up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or SetRectangle before doing any * Recognize or Get* operation. */ public void clear() { nativeClear(); } /** * Closes down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * <p> * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ public void end() { nativeEnd(); } /** * Set the value of an internal "variable" (of either old or new types). * Supply the name of the variable and the value as a string, just as you * would in a config file. * <p> * Example: <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code> * <p> * setVariable() may be used before open(), but settings will revert to * defaults on close(). * * @param var name of the variable * @param value value to set * @return false if the name lookup failed */ public boolean setVariable(String var, String value) { return nativeSetVariable(var, value); } /** * Sets the page segmentation mode. This controls how much processing the * OCR engine will perform before recognizing text. * * @param mode the page segmentation mode to set */ public void setPageSegMode(int mode) { nativeSetPageSegMode(mode); } /** * Sets debug mode. This controls how much information is displayed in the * log during recognition. * * @param enabled <code>true</code> to enable debugging mode */ public void setDebug(boolean enabled) { nativeSetDebug(enabled); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param rect the bounding rectangle */ public void setRectangle(Rect rect) { setRectangle(rect.left, rect.top, rect.width(), rect.height()); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param left the left bound * @param top the right bound * @param width the width of the bounding box * @param height the height of the bounding box */ public void setRectangle(int left, int top, int width, int height) { nativeSetRectangle(left, top, width, height); } /** * Provides an image for Tesseract to recognize. * * @param file absolute path to the image file */ public void setImage(File file) { Pix image = ReadFile.readFile(file); if (image == null) { throw new RuntimeException("Failed to read image file"); } nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Does not copy the image * buffer. The source image must persist until after Recognize or * GetUTF8Chars is called. * * @param bmp bitmap representation of the image */ public void setImage(Bitmap bmp) { Pix image = ReadFile.readBitmap(bmp); if (image == null) { throw new RuntimeException("Failed to read bitmap"); } nativeSetImagePix(image.getNativePix()); } /** * Provides a Leptonica pix format image for Tesseract to recognize. Clones * the pix object. The source image may be destroyed immediately after * SetImage is called, but its contents may not be modified. * * @param image Leptonica pix representation of the image */ public void setImage(Pix image) { nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Copies the image buffer. * The source image may be destroyed immediately after SetImage is called. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. * * @param imagedata byte representation of the image * @param width image width * @param height image height * @param bpp bytes per pixel * @param bpl bytes per line */ public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) { nativeSetImageBytes(imagedata, width, height, bpp, bpl); } /** * The recognized text is returned as a String which is coded as UTF8. * * @return the recognized text */ public String getUTF8Text() { // Trim because the text will have extra line breaks at the end String text = nativeGetUTF8Text(); return text.trim(); } /** * Returns the mean confidence of text recognition. * * @return the mean confidence */ public int meanConfidence() { return nativeMeanConfidence(); } /** * Returns all word confidences (between 0 and 100) in an array. The number * of confidences should correspond to the number of space-delimited words * in GetUTF8Text(). * * @return an array of word confidences (between 0 and 100) for each * space-delimited word returned by GetUTF8Text() */ public int[] wordConfidences() { int[] conf = nativeWordConfidences(); // We shouldn't return null confidences if (conf == null) conf = new int[0]; return conf; } // ****************** // * Native methods * // ****************** /** * Initializes static native data. Must be called on object load. */ private static native void nativeClassInit(); /** * Initializes native data. Must be called on object construction. */ private native void nativeConstruct(); /** * Finalizes native data. Must be called on object destruction. */ private native void nativeFinalize(); private native boolean nativeInit(String datapath, String language); private native void nativeClear(); private native void nativeEnd(); private native void nativeSetImageBytes( byte[] imagedata, int width, int height, int bpp, int bpl); private native void nativeSetImagePix(int nativePix); private native void nativeSetRectangle(int left, int top, int width, int height); private native String nativeGetUTF8Text(); private native int nativeMeanConfidence(); private native int[] nativeWordConfidences(); private native boolean nativeSetVariable(String var, String value); private native void nativeSetDebug(boolean debug); private native void nativeSetPageSegMode(int mode); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; import android.graphics.Rect; /** * Java representation of a native Leptonica PIX object. * * @author alanv@google.com (Alan Viverette) */ public class Pix { static { System.loadLibrary("lept"); } /** Index of the image width within the dimensions array. */ public static final int INDEX_W = 0; /** Index of the image height within the dimensions array. */ public static final int INDEX_H = 1; /** Index of the image bit-depth within the dimensions array. */ public static final int INDEX_D = 2; /** Package-accessible pointer to native pix */ final int mNativePix; private boolean mRecycled; /** * Creates a new Pix wrapper for the specified native PIX object. Never call * this twice on the same native pointer, because finalize() will attempt to * free native memory twice. * * @param nativePix A pointer to the native PIX object. */ public Pix(int nativePix) { mNativePix = nativePix; mRecycled = false; } public Pix(int width, int height, int depth) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("Pix width and height must be > 0"); } else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16 && depth != 24 && depth != 32) { throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32"); } mNativePix = nativeCreatePix(width, height, depth); mRecycled = false; } /** * Returns a pointer to the native Pix object. This is used by native code * and is only valid within the same process in which the Pix was created. * * @return a native pointer to the Pix object */ public int getNativePix() { return mNativePix; } /** * Return the raw bytes of the native PIX object. You can reconstruct the * Pix from this data using createFromPix(). * * @return a copy of this PIX object's raw data */ public byte[] getData() { int size = nativeGetDataSize(mNativePix); byte[] buffer = new byte[size]; if (!nativeGetData(mNativePix, buffer)) { throw new RuntimeException("native getData failed"); } return buffer; } /** * Returns an array of this image's dimensions. See Pix.INDEX_* for indices. * * @return an array of this image's dimensions or <code>null</code> on * failure */ public int[] getDimensions() { int[] dimensions = new int[4]; if (getDimensions(dimensions)) { return dimensions; } return null; } /** * Fills an array with this image's dimensions. The array must be at least 3 * elements long. * * @param dimensions An integer array with at least three elements. * @return <code>true</code> on success */ public boolean getDimensions(int[] dimensions) { return nativeGetDimensions(mNativePix, dimensions); } /** * Returns a clone of this Pix. This does NOT create a separate copy, just a * new pointer that can be recycled without affecting other clones. * * @return a clone (shallow copy) of the Pix */ @Override public Pix clone() { int nativePix = nativeClone(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a deep copy of this Pix that can be modified without affecting * the original Pix. * * @return a copy of the Pix */ public Pix copy() { int nativePix = nativeCopy(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Inverts this Pix in-place. * * @return <code>true</code> on success */ public boolean invert() { return nativeInvert(mNativePix); } /** * Releases resources and frees any memory associated with this Pix. You may * not modify or access the pix after calling this method. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativePix); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Creates a new Pix from raw Pix data obtained from getData(). * * @param pixData Raw pix data obtained from getData(). * @param width The width of the original Pix. * @param height The height of the original Pix. * @param depth The bit-depth of the original Pix. * @return a new Pix or <code>null</code> on error */ public static Pix createFromPix(byte[] pixData, int width, int height, int depth) { int nativePix = nativeCreateFromData(pixData, width, height, depth); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a Rect with the width and height of this Pix. * * @return a Rect with the width and height of this Pix */ public Rect getRect() { int w = getWidth(); int h = getHeight(); return new Rect(0, 0, w, h); } /** * Returns the width of this Pix. * * @return the width of this Pix */ public int getWidth() { return nativeGetWidth(mNativePix); } /** * Returns the height of this Pix. * * @return the height of this Pix */ public int getHeight() { return nativeGetHeight(mNativePix); } /** * Returns the depth of this Pix. * * @return the depth of this Pix */ public int getDepth() { return nativeGetDepth(mNativePix); } /** * Returns the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to return. * @param y The y coordinate (0...height-1) of the pixel to return. * @return The argb {@link android.graphics.Color} at the specified * coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public int getPixel(int x, int y) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } return nativeGetPixel(mNativePix, x, y); } /** * Sets the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to set. * @param y The y coordinate (0...height-1) of the pixel to set. * @param color The argb {@link android.graphics.Color} to set at the * specified coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public void setPixel(int x, int y, int color) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } nativeSetPixel(mNativePix, x, y, color); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreatePix(int w, int h, int d); private static native int nativeCreateFromData(byte[] data, int w, int h, int d); private static native boolean nativeGetData(int nativePix, byte[] data); private static native int nativeGetDataSize(int nativePix); private static native int nativeClone(int nativePix); private static native int nativeCopy(int nativePix); private static native boolean nativeInvert(int nativePix); private static native void nativeDestroy(int nativePix); private static native boolean nativeGetDimensions(int nativePix, int[] dimensions); private static native int nativeGetWidth(int nativePix); private static native int nativeGetHeight(int nativePix); private static native int nativeGetDepth(int nativePix); private static native int nativeGetPixel(int nativePix, int x, int y); private static native void nativeSetPixel(int nativePix, int x, int y, int color); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; /** * Image input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class ReadFile { static { System.loadLibrary("lept"); } /** * Creates a 32bpp Pix object from encoded data. Supported formats are BMP * and JPEG. * * @param encodedData JPEG or BMP encoded byte data. * @return a 32bpp Pix object */ public static Pix readMem(byte[] encodedData) { if (encodedData == null) throw new IllegalArgumentException("Image data byte array must be non-null"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length, opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates an 8bpp Pix object from raw 8bpp grayscale pixels. * * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static Pix readBytes8(byte[] pixelData, int width, int height) { if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); int nativePix = nativeReadBytes8(pixelData, width, height); if (nativePix == 0) throw new RuntimeException("Failed to read pix from memory"); return new Pix(nativePix); } /** * Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels. * Width and height be identical to the input Pix. * * @param pixs The Pix whose bytes will be replaced. * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); if (pixs.getWidth() != width) throw new IllegalArgumentException("Source pix width does not match image width"); if (pixs.getHeight() != height) throw new IllegalArgumentException("Source pix width does not match image width"); return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height); } /** * Creates a Pixa object from encoded files in a directory. Supported * formats are BMP and JPEG. * * @param dir The directory containing the files. * @param prefix The prefix of the files to load into a Pixa. * @return a Pixa object containing one Pix for each file */ public static Pixa readFiles(File dir, String prefix) { if (dir == null) throw new IllegalArgumentException("Directory must be non-null"); if (!dir.exists()) throw new IllegalArgumentException("Directory does not exist"); if (!dir.canRead()) throw new IllegalArgumentException("Cannot read directory"); // TODO: Remove or fix this. throw new RuntimeException("readFiles() is not current supported"); } /** * Creates a Pix object from encoded file data. Supported formats are BMP * and JPEG. * * @param file The JPEG or BMP-encoded file to read in as a Pix. * @return a Pix object */ public static Pix readFile(File file) { if (file == null) throw new IllegalArgumentException("File must be non-null"); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); if (!file.canRead()) throw new IllegalArgumentException("Cannot read file"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates a Pix object from Bitmap data. Currently supports only * ARGB_8888-formatted bitmaps. * * @param bmp The Bitmap object to convert to a Pix. * @return a Pix object */ public static Pix readBitmap(Bitmap bmp) { if (bmp == null) throw new IllegalArgumentException("Bitmap must be non-null"); if (bmp.getConfig() != Bitmap.Config.ARGB_8888) throw new IllegalArgumentException("Bitmap config must be ARGB_8888"); int nativePix = nativeReadBitmap(bmp); if (nativePix == 0) throw new RuntimeException("Failed to read pix from bitmap"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeReadMem(byte[] data, int size); private static native int nativeReadBytes8(byte[] data, int w, int h); private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h); private static native int nativeReadFiles(String dirname, String prefix); private static native int nativeReadFile(String filename); private static native int nativeReadBitmap(Bitmap bitmap); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Wrapper for Leptonica's native BOX. * * @author alanv@google.com (Alan Viverette) */ public class Box { static { System.loadLibrary("lept"); } /** The index of the X coordinate within the geometry array. */ public static final int INDEX_X = 0; /** The index of the Y coordinate within the geometry array. */ public static final int INDEX_Y = 1; /** The index of the width within the geometry array. */ public static final int INDEX_W = 2; /** The index of the height within the geometry array. */ public static final int INDEX_H = 3; /** * A pointer to the native Box object. This is used internally by native * code. */ final int mNativeBox; private boolean mRecycled = false; /** * Creates a new Box wrapper for the specified native BOX. * * @param nativeBox A pointer to the native BOX. */ Box(int nativeBox) { mNativeBox = nativeBox; mRecycled = false; } /** * Creates a box with the specified geometry. All dimensions should be * non-negative and specified in pixels. * * @param x X-coordinate of the top-left corner of the box. * @param y Y-coordinate of the top-left corner of the box. * @param w Width of the box. * @param h Height of the box. */ public Box(int x, int y, int w, int h) { if (x < 0 || y < 0 || w < 0 || h < 0) { throw new IllegalArgumentException("All box dimensions must be non-negative"); } int nativeBox = nativeCreate(x, y, w, h); if (nativeBox == 0) { throw new OutOfMemoryError(); } mNativeBox = nativeBox; mRecycled = false; } /** * Returns the box's x-coordinate in pixels. * * @return The box's x-coordinate in pixels. */ public int getX() { return nativeGetX(mNativeBox); } /** * Returns the box's y-coordinate in pixels. * * @return The box's y-coordinate in pixels. */ public int getY() { return nativeGetY(mNativeBox); } /** * Returns the box's width in pixels. * * @return The box's width in pixels. */ public int getWidth() { return nativeGetWidth(mNativeBox); } /** * Returns the box's height in pixels. * * @return The box's height in pixels. */ public int getHeight() { return nativeGetHeight(mNativeBox); } /** * Returns an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @return an array of box oordinates */ public int[] getGeometry() { int[] geometry = new int[4]; if (getGeometry(geometry)) { return geometry; } return null; } /** * Fills an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @param geometry A 4+ element integer array to fill with coordinates. * @return <code>true</code> on success */ public boolean getGeometry(int[] geometry) { if (geometry.length < 4) { throw new IllegalArgumentException("Geometry array must be at least 4 elements long"); } return nativeGetGeometry(mNativeBox, geometry); } /** * Releases resources and frees any memory associated with this Box. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativeBox); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int x, int y, int w, int h); private static native int nativeGetX(int nativeBox); private static native int nativeGetY(int nativeBox); private static native int nativeGetWidth(int nativeBox); private static native int nativeGetHeight(int nativeBox); private static native void nativeDestroy(int nativeBox); private static native boolean nativeGetGeometry(int nativeBox, int[] geometry); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image bit-depth conversion methods. * * @author alanv@google.com (Alan Viverette) */ public class Convert { static { System.loadLibrary("lept"); } /** * Converts an image of any bit depth to 8-bit grayscale. * * @param pixs Source pix of any bit-depth. * @return a new Pix image or <code>null</code> on error */ public static Pix convertTo8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeConvertTo8(pixs.mNativePix); if (nativePix == 0) throw new RuntimeException("Failed to natively convert pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeConvertTo8(int nativePix); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; import android.graphics.Rect; import java.io.File; import java.util.ArrayList; import java.util.Iterator; /** * Java representation of a native PIXA object. This object contains multiple * PIX objects and their associated bounding BOX objects. * * @author alanv@google.com (Alan Viverette) */ public class Pixa implements Iterable<Pix> { static { System.loadLibrary("lept"); } /** A pointer to the native PIXA object. This is used internally by native code. */ final int mNativePixa; /** The specified width of this Pixa. */ final int mWidth; /** The specified height of this Pixa. */ final int mHeight; private boolean mRecycled; /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * * @param size The minimum capacity of this Pixa. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size) { return createPixa(size, 0, 0); } /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * <p> * If non-zero, the specified width and height will be used to specify the * bounds of output images. * * * @param size The minimum capacity of this Pixa. * @param width (Optional) The width of this Pixa, use 0 for default. * @param height (Optional) The height of this Pixa, use 0 for default. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size, int width, int height) { int nativePixa = nativeCreate(size); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, width, height); } /** * Creates a wrapper for the specified native Pixa pointer. * * @param nativePixa Native pointer to a PIXA object. * @param width The width of the PIXA. * @param height The height of the PIXA. */ public Pixa(int nativePixa, int width, int height) { mNativePixa = nativePixa; mWidth = width; mHeight = height; mRecycled = false; } /** * Returns a pointer to the native PIXA object. This is used by native code. * * @return a pointer to the native PIXA object */ public int getNativePixa() { return mNativePixa; } /** * Creates a shallow copy of this Pixa. Contained Pix are cloned, and the * resulting Pixa may be recycled separately from the original. * * @return a shallow copy of this Pixa */ public Pixa copy() { int nativePixa = nativeCopy(mNativePixa); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Sorts this Pixa using the specified field and order. See * Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or * Constants.L_SORT_DECREASING. * * @param field The field to sort by. See Constants.L_SORT_BY_*. * @param order The order in which to sort. Must be either * Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING. * @return a sorted copy of this Pixa */ public Pixa sort(int field, int order) { int nativePixa = nativeSort(mNativePixa, field, order); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Returns the number of elements in this Pixa. * * @return the number of elements in this Pixa */ public int size() { return nativeGetCount(mNativePixa); } /** * Recycles this Pixa and frees natively allocated memory. You may not * access or modify the Pixa after calling this method. * <p> * Any Pix obtained from this Pixa or copies of this Pixa will still be * accessible until they are explicitly recycled or finalized by the garbage * collector. */ public synchronized void recycle() { if (!mRecycled) { nativeDestroy(mNativePixa); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Merges the contents of another Pixa into this one. * * @param otherPixa * @return <code>true</code> on success */ public boolean join(Pixa otherPixa) { return nativeJoin(mNativePixa, otherPixa.mNativePixa); } /** * Adds a Pix to this Pixa. * * @param pix The Pix to add. * @param mode The mode in which to add this Pix, typically * Constants.L_CLONE. */ public void addPix(Pix pix, int mode) { nativeAddPix(mNativePixa, pix.mNativePix, mode); } /** * Adds a Box to this Pixa. * * @param box The Box to add. * @param mode The mode in which to add this Box, typically * Constants.L_CLONE. */ public void addBox(Box box, int mode) { nativeAddBox(mNativePixa, box.mNativeBox, mode); } /** * Adds a Pix and associated Box to this Pixa. * * @param pix The Pix to add. * @param box The Box to add. * @param mode The mode in which to add this Pix and Box, typically * Constants.L_CLONE. */ public void add(Pix pix, Box box, int mode) { nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode); } /** * Returns the Box at the specified index, or <code>null</code> on error. * * @param index The index of the Box to return. * @return the Box at the specified index, or <code>null</code> on error */ public Box getBox(int index) { int nativeBox = nativeGetBox(mNativePixa, index); if (nativeBox == 0) { return null; } return new Box(nativeBox); } /** * Returns the Pix at the specified index, or <code>null</code> on error. * * @param index The index of the Pix to return. * @return the Pix at the specified index, or <code>null</code> on error */ public Pix getPix(int index) { int nativePix = nativeGetPix(mNativePixa, index); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Returns the width of this Pixa, or 0 if one was not set when it was * created. * * @return the width of this Pixa, or 0 if one was not set when it was * created */ public int getWidth() { return mWidth; } /** * Returns the height of this Pixa, or 0 if one was not set when it was * created. * * @return the height of this Pixa, or 0 if one was not set when it was * created */ public int getHeight() { return mHeight; } /** * Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width * and height were not specified on creation. * * @return a bounding Rect for this Pixa */ public Rect getRect() { return new Rect(0, 0, mWidth, mHeight); } /** * Returns a bounding Rect for the Box at the specified index. * * @param index The index of the Box to get the bounding Rect of. * @return a bounding Rect for the Box at the specified index */ public Rect getBoxRect(int index) { int[] dimensions = getBoxGeometry(index); if (dimensions == null) { return null; } int x = dimensions[Box.INDEX_X]; int y = dimensions[Box.INDEX_Y]; int w = dimensions[Box.INDEX_W]; int h = dimensions[Box.INDEX_H]; Rect bound = new Rect(x, y, x + w, y + h); return bound; } /** * Returns a geometry array for the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @return a bounding Rect for the Box at the specified index */ public int[] getBoxGeometry(int index) { int[] dimensions = new int[4]; if (getBoxGeometry(index, dimensions)) { return dimensions; } return null; } /** * Fills an array with the geometry of the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @param dimensions The array to fill with Box geometry. Must be at least 4 * elements. * @return <code>true</code> on success */ public boolean getBoxGeometry(int index, int[] dimensions) { return nativeGetBoxGeometry(mNativePixa, index, dimensions); } /** * Returns an ArrayList of Box bounding Rects. * * @return an ArrayList of Box bounding Rects */ public ArrayList<Rect> getBoxRects() { final int pixaCount = nativeGetCount(mNativePixa); final int[] buffer = new int[4]; final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount); for (int i = 0; i < pixaCount; i++) { getBoxGeometry(i, buffer); final int x = buffer[Box.INDEX_X]; final int y = buffer[Box.INDEX_Y]; final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]); rects.add(bound); } return rects; } /** * Replaces the Pix and Box at the specified index with the specified Pix * and Box, both of which may be recycled after calling this method. * * @param index The index of the Pix to replace. * @param pix The Pix to replace the existing Pix. * @param box The Box to replace the existing Box. */ public void replacePix(int index, Pix pix, Box box) { nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox); } /** * Merges the Pix at the specified indices and removes the Pix at the second * index. * * @param indexA The index of the first Pix. * @param indexB The index of the second Pix, which will be removed after * merging. */ public void mergeAndReplacePix(int indexA, int indexB) { nativeMergeAndReplacePix(mNativePixa, indexA, indexB); } /** * Writes the components of this Pix to a bitmap-formatted file using a * random color map. * * @param file The file to write to. * @return <code>true</code> on success */ public boolean writeToFileRandomCmap(File file) { return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight); } @Override public Iterator<Pix> iterator() { return new PixIterator(); } private class PixIterator implements Iterator<Pix> { private int mIndex; private PixIterator() { mIndex = 0; } @Override public boolean hasNext() { final int size = size(); return (size > 0 && mIndex < size); } @Override public Pix next() { return getPix(mIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int size); private static native int nativeCopy(int nativePixa); private static native int nativeSort(int nativePixa, int field, int order); private static native boolean nativeJoin(int nativePixa, int otherPixa); private static native int nativeGetCount(int nativePixa); private static native void nativeDestroy(int nativePixa); private static native void nativeAddPix(int nativePixa, int nativePix, int mode); private static native void nativeAddBox(int nativePixa, int nativeBox, int mode); private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode); private static native boolean nativeWriteToFileRandomCmap( int nativePixa, String fileName, int width, int height); private static native void nativeReplacePix( int nativePixa, int index, int nativePix, int nativeBox); private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB); private static native int nativeGetBox(int nativePix, int index); private static native int nativeGetPix(int nativePix, int index); private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); String rootname = new File(path, prefix).getAbsolutePath(); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image binarization methods. * * @author alanv@google.com (Alan Viverette) */ public class Binarize { static { System.loadLibrary("lept"); } // Otsu thresholding constants /** Desired tile X dimension; actual size may vary */ public final static int OTSU_SIZE_X = 32; /** Desired tile Y dimension; actual size may vary */ public final static int OTSU_SIZE_Y = 32; /** Desired X smoothing value */ public final static int OTSU_SMOOTH_X = 2; /** Desired Y smoothing value */ public final static int OTSU_SMOOTH_Y = 2; /** Fraction of the max Otsu score, typically 0.1 */ public final static float OTSU_SCORE_FRACTION = 0.1f; /** * Performs locally-adaptive Otsu threshold binarization with default * parameters. * * @param pixs An 8 bpp PIX source image. * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold(Pix pixs) { return otsuAdaptiveThreshold( pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION); } /** * Performs locally-adaptive Otsu threshold binarization. * <p> * Notes: * <ol> * <li>The Otsu method finds a single global threshold for an image. This * function allows a locally adapted threshold to be found for each tile * into which the image is broken up. * <li>The array of threshold values, one for each tile, constitutes a * highly downscaled image. This array is optionally smoothed using a * convolution. The full width and height of the convolution kernel are (2 * * smoothX + 1) and (2 * smoothY + 1). * <li>The minimum tile dimension allowed is 16. If such small tiles are * used, it is recommended to use smoothing, because without smoothing, each * small tile determines the splitting threshold independently. A tile that * is entirely in the image bg will then hallucinate fg, resulting in a very * noisy binarization. The smoothing should be large enough that no tile is * only influenced by one type (fg or bg) of pixels, because it will force a * split of its pixels. * <li>To get a single global threshold for the entire image, use input * values of sizeX and sizeY that are larger than the image. For this * situation, the smoothing parameters are ignored. * <li>The threshold values partition the image pixels into two classes: one * whose values are less than the threshold and another whose values are * greater than or equal to the threshold. This is the same use of * 'threshold' as in pixThresholdToBinary(). * <li>The scorefract is the fraction of the maximum Otsu score, which is * used to determine the range over which the histogram minimum is searched. * See numaSplitDistribution() for details on the underlying method of * choosing a threshold. * <li>This uses enables a modified version of the Otsu criterion for * splitting the distribution of pixels in each tile into a fg and bg part. * The modification consists of searching for a minimum in the histogram * over a range of pixel values where the Otsu score is within a defined * fraction, scoreFraction, of the max score. To get the original Otsu * algorithm, set scoreFraction == 0. * </ol> * * @param pixs An 8 bpp PIX source image. * @param sizeX Desired tile X dimension; actual size may vary. * @param sizeY Desired tile Y dimension; actual size may vary. * @param smoothX Half-width of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param smoothY Half-height of convolution kernel applied to threshold * array: use 0 for no smoothing. * @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0 * for standard Otsu). * @return A 1 bpp thresholded PIX image. */ public static Pix otsuAdaptiveThreshold( Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixs.getDepth() != 8) throw new IllegalArgumentException("Source pix depth must be 8bpp"); int nativePix = nativeOtsuAdaptiveThreshold( pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction); if (nativePix == 0) throw new RuntimeException("Failed to perform Otsu adaptive threshold on image"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeOtsuAdaptiveThreshold( int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * @author alanv@google.com (Alan Viverette) */ public class Rotate { static { System.loadLibrary("lept"); } // Rotation default /** Default rotation quality is high. */ public static final boolean ROTATE_QUALITY = true; /** * Performs rotation using the default parameters. * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees) { return rotate(pixs, degrees, false); } /** * Performs basic image rotation about the center. * <p> * Notes: * <ol> * <li>Rotation is about the center of the image. * <li>For very small rotations, just return a clone. * <li>Rotation brings either white or black pixels in from outside the * image. * <li>Above 20 degrees, if rotation by shear is requested, we rotate by * sampling. * <li>Colormaps are removed for rotation by area map and shear. * <li>The dest can be expanded so that no image pixels are lost. To invoke * expansion, input the original width and height. For repeated rotation, * use of the original width and height allows the expansion to stop at the * maximum required size, which is a square with side = sqrt(w*w + h*h). * </ol> * * @param pixs The source pix. * @param degrees The number of degrees to rotate; clockwise is positive. * @param quality Whether to use high-quality rotation. * @return the rotated source image */ public static Pix rotate(Pix pixs, float degrees, boolean quality) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeRotate(pixs.mNativePix, degrees, quality); if (nativePix == 0) return null; return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeRotate(int nativePix, float degrees, boolean quality); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image rotation and skew detection methods. * * @author alanv@google.com (Alan Viverette) */ public class Skew { static { System.loadLibrary("lept"); } // Text alignment defaults /** Default range for sweep, will detect rotation of + or - 30 degrees. */ public final static float SWEEP_RANGE = 30.0f; /** Default sweep delta, reasonably accurate within 0.05 degrees. */ public final static float SWEEP_DELTA = 5.0f; /** Default sweep reduction, one-eighth the size of the original image. */ public final static int SWEEP_REDUCTION = 8; /** Default sweep reduction, one-fourth the size of the original image. */ public final static int SEARCH_REDUCTION = 4; /** Default search minimum delta, reasonably accurate within 0.05 degrees. */ public final static float SEARCH_MIN_DELTA = 0.01f; /** * Finds and returns the skew angle using default parameters. * * @param pixs Input pix (1 bpp). * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs) { return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION, SEARCH_MIN_DELTA); } /** * Finds and returns the skew angle, doing first a sweep through a set of * equal angles, and then doing a binary search until convergence. * <p> * Notes: * <ol> * <li>In computing the differential line sum variance score, we sum the * result over scanlines, but we always skip: * <ul> * <li>at least one scanline * <li>not more than 10% of the image height * <li>not more than 5% of the image width * </ul> * </ol> * * @param pixs Input pix (1 bpp). * @param sweepRange Half the full search range, assumed about 0; in * degrees. * @param sweepDelta Angle increment of sweep; in degrees. * @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8. * @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and * must not exceed redsweep. * @param searchMinDelta Minimum binary search increment angle; in degrees. * @return the detected skew angle, or 0.0 on failure */ public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction, searchReduction, searchMinDelta); } // *************** // * NATIVE CODE * // *************** private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta, int sweepReduction, int searchReduction, float searchMinDelta); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image adaptive mapping methods. * * @author alanv@google.com (Alan Viverette) */ public class AdaptiveMap { static { System.loadLibrary("lept"); } // Background normalization constants /** Image reduction value; possible values are 1, 2, 4, 8 */ private final static int NORM_REDUCTION = 16; /** Desired tile size; actual size may vary */ private final static int NORM_SIZE = 3; /** Background brightness value; values over 200 may result in clipping */ private final static int NORM_BG_VALUE = 200; /** * Normalizes an image's background using default parameters. * * @param pixs A source pix image. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph(Pix pixs) { return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE); } /** * Normalizes an image's background to a specified value. * <p> * Notes: * <ol> * <li>This is a top-level interface for normalizing the image intensity by * mapping the image so that the background is near the input value 'bgval'. * <li>The input image is either grayscale or rgb. * <li>For each component in the input image, the background value is * estimated using a grayscale closing; hence the 'Morph' in the function * name. * <li>An optional binary mask can be specified, with the foreground pixels * typically over image regions. The resulting background map values will be * determined by surrounding pixels that are not under the mask foreground. * The origin (0,0) of this mask is assumed to be aligned with the origin of * the input image. This binary mask must not fully cover pixs, because then * there will be no pixels in the input image available to compute the * background. * <li>The map is computed at reduced size (given by 'reduction') from the * input pixs and optional pixim. At this scale, pixs is closed to remove * the background, using a square Sel of odd dimension. The product of * reduction * size should be large enough to remove most of the text * foreground. * <li>No convolutional smoothing needs to be done on the map before * inverting it. * <li>A 'bgval' target background value for the normalized image. This * should be at least 128. If set too close to 255, some clipping will occur * in the result. * </ol> * * @param pixs A source pix image. * @param normReduction Reduction at which morphological closings are done. * @param normSize Size of square Sel for the closing. * @param normBgValue Target background value. * @return the source pix image with a normalized background */ public static Pix backgroundNormMorph( Pix pixs, int normReduction, int normSize, int normBgValue) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeBackgroundNormMorph( pixs.mNativePix, normReduction, normSize, normBgValue); if (nativePix == 0) throw new RuntimeException("Failed to normalize image background"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeBackgroundNormMorph( int nativePix, int reduction, int size, int bgval); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image sharpening methods. * * @author alanv@google.com (Alan Viverette) */ public class Enhance { static { System.loadLibrary("lept"); } /** * Performs unsharp masking (edge enhancement). * <p> * Notes: * <ul> * <li>We use symmetric smoothing filters of odd dimension, typically use * sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is * (size - 1)/2; i.e., 1, 2, 3, etc.</li> * <li>The <code>fract</code> parameter is typically taken in the range: 0.2 * &lt; <code>fract</code> &lt; 0.7</li> * </ul> * * @param halfwidth The half-width of the smoothing filter. * @param fraction The fraction of edge to be added back into the source * image. * @return an edge-enhanced Pix image or copy if no enhancement requested */ public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * JPEG input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class JpegIO { static { System.loadLibrary("lept"); } /** Default quality is 85%, which is reasonably good. */ public static final int DEFAULT_QUALITY = 85; /** Progressive encoding is disabled by default to increase compatibility. */ public static final boolean DEFAULT_PROGRESSIVE = false; /** * Returns a compressed JPEG byte representation of this Pix using default * parameters. * * @param pixs * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs) { return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Returns a compressed JPEG byte representation of this Pix. * * @param pixs A source pix image. * @param quality The quality of the compressed image. Valid range is 0-100. * @param progressive Whether to use progressive compression. * @return a compressed JPEG byte array representation of the Pix */ public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (quality < 0 || quality > 100) throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)"); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final Bitmap bmp = WriteFile.writeBitmap(pixs); bmp.compress(CompressFormat.JPEG, quality, byteStream); bmp.recycle(); final byte[] encodedData = byteStream.toByteArray(); try { byteStream.close(); } catch (IOException e) { e.printStackTrace(); } return encodedData; } // *************** // * NATIVE CODE * // *************** private static native byte[] nativeCompressToJpeg( int nativePix, int quality, boolean progressive); }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Leptonica constants. * * @author alanv@google.com (Alan Viverette) */ public class Constants { /*-------------------------------------------------------------------------* * Access and storage flags * *-------------------------------------------------------------------------*/ /* * For Pix, Box, Pta and Numa, there are 3 standard methods for handling the * retrieval or insertion of a struct: (1) direct insertion (Don't do this * if there is another handle somewhere to this same struct!) (2) copy * (Always safe, sets up a refcount of 1 on the new object. Can be * undesirable if very large, such as an image or an array of images.) (3) * clone (Makes another handle to the same struct, and bumps the refcount up * by 1. Safe to do unless you're changing data through one of the handles * but don't want those changes to be seen by the other handle.) For Pixa * and Boxa, which are structs that hold an array of clonable structs, there * is an additional method: (4) copy-clone (Makes a new higher-level struct * with a refcount of 1, but clones all the structs in the array.) Unlike * the other structs, when retrieving a string from an Sarray, you are * allowed to get a handle without a copy or clone (i.e., that you don't * own!). You must not free or insert such a string! Specifically, for an * Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or * FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or * 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1, * and L_INSERT and L_NOCOPY are always 0. */ /* Stuff it in; no copy, clone or copy-clone */ public static final int L_INSERT = 0; /* Make/use a copy of the object */ public static final int L_COPY = 1; /* Make/use clone (ref count) of the object */ public static final int L_CLONE = 2; /* * Make a new object and fill with with clones of each object in the * array(s) */ public static final int L_COPY_CLONE = 3; /*--------------------------------------------------------------------------* * Sort flags * *--------------------------------------------------------------------------*/ /* Sort in increasing order */ public static final int L_SORT_INCREASING = 1; /* Sort in decreasing order */ public static final int L_SORT_DECREASING = 2; /* Sort box or c.c. by horiz location */ public static final int L_SORT_BY_X = 3; /* Sort box or c.c. by vert location */ public static final int L_SORT_BY_Y = 4; /* Sort box or c.c. by width */ public static final int L_SORT_BY_WIDTH = 5; /* Sort box or c.c. by height */ public static final int L_SORT_BY_HEIGHT = 6; /* Sort box or c.c. by min dimension */ public static final int L_SORT_BY_MIN_DIMENSION = 7; /* Sort box or c.c. by max dimension */ public static final int L_SORT_BY_MAX_DIMENSION = 8; /* Sort box or c.c. by perimeter */ public static final int L_SORT_BY_PERIMETER = 9; /* Sort box or c.c. by area */ public static final int L_SORT_BY_AREA = 10; /* Sort box or c.c. by width/height ratio */ public static final int L_SORT_BY_ASPECT_RATIO = 11; /* ------------------ Image file format types -------------- */ /* * The IFF_DEFAULT flag is used to write the file out in the same (input) * file format that the pix was read from. If the pix was not read from * file, the input format field will be IFF_UNKNOWN and the output file * format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4 * for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which * is not supported in leptonica. */ public static final int IFF_UNKNOWN = 0; public static final int IFF_BMP = 1; public static final int IFF_JFIF_JPEG = 2; public static final int IFF_PNG = 3; public static final int IFF_TIFF = 4; public static final int IFF_TIFF_PACKBITS = 5; public static final int IFF_TIFF_RLE = 6; public static final int IFF_TIFF_G3 = 7; public static final int IFF_TIFF_G4 = 8; public static final int IFF_TIFF_LZW = 9; public static final int IFF_TIFF_ZIP = 10; public static final int IFF_PNM = 11; public static final int IFF_PS = 12; public static final int IFF_GIF = 13; public static final int IFF_JP2 = 14; public static final int IFF_DEFAULT = 15; public static final int IFF_SPIX = 16; }
Java
/* * Copyright (C) 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.googlecode.leptonica.android; /** * Image scaling methods. * * @author alanv@google.com (Alan Viverette) */ public class Scale { static { System.loadLibrary("lept"); } public enum ScaleType { /* Scale in X and Y independently, so that src matches dst exactly. */ FILL, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink or * expand src to fit dst. */ FIT, /* * Compute a scale that will maintain the original src aspect ratio, but * will also ensure that src fits entirely inside dst. May shrink src to * fit dst, but will not expand it. */ FIT_SHRINK, } /** * Scales the Pix to a specified width and height using a specified scaling * type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix * if no scaling is required. * * @param pixs * @param width * @param height * @param type * @return a scaled image or a clone of the Pix if no scaling is required */ public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int pixWidth = pixs.getWidth(); int pixHeight = pixs.getHeight(); float scaleX = width / (float) pixWidth; float scaleY = height / (float) pixHeight; switch (type) { case FILL: // Retains default scaleX and scaleY values break; case FIT: scaleX = Math.min(scaleX, scaleY); scaleY = scaleX; break; case FIT_SHRINK: scaleX = Math.min(1.0f, Math.min(scaleX, scaleY)); scaleY = scaleX; break; } return scale(pixs, scaleX, scaleY); } /** * Scales the Pix to specified scale. If no scaling is required, returns a * clone of the source Pix. * * @param pixs the source Pix * @param scale dimension scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scale) { return scale(pixs, scale, scale); } /** * Scales the Pix to specified x and y scale. If no scaling is required, * returns a clone of the source Pix. * * @param pixs the source Pix * @param scaleX x-dimension (width) scaling factor * @param scaleY y-dimension (height) scaling factor * @return a Pix scaled according to the supplied factors */ public static Pix scale(Pix pixs, float scaleX, float scaleY) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (scaleX <= 0.0f) throw new IllegalArgumentException("X scaling factor must be positive"); if (scaleY <= 0.0f) throw new IllegalArgumentException("Y scaling factor must be positive"); int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY); if (nativePix == 0) throw new RuntimeException("Failed to natively scale pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeScale(int nativePix, float scaleX, float scaleY); }
Java
// vim: fileencoding=utf-8 tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo (pop.atry@gmail.com) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protocGenAs3; import static google.protobuf.compiler.Plugin.*; import static com.google.protobuf.DescriptorProtos.*; import com.google.protobuf.*; import java.io.*; import java.util.*; import java.math.*; public final class Main { private static final String[] ACTIONSCRIPT_KEYWORDS = { "as", "break", "case", "catch", "class", "const", "continue", "default", "delete", "do", "else", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "internal", "is", "native", "new", "null", "package", "private", "protected", "public", "return", "super", "switch", "this", "throw", "to", "true", "try", "typeof", "use", "var", "void", "while", "with" }; private static final class Scope<Proto> { // 如果 proto instanceOf Scope ,则这个 Scope 是对另一 Scope 的引用 public final String fullName; public final Scope<?> parent; public final Proto proto; public final boolean export; public final HashMap<String, Scope<?>> children = new HashMap<String, Scope<?>>(); private Scope<?> find(String[] pathElements, int i) { Scope<?> result = this; for (; i < pathElements.length; i++) { String name = pathElements[i]; if (result.children.containsKey(name)) { result = result.children.get(name); } else { return null; } } while (result.proto instanceof Scope) { result = (Scope<?>)result.proto; } return result; } public boolean isRoot() { return parent == null; } private Scope<?> getRoot() { Scope<?> scope = this; while (!scope.isRoot()) { scope = scope.parent; } return scope; } public Scope<?> find(String path) { String[] pathElements = path.split("\\."); if (pathElements[0].equals("")) { return getRoot().find(pathElements, 1); } else { for (Scope<?> scope = this; scope != null; scope = scope.parent) { Scope<?> result = scope.find(pathElements, 0); if (result != null) { return result; } } return null; } } private Scope<?> findOrCreate(String[] pathElements, int i) { Scope<?> scope = this; for (; i < pathElements.length; i++) { String name = pathElements[i]; if (scope.children.containsKey(name)) { scope = scope.children.get(name); } else { Scope<Object> child = new Scope<Object>(scope, null, false, name); scope.children.put(name, child); scope = child; } } return scope; } public Scope<?> findOrCreate(String path) { String[] pathElements = path.split("\\."); if (pathElements[0].equals("")) { return getRoot().findOrCreate(pathElements, 1); } else { return findOrCreate(pathElements, 0); } } private Scope(Scope<?> parent, Proto proto, boolean export, String name) { this.parent = parent; this.proto = proto; this.export = export; if (isRoot() || parent.isRoot()) { fullName = name; } else { fullName = parent.fullName + '.' + name; } } public <ChildProto> Scope<ChildProto> addChild( String name, ChildProto proto, boolean export) { assert(name != null); assert(!name.equals("")); Scope<ChildProto> child = new Scope<ChildProto>(this, proto, export, name); if(children.containsKey(child)) { throw new IllegalArgumentException(); } children.put(name, child); return child; } public static Scope<Object> newRoot() { return new Scope<Object>(null, null, false, ""); } } private static void addServiceToScope(Scope<?> scope, ServiceDescriptorProto sdp, boolean export) { scope.addChild(sdp.getName(), sdp, export); } private static void addExtensionToScope(Scope<?> scope, FieldDescriptorProto efdp, boolean export) { scope.addChild(efdp.getName().toUpperCase(), efdp, export); } private static void addEnumToScope(Scope<?> scope, EnumDescriptorProto edp, boolean export) { assert(edp.hasName()); Scope<EnumDescriptorProto> enumScope = scope.addChild(edp.getName(), edp, export); for (EnumValueDescriptorProto evdp : edp.getValueList()) { Scope<EnumValueDescriptorProto> enumValueScope = enumScope.addChild(evdp.getName(), evdp, false); scope.addChild(evdp.getName(), enumValueScope, false); } } private static void addMessageToScope(Scope<?> scope, DescriptorProto dp, boolean export) { Scope<DescriptorProto> messageScope = scope.addChild(dp.getName(), dp, export); for (EnumDescriptorProto edp : dp.getEnumTypeList()) { addEnumToScope(messageScope, edp, export); } for (DescriptorProto nested: dp.getNestedTypeList()) { addMessageToScope(messageScope, nested, export); } } private static Scope<Object> buildScopeTree(CodeGeneratorRequest request) { Scope<Object> root = Scope.newRoot(); List<String> filesToGenerate = request.getFileToGenerateList(); for (FileDescriptorProto fdp : request.getProtoFileList()) { Scope<?> packageScope = fdp.hasPackage() ? root.findOrCreate(fdp.getPackage()) : root; boolean export = filesToGenerate.contains(fdp.getName()); for (ServiceDescriptorProto sdp : fdp.getServiceList()) { addServiceToScope(packageScope, sdp, export); } for (FieldDescriptorProto efdp : fdp.getExtensionList()) { addExtensionToScope(packageScope, efdp, export); } for (EnumDescriptorProto edp : fdp.getEnumTypeList()) { addEnumToScope(packageScope, edp, export); } for (DescriptorProto dp : fdp.getMessageTypeList()) { addMessageToScope(packageScope, dp, export); } } return root; } private static String getImportType(Scope<?> scope, FieldDescriptorProto fdp) { switch (fdp.getType()) { case TYPE_ENUM: case TYPE_MESSAGE: Scope<?> typeScope = scope.find(fdp.getTypeName()); if (typeScope == null) { throw new IllegalArgumentException( fdp.getTypeName() + " not found."); } return typeScope.fullName; case TYPE_BYTES: return "flash.utils.ByteArray"; default: return null; } } private static boolean isValueType(FieldDescriptorProto.Type type) { switch (type) { case TYPE_DOUBLE: case TYPE_FLOAT: case TYPE_INT32: case TYPE_FIXED32: case TYPE_BOOL: case TYPE_UINT32: case TYPE_SFIXED32: case TYPE_SINT32: case TYPE_ENUM: return true; default: return false; } } static final int VARINT = 0; static final int FIXED_64_BIT = 1; static final int LENGTH_DELIMITED = 2; static final int FIXED_32_BIT = 5; private static int getWireType( FieldDescriptorProto.Type type) { switch (type) { case TYPE_DOUBLE: case TYPE_FIXED64: case TYPE_SFIXED64: return FIXED_64_BIT; case TYPE_FLOAT: case TYPE_FIXED32: case TYPE_SFIXED32: return FIXED_32_BIT; case TYPE_INT32: case TYPE_SINT32: case TYPE_UINT32: case TYPE_BOOL: case TYPE_INT64: case TYPE_UINT64: case TYPE_SINT64: case TYPE_ENUM: return VARINT; case TYPE_STRING: case TYPE_MESSAGE: case TYPE_BYTES: return LENGTH_DELIMITED; default: throw new IllegalArgumentException(); } } private static String getActionScript3WireType( FieldDescriptorProto.Type type) { switch (type) { case TYPE_DOUBLE: case TYPE_FIXED64: case TYPE_SFIXED64: return "FIXED_64_BIT"; case TYPE_FLOAT: case TYPE_FIXED32: case TYPE_SFIXED32: return "FIXED_32_BIT"; case TYPE_INT32: case TYPE_SINT32: case TYPE_UINT32: case TYPE_BOOL: case TYPE_INT64: case TYPE_UINT64: case TYPE_SINT64: case TYPE_ENUM: return "VARINT"; case TYPE_STRING: case TYPE_MESSAGE: case TYPE_BYTES: return "LENGTH_DELIMITED"; default: throw new IllegalArgumentException(); } } private static String getActionScript3LogicType(Scope<?> scope, FieldDescriptorProto fdp) { if (fdp.getType() == FieldDescriptorProto.Type.TYPE_ENUM) { Scope<?> typeScope = scope.find(fdp.getTypeName()); if (typeScope == null) { throw new IllegalArgumentException( fdp.getTypeName() + " not found."); } if (typeScope == scope) { // workaround for mxmlc's bug. return typeScope.fullName.substring( typeScope.fullName.lastIndexOf('.') + 1); } return typeScope.fullName; } else { return getActionScript3Type(scope, fdp); } } private static String getActionScript3Type(Scope<?> scope, FieldDescriptorProto fdp) { switch (fdp.getType()) { case TYPE_DOUBLE: case TYPE_FLOAT: return "Number"; case TYPE_INT32: case TYPE_SFIXED32: case TYPE_SINT32: case TYPE_ENUM: return "int"; case TYPE_UINT32: case TYPE_FIXED32: return "uint"; case TYPE_BOOL: return "Boolean"; case TYPE_INT64: case TYPE_SFIXED64: case TYPE_SINT64: return "Int64"; case TYPE_UINT64: case TYPE_FIXED64: return "UInt64"; case TYPE_STRING: return "String"; case TYPE_MESSAGE: Scope<?> typeScope = scope.find(fdp.getTypeName()); if (typeScope == null) { throw new IllegalArgumentException( fdp.getTypeName() + " not found."); } if (typeScope == scope) { // workaround for mxmlc's bug. return typeScope.fullName.substring( typeScope.fullName.lastIndexOf('.') + 1); } return typeScope.fullName; case TYPE_BYTES: return "flash.utils.ByteArray"; default: throw new IllegalArgumentException(); } } private static void appendQuotedString(StringBuilder sb, String value) { sb.append('\"'); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch (c) { case '\"': case '\\': sb.append('\\'); sb.append(c); break; default: if (c >= 128 || Character.isISOControl(c)) { sb.append("\\u"); sb.append(String.format("%04X", new Integer(c))); } else { sb.append(c); } } } sb.append('\"'); } private static void appendDefaultValue(StringBuilder sb, Scope<?> scope, FieldDescriptorProto fdp) { String value = fdp.getDefaultValue(); switch (fdp.getType()) { case TYPE_DOUBLE: case TYPE_FLOAT: if (value.equals("nan")) { sb.append("NaN"); } else if (value.equals("inf")) { sb.append("Infinity"); } else if (value.equals("-inf")) { sb.append("-Infinity"); } else { sb.append(value); } break; case TYPE_UINT64: case TYPE_FIXED64: { long v = new BigInteger(value).longValue(); sb.append("new UInt64("); sb.append(Long.toString(v & 0xFFFFFFFFL)); sb.append(", "); sb.append(Long.toString((v >>> 32) & 0xFFFFFFFFL)); sb.append(")"); } break; case TYPE_INT64: case TYPE_SFIXED64: case TYPE_SINT64: { long v = Long.parseLong(value); sb.append("new Int64("); sb.append(Long.toString(v & 0xFFFFFFFFL)); sb.append(", "); sb.append(Integer.toString((int)v >>> 32)); sb.append(")"); } break; case TYPE_INT32: case TYPE_FIXED32: case TYPE_SFIXED32: case TYPE_SINT32: case TYPE_UINT32: case TYPE_BOOL: sb.append(value); break; case TYPE_STRING: appendQuotedString(sb, value); break; case TYPE_ENUM: sb.append(scope.find(fdp.getTypeName()). children.get(value).fullName); break; case TYPE_BYTES: sb.append("stringToByteArray("); sb.append("\""); sb.append(value); sb.append("\")"); break; default: throw new IllegalArgumentException(); } } private static void appendLowerCamelCase(StringBuilder sb, String s) { if (Arrays.binarySearch(ACTIONSCRIPT_KEYWORDS, s) >= 0) { sb.append("__"); } sb.append(Character.toLowerCase(s.charAt(0))); boolean upper = false; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (upper) { if (Character.isLowerCase(c)) { sb.append(Character.toUpperCase(c)); upper = false; continue; } else { sb.append('_'); } } upper = c == '_'; if (!upper) { sb.append(c); } } } private static void appendUpperCamelCase(StringBuilder sb, String s) { sb.append(Character.toUpperCase(s.charAt(0))); boolean upper = false; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (upper) { if (Character.isLowerCase(c)) { sb.append(Character.toUpperCase(c)); upper = false; continue; } else { sb.append('_'); } } upper = c == '_'; if (!upper) { sb.append(c); } } } private static void writeMessage(Scope<DescriptorProto> scope, StringBuilder content, StringBuilder initializerContent) { content.append("\timport com.netease.protobuf.*;\n"); content.append("\tuse namespace com.netease.protobuf.used_by_generated_code;\n"); content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n"); content.append("\timport flash.utils.Endian;\n"); content.append("\timport flash.utils.IDataInput;\n"); content.append("\timport flash.utils.IDataOutput;\n"); content.append("\timport flash.utils.IExternalizable;\n"); content.append("\timport flash.errors.IOError;\n"); HashSet<String> importTypes = new HashSet<String>(); for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) { importTypes.add(scope.find(efdp.getExtendee()).fullName); if (efdp.getType().equals(FieldDescriptorProto.Type.TYPE_MESSAGE)) { importTypes.add(scope.find(efdp.getTypeName()).fullName); } String importType = getImportType(scope, efdp); if (importType != null) { importTypes.add(importType); } } for (FieldDescriptorProto fdp : scope.proto.getFieldList()) { String importType = getImportType(scope, fdp); if (importType != null) { importTypes.add(importType); } } for (String importType : importTypes) { content.append("\timport "); content.append(importType); content.append(";\n"); } content.append("\t// @@protoc_insertion_point(imports)\n\n"); String remoteClassAlias; if (scope.proto.hasOptions()) { if (scope.proto.getOptions().hasExtension(Options.as3AmfAlias)) { remoteClassAlias = scope.proto.getOptions().getExtension(Options.as3AmfAlias); } else if (scope.proto.getOptions().getExtension(Options.as3AmfAutoAlias)) { remoteClassAlias = scope.fullName; } else { remoteClassAlias = null; } if (remoteClassAlias != null) { content.append("\t[RemoteClass(alias="); appendQuotedString(content, remoteClassAlias); content.append(")]\n"); } if (scope.proto.getOptions().getExtension(Options.as3Bindable)) { content.append("\t[Bindable]\n"); } } else { remoteClassAlias = null; } content.append("\t// @@protoc_insertion_point(class_metadata)\n"); content.append("\tpublic dynamic final class "); content.append(scope.proto.getName()); content.append(" extends com.netease.protobuf.Message"); if (remoteClassAlias != null) { content.append(" implements flash.utils.IExternalizable {\n"); content.append("\t\tpublic final function writeExternal(output:flash.utils.IDataOutput):void {\n"); content.append("\t\t\twriteDelimitedTo(output);\n"); content.append("\t\t}\n\n"); content.append("\t\tpublic final function readExternal(input:flash.utils.IDataInput):void {\n"); content.append("\t\t\tmergeDelimitedFrom(input);\n"); content.append("\t\t}\n\n"); } else { content.append(" {\n"); } if (scope.proto.getExtensionRangeCount() > 0) { content.append("\t\t[ArrayElementType(\"Function\")]\n"); content.append("\t\tpublic static const extensionReadFunctions:Array = [];\n\n"); } if (scope.proto.getExtensionCount() > 0) { initializerContent.append("import "); initializerContent.append(scope.fullName); initializerContent.append(";\n"); initializerContent.append("if(!"); initializerContent.append(scope.fullName); initializerContent.append(") throw new Error();\n"); } for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) { if (efdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); continue; } String extendee = scope.find(efdp.getExtendee()).fullName; content.append("\t\t/**\n\t\t * @private\n\t\t */\n"); content.append("\t\tpublic static const "); content.append(efdp.getName().toUpperCase()); content.append(":"); appendFieldDescriptorClass(content, efdp); content.append(" = "); appendFieldDescriptor(content, scope, efdp); content.append(";\n\n"); if (efdp.hasDefaultValue()) { content.append("\t\t"); content.append(extendee); content.append(".prototype["); content.append(efdp.getName().toUpperCase()); content.append("] = "); appendDefaultValue(content, scope, efdp); content.append(";\n\n"); } appendExtensionReadFunction(content, "\t\t", scope, efdp); } int valueTypeCount = 0; for (FieldDescriptorProto fdp : scope.proto.getFieldList()) { if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); continue; } content.append("\t\t/**\n\t\t * @private\n\t\t */\n"); content.append("\t\tpublic static const "); content.append(fdp.getName().toUpperCase()); content.append(":"); appendFieldDescriptorClass(content, fdp); content.append(" = "); appendFieldDescriptor(content, scope, fdp); content.append(";\n\n"); assert(fdp.hasLabel()); switch (fdp.getLabel()) { case LABEL_OPTIONAL: content.append("\t\tprivate var "); content.append(fdp.getName()); content.append("$field:"); content.append(getActionScript3Type(scope, fdp)); content.append(";\n\n"); if (isValueType(fdp.getType())) { final int valueTypeId = valueTypeCount++; final int valueTypeField = valueTypeId / 32; final int valueTypeBit = valueTypeId % 32; if (valueTypeBit == 0) { content.append("\t\tprivate var hasField$"); content.append(valueTypeField); content.append(":uint = 0;\n\n"); } content.append("\t\tpublic function clear"); appendUpperCamelCase(content, fdp.getName()); content.append("():void {\n"); content.append("\t\t\thasField$"); content.append(valueTypeField); content.append(" &= 0x"); content.append(Integer.toHexString(~(1 << valueTypeBit))); content.append(";\n"); content.append("\t\t\t"); content.append(fdp.getName()); content.append("$field = new "); content.append(getActionScript3Type(scope, fdp)); content.append("();\n"); content.append("\t\t}\n\n"); content.append("\t\tpublic function get has"); appendUpperCamelCase(content, fdp.getName()); content.append("():Boolean {\n"); content.append("\t\t\treturn (hasField$"); content.append(valueTypeField); content.append(" & 0x"); content.append(Integer.toHexString(1 << valueTypeBit)); content.append(") != 0;\n"); content.append("\t\t}\n\n"); content.append("\t\tpublic function set "); appendLowerCamelCase(content, fdp.getName()); content.append("(value:"); content.append(getActionScript3Type(scope, fdp)); content.append("):void {\n"); content.append("\t\t\thasField$"); content.append(valueTypeField); content.append(" |= 0x"); content.append(Integer.toHexString(1 << valueTypeBit)); content.append(";\n"); content.append("\t\t\t"); content.append(fdp.getName()); content.append("$field = value;\n"); content.append("\t\t}\n\n"); } else { content.append("\t\tpublic function clear"); appendUpperCamelCase(content, fdp.getName()); content.append("():void {\n"); content.append("\t\t\t"); content.append(fdp.getName()); content.append("$field = null;\n"); content.append("\t\t}\n\n"); content.append("\t\tpublic function get has"); appendUpperCamelCase(content, fdp.getName()); content.append("():Boolean {\n"); content.append("\t\t\treturn "); content.append(fdp.getName()); content.append("$field != null;\n"); content.append("\t\t}\n\n"); content.append("\t\tpublic function set "); appendLowerCamelCase(content, fdp.getName()); content.append("(value:"); content.append(getActionScript3Type(scope, fdp)); content.append("):void {\n"); content.append("\t\t\t"); content.append(fdp.getName()); content.append("$field = value;\n"); content.append("\t\t}\n\n"); } content.append("\t\tpublic function get "); appendLowerCamelCase(content, fdp.getName()); content.append("():"); content.append(getActionScript3Type(scope, fdp)); content.append(" {\n"); if (fdp.hasDefaultValue()) { content.append("\t\t\tif(!has"); appendUpperCamelCase(content, fdp.getName()); content.append(") {\n"); content.append("\t\t\t\treturn "); appendDefaultValue(content, scope, fdp); content.append(";\n"); content.append("\t\t\t}\n"); } content.append("\t\t\treturn "); content.append(fdp.getName()); content.append("$field;\n"); content.append("\t\t}\n\n"); break; case LABEL_REQUIRED: content.append("\t\tpublic var "); appendLowerCamelCase(content, fdp.getName()); content.append(":"); content.append(getActionScript3Type(scope, fdp)); if (fdp.hasDefaultValue()) { content.append(" = "); appendDefaultValue(content, scope, fdp); } content.append(";\n\n"); break; case LABEL_REPEATED: content.append("\t\t[ArrayElementType(\""); content.append(getActionScript3Type(scope, fdp)); content.append("\")]\n"); content.append("\t\tpublic var "); appendLowerCamelCase(content, fdp.getName()); content.append(":Array = [];\n\n"); break; default: throw new IllegalArgumentException(); } } content.append("\t\t/**\n\t\t * @private\n\t\t */\n\t\toverride com.netease.protobuf.used_by_generated_code final function writeToBuffer(output:com.netease.protobuf.WritingBuffer):void {\n"); for (FieldDescriptorProto fdp : scope.proto.getFieldList()) { if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); continue; } switch (fdp.getLabel()) { case LABEL_OPTIONAL: content.append("\t\t\tif ("); content.append("has"); appendUpperCamelCase(content, fdp.getName()); content.append(") {\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); content.append(", "); content.append(Integer.toString(fdp.getNumber())); content.append(");\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$"); content.append(fdp.getType().name()); content.append("(output, "); content.append(fdp.getName()); content.append("$field);\n"); content.append("\t\t\t}\n"); break; case LABEL_REQUIRED: content.append("\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); content.append(", "); content.append(Integer.toString(fdp.getNumber())); content.append(");\n"); content.append("\t\t\tcom.netease.protobuf.WriteUtils.write$"); content.append(fdp.getType().name()); content.append("(output, this."); appendLowerCamelCase(content, fdp.getName()); content.append(");\n"); break; case LABEL_REPEATED: if (fdp.hasOptions() && fdp.getOptions().getPacked()) { content.append("\t\t\tif (this."); appendLowerCamelCase(content, fdp.getName()); content.append(" != null && this."); appendLowerCamelCase(content, fdp.getName()); content.append(".length > 0) {\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.LENGTH_DELIMITED, "); content.append(Integer.toString(fdp.getNumber())); content.append(");\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writePackedRepeated(output, com.netease.protobuf.WriteUtils.write$"); content.append(fdp.getType().name()); content.append(", this."); appendLowerCamelCase(content, fdp.getName()); content.append(");\n"); content.append("\t\t\t}\n"); } else { content.append("\t\t\tfor (var "); appendLowerCamelCase(content, fdp.getName()); content.append("$index:uint = 0; "); appendLowerCamelCase(content, fdp.getName()); content.append("$index < this."); appendLowerCamelCase(content, fdp.getName()); content.append(".length; ++"); appendLowerCamelCase(content, fdp.getName()); content.append("$index) {\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); content.append(", "); content.append(Integer.toString(fdp.getNumber())); content.append(");\n"); content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$"); content.append(fdp.getType().name()); content.append("(output, this."); appendLowerCamelCase(content, fdp.getName()); content.append("["); appendLowerCamelCase(content, fdp.getName()); content.append("$index]);\n"); content.append("\t\t\t}\n"); } break; } } content.append("\t\t\tfor (var fieldKey:* in this) {\n"); if (scope.proto.getExtensionRangeCount() > 0) { content.append("\t\t\t\tsuper.writeExtensionOrUnknown(output, fieldKey);\n"); } else { content.append("\t\t\t\tsuper.writeUnknown(output, fieldKey);\n"); } content.append("\t\t\t}\n"); content.append("\t\t}\n\n"); content.append("\t\t/**\n\t\t * @private\n\t\t */\n"); content.append("\t\toverride com.netease.protobuf.used_by_generated_code final function readFromSlice(input:flash.utils.IDataInput, bytesAfterSlice:uint):void {\n"); for (FieldDescriptorProto fdp : scope.proto.getFieldList()) { if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); continue; } switch (fdp.getLabel()) { case LABEL_OPTIONAL: case LABEL_REQUIRED: content.append("\t\t\tvar "); content.append(fdp.getName()); content.append("$count:uint = 0;\n"); break; } } content.append("\t\t\twhile (input.bytesAvailable > bytesAfterSlice) {\n"); content.append("\t\t\t\tvar tag:uint = com.netease.protobuf.ReadUtils.read$TYPE_UINT32(input);\n"); content.append("\t\t\t\tswitch (tag >> 3) {\n"); for (FieldDescriptorProto fdp : scope.proto.getFieldList()) { if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); continue; } content.append("\t\t\t\tcase "); content.append(Integer.toString(fdp.getNumber())); content.append(":\n"); switch (fdp.getLabel()) { case LABEL_OPTIONAL: case LABEL_REQUIRED: content.append("\t\t\t\t\tif ("); content.append(fdp.getName()); content.append("$count != 0) {\n"); content.append("\t\t\t\t\t\tthrow new flash.errors.IOError('Bad data format: "); content.append(scope.proto.getName()); content.append('.'); appendLowerCamelCase(content, fdp.getName()); content.append(" cannot be set twice.');\n"); content.append("\t\t\t\t\t}\n"); content.append("\t\t\t\t\t++"); content.append(fdp.getName()); content.append("$count;\n"); if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) { content.append("\t\t\t\t\tthis."); appendLowerCamelCase(content, fdp.getName()); content.append(" = new "); content.append(getActionScript3Type(scope, fdp)); content.append("();\n"); content.append("\t\t\t\t\tcom.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, this."); appendLowerCamelCase(content, fdp.getName()); content.append(");\n"); } else { content.append("\t\t\t\t\tthis."); appendLowerCamelCase(content, fdp.getName()); content.append(" = com.netease.protobuf.ReadUtils.read$"); content.append(fdp.getType().name()); content.append("(input);\n"); } break; case LABEL_REPEATED: switch (fdp.getType()) { case TYPE_DOUBLE: case TYPE_FLOAT: case TYPE_BOOL: case TYPE_INT32: case TYPE_FIXED32: case TYPE_UINT32: case TYPE_SFIXED32: case TYPE_SINT32: case TYPE_INT64: case TYPE_FIXED64: case TYPE_UINT64: case TYPE_SFIXED64: case TYPE_SINT64: case TYPE_ENUM: content.append("\t\t\t\t\tif ((tag & 7) == com.netease.protobuf.WireType.LENGTH_DELIMITED) {\n"); content.append("\t\t\t\t\t\tcom.netease.protobuf.ReadUtils.readPackedRepeated(input, com.netease.protobuf.ReadUtils.read$"); content.append(fdp.getType().name()); content.append(", this."); appendLowerCamelCase(content, fdp.getName()); content.append(");\n"); content.append("\t\t\t\t\t\tbreak;\n"); content.append("\t\t\t\t\t}\n"); } if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) { content.append("\t\t\t\t\tthis."); appendLowerCamelCase(content, fdp.getName()); content.append(".push("); content.append("com.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, "); content.append("new "); content.append(getActionScript3Type(scope, fdp)); content.append("()));\n"); } else { content.append("\t\t\t\t\tthis."); appendLowerCamelCase(content, fdp.getName()); content.append(".push(com.netease.protobuf.ReadUtils.read$"); content.append(fdp.getType().name()); content.append("(input));\n"); } break; } content.append("\t\t\t\t\tbreak;\n"); } content.append("\t\t\t\tdefault:\n"); if (scope.proto.getExtensionRangeCount() > 0) { content.append("\t\t\t\t\tsuper.readExtensionOrUnknown(extensionReadFunctions, input, tag);\n"); } else { content.append("\t\t\t\t\tsuper.readUnknown(input, tag);\n"); } content.append("\t\t\t\t\tbreak;\n"); content.append("\t\t\t\t}\n"); content.append("\t\t\t}\n"); content.append("\t\t}\n\n"); content.append("\t}\n"); } private static void appendFieldDescriptorClass(StringBuilder content, FieldDescriptorProto fdp) { switch (fdp.getLabel()) { case LABEL_REQUIRED: case LABEL_OPTIONAL: break; case LABEL_REPEATED: content.append("Repeated"); break; default: throw new IllegalArgumentException(); } content.append("FieldDescriptor$"); content.append(fdp.getType().name()); } private static void appendFieldDescriptor(StringBuilder content, Scope<?> scope, FieldDescriptorProto fdp) { content.append("new "); appendFieldDescriptorClass(content, fdp); content.append("("); if (scope.parent == null) { appendQuotedString(content, fdp.getName()); } else { appendQuotedString(content, scope.fullName + '.' + fdp.getName()); } content.append(", "); if (fdp.hasExtendee()) { if (scope.proto instanceof DescriptorProto) { appendQuotedString(content, scope.fullName + '/' + fdp.getName().toUpperCase()); } else { if (scope.parent == null) { appendQuotedString(content, fdp.getName().toUpperCase()); } else { appendQuotedString(content, scope.fullName + '.' + fdp.getName().toUpperCase()); } } } else { StringBuilder fieldName = new StringBuilder(); appendLowerCamelCase(fieldName, fdp.getName()); appendQuotedString(content, fieldName.toString()); } content.append(", ("); switch (fdp.getLabel()) { case LABEL_REQUIRED: case LABEL_OPTIONAL: content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); break; case LABEL_REPEATED: if (fdp.hasOptions() && fdp.getOptions().getPacked()) { content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED"); } else { content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); } break; } switch (fdp.getType()) { case TYPE_MESSAGE: if (scope.proto instanceof DescriptorProto) { content.append(", function():Class { return "); content.append(getActionScript3LogicType(scope, fdp)); content.append("; }"); } else { content.append(", "); content.append(getActionScript3LogicType(scope, fdp)); } break; case TYPE_ENUM: content.append(", "); content.append(getActionScript3LogicType(scope, fdp)); break; } content.append(")"); } private static void appendExtensionReadFunction(StringBuilder content, String tabs, Scope<?> scope, FieldDescriptorProto fdp) { String extendee = scope.find(fdp.getExtendee()).fullName; switch (fdp.getLabel()) { case LABEL_REQUIRED: case LABEL_OPTIONAL: content.append(tabs); content.append(extendee); content.append(".extensionReadFunctions[("); content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); content.append("] = "); content.append(fdp.getName().toUpperCase()); content.append(".read;\n\n"); break; case LABEL_REPEATED: content.append(tabs); content.append(extendee); content.append(".extensionReadFunctions[("); content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType."); content.append(getActionScript3WireType(fdp.getType())); content.append("] = "); content.append(fdp.getName().toUpperCase()); content.append(".readNonPacked;\n\n"); switch (fdp.getType()) { case TYPE_MESSAGE: case TYPE_BYTES: case TYPE_STRING: break; default: content.append(tabs); content.append(extendee); content.append(".extensionReadFunctions[("); content.append(Integer.toString(fdp.getNumber())); content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED] = "); content.append(fdp.getName().toUpperCase()); content.append(".readPacked;\n\n"); break; } break; } } private static void writeExtension(Scope<FieldDescriptorProto> scope, StringBuilder content, StringBuilder initializerContent) { initializerContent.append("import "); initializerContent.append(scope.fullName); initializerContent.append(";\n"); initializerContent.append("if(!"); initializerContent.append(scope.fullName); initializerContent.append(") throw new Error;\n"); content.append("\timport com.netease.protobuf.*;\n"); content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n"); String importType = getImportType(scope.parent, scope.proto); if (importType != null) { content.append("\timport "); content.append(importType); content.append(";\n"); } String extendee = scope.parent.find(scope.proto.getExtendee()).fullName; content.append("\timport "); content.append(extendee); content.append(";\n"); content.append("\t// @@protoc_insertion_point(imports)\n\n"); content.append("\t// @@protoc_insertion_point(constant_metadata)\n"); content.append("\t/**\n\t * @private\n\t */\n"); content.append("\tpublic const "); content.append(scope.proto.getName().toUpperCase()); content.append(":"); appendFieldDescriptorClass(content, scope.proto); content.append(" = "); appendFieldDescriptor(content, scope.parent, scope.proto); content.append(";\n\n"); if (scope.proto.hasDefaultValue()) { content.append("\t"); content.append(extendee); content.append(".prototype["); content.append(scope.proto.getName().toUpperCase()); content.append("] = "); appendDefaultValue(content, scope.parent, scope.proto); content.append(";\n\n"); } appendExtensionReadFunction(content, "\t", scope.parent, scope.proto); } private static void writeEnum(Scope<EnumDescriptorProto> scope, StringBuilder content) { content.append("\tpublic final class "); content.append(scope.proto.getName()); content.append(" {\n"); for (EnumValueDescriptorProto evdp : scope.proto.getValueList()) { content.append("\t\tpublic static const "); content.append(evdp.getName()); content.append(":int = "); content.append(evdp.getNumber()); content.append(";\n"); } content.append("\t}\n"); } @SuppressWarnings("unchecked") private static void writeFile(Scope<?> scope, StringBuilder content, StringBuilder initializerContent) { content.append("package "); content.append(scope.parent.fullName); content.append(" {\n"); if (scope.proto instanceof DescriptorProto) { writeMessage((Scope<DescriptorProto>)scope, content, initializerContent); } else if (scope.proto instanceof EnumDescriptorProto) { writeEnum((Scope<EnumDescriptorProto>)scope, content); } else if (scope.proto instanceof FieldDescriptorProto) { Scope<FieldDescriptorProto> fdpScope = (Scope<FieldDescriptorProto>)scope; if (fdpScope.proto.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { System.err.println("Warning: Group is not supported."); } else { writeExtension(fdpScope, content, initializerContent); } } else { throw new IllegalArgumentException(); } content.append("}\n"); } @SuppressWarnings("unchecked") private static void writeFiles(Scope<?> root, CodeGeneratorResponse.Builder responseBuilder, StringBuilder initializerContent) { for (Map.Entry<String, Scope<?>> entry : root.children.entrySet()) { Scope<?> scope = entry.getValue(); if (scope.export) { if (scope.proto instanceof ServiceDescriptorProto) { ServiceDescriptorProto serviceProto = (ServiceDescriptorProto)scope.proto; if (serviceProto.getOptions().getExtension(Options.as3ClientSideService) || serviceProto.getOptions().getExtension(Options.as3ServerSideService)) { StringBuilder classContent = new StringBuilder(); writeServiceClass((Scope<ServiceDescriptorProto>)scope, classContent); responseBuilder.addFile( CodeGeneratorResponse.File.newBuilder(). setName(scope.fullName.replace('.', '/') + ".as"). setContent(classContent.toString()). build() ); StringBuilder interfaceContent = new StringBuilder(); writeServiceInterface((Scope<ServiceDescriptorProto>)scope, interfaceContent); String[] servicePath = scope.fullName.split("\\."); StringBuilder sb = new StringBuilder(); int i = 0; for (; i < servicePath.length - 1; i++) { sb.append(servicePath[i]); sb.append('/'); } sb.append('I'); sb.append(servicePath[i]); sb.append(".as"); responseBuilder.addFile( CodeGeneratorResponse.File.newBuilder(). setName(sb.toString()). setContent(interfaceContent.toString()). build() ); } } else { StringBuilder content = new StringBuilder(); writeFile(scope, content, initializerContent); responseBuilder.addFile( CodeGeneratorResponse.File.newBuilder(). setName(scope.fullName.replace('.', '/') + ".as"). setContent(content.toString()). build() ); } } writeFiles(scope, responseBuilder, initializerContent); } } private static void writeFiles(Scope<?> root, CodeGeneratorResponse.Builder responseBuilder) { StringBuilder initializerContent = new StringBuilder(); initializerContent.append("{\n"); writeFiles(root, responseBuilder, initializerContent); initializerContent.append("}\n"); responseBuilder.addFile( CodeGeneratorResponse.File.newBuilder(). setName("initializer.as.inc"). setContent(initializerContent.toString()). build() ); } private static void writeServiceClass(Scope<ServiceDescriptorProto> scope, StringBuilder content) { content.append("package "); content.append(scope.parent.fullName); content.append(" {\n"); HashSet<String> importTypes = new HashSet<String>(); for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { importTypes.add(scope.find(mdp.getInputType()).fullName); if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) { importTypes.add(scope.find(mdp.getOutputType()).fullName); } } for (String importType : importTypes) { content.append("\timport "); content.append(importType); content.append(";\n"); } content.append("\timport google.protobuf.*;\n"); content.append("\timport flash.utils.*;\n"); content.append("\timport com.netease.protobuf.*;\n"); content.append("\t// @@protoc_insertion_point(imports)\n\n"); content.append("\tpublic final class "); content.append(scope.proto.getName()); if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) { content.append(" implements "); if (scope.parent.isRoot()) { content.append("I"); } else { content.append(scope.parent.fullName); content.append(".I"); } content.append(scope.proto.getName()); } content.append(" {\n"); if (scope.proto.hasOptions()) { content.append("\t\tpublic static const OPTIONS_BYTES:flash.utils.ByteArray = com.netease.protobuf.stringToByteArray(\""); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { scope.proto.getOptions().writeTo(buffer); } catch (IOException e) { throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e); } for (byte b : buffer.toByteArray()) { content.append("\\x"); content.append(Character.forDigit((b & 0xF0) >>> 4, 16)); content.append(Character.forDigit(b & 0x0F, 16)); } content.append("\");\n\n"); content.append("\t\tpublic static function getOptions():google.protobuf.ServiceOptions\n"); content.append("\t\t{\n"); content.append("\t\t\tOPTIONS_BYTES.position = 0;\n"); content.append("\t\t\tconst options:google.protobuf.ServiceOptions = new google.protobuf.ServiceOptions();\n"); content.append("\t\t\toptions.mergeFrom(OPTIONS_BYTES);\n\n"); content.append("\t\t\treturn options;\n"); content.append("\t\t}\n\n"); } boolean hasMethodOptions = false; for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { if (mdp.hasOptions()) { if (!hasMethodOptions) { hasMethodOptions = true; content.append("\t\tpublic static const OPTIONS_BYTES_BY_METHOD_NAME:Object =\n"); content.append("\t\t{\n"); } else { content.append(",\n"); } content.append("\t\t\t\""); content.append(scope.fullName); content.append("."); content.append(mdp.getName()); content.append("\" : stringToByteArray(\""); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { mdp.getOptions().writeTo(buffer); } catch (IOException e) { throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e); } for (byte b : buffer.toByteArray()) { content.append("\\x"); content.append(Character.forDigit((b & 0xF0) >>> 4, 16)); content.append(Character.forDigit(b & 0x0F, 16)); } content.append("\")"); } } if (hasMethodOptions) { content.append("\n\t\t};\n\n"); } if (scope.proto.getOptions().getExtension(Options.as3ServerSideService)) { content.append("\t\tpublic static const REQUEST_CLASSES_BY_METHOD_NAME:Object =\n"); content.append("\t\t{\n"); boolean comma = false; for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { if (comma) { content.append(",\n"); } else { comma = true; } content.append("\t\t\t\""); content.append(scope.fullName); content.append("."); content.append(mdp.getName()); content.append("\" : "); content.append(scope.find(mdp.getInputType()).fullName); } content.append("\n\t\t};\n\n"); content.append("\t\tpublic static function callMethod(service:"); if (scope.parent.isRoot()) { content.append("I"); } else { content.append(scope.parent.fullName); content.append(".I"); } content.append(scope.proto.getName()); content.append(", methodName:String, request:com.netease.protobuf.Message, responseHandler:Function):void {\n"); content.append("\t\t\tswitch (methodName) {\n"); for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { content.append("\t\t\t\tcase \""); content.append(scope.fullName); content.append("."); content.append(mdp.getName()); content.append("\":\n"); content.append("\t\t\t\t{\n"); content.append("\t\t\t\t\tservice."); appendLowerCamelCase(content, mdp.getName()); content.append("("); content.append(scope.find(mdp.getInputType()).fullName); content.append("(request), responseHandler);\n"); content.append("\t\t\t\t\tbreak;\n"); content.append("\t\t\t\t}\n"); } content.append("\t\t\t}\n"); content.append("\t\t}\n\n"); } if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) { content.append("\t\tpublic var sendFunction:Function;\n\n"); for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { content.append("\t\tpublic function "); appendLowerCamelCase(content, mdp.getName()); content.append("(request:"); content.append(scope.find(mdp.getInputType()).fullName); content.append(", responseHandler:Function):void {\n"); content.append("\t\t\tsendFunction(\""); content.append(scope.fullName); content.append("."); content.append(mdp.getName()); content.append("\", request, responseHandler, "); content.append(scope.find(mdp.getOutputType()).fullName); content.append(");\n"); content.append("\t\t}\n\n"); } } content.append("\t}\n"); content.append("}\n"); } private static void writeServiceInterface( Scope<ServiceDescriptorProto> scope, StringBuilder content) { content.append("package "); content.append(scope.parent.fullName); content.append(" {\n"); HashSet<String> importTypes = new HashSet<String>(); for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { importTypes.add(scope.find(mdp.getInputType()).fullName); } for (String importType : importTypes) { content.append("\timport "); content.append(importType); content.append(";\n"); } content.append("\t// @@protoc_insertion_point(imports)\n\n"); content.append("\tpublic interface I"); content.append(scope.proto.getName()); content.append(" {\n\n"); for (MethodDescriptorProto mdp : scope.proto.getMethodList()) { content.append("\t\tfunction "); appendLowerCamelCase(content, mdp.getName()); content.append("(input:"); content.append(scope.find(mdp.getInputType()).fullName); content.append(", done:Function):void;\n\n"); } content.append("\t}\n"); content.append("}\n"); } public static void main(String[] args) throws IOException { ExtensionRegistry registry = ExtensionRegistry.newInstance(); Options.registerAllExtensions(registry); CodeGeneratorRequest request = CodeGeneratorRequest. parseFrom(System.in, registry); CodeGeneratorResponse response; try { Scope<Object> root = buildScopeTree(request); CodeGeneratorResponse.Builder responseBuilder = CodeGeneratorResponse.newBuilder(); writeFiles(root, responseBuilder); response = responseBuilder.build(); } catch (Exception e) { // 出错,报告给 protoc ,然后退出 StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); CodeGeneratorResponse.newBuilder().setError(sw.toString()). build().writeTo(System.out); System.out.flush(); return; } response.writeTo(System.out); System.out.flush(); } }
Java
public class TestSVNCode { //nhom google code nhom 8 public static void main(String[] args) { System.out.println("hello world"); System.out.println("hello world"); System.out.println("nhom 8"); } }
Java
package com.google.gwt.sample.stockwatcher.client.service; import java.util.List; import com.google.gwt.sample.stockwatcher.client.shared.StockBuy; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("stockPrices") public interface StockPriceService extends RemoteService { StockPrice[] getPrices(List<String> symbols); StockBuy buyStock(StockBuy stockBuy); List<StockBuy> getStockBuyingHistory(); }
Java
package com.google.gwt.sample.stockwatcher.client.service; import java.util.List; import com.google.gwt.sample.stockwatcher.client.shared.StockBuy; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; import com.google.gwt.user.client.rpc.AsyncCallback; public interface StockPriceServiceAsync { void getPrices(List<String> symbol, AsyncCallback<StockPrice[]> callback); void buyStock(StockBuy stockBuy, AsyncCallback<StockBuy> callback); void getStockBuyingHistory(AsyncCallback<List<StockBuy>> callback); }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; public interface BuyStockPresenter extends Presenter<BuyStockPresenter.Display> { public interface Display extends com.google.gwt.sample.stockwatcher.client.view.Display { void displaySymbol(String symbol); void displayPrice(String price); void setPresenter(BuyStockPresenter presenter); } void onSaveButtonClicked(Long amount); void onCancelButtonClicked(); }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.sample.stockwatcher.client.view.Display; /** * */ public abstract class BasePresenter<D extends Display> implements Presenter<D> { protected final HandlerManager eventBus; protected final D display; public BasePresenter(HandlerManager eventBus, D display) { this.eventBus = eventBus; this.display = display; } @Override public void bind() { onBind(); postBind(); } /** * Do actually event binding. */ protected abstract void onBind(); /** * Override in case data init after bind. */ protected void postBind() { } public D getDisplay() { return this.display; } }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; import java.util.ArrayList; import java.util.List; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.sample.stockwatcher.client.event.BuyStockEvent; import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync; import com.google.gwt.sample.stockwatcher.client.shared.StockBuy; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; public class StockWatcherPresenterImpl extends BasePresenter<StockWatcherPresenter.Display> implements StockWatcherPresenter { private List<String> symbolList = new ArrayList<String>(); private StockPriceServiceAsync rpcService; public StockWatcherPresenterImpl(StockPriceServiceAsync rpcService, HandlerManager eventBus, Display view) { super(eventBus, view); this.rpcService = rpcService; } @Override protected void onBind() { } private void addStock(final String symbol) { if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) { Window.alert("'" + symbol + "' is not a valid symbol."); return; } if (symbolList.contains(symbol)) { Window.alert("Unique constraint of symbol."); return; } symbolList.add(symbol); display.addNewRow(symbol); refreshWatchList(); display.getRemoveButton(symbol).addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { display.removeRow(symbol); symbolList.remove(symbol); } }); display.getBuyButton(symbol).addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { final double price = Double.parseDouble(display .getPrice(symbol)); StockPrice stockPrice = new StockPrice(symbol, price); eventBus.fireEvent(new BuyStockEvent(stockPrice)); } }); } private void refreshWatchList() { this.rpcService.getPrices(this.symbolList, new AsyncCallback<StockPrice[]>() { @Override public void onFailure(Throwable caught) { Window.alert("refreshWatchList error"); } @Override public void onSuccess(StockPrice[] result) { for (int i = 0; i < result.length; i++) { int row = i + 1; display.updatePrice(row, result[i].getPrice()); display.updateChangePercent(row, result[i] .getChange(), result[i].getChangePercent()); } } }); } /** * TODO: duplicated row. */ private void refreshBuyingHistory() { this.rpcService .getStockBuyingHistory(new AsyncCallback<List<StockBuy>>() { @Override public void onFailure(Throwable caught) { Window.alert("refreshBuyingHistory error" + caught.getMessage()); } @Override public void onSuccess(List<StockBuy> result) { for (StockBuy stockBuy : result) { display.addNewBuyingHistory(stockBuy.getSymbol(), String.valueOf(stockBuy.getPrice()), String .valueOf(stockBuy.getCount())); } } }); } @Override protected void postBind() { refreshWatchList(); refreshBuyingHistory(); } @Override public void onAddButtonClicked(String value) { addStock(value); } @Override public void onInputBoxEnterKeyPressed(String value) { addStock(value); } // private void scheduleTimeRefresh() { // // Setup timer to refresh list automatically. // Timer refreshTimer = new Timer() { // @Override // public void run() { // refreshWatchList(); // } // }; // refreshTimer.scheduleRepeating(REFRESH_INTERVAL); // } // private static final int REFRESH_INTERVAL = 2000; }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; import com.google.gwt.event.dom.client.HasClickHandlers; public interface StockWatcherPresenter extends Presenter<StockWatcherPresenter.Display> { public interface Display extends com.google.gwt.sample.stockwatcher.client.view.Display { /** * Get the Remove button for <code>symbol<code>. */ HasClickHandlers getRemoveButton(String symbol); HasClickHandlers getBuyButton(String symbol); /** * Add new Row that has the <code>symbol<code> into Table */ void addNewRow(String symbol); /** * Remove the Row that has the <code>symbol<code> in the Table */ void removeRow(String symbol); /** * Get price of current row. */ String getPrice(String symbol); /** * TODO: Add a single API to update Price and ChangePercentage. */ void updateChangePercent(int row, double change, double changePercent); void updatePrice(int row, double value); void addNewBuyingHistory(String symbol, String price, String count); void setPresenter(StockWatcherPresenter presenter); } // void refreshWatchList(); // void refreshBuyingHistory(); void onAddButtonClicked(String value); void onInputBoxEnterKeyPressed(String value); }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; import com.google.gwt.sample.stockwatcher.client.view.Display; /** * Presenter Interface. */ public interface Presenter<D extends Display> { void bind(); D getDisplay(); }
Java
package com.google.gwt.sample.stockwatcher.client.presenter; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEvent; import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync; import com.google.gwt.sample.stockwatcher.client.shared.StockBuy; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; public class BuyStockPresenterImpl extends BasePresenter<BuyStockPresenter.Display> implements BuyStockPresenter { private StockPriceServiceAsync rpcService; private StockPrice stockPrice; public BuyStockPresenterImpl(StockPriceServiceAsync rpcService, HandlerManager eventBus, Display view, StockPrice stockPrice) { super(eventBus, view); this.rpcService = rpcService; this.stockPrice = stockPrice; displayValue(stockPrice); } private void displayValue(StockPrice stockPrice) { display.displaySymbol(stockPrice.getSymbol()); display.displayPrice(String.valueOf(stockPrice.getPrice())); } @Override public void onCancelButtonClicked() { eventBus.fireEvent(new ShowStockWaterEvent()); } @Override public void onSaveButtonClicked(Long amount) { StockBuy stockBuy = new StockBuy(this.stockPrice.getSymbol(), this.stockPrice.getPrice(), amount); rpcService.buyStock(stockBuy, new AsyncCallback<StockBuy>() { @Override public void onSuccess(StockBuy result) { eventBus.fireEvent(new ShowStockWaterEvent()); } @Override public void onFailure(Throwable caught) { Window.alert(caught.getMessage()); } }); } @Override protected void onBind() { } }
Java
package com.google.gwt.sample.stockwatcher.client.view; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenter; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; /** * */ public class StockWatcherView extends Composite implements StockWatcherPresenter.Display { /** * FlexTable is used when you have content added/removed dynamically - which * means you won't be adding stuff via UiBinder templates (that doesn't even * makes sense). */ @UiField FlexTable stocksFlexTable = new FlexTable(); @UiField FlexTable buyingHistory = new FlexTable(); @UiField TextBox newSymbolTextBox; @UiField Button addButton; private StockWatcherPresenter presenter; @UiTemplate("StockWatcherView.ui.xml") interface StockWatcherViewUiBinder extends UiBinder<Widget, StockWatcherView> { } private static StockWatcherViewUiBinder uiBinder = GWT .create(StockWatcherViewUiBinder.class); public StockWatcherView() { initWidget(uiBinder.createAndBindUi(this)); buildStocksTable(); buildBuyingHistoryTable(); // this.newSymbolTextBox.setFocus(true); } private void buildBuyingHistoryTable() { buyingHistory.setText(0, 0, "Symbol"); buyingHistory.setText(0, 1, "Price"); buyingHistory.setText(0, 2, "Count"); // stocksFlexTable.setCellPadding(6); buyingHistory.getRowFormatter().addStyleName(0, "watchListHeader"); buyingHistory.addStyleName("watchList"); buyingHistory.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn"); buyingHistory.getCellFormatter().addStyleName(0, 2, "watchListNumericColumn"); } private void buildStocksTable() { // Create table for stock data. stocksFlexTable.setText(0, 0, "Symbol"); stocksFlexTable.setText(0, 1, "Price"); stocksFlexTable.setText(0, 2, "Change"); stocksFlexTable.setText(0, 3, "Remove"); stocksFlexTable.setText(0, 4, "Buy"); // Add styles to elements in the stock list table. stocksFlexTable.setCellPadding(6); stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader"); stocksFlexTable.addStyleName("watchList"); stocksFlexTable.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn"); stocksFlexTable.getCellFormatter().addStyleName(0, 2, "watchListNumericColumn"); stocksFlexTable.getCellFormatter().addStyleName(0, 3, "watchListButtonColumn"); stocksFlexTable.getCellFormatter().addStyleName(0, 4, "watchListButtonColumn"); } @UiHandler("addButton") void onAddButtonClicked(ClickEvent event) { if (presenter != null) { presenter.onAddButtonClicked(newSymbolTextBox.getValue()); } } @UiHandler("newSymbolTextBox") void onInputBoxEnterKeyPressed(KeyPressEvent event) { if (presenter != null && event.getCharCode() == KeyCodes.KEY_ENTER) { presenter.onInputBoxEnterKeyPressed(newSymbolTextBox.getValue()); } } // ============================================== // ========================= Override // ============================================== @Override public void setPresenter(StockWatcherPresenter presenter) { this.presenter = presenter; } @Override public Widget asWidget() { return this; } @Override public HasClickHandlers getRemoveButton(String symbol) { return (HasClickHandlers) stocksFlexTable.getWidget( findRowNumberOfSymbol(symbol), 3); } @Override public HasClickHandlers getBuyButton(String symbol) { return (HasClickHandlers) stocksFlexTable.getWidget( findRowNumberOfSymbol(symbol), 4); } @Override public void updatePrice(int row, double value) { String priceText = NumberFormat.getFormat("#,##0.00").format(value); stocksFlexTable.setText(row, 1, priceText); } @Override public String getPrice(String symbol) { return stocksFlexTable.getText(findRowNumberOfSymbol(symbol), 1); } @Override public void updateChangePercent(int row, double change, double changePercent) { NumberFormat changeFormat = NumberFormat .getFormat("+#,##0.00;-#,##0.00"); String changeText = changeFormat.format(change); String changePercentText = changeFormat.format(changePercent); Label changeWidget = (Label) stocksFlexTable.getWidget(row, 2); changeWidget.setText(changeText + " (" + changePercentText + "%)"); String changeStyleName = "noChange"; if (changePercent < -0.1f) { changeStyleName = "negativeChange"; } else if (changePercent > 0.1f) { changeStyleName = "positiveChange"; } changeWidget.setStyleName(changeStyleName); } @Override public void addNewRow(String symbol) { int row = stocksFlexTable.getRowCount(); stocksFlexTable.setText(row, 0, symbol); stocksFlexTable.setWidget(row, 2, new Label()); stocksFlexTable.getCellFormatter().addStyleName(row, 1, "watchListNumericColumn"); stocksFlexTable.getCellFormatter().addStyleName(row, 2, "watchListNumericColumn"); stocksFlexTable.getCellFormatter().addStyleName(row, 3, "watchListRemoveColumn"); Button removeStockButton = new Button("x"); removeStockButton.addStyleDependentName("remove"); stocksFlexTable.setWidget(row, 3, removeStockButton); Button buyButton = new Button("$"); buyButton.addStyleDependentName("Buy"); stocksFlexTable.setWidget(row, 4, buyButton); this.newSymbolTextBox.setText(""); } @Override public void addNewBuyingHistory(String symbol, String price, String count) { buyingHistory.clear(); int row = buyingHistory.getRowCount(); buyingHistory.setText(row, 0, symbol); buyingHistory.setText(row, 1, price); buyingHistory.setText(row, 2, count); } @Override public void removeRow(String symbol) { stocksFlexTable.removeRow(findRowNumberOfSymbol(symbol)); } private int findRowNumberOfSymbol(String symbol) { for (int row = 1; row < stocksFlexTable.getRowCount(); row++) { if (this.stocksFlexTable.getText(row, 0).equals(symbol)) { return row; } } return 0; } }
Java
package com.google.gwt.sample.stockwatcher.client.view; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenter; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; public class BuyStockView extends Composite implements BuyStockPresenter.Display { @UiTemplate("BuyStockView.ui.xml") interface BuyStockViewUiBinder extends UiBinder<DecoratorPanel, BuyStockView> { } private static BuyStockViewUiBinder uiBinder = GWT .create(BuyStockViewUiBinder.class); @UiField TextBox symbol; @UiField TextBox price; @UiField TextBox amount; @UiField Button saveButton; @UiField Button cancelButton; private BuyStockPresenter presenter; public BuyStockView() { initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("saveButton") void onSaveButtonClicked(ClickEvent event) { if (presenter != null) { presenter.onSaveButtonClicked(Long.valueOf(amount.getValue())); } } @UiHandler("cancelButton") void onCancelButtonClicked(ClickEvent event) { if (presenter != null) { presenter.onCancelButtonClicked(); } } @Override public void setPresenter(BuyStockPresenter presenter) { this.presenter = presenter; } @Override public Widget asWidget() { return this; } @Override public void displaySymbol(String value) { symbol.setText(value); } @Override public void displayPrice(String price) { this.price.setText(price); } }
Java
package com.google.gwt.sample.stockwatcher.client.view; import com.google.gwt.user.client.ui.Widget; public interface Display { Widget asWidget(); }
Java
package com.google.gwt.sample.stockwatcher.client.shared; import java.io.Serializable; public class StockPrice implements Serializable { /** */ private static final long serialVersionUID = 8040259246828316386L; private String symbol; private double price; private double change; public StockPrice() { } public StockPrice(String symbol, double price, double change) { this.symbol = symbol; this.price = price; this.change = change; } public StockPrice(String symbol, double price) { this.symbol = symbol; this.price = price; } public String getSymbol() { return this.symbol; } public double getPrice() { return this.price; } public double getChange() { return this.change; } public double getChangePercent() { return 100.0 * this.change / this.price; } public void setSymbol(String symbol) { this.symbol = symbol; } public void setPrice(double price) { this.price = price; } public void setChange(double change) { this.change = change; } }
Java
package com.google.gwt.sample.stockwatcher.client.shared; import java.io.Serializable; public class StockBuy implements Serializable { /** */ private static final long serialVersionUID = -5423954446375892903L; private String symbol; private Double price; private Long count; public StockBuy() { } public StockBuy(String symbol, Double price, Long count) { this.symbol = symbol; this.price = price; this.count = count; } public String getSymbol() { return this.symbol; } public double getPrice() { return this.price; } public long getCount() { return count; } }
Java
package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.sample.stockwatcher.client.event.BuyStockEvent; import com.google.gwt.sample.stockwatcher.client.event.BuyStockEventHandler; import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEvent; import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEventHandler; import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenter; import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenterImpl; import com.google.gwt.sample.stockwatcher.client.presenter.Presenter; import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenter; import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenterImpl; import com.google.gwt.sample.stockwatcher.client.service.StockPriceService; import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync; import com.google.gwt.sample.stockwatcher.client.view.BuyStockView; import com.google.gwt.sample.stockwatcher.client.view.Display; import com.google.gwt.sample.stockwatcher.client.view.StockWatcherView; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.RootPanel; public class StockWatcherMVP implements EntryPoint { private StockPriceServiceAsync stockPriceSvc = GWT .create(StockPriceService.class); private static HandlerManager eventBus = new HandlerManager(null); /** * Entry point method. */ public void onModuleLoad() { bind(); openStockWater(); } private void openStockWater() { StockWatcherView view = new StockWatcherView(); StockWatcherPresenter presenter = new StockWatcherPresenterImpl(stockPriceSvc, eventBus, view); presenter.bind(); view.setPresenter(presenter); displayView(presenter, RootPanel.get("stockList")); } private void displayView(Presenter<? extends Display> presenter, HasWidgets container) { container.clear(); container.add(presenter.getDisplay().asWidget()); } private void bind() { eventBus.addHandler(BuyStockEvent.TYPE, new BuyStockEventHandler() { @Override public void onBuyStock(BuyStockEvent event) { BuyStockView view = new BuyStockView(); BuyStockPresenter presenter = new BuyStockPresenterImpl( stockPriceSvc, eventBus, view, event.getStockPrice()); presenter.bind(); view.setPresenter(presenter); displayView(presenter, RootPanel.get("stockList")); } }); eventBus.addHandler(ShowStockWaterEvent.TYPE, new ShowStockWaterEventHandler() { @Override public void onShowStockWater(ShowStockWaterEvent event) { openStockWater(); } }); } }
Java
package com.google.gwt.sample.stockwatcher.client.event; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; public class BuyStockEvent extends GwtEvent<BuyStockEventHandler> { private StockPrice stockPrice; public BuyStockEvent(StockPrice stockPrice) { super(); this.stockPrice = stockPrice; } public static Type<BuyStockEventHandler> TYPE = new Type<BuyStockEventHandler>(); @Override protected void dispatch(BuyStockEventHandler handler) { handler.onBuyStock(this); } @Override public com.google.gwt.event.shared.GwtEvent.Type<BuyStockEventHandler> getAssociatedType() { // TODO Auto-generated method stub return TYPE; } public StockPrice getStockPrice() { return stockPrice; } }
Java
package com.google.gwt.sample.stockwatcher.client.event; import com.google.gwt.event.shared.EventHandler; public interface BuyStockEventHandler extends EventHandler { void onBuyStock(BuyStockEvent event); }
Java
package com.google.gwt.sample.stockwatcher.client.event; import com.google.gwt.event.shared.GwtEvent; public class ShowStockWaterEvent extends GwtEvent<ShowStockWaterEventHandler> { public ShowStockWaterEvent() { super(); } public static Type<ShowStockWaterEventHandler> TYPE = new Type<ShowStockWaterEventHandler>(); @Override protected void dispatch(ShowStockWaterEventHandler handler) { handler.onShowStockWater(this); } @Override public com.google.gwt.event.shared.GwtEvent.Type<ShowStockWaterEventHandler> getAssociatedType() { // TODO Auto-generated method stub return TYPE; } }
Java
package com.google.gwt.sample.stockwatcher.client.event; import com.google.gwt.event.shared.EventHandler; public interface ShowStockWaterEventHandler extends EventHandler { void onShowStockWater(ShowStockWaterEvent event); }
Java
package com.google.gwt.sample.stockwatcher.server; import java.util.LinkedList; import java.util.List; import java.util.Random; import com.google.gwt.sample.stockwatcher.client.service.StockPriceService; import com.google.gwt.sample.stockwatcher.client.shared.StockBuy; import com.google.gwt.sample.stockwatcher.client.shared.StockPrice; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class StockPriceServiceImpl extends RemoteServiceServlet implements StockPriceService { /** */ private static final long serialVersionUID = 155669477848585224L; private static final double MAX_PRICE = 100.0; // $100.00 private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2% private static List<StockBuy> buyingHistory = new LinkedList<StockBuy>(); @Override public StockPrice[] getPrices(List<String> symbols) { Random rnd = new Random(); StockPrice[] prices = new StockPrice[symbols.size()]; for (int i = 0; i < symbols.size(); i++) { double price = rnd.nextDouble() * MAX_PRICE; double change = price * MAX_PRICE_CHANGE * (rnd.nextDouble() * 2f - 1f); prices[i] = new StockPrice(symbols.get(i), price, change); } return prices; } // ===================================================== @Override public StockBuy buyStock(StockBuy stockBuy) { buyingHistory.add(stockBuy); return stockBuy; } @Override public List<StockBuy> getStockBuyingHistory() { return buyingHistory; } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.TextView; /** * A dialog-like floating activity * @author Kevin Yuan * */ public class Floating extends Activity { private static final int[] BUTTONS = {R.id.button1, R.id.button2, R.id.button3}; private View mView; private ViewGroup mContentViewContainer; private Content mContent; @Override public void onCreate(Bundle savedInstanceState) { // It will not work if we setTheme here. // Please add android:theme="@android:style/Theme.Dialog" to any descendant class in AndroidManifest.xml! // See http://code.google.com/p/android/issues/detail?id=4394 // setTheme(android.R.style.Theme_Dialog); getWindow().requestFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); mView = View.inflate(this, R.layout.floating, null); final DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); mView.setMinimumWidth(Math.min(dm.widthPixels, dm.heightPixels) - 20); setContentView(mView); mContentViewContainer = (ViewGroup) mView.findViewById(R.id.content); } private void setDialogContentView(final View contentView) { mContentViewContainer.removeAllViews(); mContentViewContainer.addView(contentView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } public void setContent(Content content) { mContent = content; refreshContent(); } public void refreshContent() { setDialogContentView(mContent.getView()); ((TextView)findViewById(R.id.title)).setText(mContent.getTitle()); final int btnCount = mContent.getButtonCount(); if(btnCount > BUTTONS.length) { throw new RuntimeException(String.format("%d exceeds maximum button count: %d!", btnCount, BUTTONS.length)); } findViewById(R.id.buttons_view).setVisibility(btnCount > 0 ? View.VISIBLE : View.GONE); for(int buttonId:BUTTONS) { final Button btn = (Button) findViewById(buttonId); btn.setOnClickListener(null); btn.setVisibility(View.GONE); } for(int btnIndex = 0; btnIndex < btnCount; btnIndex++){ final Button btn = (Button)findViewById(BUTTONS[btnIndex]); btn.setText(mContent.getButtonText(btnIndex)); btn.setVisibility(View.VISIBLE); btn.setOnClickListener(mContent.getButtonOnClickListener(btnIndex)); } } public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if(mContent != null) { mContent.onCreateContextMenu(menu, v, menuInfo); } } public boolean onContextItemSelected (MenuItem item) { if(mContent != null) { return mContent.onContextItemSelected(item); } return false; } public interface Content { CharSequence getTitle(); View getView(); int getButtonCount(); CharSequence getButtonText(int index); OnClickListener getButtonOnClickListener(int index); void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo); boolean onContextItemSelected (MenuItem item); } }
Java
package com.farproc.wifi.connecter; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.AuthAlgorithm; import android.net.wifi.WifiConfiguration.GroupCipher; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiConfiguration.PairwiseCipher; import android.net.wifi.WifiConfiguration.Protocol; import android.text.TextUtils; import android.util.Log; public class ConfigurationSecuritiesOld extends ConfigurationSecurities { // Constants used for different security types public static final String WPA2 = "WPA2"; public static final String WPA = "WPA"; public static final String WEP = "WEP"; public static final String OPEN = "Open"; // For EAP Enterprise fields public static final String WPA_EAP = "WPA-EAP"; public static final String IEEE8021X = "IEEE8021X"; public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" }; public static final int WEP_PASSWORD_AUTO = 0; public static final int WEP_PASSWORD_ASCII = 1; public static final int WEP_PASSWORD_HEX = 2; static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X }; private static final String TAG = "ConfigurationSecuritiesOld"; @Override public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) { // If we never set group ciphers, wpa_supplicant puts all of them. // For open, we don't set group ciphers. // For WEP, we specifically only set WEP40 and WEP104, so CCMP // and TKIP should not be there. if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP) && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40) || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) { return WEP; } else { return OPEN; } } else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) { return WPA2; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP)) { return WPA_EAP; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return IEEE8021X; } else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) { return WPA; } else { Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open."); return OPEN; } } @Override public String getScanResultSecurity(ScanResult scanResult) { final String cap = scanResult.capabilities; for (int i = SECURITY_MODES.length - 1; i >= 0; i--) { if (cap.contains(SECURITY_MODES[i])) { return SECURITY_MODES[i]; } } return OPEN; } @Override public String getDisplaySecirityString(final ScanResult scanResult) { return getScanResultSecurity(scanResult); } private static boolean isHexWepKey(String wepKey) { final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } private static boolean isHex(String key) { for (int i = key.length() - 1; i >= 0; i--) { final char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; } @Override public void setupSecurity(WifiConfiguration config, String security, final String password) { config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); if (TextUtils.isEmpty(security)) { security = OPEN; Log.w(TAG, "Empty security, assuming open"); } if (security.equals(WEP)) { int wepPasswordType = WEP_PASSWORD_AUTO; // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (wepPasswordType == WEP_PASSWORD_AUTO) { if (isHexWepKey(password)) { config.wepKeys[0] = password; } else { config.wepKeys[0] = Wifi.convertToQuotedString(password); } } else { config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII ? Wifi.convertToQuotedString(password) : password; } } config.wepTxKeyIndex = 0; config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedGroupCiphers.set(GroupCipher.WEP40); config.allowedGroupCiphers.set(GroupCipher.WEP104); } else if (security.equals(WPA) || security.equals(WPA2)){ config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP); config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP); config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA); // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (password.length() == 64 && isHex(password)) { // Goes unquoted as hex config.preSharedKey = password; } else { // Goes quoted as ASCII config.preSharedKey = Wifi.convertToQuotedString(password); } } } else if (security.equals(OPEN)) { config.allowedKeyManagement.set(KeyMgmt.NONE); } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) { config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); if (security.equals(WPA_EAP)) { config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); } else { config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); } if (!TextUtils.isEmpty(password)) { config.preSharedKey = Wifi.convertToQuotedString(password); } } } @Override public boolean isOpenNetwork(String security) { return OPEN.equals(security); } }
Java
End of preview. Expand in Data Studio

Java-Code-Large

Java-Code-Large is a large-scale corpus of publicly available Java source code comprising more than 15 million java codes. The dataset is designed to support research in large language model (LLM) pretraining, code intelligence, software engineering automation, and program analysis.

By providing a high-volume, language-specific corpus, Java-Code-Large enables systematic experimentation in Java-focused model training, domain adaptation, and downstream code understanding tasks.

1. Introduction

Large-scale code corpora have become fundamental resources for training and evaluating machine learning models for code-related tasks. While multilingual code datasets exist, there is increasing interest in language-specialized corpora to:

  • Improve domain-specific performance

  • Reduce cross-language noise

  • Enable controlled experimental settings

  • Support Java-specific tooling and research

Java-Code-Large addresses this need by providing a dedicated Java-only dataset at substantial scale.

2. Dataset Composition

Programming Language: Java

File Count: 15M+ Java files

File Format: .jsonl

Content Types:

  • Classes

  • Interfaces

  • Enums

  • Methods

  • Annotations

  • JavaDoc comments

  • Exception handling structures

  • Generics and concurrency constructs

The dataset consists of source code extracted from publicly accessible open-source repositories.

3. Intended Research Applications

3.1 Pretraining

  • Training code foundation models from scratch

  • Continued pretraining of existing LLMs

  • Java-specialized language modeling

3.2 Fine-Tuning and Adaptation

  • Code completion systems

  • Automated refactoring tools

  • IDE copilots

  • Java-specific conversational assistants

3.3 Code Intelligence Tasks

  • Code summarization

  • Code-to-text generation

  • Bug detection

  • Vulnerability detection

  • Clone detection

  • Code similarity modeling

  • Static and structural analysis

3.4 Software Engineering Research

  • Empirical studies of Java programming patterns

  • Tokenization and AST modeling experiments

Thanks to open source community for all the guidance & support!!

Downloads last month
-