code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package net.telematics; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Tuple; import java.util.Map; public class CriticalSeverityBolt extends BaseRichBolt { private OutputCollector collector; @Override public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = collector; } @Override public void execute(Tuple tuple) { // output of critical streams only //System.out.println("entering the criticalSeverityBolt.execute()"); int number = tuple.getInteger(0); String severity = tuple.getString(2); if (tuple.getString(2).contains("Critical")) { System.out.println("CRITICAL!!! - the number is:" + number + " severity is:" + severity); } // since I am not emitting anything // the tuple below is null //collector.ack(tuple); } @Override public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { // nothing here because I am not sending to another bolt } }
DavidNovo/storm-simple
src/main/java/net/novogrodsky/CriticalSeverityBolt.java
Java
gpl-2.0
1,248
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jintangible; import no.uib.cipr.matrix.*; import java.text.*; import java.io.*; import java.util.*; /** * * @author grouptheory */ public class AllProxies { public static String DIR = "analysis/"; protected static String OUTNAME(int numvars, int numobjs, int numtimes) { NumberFormat FORMAT = new DecimalFormat("0.00"); String s= AllProxies.DIR+"out-analysis-n="+numobjs+"-m="+numtimes+"-l="+numvars+".dat"; return s; } private static CSVLoader.ProxyTable loadVariableFile(String infile, boolean verbose, FileWriter LOG) { CSVLoader.ProxyTable pt = null; try { pt = CSVLoader.ReadProxyCSV(infile, verbose, LOG); try { LOG.write("Processed valid proxy file "+infile+".\n"); LOG.flush(); } catch (IOException ex2) { } } catch (IOException ex) { try { LOG.write("Did not find valid proxy file "+infile+".\n"); LOG.flush(); } catch (IOException ex2) { } } return pt; } private static CSVLoader.ProxyTable loadTangibleLHSFile(FileWriter LOG) { String infile = AllProxies.DIR+"in-lhs-tangible.csv"; return loadVariableFile(infile, true, LOG); } private static CSVLoader.ProxyTable loadOneProxyVariableFile(int k, FileWriter LOG) { String infile = AllProxies.DIR+"in-rhs-intangible-proxy-"+k+".csv"; return loadVariableFile(infile, false, LOG); } protected static final HashMap loadAllVariableProxyFiles(int numvars, FileWriter LOG) { HashMap var2pt = new HashMap(); for (int k=0; k<numvars; k++) { CSVLoader.ProxyTable pt = loadOneProxyVariableFile(k, LOG); if (pt != null) var2pt.put(k, pt); } return var2pt; } /** * @param args the command line arguments */ public static void main(String[] args) { int numobjs = 7; int numtimes = 3; int numprops = 3; InstanceSpec spec = new InstanceSpec(numprops, numobjs, numtimes); // open the log FileWriter LOG = Main.openFile("log.txt"); FileWriter OUT = Main.openFile( OUTNAME(numprops, numobjs, numtimes)); Equations eqn = new Equations(spec.NumObjs(), spec.NumTimes(), spec.NumProps()); HashMap var2pt = loadAllVariableProxyFiles(spec.NumProps(), LOG); //------------------------------------- CSVLoader.ProxyTable zproxy = setupViaProxies(spec, eqn, var2pt, LOG); prepareLinearAlgebraSystem(spec, eqn, var2pt, 0, LOG); solve(spec, eqn, var2pt, LOG); //------------------------------------- // close the log, output Main.closeFile(OUT); Main.closeFile(LOG); } static protected final CSVLoader.ProxyTable setupViaProxies(InstanceSpec spec, Equations eqn, HashMap var2pt, FileWriter LOG) { CSVLoader.ProxyTable zproxy = loadTangibleLHSFile(LOG); if (zproxy == null) { try { LOG.write("Unable to set LHS tangible values!\n"); LOG.flush(); } catch (IOException ex2) { } } else { try { LOG.write("Setting LHS tangible values.\n"); LOG.flush(); } catch (IOException ex2) { } for (int i=0;i<spec.NumObjs();i++) { String ci = zproxy.get_ci(i); for (int j=0;j<spec.NumTimes();j++) { String tj = zproxy.get_tj(j); double val = zproxy.get(ci, tj); eqn.setZ(i, j, val); } } } for (int k=0;k<spec.NumProps();k++) { if (!var2pt.containsKey(k)) { try { LOG.write("Did not use proxy variable to set alphas/betas for intangible "+k+".\n"); LOG.flush(); continue; } catch (IOException ex2) { } } CSVLoader.ProxyTable xproxy = (CSVLoader.ProxyTable)var2pt.get(k); try { LOG.write("Used proxy variable to set alphas/betas for intangible "+k+": "+xproxy.name()+".\n"); LOG.flush(); } catch (IOException ex2) { } // init alpha for (int i=1; i<spec.NumObjs(); i++) { double v = 0.0; double num = xproxy.get(xproxy.get_ci(0),xproxy.get_tj(0)); double den = xproxy.get(xproxy.get_ci(i),xproxy.get_tj(0)); v = num/den; String ci = xproxy.get_ci(i); int imapped = -1; try { imapped = zproxy.get_objectInd(ci); } catch (Exception ex) { System.out.println("prop="+k); System.out.println("obj="+i); } eqn.setalpha(k, imapped, v); } // init beta for (int i=0; i<spec.NumObjs(); i++) { for (int j=1; j<spec.NumTimes(); j++) { double v = 0.0; double num = xproxy.get(xproxy.get_ci(i),xproxy.get_tj(0)); double den = xproxy.get(xproxy.get_ci(i),xproxy.get_tj(j)); v = num/den; String ci = xproxy.get_ci(i); int imapped = zproxy.get_objectInd(ci); String tj = xproxy.get_tj(j); int jmapped = zproxy.get_timeInd(tj); eqn.setbeta(k, imapped, jmapped, v); } } } return zproxy; } static protected MatrixSolver TheMatrixSolver; static protected DenseVector TheVector; static protected final void prepareLinearAlgebraSystem(InstanceSpec spec, Equations eqn, HashMap var2pt, int maxAuxRatios, FileWriter LOG) { try { LOG.write("\n\nConstraint system derived from proxies:\n"); LOG.flush(); eqn.printsystem(LOG); TheMatrixSolver = new MatrixSolver(spec, eqn, maxAuxRatios, LOG); } catch (IOException e) { e.printStackTrace(); } } static protected final void solve(InstanceSpec spec, Equations eqn, HashMap var2pt, FileWriter LOG) { try { TheVector = TheMatrixSolver.solve(spec, true, LOG); LOG.write("\n\nSolution via pseudo-inverses:\n"); for (int k=0;k<spec.NumProps();k++) { if (var2pt.containsKey(k)) { CSVLoader.ProxyTable xproxy = (CSVLoader.ProxyTable)var2pt.get(k); for (int i=0; i<spec.NumObjs(); i++) { for (int j=0; j<spec.NumTimes(); j++) { int index = spec.index_val(k, i, j); double val=TheVector.get(index); String ci = xproxy.get_ci(i); String tj = xproxy.get_tj(j); LOG.write(""+xproxy.name()+"("+ci+","+tj+") = "+val+"\n"); } } } } } catch (IOException e) { e.printStackTrace(); } } }
grouptheory/EPIC
src/jintangible/AllProxies.java
Java
gpl-2.0
7,550
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene; /** Builder class for javafx.scene.SnapshotParameters @see javafx.scene.SnapshotParameters @deprecated This class is deprecated and will be removed in the next version * @since JavaFX 2.2 */ @javax.annotation.Generated("Generated by javafx.builder.processor.BuilderProcessor") @Deprecated public class SnapshotParametersBuilder<B extends javafx.scene.SnapshotParametersBuilder<B>> implements javafx.util.Builder<javafx.scene.SnapshotParameters> { protected SnapshotParametersBuilder() { } /** Creates a new instance of SnapshotParametersBuilder. */ @SuppressWarnings({"deprecation", "rawtypes", "unchecked"}) public static javafx.scene.SnapshotParametersBuilder<?> create() { return new javafx.scene.SnapshotParametersBuilder(); } private int __set; public void applyTo(javafx.scene.SnapshotParameters x) { int set = __set; if ((set & (1 << 0)) != 0) x.setCamera(this.camera); if ((set & (1 << 1)) != 0) x.setDepthBuffer(this.depthBuffer); if ((set & (1 << 2)) != 0) x.setFill(this.fill); if ((set & (1 << 3)) != 0) x.setTransform(this.transform); if ((set & (1 << 4)) != 0) x.setViewport(this.viewport); } private javafx.scene.Camera camera; /** Set the value of the {@link javafx.scene.SnapshotParameters#getCamera() camera} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B camera(javafx.scene.Camera x) { this.camera = x; __set |= 1 << 0; return (B) this; } private boolean depthBuffer; /** Set the value of the {@link javafx.scene.SnapshotParameters#isDepthBuffer() depthBuffer} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B depthBuffer(boolean x) { this.depthBuffer = x; __set |= 1 << 1; return (B) this; } private javafx.scene.paint.Paint fill; /** Set the value of the {@link javafx.scene.SnapshotParameters#getFill() fill} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B fill(javafx.scene.paint.Paint x) { this.fill = x; __set |= 1 << 2; return (B) this; } private javafx.scene.transform.Transform transform; /** Set the value of the {@link javafx.scene.SnapshotParameters#getTransform() transform} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B transform(javafx.scene.transform.Transform x) { this.transform = x; __set |= 1 << 3; return (B) this; } private javafx.geometry.Rectangle2D viewport; /** Set the value of the {@link javafx.scene.SnapshotParameters#getViewport() viewport} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B viewport(javafx.geometry.Rectangle2D x) { this.viewport = x; __set |= 1 << 4; return (B) this; } /** Make an instance of {@link javafx.scene.SnapshotParameters} based on the properties set on this builder. */ public javafx.scene.SnapshotParameters build() { javafx.scene.SnapshotParameters x = new javafx.scene.SnapshotParameters(); applyTo(x); return x; } }
maiklos-mirrors/jfx78
modules/builders/src/main/java/javafx/scene/SnapshotParametersBuilder.java
Java
gpl-2.0
4,744
/** * */ package word_java; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * @author adalberto * */ public class EditWord { /** * */ public EditWord() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { File doc = new File("FBolo.doc"); FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(doc); BufferedInputStream buffInputStream = new BufferedInputStream(fileInputStream); HWPFDocument word = new HWPFDocument(new POIFSFileSystem(buffInputStream)); Range range = word.getRange(); range.replaceText("<@activitat>", "Activitat Alex"); range.replaceText("<@compañia>", "Compañia Alex"); OutputStream output = new FileOutputStream("resultado.doc"); output.flush(); word.write(output); output.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
AdalbertoJoseToledoEscalona/catalogo_productos_old_version
web/workspace/Test/src/word_java/EditWord.java
Java
gpl-2.0
1,379
/* * Copyright (C) 2005-2009 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC Remote; see the file license. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ package org.xbmc.android.remote.business.provider; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.content.res.Resources; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; public class HostProvider extends ContentProvider { private static final String TAG = "HostProvider"; public static final String AUTHORITY = "org.xbmc.android.provider.remote"; private static final int DATABASE_VERSION = 4; private static final String DATABASE_NAME = "xbmc_hosts.db"; private static final String HOSTS_TABLE_NAME = "hosts"; private static HashMap<String, String> sHostsProjectionMap; private static final int HOSTS = 1; private static final int HOST_ID = 2; private static final UriMatcher sUriMatcher; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + HOSTS_TABLE_NAME + " (" + Hosts._ID + " INTEGER PRIMARY KEY," + Hosts.NAME + " TEXT," + Hosts.ADDR + " TEXT," + Hosts.PORT + " INTEGER," + Hosts.USER + " TEXT," + Hosts.PASS + " TEXT," + Hosts.ESPORT + " INTEGER," + Hosts.TIMEOUT + " INTEGER," + Hosts.WIFI_ONLY + " INTEGER," + Hosts.ACCESS_POINT + " TEXT," + Hosts.MAC_ADDR + " TEXT," + Hosts.WOL_PORT + " INTEGER," + Hosts.WOL_WAIT + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String altertable; switch (oldVersion) { case 2: Log.d(TAG, "Upgrading database from version 2 to 3"); altertable = "ALTER TABLE " + HOSTS_TABLE_NAME + " ADD COLUMN " + Hosts.WIFI_ONLY + " INTEGER DEFAULT 0;"; db.execSQL(altertable); Log.d(TAG, "executed: " + altertable); altertable = "ALTER TABLE " + HOSTS_TABLE_NAME + " ADD COLUMN " + Hosts.ACCESS_POINT + " TEXT;"; db.execSQL(altertable); Log.d(TAG, "executed: " + altertable); altertable = "ALTER TABLE " + HOSTS_TABLE_NAME + " ADD COLUMN " + Hosts.MAC_ADDR + " TEXT;"; db.execSQL(altertable); Log.d(TAG, "executed: " + altertable); case 3: Log.d(TAG, "Upgrading database from version 3 to 4"); altertable = "ALTER TABLE " + HOSTS_TABLE_NAME + " ADD COLUMN " + Hosts.WOL_PORT + " INTEGER;"; db.execSQL(altertable); Log.d(TAG, "executed: " + altertable); altertable = "ALTER TABLE " + HOSTS_TABLE_NAME + " ADD COLUMN " + Hosts.WOL_WAIT + " INTEGER;"; db.execSQL(altertable); Log.d(TAG, "executed: " + altertable); //WARNING!!! ADD A break; BEFORE THE DEFAULT BLOCK OF THE DATABASE WILL BE DROPPED!!! break; default: Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + HOSTS_TABLE_NAME); onCreate(db); } } } private DatabaseHelper mOpenHelper; @Override public boolean onCreate() { mOpenHelper = new DatabaseHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch (sUriMatcher.match(uri)) { case HOSTS: qb.setTables(HOSTS_TABLE_NAME); qb.setProjectionMap(sHostsProjectionMap); break; case HOST_ID: qb.setTables(HOSTS_TABLE_NAME); qb.setProjectionMap(sHostsProjectionMap); qb.appendWhere(Hosts._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy = Hosts.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } // Get the database and run the query SQLiteDatabase db = mOpenHelper.getReadableDatabase(); Log.d(TAG, "SQLite database version: " + db.getVersion()); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); // Tell the cursor what uri to watch, so it knows when its source data // changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case HOSTS: return Hosts.CONTENT_TYPE; case HOST_ID: return Hosts.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != HOSTS) { throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } if (values.containsKey(Hosts.NAME) == false) { Resources r = Resources.getSystem(); values.put(Hosts.NAME, r.getString(android.R.string.untitled)); } if (values.containsKey(Hosts.ADDR) == false) { values.put(Hosts.ADDR, ""); } if (values.containsKey(Hosts.PORT) == false) { values.put(Hosts.PORT, 0); } if (values.containsKey(Hosts.USER) == false) { values.put(Hosts.USER, ""); } if (values.containsKey(Hosts.PASS) == false) { values.put(Hosts.PASS, ""); } if (values.containsKey(Hosts.ESPORT) == false) { values.put(Hosts.ESPORT, 0); } if (values.containsKey(Hosts.TIMEOUT) == false) { values.put(Hosts.TIMEOUT, -1); } if (values.containsKey(Hosts.WIFI_ONLY) == false) { values.put(Hosts.WIFI_ONLY, 0); } if (values.containsKey(Hosts.ACCESS_POINT) == false) { values.put(Hosts.ACCESS_POINT, ""); } if (values.containsKey(Hosts.MAC_ADDR) == false) { values.put(Hosts.MAC_ADDR, ""); } if (values.containsKey(Hosts.WOL_PORT) == false) { values.put(Hosts.WOL_PORT, 0); } if (values.containsKey(Hosts.WOL_WAIT) == false) { values.put(Hosts.WOL_WAIT, 0); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(HOSTS_TABLE_NAME, Hosts.ADDR, values); if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(Hosts.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new SQLException("Failed to insert row into " + uri); } @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case HOSTS: count = db.delete(HOSTS_TABLE_NAME, where, whereArgs); break; case HOST_ID: String hostId = uri.getPathSegments().get(1); count = db.delete(HOSTS_TABLE_NAME, Hosts._ID + "=" + hostId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case HOSTS: count = db.update(HOSTS_TABLE_NAME, values, where, whereArgs); break; case HOST_ID: String hostId = uri.getPathSegments().get(1); count = db.update(HOSTS_TABLE_NAME, values, Hosts._ID + "=" + hostId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, "hosts", HOSTS); sUriMatcher.addURI(AUTHORITY, "hosts/#", HOST_ID); sHostsProjectionMap = new HashMap<String, String>(); sHostsProjectionMap.put(Hosts._ID, Hosts._ID); sHostsProjectionMap.put(Hosts.NAME, Hosts.NAME); sHostsProjectionMap.put(Hosts.ADDR, Hosts.ADDR); sHostsProjectionMap.put(Hosts.PORT, Hosts.PORT); sHostsProjectionMap.put(Hosts.USER, Hosts.USER); sHostsProjectionMap.put(Hosts.PASS, Hosts.PASS); sHostsProjectionMap.put(Hosts.ESPORT, Hosts.ESPORT); sHostsProjectionMap.put(Hosts.TIMEOUT, Hosts.TIMEOUT); sHostsProjectionMap.put(Hosts.WIFI_ONLY, Hosts.WIFI_ONLY); sHostsProjectionMap.put(Hosts.ACCESS_POINT, Hosts.ACCESS_POINT); sHostsProjectionMap.put(Hosts.MAC_ADDR, Hosts.MAC_ADDR); sHostsProjectionMap.put(Hosts.WOL_PORT, Hosts.WOL_PORT); sHostsProjectionMap.put(Hosts.WOL_WAIT, Hosts.WOL_WAIT); } /** * Notes table */ public static final class Hosts implements BaseColumns { // This class cannot be instantiated private Hosts() { } /** * The name of the host (as in label/title) * <P> * Type: TEXT * </P> */ public static final String NAME = "name"; /** * The address or IP of the host * <P> * Type: TEXT * </P> */ public static final String ADDR = "address"; /** * The note itself * <P> * Type: INTEGER * </P> */ public static final String PORT = "http_port"; /** * The user name if HTTP Auth is used * <P> * Type: TEXT * </P> */ public static final String USER = "user"; /** * The password if HTTP Auth is used * <P> * Type: TEXT * </P> */ public static final String PASS = "pass"; /** * The event server port * <P> * Type: INTEGER * </P> */ public static final String ESPORT = "esport"; /** * The socket read timeout in milliseconds * <P> * Type: INTEGER * </P> */ public static final String TIMEOUT = "timeout"; /** * If this connection is for wireless lan only * <P> * Type: BOOLEAN * </P> */ public static final String WIFI_ONLY = "wifi_only"; /** * If WIFI_ONLY is set this may or may not include an access point name * <P> * Type: TEXT * </P> */ public static final String ACCESS_POINT = "access_point"; /** * The MAC address of this host * <P> * Type: TEXT * </P> */ public static final String MAC_ADDR = "mac_addr"; /** * The time in seconds to wait after sending WOL paket * <P> * Type: INTEGER * </P> */ public static final String WOL_WAIT = "wol_wait"; /** * The port the WOL packet should be send to * <P> * Type: INTEGER * </P> */ public static final String WOL_PORT = "wol_port"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + HOSTS_TABLE_NAME); /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.xbmc.host"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single * note. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.xbmc.host"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = NAME + " ASC"; } }
star-app/xbmc-remote-control
src/org/xbmc/android/remote/business/provider/HostProvider.java
Java
gpl-2.0
12,527
package org.bubble.cloud.speech; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import fi.iki.elonen.NanoHTTPD; import org.apache.log4j.xml.DOMConfigurator; import org.bubblecloud.speech.nlpapi.NanoHttpdJsonRpcServer; import org.bubblecloud.speech.nlpapi.NanoHttpdJsonRpcServerResponse; import org.bubblecloud.speech.nlpapi.SpeechNlpApi; import org.bubblecloud.speech.nlpapi.SpeechNlpApiImpl; /** * Speech NPL JSON RPC HTTP server. * * @author Tommi S.E. Laukkanen */ public class SpeechNlpHerokuMain extends NanoHTTPD { /** * The logger. */ final static Logger LOGGER = Logger.getLogger("org.bubble.cloud.speech"); /** * The JSON ROC server. */ private final NanoHttpdJsonRpcServer jsonRpcServer; public static void main(String[] args) { try { DOMConfigurator.configure("log4j.xml"); new SpeechNlpHerokuMain(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error starting Speech NLP JSON RPC HTTP server.", e); } } public SpeechNlpHerokuMain() throws IOException { super(Integer.valueOf(System.getenv("PORT"))); final SpeechNlpApi api = new SpeechNlpApiImpl(); jsonRpcServer = new NanoHttpdJsonRpcServer(api, SpeechNlpApi.class); start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); LOGGER.info("Speech NLP JSON RPC HTTP server started."); } @Override public Response serve(IHTTPSession session) { final NanoHttpdJsonRpcServerResponse response = jsonRpcServer.handle(session); return newFixedLengthResponse(response.getStatus(), "application/json-rpc", response.getMessage()); } }
bubblecloud/speech-nlp-api-heroku
src/main/java/org/bubble/cloud/speech/SpeechNlpHerokuMain.java
Java
gpl-2.0
1,716
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Emil Ong */ package com.caucho.xtpdoc; public class DefunSchema extends Def { public DefunSchema(Defun defun) { super(defun.getDocument()); setTitle(defun.getTitle() + " schema"); } @Override public String getCssClass() { return "reference-schema"; } }
dlitz/resin
modules/webutil/src/com/caucho/xtpdoc/DefunSchema.java
Java
gpl-2.0
1,300
/** * Copyright (C) 2015 Bonitasoft S.A. * Bonitasoft, 32 rue Gustave Eiffel - 38000 Grenoble * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.0 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.web.designer.controller.export; import org.bonitasoft.web.designer.controller.export.steps.ExportStep; import org.bonitasoft.web.designer.model.DesignerArtifact; import org.bonitasoft.web.designer.model.JsonHandler; import org.bonitasoft.web.designer.model.JsonViewPersistence; import org.bonitasoft.web.designer.model.ModelException; import org.bonitasoft.web.designer.model.widget.Widget; import org.bonitasoft.web.designer.service.ArtifactService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.copy; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.bonitasoft.web.designer.controller.export.steps.ExportStep.RESOURCES; public abstract class Exporter<T extends DesignerArtifact> { private static final Logger logger = LoggerFactory.getLogger(Exporter.class); protected final ExportStep<T>[] exportSteps; protected final ArtifactService<T> artifactService; protected JsonHandler jsonHandler; @SafeVarargs protected Exporter(JsonHandler jsonHandler, ArtifactService<T> artifactService, ExportStep<T>... exportSteps) { this.jsonHandler = jsonHandler; this.artifactService = artifactService; this.exportSteps = exportSteps; } protected abstract String getComponentType(); public void handleFileExport(String id, OutputStream stream) throws ModelException, ExportException, IOException { if (isBlank(id)) { throw new IllegalArgumentException("Id is needed to successfully export a component"); } //We can't write directly in response outputstream. When you start to write a message, you can't remove it after the first flush. // If an error occurs you can't prevent a partial file loading. So we need to use a temp stream. ByteArrayOutputStream zipStream; //In the first step the zipStream is created try (var outputStream = new ByteArrayOutputStream(); Zipper zipper = new Zipper(outputStream)) { //The outputStream scope is local in the try-with-resource-block zipStream = outputStream; var identifiable = artifactService.get(id); if (identifiable.getStatus() == null) { identifiable.setStatus(artifactService.getStatus(identifiable)); } if (!identifiable.getStatus().isCompatible()) { var errorMessage = String.format("%s export failed. A newer UI Designer version is required.e", identifiable.getName()); throw new ModelException(errorMessage); } if (identifiable instanceof Widget) { ((Widget) identifiable).prepareWidgetToSerialize(); } final byte[] json = jsonHandler.toJson(identifiable, JsonViewPersistence.class); zipper.addToZip(json, format("%s/%s.json", RESOURCES, getComponentType())); // forceExecution export steps for (ExportStep<T> exporter : exportSteps) { exporter.execute(zipper, identifiable); } } catch (ModelException e) { throw e; } catch (Exception e) { throw new ExportException(format("Technical error on zip creation %s with id %s", getComponentType(), id), e); } //Copy work/zip stream content to response stream (we can't do that in the first block, because the zip has to be closed before to be able to read it) try (var inputStream = new ByteArrayInputStream(zipStream.toByteArray())) { copy(inputStream, stream); } catch (Exception e) { throw new ExportException(format("Technical error when exporting %s with id %s", getComponentType(), id), e); } } }
bonitasoft/bonita-ui-designer
backend/artifact-builder/src/main/java/org/bonitasoft/web/designer/controller/export/Exporter.java
Java
gpl-2.0
4,705
/* * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 3 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 3 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.nodes.unary; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.ControlFlowException; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.r.nodes.builtin.ArgumentFilter; import com.oracle.truffle.r.runtime.data.RMissing; import com.oracle.truffle.r.runtime.data.RNull; import com.oracle.truffle.r.runtime.nodes.unary.CastNode; public abstract class ConditionalMapNode extends CastNode { private final ArgumentFilter<Object, Object> argFilter; private final boolean resultForNull; private final boolean resultForMissing; private final boolean returns; @Child private CastNode trueBranch; @Child private CastNode falseBranch; protected ConditionalMapNode(ArgumentFilter<Object, Object> argFilter, CastNode trueBranch, CastNode falseBranch, boolean resultForNull, boolean resultForMissing, boolean returns) { this.argFilter = argFilter; this.trueBranch = trueBranch; this.falseBranch = falseBranch; this.resultForNull = resultForNull; this.resultForMissing = resultForMissing; this.returns = returns; } public static ConditionalMapNode create(ArgumentFilter<Object, Object> argFilter, CastNode trueBranch, CastNode falseBranch, boolean resultForNull, boolean resultForMissing, boolean returns) { return ConditionalMapNodeGen.create(argFilter, trueBranch, falseBranch, resultForNull, resultForMissing, returns); } private Object executeConditional(boolean isTrue, Object x) { if (isTrue) { Object result = trueBranch == null ? x : trueBranch.execute(x); if (returns) { throw new PipelineReturnException(result); } else { return result; } } else { return falseBranch == null ? x : falseBranch.execute(x); } } @Specialization protected Object executeNull(RNull x) { return executeConditional(resultForNull, x); } @Specialization protected Object executeMissing(RMissing x) { return executeConditional(resultForMissing, x); } @Specialization(guards = {"!isRNull(x)", "!isRMissing(x)"}) protected Object executeRest(Object x, @Cached("createBinaryProfile()") ConditionProfile conditionProfile) { return executeConditional(conditionProfile.profile(argFilter.test(x)), x); } @SuppressWarnings("serial") public final class PipelineReturnException extends ControlFlowException { private final Object result; public PipelineReturnException(Object result) { this.result = result; } public Object getResult() { return result; } } }
graalvm/fastr
com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/unary/ConditionalMapNode.java
Java
gpl-2.0
3,901
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.7 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.gs.ledstrip.ws2812; class Color_t { private long swigCPtr; protected boolean swigCMemOwn; protected Color_t(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(Color_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() { delete(); } synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; ws2812JNI.delete_Color_t(swigCPtr); } swigCPtr = 0; } } void setR(short value) { ws2812JNI.Color_t_r_set(swigCPtr, this, value); } short getR() { return ws2812JNI.Color_t_r_get(swigCPtr, this); } void setG(short value) { ws2812JNI.Color_t_g_set(swigCPtr, this, value); } short getG() { return ws2812JNI.Color_t_g_get(swigCPtr, this); } void setB(short value) { ws2812JNI.Color_t_b_set(swigCPtr, this, value); } short getB() { return ws2812JNI.Color_t_b_get(swigCPtr, this); } Color_t() { this(ws2812JNI.new_Color_t(), true); } }
Mickeyrourkeske/rpi_ws281x_java
src/main/java/com/gs/ledstrip/ws2812/Color_t.java
Java
gpl-2.0
1,408
package POJO; // Generated 19-ago-2015 14:32:50 by Hibernate Tools 3.6.0 import java.util.HashSet; import java.util.Set; /** * DetalleProgramacion generated by hbm2java */ public class DetalleProgramacion implements java.io.Serializable { private Integer idDetalleProgramacion; private Programacion programacion; private ProfesorAsignatura profesorAsignatura; private Set horarios = new HashSet(0); public DetalleProgramacion() { } public DetalleProgramacion(Programacion programacion, ProfesorAsignatura profesorAsignatura, Set horarios) { this.programacion = programacion; this.profesorAsignatura = profesorAsignatura; this.horarios = horarios; } public Integer getIdDetalleProgramacion() { return this.idDetalleProgramacion; } public void setIdDetalleProgramacion(Integer idDetalleProgramacion) { this.idDetalleProgramacion = idDetalleProgramacion; } public Programacion getProgramacion() { return this.programacion; } public void setProgramacion(Programacion programacion) { this.programacion = programacion; } public ProfesorAsignatura getProfesorAsignatura() { return this.profesorAsignatura; } public void setProfesorAsignatura(ProfesorAsignatura profesorAsignatura) { this.profesorAsignatura = profesorAsignatura; } public Set getHorarios() { return this.horarios; } public void setHorarios(Set horarios) { this.horarios = horarios; } }
unscharf/Colegio
Colegio 19-08-15/src/POJO/DetalleProgramacion.java
Java
gpl-2.0
1,570
/** * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ca.sfu.federation.viewer.propertysheet; import ca.sfu.federation.Application; import ca.sfu.federation.ApplicationContext; import ca.sfu.federation.model.Assembly; import ca.sfu.federation.model.INamed; import ca.sfu.federation.model.ParametricModel; import ca.sfu.federation.model.Scenario; import ca.sfu.federation.model.geometry.CoordinateSystem; import ca.sfu.federation.model.geometry.Line; import ca.sfu.federation.model.geometry.Plane; import ca.sfu.federation.model.geometry.Point; import java.util.Observable; import java.util.Observer; import javax.swing.JPanel; /** * Property sheet panel. * @author dmarques */ public class PropertySheetPanel extends javax.swing.JPanel implements Observer { /** * PropertySheetPanel default constructor. */ public PropertySheetPanel() { initComponents(); Application.getContext().addObserver(this); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables /** * Build property sheet. */ private void buildPropertySheet() { INamed named = (INamed) Application.getContext().getViewState(ApplicationContext.VIEWER_SELECTION); JPanel panel = null; if (named instanceof ParametricModel) { panel = new ParametricModelPropertySheetPanel(); } else if (named instanceof Scenario) { panel = new ScenarioPropertySheet(); } else if (named instanceof Assembly) { panel = new AssemblyPropertySheet(); } else if (named instanceof CoordinateSystem) { panel = new CoordinateSystemPropertySheet(); } else if (named instanceof Point) { panel = new PointPropertySheet(); } else if (named instanceof Line) { panel = new LinePropertySheet(); } else if (named instanceof Plane) { panel = new PlanePropertySheet(); } if (named != null) { jScrollPane1.getViewport().removeAll(); jScrollPane1.setViewportView(panel); } } /** * Handle update event. * @param o Observable * @param arg Argument */ public void update(Observable o, Object arg) { if (arg instanceof Integer) { Integer eventId = (Integer) arg; switch (eventId) { case ApplicationContext.MODEL_CLOSED: this.jScrollPane1.getViewport().removeAll(); break; case ApplicationContext.MODEL_LOADED: case ApplicationContext.EVENT_SELECTION_CHANGE: buildPropertySheet(); break; } } } }
elmarquez/Federation
src/ca/sfu/federation/viewer/propertysheet/PropertySheetPanel.java
Java
gpl-2.0
4,541
// // IstringHelper.java (helper) // // File generated: Wed Feb 25 11:12:05 CET 2009 // by TIDorb idl2java 1.3.7 // package org.omg.CosNotification; abstract public class IstringHelper { private static org.omg.CORBA.ORB _orb() { return org.omg.CORBA.ORB.init(); } public static void insert(org.omg.CORBA.Any any, java.lang.String value) { any.insert_Streamable(new org.omg.CORBA.StringHolder(value)); }; public static java.lang.String extract(org.omg.CORBA.Any any) { if(any instanceof es.tid.CORBA.Any) { try { org.omg.CORBA.portable.Streamable holder = ((es.tid.CORBA.Any)any).extract_Streamable(); if(holder instanceof org.omg.CORBA.StringHolder){ return ((org.omg.CORBA.StringHolder) holder).value; } } catch (Exception e) {} } return read(any.create_input_stream()); }; private static org.omg.CORBA.TypeCode _type = null; public static org.omg.CORBA.TypeCode type() { if (_type == null) { org.omg.CORBA.TypeCode original_type = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string); _type = _orb().create_alias_tc(id(), "Istring", original_type); } return _type; }; public static String id() { return "IDL:org.omg/CosNotification/Istring:1.0"; }; public static java.lang.String read(org.omg.CORBA.portable.InputStream is) { java.lang.String result; result = is.read_string(); return result; }; public static void write(org.omg.CORBA.portable.OutputStream os, java.lang.String val) { os.write_string(val); }; }
AlvaroVega/TIDNotifJ
test/notif/overload/org/omg/CosNotification/IstringHelper.java
Java
gpl-2.0
1,598
/* * Mars Simulation Project * VehicleMission.java * @date 2021-10-17 * @author Scott Davis */ package org.mars_sim.msp.core.person.ai.mission; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.stream.Collectors; import org.mars_sim.msp.core.Coordinates; import org.mars_sim.msp.core.UnitEvent; import org.mars_sim.msp.core.UnitEventType; import org.mars_sim.msp.core.UnitListener; import org.mars_sim.msp.core.UnitType; import org.mars_sim.msp.core.equipment.ContainerUtil; import org.mars_sim.msp.core.equipment.EquipmentType; import org.mars_sim.msp.core.events.HistoricalEvent; import org.mars_sim.msp.core.logging.SimLogger; import org.mars_sim.msp.core.malfunction.Malfunction; import org.mars_sim.msp.core.malfunction.MalfunctionManager; import org.mars_sim.msp.core.person.EventType; import org.mars_sim.msp.core.person.Person; import org.mars_sim.msp.core.person.ai.task.LoadVehicleGarage; import org.mars_sim.msp.core.person.ai.task.LoadingController; import org.mars_sim.msp.core.person.ai.task.OperateVehicle; import org.mars_sim.msp.core.person.ai.task.utils.TaskPhase; import org.mars_sim.msp.core.person.ai.task.utils.Worker; import org.mars_sim.msp.core.resource.ItemResourceUtil; import org.mars_sim.msp.core.resource.ResourceUtil; import org.mars_sim.msp.core.robot.Robot; import org.mars_sim.msp.core.structure.Settlement; import org.mars_sim.msp.core.time.ClockPulse; import org.mars_sim.msp.core.time.MarsClock; import org.mars_sim.msp.core.tool.RandomUtil; import org.mars_sim.msp.core.vehicle.Drone; import org.mars_sim.msp.core.vehicle.Rover; import org.mars_sim.msp.core.vehicle.StatusType; import org.mars_sim.msp.core.vehicle.Vehicle; import org.mars_sim.msp.core.vehicle.VehicleType; /** * A mission that involves driving a vehicle along a series of navpoints. */ public abstract class VehicleMission extends TravelMission implements UnitListener { /** default serial id. */ private static final long serialVersionUID = 1L; /** default logger. */ private static final SimLogger logger = SimLogger.getLogger(VehicleMission.class.getName()); /** Mission phases. */ public static final MissionPhase REVIEWING = new MissionPhase("Mission.phase.reviewing"); public static final MissionPhase EMBARKING = new MissionPhase("Mission.phase.embarking"); public static final MissionPhase TRAVELLING = new MissionPhase("Mission.phase.travelling"); public static final MissionPhase DISEMBARKING = new MissionPhase("Mission.phase.disembarking"); // Static members private static final String ROVER_WHEEL = "rover wheel"; private static final String ROVER_BATTERY = "rover battery"; private static final String LASER = "laser"; private static final String STEPPER_MOTOR = "stepper motor"; private static final String OVEN = "oven"; private static final String BLENDER = "blender"; private static final String AUTOCLAVE = "autoclave"; private static final String REFRIGERATOR = "refrigerator"; private static final String STOVE = "stove"; private static final String MICROWAVE = "microwave"; private static final String POLY_ROOFING = "polycarbonate roofing"; private static final String LENS = "lens"; private static final String FIBERGLASS = "fiberglass"; private static final String SHEET = "sheet"; private static final String PRISM = "prism"; /** The small insignificant amount of distance in km. */ private static final double SMALL_DISTANCE = .1; /** Modifier for number of parts needed for a trip. */ private static final double PARTS_NUMBER_MODIFIER = MalfunctionManager.PARTS_NUMBER_MODIFIER; /** Estimate number of broken parts per malfunctions */ private static final double AVERAGE_NUM_MALFUNCTION = MalfunctionManager.AVERAGE_NUM_MALFUNCTION; /** Estimate number of broken parts per malfunctions for EVA suits. */ protected static final double AVERAGE_EVA_MALFUNCTION = MalfunctionManager.AVERAGE_EVA_MALFUNCTION; /** Default speed if no operators have ever driven */ private static final double DEFAULT_SPEED = 10D; // How often are remaning resources checked private static final int RESOURCE_CHECK_DURATION = 40; /** True if a person is submitting the mission plan request. */ private boolean isMissionPlanReady; /** Vehicle traveled distance at start of mission. */ private double startingTravelledDistance; /** Total traveled distance. */ private double distanceTravelled; // Data members /** The vehicle currently used in the mission. */ private Vehicle vehicle; /** The last operator of this vehicle in the mission. */ private Worker lastOperator; /** The current operate vehicle task. */ private OperateVehicle operateVehicleTask; /** Details of the loading operation */ private LoadingController loadingPlan; /** Caches */ private transient Map<Integer, Integer> equipmentNeededCache; private transient Map<Integer, Number> cachedParts = null; private transient double cachedDistance = -1; private Settlement startingSettlement; // When was the last check on the remaining resources private int lastResourceCheck = 0; private String dateEmbarked; /** * Constructor 1. Started by RoverMission or DroneMission constructor 1. * * @param missionName * @param startingMember * @param minPeople */ protected VehicleMission(String missionName, MissionType missionType, MissionMember startingMember) { // Use TravelMission constructor. super(missionName, missionType, startingMember); setStartingSettlement(getStartingPerson().getAssociatedSettlement()); reserveVehicle(); } /** * Constructor 2. Manually initiated by player. * * @param missionName * @param startingMember * @param minPeople * @param vehicle */ protected VehicleMission(String missionName, MissionType missionType, MissionMember startingMember, Vehicle vehicle) { // Use TravelMission constructor. super(missionName, missionType, startingMember); setStartingSettlement(getStartingPerson().getAssociatedSettlement()); // Set the vehicle. setVehicle(vehicle); } /** * Reserve a vehicle * * @return */ protected boolean reserveVehicle() { MissionMember startingMember = getStartingPerson(); // Reserve a vehicle. if (!reserveVehicle(startingMember)) { endMission(MissionStatus.NO_RESERVABLE_VEHICLES); logger.warning(startingMember, "Could not reserve a vehicle for " + getTypeID() + "."); return false; } return true; } /** * Is the vehicle under maintenance and unable to be embarked ? * * @return */ private boolean checkVehicleMaintenance() { if (vehicle.haveStatusType(StatusType.MAINTENANCE)) { logger.warning(vehicle, "Under maintenance and not ready for " + getTypeID() + "."); endMission(MissionStatus.VEHICLE_UNDER_MAINTENANCE); return false; } return true; } /** * Gets the mission's vehicle if there is one. * * @return vehicle or null if none. */ public Vehicle getVehicle() { return vehicle; } /** * Get the current loading plan for this Mission phase. * @return */ public LoadingController getLoadingPlan() { return loadingPlan; } /** * Prepare a loading plan taking resources from a site. If a plan for the same * site is already in place then it is re-used. * @param loadingSite */ public LoadingController prepareLoadingPlan(Settlement loadingSite) { if ((loadingPlan == null) || !loadingPlan.getSettlement().equals(loadingSite)) { logger.info(vehicle, 10_000L, "Prepared a loading plan sourced from " + loadingSite.getName() + "."); loadingPlan = new LoadingController(loadingSite, vehicle, getRequiredResourcesToLoad(), getOptionalResourcesToLoad(), getRequiredEquipmentToLoad(), getOptionalEquipmentToLoad()); } return loadingPlan; } /** * Clear the current loading plan */ public void clearLoadingPlan() { loadingPlan = null; } /** * Sets the vehicle for this mission. * * @param newVehicle the vehicle to use. * @throws MissionException if vehicle cannot be used. */ protected void setVehicle(Vehicle newVehicle) { if (newVehicle != null) { boolean usable = false; usable = isUsableVehicle(newVehicle); if (usable) { vehicle = newVehicle; startingTravelledDistance = vehicle.getOdometerMileage(); newVehicle.setReservedForMission(true); vehicle.addUnitListener(this); // Record the name of this vehicle in Mission setReservedVehicle(newVehicle.getName()); fireMissionUpdate(MissionEventType.VEHICLE_EVENT); } if (!usable) { throw new IllegalStateException(getPhase() + " : newVehicle is not usable for this mission."); } } else { throw new IllegalArgumentException("newVehicle is null."); } } /** * Checks if the mission has a vehicle. * * @return true if vehicle. */ public final boolean hasVehicle() { return (vehicle != null); } /** * Leaves the mission's vehicle and unreserves it. */ protected final void leaveVehicle() { if (hasVehicle()) { vehicle.setReservedForMission(false); vehicle.removeUnitListener(this); vehicle = null; fireMissionUpdate(MissionEventType.VEHICLE_EVENT); } } /** * Checks if vehicle is usable for this mission. (This method should be added to * by children) * * @param newVehicle the vehicle to check * @return true if vehicle is usable. * @throws IllegalArgumentException if newVehicle is null. * @throws MissionException if problem checking vehicle is loadable. */ protected boolean isUsableVehicle(Vehicle vehicle) { if (vehicle != null) { boolean usable = vehicle.isVehicleReady(); if (vehicle.getStoredMass() > 0D) usable = false; logger.log(vehicle, Level.FINER, 1000, "Was checked on the status: (available : " + usable + ") for " + getTypeID() + "."); return usable; } else { throw new IllegalArgumentException("isUsableVehicle: newVehicle is null."); } } /** * Compares the quality of two vehicles for use in this mission. (This method * should be added to by children) * * @param firstVehicle the first vehicle to compare * @param secondVehicle the second vehicle to compare * @return -1 if the second vehicle is better than the first vehicle, 0 if * vehicle are equal in quality, and 1 if the first vehicle is better * than the second vehicle. * @throws MissionException if error determining vehicle range. */ protected int compareVehicles(Vehicle firstVehicle, Vehicle secondVehicle) { if (isUsableVehicle(firstVehicle)) { if (isUsableVehicle(secondVehicle)) { return 0; } else { return 1; } } else { if (isUsableVehicle(secondVehicle)) { return -1; } else { return 0; } } } /** * Reserves a vehicle for the mission if possible. * * @param person the person reserving the vehicle. * @return true if vehicle is reserved, false if unable to. * @throws MissionException if error reserving vehicle. */ protected final boolean reserveVehicle(MissionMember member) { Collection<Vehicle> bestVehicles = new ConcurrentLinkedQueue<>(); if (member.getSettlement() == null) return false; Collection<Vehicle> vList = getAvailableVehicles(member.getSettlement()); if (vList.isEmpty()) { return false; } else { for (Vehicle v : vList) { if (!bestVehicles.isEmpty()) { int comparison = compareVehicles(v, (Vehicle) bestVehicles.toArray()[0]); if (comparison == 0) { bestVehicles.add(v); } else if (comparison == 1) { bestVehicles.clear(); bestVehicles.add(v); } } else bestVehicles.add(v); } // Randomly select from the best vehicles. if (!bestVehicles.isEmpty()) { Vehicle selected = null; int bestVehicleIndex = RandomUtil.getRandomInt(bestVehicles.size() - 1); try { selected = (Vehicle) bestVehicles.toArray()[bestVehicleIndex]; setVehicle(selected); } catch (Exception e) { logger.severe(selected, "Cannot set the best vehicle: ", e); } } return hasVehicle(); } } /** * Gets a collection of available vehicles at a settlement that are usable for * this mission. * * @param settlement the settlement to find vehicles. * @return list of available vehicles. * @throws MissionException if problem determining if vehicles are usable. */ private Collection<Vehicle> getAvailableVehicles(Settlement settlement) { Collection<Vehicle> result = new ConcurrentLinkedQueue<>(); if (getMissionType() == MissionType.DELIVERY) { Collection<Drone> list = settlement.getParkedDrones(); if (!list.isEmpty()) { for (Drone v : list) { if (!v.haveStatusType(StatusType.MAINTENANCE) && v.getMalfunctionManager().getMalfunctions().isEmpty() && isUsableVehicle(v) && !v.isReserved()) { result.add(v); } } } } else { Collection<Vehicle> vList = settlement.getParkedVehicles(); if (!vList.isEmpty()) { for (Vehicle v : vList) { if (VehicleType.isRover(v.getVehicleType()) && !v.haveStatusType(StatusType.MAINTENANCE) && v.getMalfunctionManager().getMalfunctions().isEmpty() && isUsableVehicle(v) && !v.isReserved()) { result.add(v); } } } } return result; } /** * Finalizes the mission * * @param reason the reason of ending the mission. */ @Override protected void endMission(MissionStatus endStatus) { // Release the loading plan if it exists loadingPlan = null; equipmentNeededCache = null; cachedParts = null; boolean continueToEndMission = true; if (hasVehicle()) { // if user hit the "End Mission" button to abort the mission // Check if user aborted the mission and if // the vehicle has been disembarked. // What if a vehicle is still at a settlement and Mission is not approved ? // for ALL OTHER REASONS setPhaseEnded(true); if (vehicle.getVehicleType() == VehicleType.DELIVERY_DRONE) { if (vehicle.getStoredMass() != 0D) { continueToEndMission = false; startDisembarkingPhase(); } } else if (VehicleType.isRover(vehicle.getVehicleType())) { if (((Rover)vehicle).getCrewNum() != 0 || (vehicle.getStoredMass() != 0D)) { continueToEndMission = false; startDisembarkingPhase(); } } } if (continueToEndMission) { setPhaseEnded(true); leaveVehicle(); super.endMission(endStatus); } } /** * Get help for the mission. The reason becomes a Mission Status. * @param reason The reason why help is needed. */ public void getHelp(MissionStatus reason) { logger.info(vehicle, 20_000, "Needs help."); addMissionStatus(reason); // Set emergency beacon if vehicle is not at settlement. // Note: need to find out if there are other matching reasons for setting // emergency beacon. if (vehicle.getSettlement() == null) { // if the vehicle somewhere on Mars if (!vehicle.isBeaconOn()) { triggerEmergencyBeacon(); if (VehicleType.isRover(vehicle.getVehicleType()) && vehicle.isBeingTowed()) { // Note: the vehicle is being towed, wait till the journey is over // don't end the mission yet logger.log(vehicle, Level.INFO, 20_000, "Currently being towed by " + vehicle.getTowingVehicle().getName()); } } else { // Note : if the emergency beacon is on, don't end the mission yet // May use logger.info(vehicle + "'s emergency beacon is on. awaiting the response for rescue right now."); } } else { // Vehicle is still in the settlement vicinity or has arrived in a settlement if (!vehicle.isBeaconOn()) { triggerEmergencyBeacon(); } // if the vehicle is still somewhere inside the settlement when it got broken // down // Note: consider to wait till the repair is done and the mission may resume ?!? else if (vehicle.getSettlement() != null) { // if a vehicle is at a settlement setPhaseEnded(true); endMission(reason); } } } /** * Trigger the emergency beacon on the Mission vehicle */ private void triggerEmergencyBeacon() { var message = new StringBuilder(); // if the emergency beacon is off // Question: could the emergency beacon itself be broken ? message.append("Turned on emergency beacon. Request for towing with status flag(s) :"); message.append(getMissionStatus().stream().map(MissionStatus::getName).collect(Collectors.joining(", "))); logger.info(vehicle, 20_000, message.toString()); vehicle.setEmergencyBeacon(true); } /** * Determine if a vehicle is sufficiently loaded with fuel and supplies. * * @return true if rover is loaded. * @throws MissionException if error checking vehicle. */ public final boolean isVehicleLoaded() { if (vehicle == null) { throw new IllegalStateException(getPhase().getName() + ": vehicle is null."); } if (loadingPlan != null) { if (loadingPlan.isFailure()) { logger.warning(vehicle, "Loading has failed"); endMission(MissionStatus.CANNOT_LOAD_RESOURCES); } return loadingPlan.isCompleted(); } return false; } /** * Checks if a vehicle can load the supplies needed by the mission. * * @return true if vehicle is loadable. * @throws Exception if error checking vehicle. */ protected final boolean isVehicleLoadable() { Map<Integer, Number> resources = getRequiredResourcesToLoad(); Map<Integer, Integer> equipment = getRequiredEquipmentToLoad(); Settlement settlement = vehicle.getSettlement(); double tripTime = getEstimatedRemainingMissionTime(true); if (tripTime == 0) { // Disapprove this mission logger.warning(settlement, "Has estimated zero trip time"); return false; } boolean settlementSupplies = LoadVehicleGarage.hasEnoughSupplies(settlement, vehicle, resources, equipment, getPeopleNumber(), tripTime); if (!settlementSupplies) { logger.warning(settlement, "Not enough supplies for " + vehicle.getName() + "'s proposed excursion."); } return settlementSupplies; } /** * Gets the amount of fuel (kg) needed for a trip of a given distance (km). * * @param tripDistance the distance (km) of the trip. * @param fuelEconomy the vehicle's instantaneous fuel economy (km/kg). * @param useMargin Apply safety margin when loading resources before embarking if true. * @return amount of fuel needed for trip (kg) */ public static double getFuelNeededForTrip(Vehicle vehicle, double tripDistance, double fuelEconomy, boolean useMargin) { double result = tripDistance / fuelEconomy; double factor = 1; if (useMargin) { if (tripDistance < 1000) { // Note: use formula below to add more extra fuel for short travel distance on top of the fuel margin // For short trips, there has been a history of getting stranded and require 4x more fuel to come back home factor = Vehicle.getFuelRangeErrorMargin() + (2 - 0.002 * tripDistance); } else { // beyond 1000 km, no more modding on top of the fuel margin factor = Vehicle.getFuelRangeErrorMargin(); } result *= factor; } // double cap = vehicle.getAmountResourceCapacity(vehicle.getFuelType()); // if (result > cap) // // Make sure the amount requested is less than the max resource cap of this vehicle // result = cap; logger.info(vehicle, 30_000, "Trip Distance: " + Math.round(tripDistance * 10.0)/10.0 + " km " + "Fuel Economy: " + Math.round(fuelEconomy * 10.0)/10.0 + " km/kg " + "Fuel Margin: " + Math.round(factor * 10.0)/10.0 + " " + "Fuel: " + Math.round(result * 10.0)/10.0 + " kg"); return result; } /** * Determines a new phase for the mission when the current phase has ended. * Subclass are expected to determine the next Phase for TRAVELLING * * @throws MissionException if problem setting a new phase. */ protected boolean determineNewPhase() { boolean handled = true; if (REVIEWING.equals(getPhase())) { // Check the vehicle is loadable before starting the embarking if (isVehicleLoadable()) { setPhase(EMBARKING, getCurrentNavpoint().getDescription()); } else { logger.warning(vehicle, getName() + " cannot load Resources."); endMission(MissionStatus.CANNOT_LOAD_RESOURCES); } } else if (EMBARKING.equals(getPhase())) { startTravellingPhase(); } else if (DISEMBARKING.equals(getPhase())) { setPhase(COMPLETED, null); } else if (COMPLETED.equals(getPhase())) { endMission(MissionStatus.MISSION_ACCOMPLISHED); } else { handled = false; } return handled; } /** * Gets the date embarked timestamp of the mission. * * @return */ @Override public String getDateEmbarked() { return dateEmbarked; } public void flag4Submission() { isMissionPlanReady = true; } public void recordStartMass() { vehicle.recordStartMass(); } @Override protected void performPhase(MissionMember member) { super.performPhase(member); if (REVIEWING.equals(getPhase())) { if (isMissionPlanReady) { computeEstimatedTotalDistance(); requestReviewPhase(member); } } else if (EMBARKING.equals(getPhase())) { checkVehicleMaintenance(); performEmbarkFromSettlementPhase(member); } else if (TRAVELLING.equals(getPhase())) { performTravelPhase(member); } else if (DISEMBARKING.equals(getPhase())) { performDisembarkToSettlementPhase(member, getCurrentNavpoint().getSettlement()); } else if (COMPLETED.equals(getPhase())) { setPhaseEnded(true); } } /** * Performs the travel phase of the mission. * * @param member the mission member currently performing the mission. */ protected final void performTravelPhase(MissionMember member) { NavPoint destination = getNextNavpoint(); // If vehicle has not reached destination and isn't broken down, travel to // destination. boolean reachedDestination = false; boolean malfunction = false; boolean allCrewHasMedical = hasDangerousMedicalProblemsAllCrew(); boolean hasEmergency = hasEmergency(); if (destination != null && vehicle != null && vehicle.getCoordinates() != null && destination.getLocation() != null) { reachedDestination = vehicle.getCoordinates().equals(destination.getLocation()) || Coordinates.computeDistance(vehicle.getCoordinates(), destination.getLocation()) < SMALL_DISTANCE; malfunction = vehicle.getMalfunctionManager().hasMalfunction(); } // If emergency, make sure the current operateVehicleTask is pointed home. if ((allCrewHasMedical || hasEmergency || malfunction) && operateVehicleTask != null && destination != null && destination.getLocation() != null && operateVehicleTask.getDestination() != null && !operateVehicleTask.getDestination().equals(destination.getLocation())) { updateTravelDestination(); } // Choose a driver if (!reachedDestination && !malfunction) { boolean becomeDriver = false; if (operateVehicleTask != null) { // Someone should be driving or it's me !!! becomeDriver = vehicle != null && ((vehicle.getOperator() == null) || (vehicle.getOperator().equals(member))); } else { // None is driving becomeDriver = true; } // Take control if (becomeDriver) { if (operateVehicleTask != null) { operateVehicleTask = createOperateVehicleTask(member, operateVehicleTask.getPhase()); } else { operateVehicleTask = createOperateVehicleTask(member, null); } if (operateVehicleTask != null) { if (member.getUnitType() == UnitType.PERSON) { assignTask((Person)member, operateVehicleTask); } else { assignTask((Robot)member, operateVehicleTask); } lastOperator = member; return; } } } // If the destination has been reached, end the phase. if (reachedDestination) { Settlement base = destination.getSettlement(); if (vehicle.getAssociatedSettlement().equals(base)) { logger.info(vehicle, "Arrived back home " + base.getName()); vehicle.transfer(base); // TODO There is a problem with the Vehicle not being on the // surface vehicle list. The problem is a lack of transfer at the start of TRAVEL phase // This is temporary fix pending #474 which will revisit transfers if (!base.equals(vehicle.getContainerUnit())) { vehicle.setContainerUnit(base); logger.warning(vehicle, "Had to force container to home base"); } } reachedNextNode(); setPhaseEnded(true); } if (vehicle != null && VehicleType.isRover(vehicle.getVehicleType())) { // Check the remaining trip if there's enough resource // Must set margin to false since it's not needed. if (!hasEnoughResourcesForRemainingMission(false)) { // If not, determine an emergency destination. determineEmergencyDestination(member); } // If vehicle has unrepairable malfunction, end mission. if (hasUnrepairableMalfunction()) { getHelp(MissionStatus.UNREPAIRABLE_MALFUNCTION); } } } public Worker getLastOperator() { return lastOperator; } /** * Gets a new instance of an OperateVehicle task for the person. * * @param member the mission member operating the vehicle. * @return an OperateVehicle task for the person. */ protected abstract OperateVehicle createOperateVehicleTask(MissionMember member, TaskPhase lastOperateVehicleTaskPhase); /** * Performs the embark from settlement phase of the mission. * * @param member the mission member currently performing the mission. */ protected abstract void performEmbarkFromSettlementPhase(MissionMember member); /** * Performs the disembark to settlement phase of the mission. * * @param member the mission member currently performing the * mission. * @param disembarkSettlement the settlement to be disembarked to. */ protected abstract void performDisembarkToSettlementPhase(MissionMember member, Settlement disembarkSettlement); /** * Gets the estimated time of arrival (ETA) for the current leg of the mission. * * @return time (MarsClock) or null if not applicable. */ public final MarsClock getLegETA() { if (TRAVELLING.equals(getPhase()) && operateVehicleTask != null && vehicle.getOperator() != null) { return operateVehicleTask.getETA(); } else { return null; } } /** * Gets the estimated time for a trip. * * @param useMargin use time buffers in estimation if true. * @param distance the distance of the trip. * @return time (millisols) * @throws MissionException */ public final double getEstimatedTripTime(boolean useMargin, double distance) { double result = 0; // Determine average driving speed for all mission members. double averageSpeed = getAverageVehicleSpeedForOperators(); if (averageSpeed > 0) { double averageSpeedMillisol = averageSpeed / MarsClock.MILLISOLS_PER_HOUR; result = distance / averageSpeedMillisol; } // If buffer, add one sol. if (useMargin) { result += 500D; } return result; } /** * Gets the estimated time remaining for the mission. * * @param useMargin Use time buffer in estimations if true. * @return time (millisols) * @throws MissionException */ protected double getEstimatedRemainingMissionTime(boolean useMargin) { double distance = getEstimatedTotalRemainingDistance(); if (distance > 0) { double time = getEstimatedTripTime(useMargin, distance); logger.info(vehicle, 20_000, this + " has an estimated remaining trip time of " + time); return time; } return 0; } /** * Gets the average operating speed of the mission vehicle for all of the * mission members. This returns a default if no one has ever driven a vehicle. * * @return average operating speed (km/h) */ protected final double getAverageVehicleSpeedForOperators() { double result = DEFAULT_SPEED; double totalSpeed = 0D; int count = 0; for (MissionMember member : getMembers()) { if (member instanceof Person) { totalSpeed += getAverageVehicleSpeedForOperator((Person) member); count++; } } if (count > 0) { result = totalSpeed / count; } if (result == 0) { result = DEFAULT_SPEED; } return result; } /** * Gets the average speed of a vehicle with a given person operating it. * * @param operator the vehicle operator. * @return average speed (km/h) */ private double getAverageVehicleSpeedForOperator(Worker operator) { return OperateVehicle.getAverageVehicleSpeed(vehicle, operator, this); } /** * Gets the number and amounts of resources needed for the mission. * * @param useMargin Apply safety margin when loading resources before embarking if true. * Note : True if estimating trip. False if calculating remaining trip. * @return map of amount and item resources and their Double amount or Integer * number. */ protected Map<Integer, Number> getResourcesNeededForRemainingMission(boolean useMargin) { double distance = getEstimatedTotalRemainingDistance(); if (distance > 0) { logger.info(vehicle, 20_000, "1. " + this + " has an estimated remaining distance of " + Math.round(distance * 10.0)/10.0 + " km."); return getResourcesNeededForTrip(useMargin, distance); } return new HashMap<>(); } /** * Gets the number and amounts of resources needed for a trip. * * @param useMargin Apply safety margin when loading resources before embarking if true. * Note : True if estimating trip. False if calculating remaining trip. * * @param distance the distance (km) of the trip. * @return map of amount and item resources and their Double amount or Integer * number. */ public Map<Integer, Number> getResourcesNeededForTrip(boolean useMargin, double distance) { Map<Integer, Number> result = new HashMap<>(); if (vehicle != null) { // Add the methane resource if (getPhase() == null || getPhase().equals(VehicleMission.EMBARKING) || getPhase().equals(VehicleMission.REVIEWING) || useMargin) // Use margin only when estimating how much fuel needed before starting the mission result.put(vehicle.getFuelType(), getFuelNeededForTrip(vehicle, distance, vehicle.getEstimatedAveFuelEconomy(), true)); else // When the vehicle is already on the road, do NOT use margin // or else it would constantly complain not having enough fuel result.put(vehicle.getFuelType(), getFuelNeededForTrip(vehicle, distance, vehicle.getIFuelEconomy(), false)); } return result; } /** * Gets spare parts for the trip. * * @param distance the distance of the trip. * @return map of part resources and their number. */ protected Map<Integer, Number> getSparePartsForTrip(double distance) { Map<Integer, Number> result = null; // Determine vehicle parts. only if there is a change of distance if (vehicle != null) { // If the distance is the same as last time then use the cached value if ((cachedDistance == distance) && (cachedParts != null)) { result = cachedParts; } else { result = new HashMap<>(); cachedParts = result; cachedDistance = distance; double drivingTime = getEstimatedTripTime(true, distance); double numberAccidents = drivingTime * OperateVehicle.BASE_ACCIDENT_CHANCE; double numberMalfunctions = numberAccidents * AVERAGE_NUM_MALFUNCTION; Map<Integer, Double> parts = vehicle.getMalfunctionManager().getRepairPartProbabilities(); // Note: need to figure out why a vehicle's scope would contain the following parts : parts = removeParts(parts, LASER, STEPPER_MOTOR, OVEN, BLENDER, AUTOCLAVE, REFRIGERATOR, STOVE, MICROWAVE, POLY_ROOFING, LENS, FIBERGLASS, SHEET, PRISM); for (Integer id : parts.keySet()) { double freq = parts.get(id) * numberMalfunctions * PARTS_NUMBER_MODIFIER; int number = (int) Math.round(freq); if (number > 0) { result.put(id, number); } } // Manually override the number of wheel and battery needed for each mission if (VehicleType.isRover(vehicle.getVehicleType())) { Integer wheel = ItemResourceUtil.findIDbyItemResourceName(ROVER_WHEEL); Integer battery = ItemResourceUtil.findIDbyItemResourceName(ROVER_BATTERY); result.put(wheel, 2); result.put(battery, 1); } } } else { result = new HashMap<>(); } return result; } /** * Removes a variable list of parts from a resource part * * @param parts a map of parts * @param names * @return a map of parts */ private static Map<Integer, Double> removeParts(Map<Integer, Double> parts, String... names) { for (String n : names) { Integer i = ItemResourceUtil.findIDbyItemResourceName(n); if (i != null) { parts.remove(i); } } return parts; } /** * Checks if there are enough resources available in the vehicle for the * remaining mission. * * @param useMargin True if estimating trip. False if calculating remaining * trip. * @return true if enough resources. */ protected final boolean hasEnoughResourcesForRemainingMission(boolean useMargin) { int currentMSols = marsClock.getMillisolInt(); if ((currentMSols - lastResourceCheck ) > RESOURCE_CHECK_DURATION) { lastResourceCheck = currentMSols; return hasEnoughResources(getResourcesNeededForRemainingMission(useMargin)); } // Assume it is still fine return true; } /** * Checks if there are enough resources available in the vehicle. * * @param neededResources map of amount and item resources and their Double * amount or Integer number. * @return true if enough resources. */ private boolean hasEnoughResources(Map<Integer, Number> neededResources) { boolean result = true; if (vehicle != null) { for (Map.Entry<Integer, Number> entry : neededResources.entrySet()) { int id = entry.getKey(); Object value = entry.getValue(); if (id < ResourceUtil.FIRST_ITEM_RESOURCE_ID) { double amount = (Double) value; double amountStored = vehicle.getAmountResourceStored(id); if (amountStored < amount) { String newLog = "Not enough " + ResourceUtil.findAmountResourceName(id) + " to continue with " + getTypeID() + " Required: " + Math.round(amount * 100D) / 100D + " kg Vehicle stored: " + Math.round(amountStored * 100D) / 100D + " kg"; logger.log(vehicle, Level.WARNING, 10_000, newLog); return false; } } else if (id >= ResourceUtil.FIRST_ITEM_RESOURCE_ID && id < ResourceUtil.FIRST_VEHICLE_RESOURCE_ID) { int num = (Integer) value; int numStored = vehicle.getItemResourceStored(id); if (numStored < num) { String newLog = "Not enough " + ItemResourceUtil.findItemResource(id).getName() + " to continue with " + getTypeID() + " Required: " + num + " Vehicle stored: " + numStored + "."; logger.log(vehicle, Level.WARNING, 10_000, newLog); return false; } } else { throw new IllegalStateException(getPhase() + " : issues with the resource type of " + ResourceUtil.findAmountResourceName(id)); } } } return result; } /** * Gets the closet distance * * @return */ protected double getClosestDistance() { Settlement settlement = findClosestSettlement(); if (settlement != null) return Coordinates.computeDistance(getCurrentMissionLocation(), settlement.getCoordinates()); return 0; } /** * Determines a new route for traveling * * @param reason * @param member * @param oldHome * @param newDestination * @param oldDistance * @param newDistance */ protected void travel(String reason, MissionMember member, Settlement oldHome, Settlement newDestination, double oldDistance, double newDistance) { double newTripTime = getEstimatedTripTime(false, newDistance); NavPoint nextNav = getNextNavpoint(); if ((nextNav != null) && (newDestination == nextNav.getSettlement())) { // If the closest settlement is already the next navpoint. logger.log(vehicle, Level.WARNING, 10000, "Emergency encountered. Returning to home settlement (" + newDestination.getName() + ") : " + Math.round(newDistance * 100D) / 100D + " km Duration : " + Math.round(newTripTime * 100.0 / 1000.0) / 100.0 + " sols"); endCollectionPhase(); returnHome(); } else { // If the closet settlement is not the home settlement logger.log(vehicle, Level.WARNING, 10000, "Emergency encountered. Home settlement (" + oldHome.getName() + ") : " + Math.round(oldDistance * 100D) / 100D + " km Going to nearest Settlement (" + newDestination.getName() + ") : " + Math.round(newDistance * 100D) / 100D + " km Duration : " + Math.round(newTripTime * 100.0 / 1000.0) / 100.0 + " sols"); // Creating emergency destination mission event for going to a new settlement. HistoricalEvent newEvent = new MissionHistoricalEvent(EventType.MISSION_EMERGENCY_DESTINATION, this, reason, this.getTypeID(), member.getName(), vehicle.getName(), vehicle.getCoordinates().getCoordinateString(), oldHome.getName() ); eventManager.registerNewEvent(newEvent); // Note: use Mission.goToNearestSettlement() as reference // Set the new destination as the travel mission's next and final navpoint. clearRemainingNavpoints(); addNavpoint(newDestination); // each member to switch the associated settlement to the new destination // Note: need to consider if enough beds are available at the destination settlement // Note: can they go back to the settlement of their origin ? // Added updateTravelDestination() below updateTravelDestination(); endCollectionPhase(); } } /** * Determines the emergency destination settlement for the mission if one is * reachable, otherwise sets the emergency beacon and ends the mission. * * @param member the mission member performing the mission. */ protected final void determineEmergencyDestination(MissionMember member) { boolean hasMedicalEmergency = false; Person person = (Person) member; String reason = ""; if (member instanceof Person && (hasAnyPotentialMedicalProblems() || person.getPhysicalCondition().hasSeriousMedicalProblems() || hasEmergencyAllCrew()) ) { reason = EventType.MISSION_MEDICAL_EMERGENCY.getName(); hasMedicalEmergency = true; // 1. Create the medical emergency mission event. HistoricalEvent newEvent = new MissionHistoricalEvent(EventType.MISSION_MEDICAL_EMERGENCY, this, person.getName() + " had " + person.getPhysicalCondition().getHealthSituation(), this.getTypeID(), member.getName(), vehicle.getName(), vehicle.getCoordinates().getCoordinateString(), person.getAssociatedSettlement().getName() ); eventManager.registerNewEvent(newEvent); } else { reason = EventType.MISSION_NOT_ENOUGH_RESOURCES.getName(); // 2. Create the resource emergency mission event. HistoricalEvent newEvent = new MissionHistoricalEvent(EventType.MISSION_NOT_ENOUGH_RESOURCES, this, "Dwindling resource(s)", this.getTypeID(), member.getName(), vehicle.getName(), vehicle.getCoordinates().getCoordinateString(), person.getAssociatedSettlement().getName() ); eventManager.registerNewEvent(newEvent); } Settlement oldHome = person.getAssociatedSettlement(); double oldDistance = Coordinates.computeDistance(getCurrentMissionLocation(), oldHome.getCoordinates()); // Determine closest settlement. boolean requestHelp = false; Settlement newDestination = findClosestSettlement(); if (newDestination != null) { double newDistance = Coordinates.computeDistance(getCurrentMissionLocation(), newDestination.getCoordinates()); boolean enough = true; // for delivery mission, Will need to alert the player differently if it runs out of fuel if (!(this instanceof Delivery)) { enough = hasEnoughResources(getResourcesNeededForTrip(false, newDistance)); // Check if enough resources to get to settlement. if (newDistance > 0 && enough) { travel(reason, member, oldHome, newDestination, oldDistance, newDistance); } else if (newDistance > 0 && hasEnoughResources(getResourcesNeededForTrip(false, newDistance * 0.667))) { travel(reason, member, oldHome, newDestination, oldDistance, newDistance * 0.667); } else if (newDistance > 0 && hasEnoughResources(getResourcesNeededForTrip(false, newDistance * 0.333))) { travel(reason, member, oldHome, newDestination, oldDistance, newDistance * 0.333); } else { requestHelp = true; } } } else { requestHelp = true; } // Need help if (requestHelp) { endCollectionPhase(); getHelp(hasMedicalEmergency ? MissionStatus.MEDICAL_EMERGENCY : MissionStatus.NO_EMERGENCY_SETTLEMENT_DESTINATION_FOUND); } } /** * Sets the vehicle's emergency beacon on or off. * * @param member the mission member performing the mission. * @param vehicle the vehicle on the mission. * @param beaconOn true if beacon is on, false if not. */ public void setEmergencyBeacon(MissionMember member, Vehicle vehicle, boolean beaconOn, String reason) { if (beaconOn) { String settlement = null; if (member instanceof Person) { settlement = ((Person)member).getAssociatedSettlement().getName(); } else { settlement = ((Robot)member).getAssociatedSettlement().getName(); } // Creating mission emergency beacon event. HistoricalEvent newEvent = new MissionHistoricalEvent(EventType.MISSION_EMERGENCY_BEACON_ON, this, reason, this.getTypeID(), member.getName(), vehicle.getName(), vehicle.getCoordinates().getCoordinateString(), settlement ); eventManager.registerNewEvent(newEvent); logger.info(vehicle, member.getName() + " activated emergency beacon on"); } else { logger.info(vehicle, member.getName() + " deactivated emergency beacon on"); } vehicle.setEmergencyBeacon(beaconOn); } /** * Go to the nearest settlement and end collection phase if necessary. */ public void goToNearestSettlement() { Settlement nearestSettlement = findClosestSettlement(); if (nearestSettlement != null) { clearRemainingNavpoints(); addNavpoint(nearestSettlement); // Note: Not sure if they should become citizens of another settlement updateTravelDestination(); endCollectionPhase(); } } /** * Update mission to the next navpoint destination. */ public void updateTravelDestination() { NavPoint nextPoint = getNextNavpoint(); if (operateVehicleTask != null) { operateVehicleTask.setDestination(nextPoint.getLocation()); } setPhaseDescription(MessageFormat.format(TRAVELLING.getDescriptionTemplate(), getNextNavpoint().getDescription())); // $NON-NLS-1$ } /** * Finds the closest settlement to the mission. * * @return settlement */ public final Settlement findClosestSettlement() { Settlement result = null; Coordinates location = getCurrentMissionLocation(); double closestDistance = Double.MAX_VALUE; for (Settlement settlement : unitManager.getSettlements()) { double distance = Coordinates.computeDistance(settlement.getCoordinates(), location); if (distance < closestDistance) { result = settlement; closestDistance = distance; } } return result; } /** * Gets the actual total distance travelled during the mission so far. * * @return distance (km) */ public final double getActualTotalDistanceTravelled() { if (vehicle != null) { double dist = vehicle.getOdometerMileage() - startingTravelledDistance; if (dist > distanceTravelled) { // Update or record the distance distanceTravelled = dist; fireMissionUpdate(MissionEventType.DISTANCE_EVENT); return dist; } else { return distanceTravelled; } } return distanceTravelled; } /** * Time passing for mission. * * @param time the amount of time passing (in millisols) */ @Override public boolean timePassing(ClockPulse pulse) { // Add this mission as a vehicle listener (does nothing if already listening to // vehicle). // Note : this is needed so that mission will re-attach itself as a vehicle // listener after deserialization // since listener collection is transient. - Scott if (hasVehicle() && !vehicle.hasUnitListener(this)) { vehicle.addUnitListener(this); } return true; } /** * Catch unit update event. * * @param event the unit event. */ public void unitUpdate(UnitEvent event) { UnitEventType type = event.getType(); if (type == UnitEventType.LOCATION_EVENT) { fireMissionUpdate(MissionEventType.DISTANCE_EVENT); } else if (type == UnitEventType.NAME_EVENT) { fireMissionUpdate(MissionEventType.VEHICLE_EVENT); } } /** * Gets the required resources needed for loading the vehicle. * * @return resources and their number. */ protected Map<Integer, Number> getRequiredResourcesToLoad() { return getResourcesNeededForRemainingMission(true); } /** * Gets the optional resources needed for loading the vehicle. * * @return resources and their number. */ protected Map<Integer, Number> getOptionalResourcesToLoad() { // Also load EVA suit related parts return getSparePartsForTrip(getEstimatedTotalRemainingDistance()); } /** * Gets the required type of equipment needed for loading the vehicle. * * @return type of equipment and their number. */ protected Map<Integer, Integer> getRequiredEquipmentToLoad() { if (equipmentNeededCache == null) { equipmentNeededCache = getEquipmentNeededForRemainingMission(true); } return equipmentNeededCache; } /** * Gets the optional containers needed for storing the optional resources when loading up the vehicle. * * @return the containers needed. */ protected Map<Integer, Integer> getOptionalEquipmentToLoad() { Map<Integer, Integer> result = new ConcurrentHashMap<>(); // Figure out the type of containers needed by optional amount resources. Map<Integer, Number> optionalResources = getOptionalResourcesToLoad(); Iterator<Integer> i = optionalResources.keySet().iterator(); while (i.hasNext()) { Integer id = i.next(); // Check if it's an amount resource that can be stored inside if (id < ResourceUtil.FIRST_ITEM_RESOURCE_ID) { double amount = (double) optionalResources.get(id); // Obtain a container for storing the amount resource EquipmentType containerType = ContainerUtil.getContainerClassToHoldResource(id); int containerID = EquipmentType.getResourceID(containerType); double capacity = ContainerUtil.getContainerCapacity(containerType); int numContainers = (int) Math.ceil(amount / capacity); if (result.containsKey(containerID)) { numContainers += result.get(containerID); } result.put(containerID, numContainers); } // Note: containers are NOT designed to hold parts // Parts do not need a container. Any exceptions for that ? } return result; } /** * Checks if the vehicle has a malfunction that cannot be repaired. * * @return true if unrepairable malfunction. */ private boolean hasUnrepairableMalfunction() { boolean result = false; if (vehicle != null) { vehicle.getMalfunctionManager(); Iterator<Malfunction> i = vehicle.getMalfunctionManager().getMalfunctions().iterator(); while (i.hasNext()) { Malfunction malfunction = i.next(); Map<Integer, Integer> parts = malfunction.getRepairParts(); Iterator<Integer> j = parts.keySet().iterator(); while (j.hasNext()) { Integer part = j.next(); int number = parts.get(part); if (vehicle.getItemResourceStored(part) < number) { // vehicle.getInventory().addItemDemand(part, number); result = true; } } } } return result; } /** * If the mission is in TRAVELLING phase then only the current driver can participate. * If the mission is in REVIEWING phase then only the leader can participate. * * @param worker Worker requesting to help */ @Override public boolean canParticipate(MissionMember worker) { boolean valid = true; if (REVIEWING.equals(getPhase())) { valid = getStartingPerson().equals(worker); } else if (TRAVELLING.equals(getPhase())) { // Note: may check if vehicle operator() is null or not } return valid && super.canParticipate(worker); } /** * Checks to see if there are any currently embarking missions at the * settlement. * * @param settlement the settlement. * @return true if embarking missions. */ public static boolean hasEmbarkingMissions(Settlement settlement) { boolean result = false; Iterator<Mission> i = missionManager.getMissionsForSettlement(settlement).iterator(); while (i.hasNext()) { if (EMBARKING.equals(i.next().getPhase())) { result = true; break; } } return result; } /** * Checks to see how many currently embarking missions at the settlement. * * @param settlement the settlement. * @return true if embarking missions. */ public static int numEmbarkingMissions(Settlement settlement) { int result = 0; Iterator<Mission> i = missionManager.getMissionsForSettlement(settlement).iterator(); while (i.hasNext()) { if (EMBARKING.equals(i.next().getPhase())) { result++; } } return result; } /** * Checks to see how many missions currently under the approval phase at the settlement. * * @param settlement the settlement. * @return true if embarking missions. */ public static int numApprovingMissions(Settlement settlement) { int result = 0; Iterator<Mission> i = missionManager.getMissionsForSettlement(settlement).iterator(); while (i.hasNext()) { if (REVIEWING.equals(i.next().getPhase())) { result++; } } return result; } /** * Gets the settlement associated with the vehicle. * * @return settlement or null if none. */ @Override public Settlement getAssociatedSettlement() { return vehicle.getAssociatedSettlement(); } /** * For a Vehicle Mission used the vehicles position directly */ @Override public Coordinates getCurrentMissionLocation() { if (vehicle != null) { return vehicle.getCoordinates(); } return super.getCurrentMissionLocation(); } @Override public void destroy() { super.destroy(); vehicle = null; lastOperator = null; operateVehicleTask = null; if (equipmentNeededCache != null) { equipmentNeededCache.clear(); } equipmentNeededCache = null; } /** * Can the mission vehicle be unloaded at this Settlement * * @param settlement * @return */ public boolean isVehicleUnloadableHere(Settlement settlement) { // It is either a local mission unloading return DISEMBARKING.equals(getPhase()) && getAssociatedSettlement().equals(settlement); } /** * Can the mission vehicle be loaded at a Settlement. Must be in * the EMBARKING phase at the mission starting point. * * @param settlement * @return */ public boolean isVehicleLoadableHere(Settlement settlement) { return EMBARKING.equals(getPhase()) && getAssociatedSettlement().equals(settlement); } /** * Start the TRAVELLING phase of the mission. This will advanced to the * next navigation point. */ protected void startTravellingPhase() { if (dateEmbarked == null) { dateEmbarked = marsClock.getTrucatedDateTimeStamp(); } startTravelToNextNode(); setPhase(TRAVELLING, getNextNavpoint().getDescription()); } /** * Start the disembarking phase */ protected void startDisembarkingPhase() { NavPoint np = getCurrentNavpoint(); setPhase(DISEMBARKING, (np != null ? np.getDescription() : "Unknown")); } /** * Sets the starting settlement. * * @param startingSettlement the new starting settlement */ private final void setStartingSettlement(Settlement startingSettlement) { this.startingSettlement = startingSettlement; fireMissionUpdate(MissionEventType.STARTING_SETTLEMENT_EVENT); } /** * Gets the starting settlement. * * @return starting settlement */ public final Settlement getStartingSettlement() { return startingSettlement; } }
mars-sim/mars-sim
mars-sim-core/src/main/java/org/mars_sim/msp/core/person/ai/mission/VehicleMission.java
Java
gpl-3.0
54,214
/******************************************************************************* * Pineapple - a tool to install, configure and test Java web applications * and infrastructure. * * Copyright (C) 2007-2013 Allan Thrane Andersen.. * * This file is part of Pineapple. * * Pineapple is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * Pineapple is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * license for more details. * * You should have received a copy of the GNU General Public License along * with Pineapple. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.alpha.pineapple.plugin; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PluginSession { }
athrane/pineapple
modules/pineapple-api/src/main/java/com/alpha/pineapple/plugin/PluginSession.java
Java
gpl-3.0
1,394
package info.novatec.testit.livingdoc.server.domain.dao.hibernate; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.hibernate.Criteria; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import info.novatec.testit.livingdoc.server.LivingDocServerErrorKey; import info.novatec.testit.livingdoc.server.LivingDocServerException; import info.novatec.testit.livingdoc.server.database.SessionService; import info.novatec.testit.livingdoc.server.domain.Execution; import info.novatec.testit.livingdoc.server.domain.Reference; import info.novatec.testit.livingdoc.server.domain.Repository; import info.novatec.testit.livingdoc.server.domain.Requirement; import info.novatec.testit.livingdoc.server.domain.Specification; import info.novatec.testit.livingdoc.server.domain.SystemUnderTest; import info.novatec.testit.livingdoc.server.domain.component.ContentType; import info.novatec.testit.livingdoc.server.domain.dao.DocumentDao; import info.novatec.testit.livingdoc.server.domain.dao.RepositoryDao; import info.novatec.testit.livingdoc.server.domain.dao.SystemUnderTestDao; public class HibernateDocumentDao implements DocumentDao { public static final String SYSTEM_UNDER_TEST_NOT_FOUND_MSG = "SystemUnderTest not found"; public static final String SYSTEM_UNDER_TEST = "systemUnderTest"; public static final String SUT = "sut"; public static final String SUT_NAME = "sut.name"; public static final String REPO = "repo"; public static final String REPO_UID = "repo.uid"; public static final String SUPPRESS_UNCHECKED = "unchecked"; private SessionService sessionService; private RepositoryDao repositoryDao; private SystemUnderTestDao systemUnderTestDao; public HibernateDocumentDao(SessionService sessionService, RepositoryDao repositoryDao, SystemUnderTestDao systemUnderTestDao) { this.sessionService = sessionService; this.repositoryDao = repositoryDao; this.systemUnderTestDao = systemUnderTestDao; } public HibernateDocumentDao(SessionService sessionService) { this(sessionService, new HibernateRepositoryDao(sessionService), new HibernateSystemUnderTestDao(sessionService)); } @Override public Requirement getRequirementByName(String repositoryUid, String requirementName) { Criteria crit = sessionService.getSession().createCriteria(Requirement.class); crit.add(Restrictions.eq("name", requirementName)); crit.createAlias("repository", "r"); crit.add(Restrictions.eq("r.uid", repositoryUid)); Requirement requirement = ( Requirement ) crit.uniqueResult(); HibernateLazyInitializer.init(requirement); return requirement; } @Override public Requirement createRequirement(String repositoryUid, String requirementName) throws LivingDocServerException { Repository repository = repositoryDao.getByUID(repositoryUid); if (repository == null) { throw new LivingDocServerException(LivingDocServerErrorKey.REPOSITORY_NOT_FOUND, "Repo not found"); } Requirement requirement = Requirement.newInstance(requirementName); repository.addRequirement(requirement); sessionService.getSession().save(repository); return requirement; } @Override public Requirement getOrCreateRequirement(String repositoryUid, String requirementName) throws LivingDocServerException { Requirement requirement = getRequirementByName(repositoryUid, requirementName); if (requirement == null) { return createRequirement(repositoryUid, requirementName); } HibernateLazyInitializer.init(requirement); return requirement; } /** * @throws LivingDocServerException */ @Override public void removeRequirement(Requirement requirement) throws LivingDocServerException { requirement = getRequirementByName(requirement.getRepository().getUid(), requirement.getName()); if (requirement != null) { requirement.getRepository().removeRequirement(requirement); sessionService.getSession().delete(requirement); } } @Override public Specification getSpecificationByName(String repositoryUid, String specificationName) { Criteria crit = sessionService.getSession().createCriteria(Specification.class); crit.add(Restrictions.ilike("name", specificationName, MatchMode.EXACT)); crit.createAlias("repository", "r"); crit.add(Restrictions.eq("r.uid", repositoryUid)); Specification specification = ( Specification ) crit.uniqueResult(); HibernateLazyInitializer.init(specification); return specification; } @Override public Specification getSpecificationById(Long id) { Criteria crit = sessionService.getSession().createCriteria(Specification.class); crit.add(Restrictions.eq("id", id)); Specification specification = ( Specification ) crit.uniqueResult(); HibernateLazyInitializer.init(specification); return specification; } @Override public Specification createSpecification(String systemUnderTestName, String repositoryUid, String specificationName) throws LivingDocServerException { Repository repository = repositoryDao.getByUID(repositoryUid); if (repository == null) { throw new LivingDocServerException(LivingDocServerErrorKey.REPOSITORY_NOT_FOUND, "Repo not found"); } SystemUnderTest sut; if (systemUnderTestName != null) { sut = systemUnderTestDao.getByName(repository.getProject().getName(), systemUnderTestName); if (sut == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SUT_NOT_FOUND, SYSTEM_UNDER_TEST_NOT_FOUND_MSG); } } else { sut = repository.getProject().getDefaultSystemUnderTest(); if (sut == null) { throw new LivingDocServerException(LivingDocServerErrorKey.PROJECT_DEFAULT_SUT_NOT_FOUND, "Default sut not found"); } } Specification specification = Specification.newInstance(specificationName); repository.addSpecification(specification); specification.addSystemUnderTest(sut); if (repository.getContentType().equals(ContentType.REQUIREMENT)) { repository.setContentType(ContentType.BOTH); } sessionService.getSession().save(repository); return specification; } @Override public Specification getOrCreateSpecification(String systemUnderTestName, String repositoryUid, String specificationName) throws LivingDocServerException { Specification specification = getSpecificationByName(repositoryUid, specificationName); if (specification == null) { specification = createSpecification(systemUnderTestName, repositoryUid, specificationName); } return specification; } @Override public void updateSpecification(Specification oldSpecification, Specification newSpecification) throws LivingDocServerException { String oldUid = oldSpecification.getRepository().getUid(); Specification specificationToUpdate = getSpecificationByName(oldUid, oldSpecification.getName()); if (specificationToUpdate == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SPECIFICATION_NOT_FOUND, "Specification not found"); } specificationToUpdate.setName(newSpecification.getName()); sessionService.getSession().update(specificationToUpdate); } @Override public void removeSpecification(Specification specification) throws LivingDocServerException { specification = getSpecificationByName(specification.getRepository().getUid(), specification.getName()); if (specification != null) { specification.getRepository().removeSpecification(specification); sessionService.getSession().delete(specification); } } @Override public void addSystemUnderTest(SystemUnderTest systemUnderTest, Specification specification) throws LivingDocServerException { SystemUnderTest sut = systemUnderTestDao.getByName(systemUnderTest.getProject().getName(), systemUnderTest .getName()); if (sut == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SUT_NOT_FOUND, SYSTEM_UNDER_TEST_NOT_FOUND_MSG); } specification = getSpecificationByName(specification.getRepository().getUid(), specification.getName()); if (specification == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SPECIFICATION_NOT_FOUND, "Specification not found"); } specification.addSystemUnderTest(sut); sessionService.getSession().save(specification); } @Override public void removeSystemUnderTest(SystemUnderTest systemUnderTest, Specification specification) throws LivingDocServerException { if ( ! getAllReferences(systemUnderTest, specification).isEmpty()) { throw new LivingDocServerException(LivingDocServerErrorKey.SUT_REFERENCE_ASSOCIATED, "SystemUnderTest is in a reference"); } SystemUnderTest sut = systemUnderTestDao.getByName(systemUnderTest.getProject().getName(), systemUnderTest .getName()); if (sut == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SUT_NOT_FOUND, SYSTEM_UNDER_TEST_NOT_FOUND_MSG); } specification = getSpecificationByName(specification.getRepository().getUid(), specification.getName()); if (specification == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SPECIFICATION_NOT_FOUND, "Specification not found"); } specification.removeSystemUnderTest(sut); sessionService.getSession().save(specification); } @Override public Reference get(Reference reference) { final Criteria crit = sessionService.getSession().createCriteria(Reference.class); if (StringUtils.isEmpty(reference.getSections())) { crit.add(Restrictions.isNull("sections")); } else { crit.add(Restrictions.eq("sections", reference.getSections())); } crit.createAlias("requirement", "req"); crit.add(Restrictions.eq("req.name", reference.getRequirement().getName())); crit.createAlias("req.repository", "reqRepo"); crit.add(Restrictions.eq("reqRepo.uid", reference.getRequirement().getRepository().getUid())); crit.createAlias("specification", "spec"); crit.add(Restrictions.eq("spec.name", reference.getSpecification().getName())); crit.createAlias("spec.repository", "specRepo"); crit.add(Restrictions.eq("specRepo.uid", reference.getSpecification().getRepository().getUid())); crit.createAlias(SYSTEM_UNDER_TEST, SUT); crit.add(Restrictions.eq(SUT_NAME, reference.getSystemUnderTest().getName())); crit.createAlias("sut.project", "sp"); crit.add(Restrictions.eq("sp.name", reference.getSystemUnderTest().getProject().getName())); Reference result = ( Reference ) crit.uniqueResult(); HibernateLazyInitializer.init(result); return result; } public List<Reference> getAllReferences(SystemUnderTest systemUnderTest, Specification specification) { final Criteria crit = sessionService.getSession().createCriteria(Reference.class); crit.createAlias("specification", "spec"); crit.add(Restrictions.eq("spec.name", specification.getName())); crit.createAlias("spec.repository", REPO); crit.add(Restrictions.eq(REPO_UID, specification.getRepository().getUid())); crit.createAlias(SYSTEM_UNDER_TEST, SUT); crit.add(Restrictions.eq(SUT_NAME, systemUnderTest.getName())); crit.createAlias("sut.project", "sp"); crit.add(Restrictions.eq("sp.name", systemUnderTest.getProject().getName())); @SuppressWarnings(SUPPRESS_UNCHECKED) List<Reference> references = crit.list(); HibernateLazyInitializer.initCollection(references); return references; } @Override public List<Reference> getAllReferences(Specification specification) { final Criteria crit = sessionService.getSession().createCriteria(Reference.class); crit.createAlias("specification", "spec"); crit.add(Restrictions.eq("spec.name", specification.getName())); crit.createAlias("spec.repository", REPO); crit.add(Restrictions.eq(REPO_UID, specification.getRepository().getUid())); crit.createAlias("requirement", "req"); crit.addOrder(Order.asc("req.name")); crit.createAlias(SYSTEM_UNDER_TEST, SUT); crit.addOrder(Order.asc(SUT_NAME)); @SuppressWarnings(SUPPRESS_UNCHECKED) List<Reference> references = crit.list(); HibernateLazyInitializer.initCollection(references); return references; } @Override public List<Reference> getAllReferences(Requirement requirement) { final Criteria crit = sessionService.getSession().createCriteria(Reference.class); crit.createAlias("requirement", "req"); crit.add(Restrictions.eq("req.name", requirement.getName())); crit.createAlias("req.repository", REPO); crit.add(Restrictions.eq(REPO_UID, requirement.getRepository().getUid())); @SuppressWarnings(SUPPRESS_UNCHECKED) List<Reference> references = crit.list(); HibernateLazyInitializer.initCollection(references); return references; } @Override public Reference createReference(Reference reference) throws LivingDocServerException { String projectName = reference.getSystemUnderTest().getProject().getName(); String reqRepoUid = reference.getRequirement().getRepository().getUid(); String requirementName = reference.getRequirement().getName(); String testName = reference.getSpecification().getName(); String testRepoUid = reference.getSpecification().getRepository().getUid(); String sutName = reference.getSystemUnderTest().getName(); String sections = reference.getSections(); Requirement requirement = getOrCreateRequirement(reqRepoUid, requirementName); checkDuplicatedReference(requirement, testName, testRepoUid, sutName, sections); Specification specification = getOrCreateSpecification(sutName, testRepoUid, testName); SystemUnderTest sut = systemUnderTestDao.getByName(projectName, sutName); reference = Reference.newInstance(requirement, specification, sut, sections); sessionService.getSession().save(reference); return reference; } private void checkDuplicatedReference(Requirement requirement, String testName, String testRepoUid, String sutName, String sections) throws LivingDocServerException { Set<Reference> references = requirement.getReferences(); for (Reference reference : references) { if (reference.getSystemUnderTest().getName().equalsIgnoreCase(sutName) && reference.getSpecification() .getRepository().getUid().equalsIgnoreCase(testRepoUid) && reference.getSpecification().getName() .equalsIgnoreCase(testName) && StringUtils.equals(reference.getSections(), sections)) { throw new LivingDocServerException(LivingDocServerErrorKey.REFERENCE_CREATE_ALREADYEXIST, "Reference already exist"); } } } @Override public void removeReference(Reference reference) throws LivingDocServerException { reference = get(reference); if (reference != null) { Requirement requirement = reference.getRequirement(); requirement.removeReference(reference); reference.getSpecification().removeReference(reference); if (requirement.getReferences().isEmpty()) { requirement.getRepository().removeRequirement(requirement); sessionService.getSession().delete(requirement); } sessionService.getSession().delete(reference); } } @Override public Reference updateReference(Reference oldReference, Reference newReference) throws LivingDocServerException { removeReference(oldReference); return createReference(newReference); } @Override public Execution createExecution(Execution execution) throws LivingDocServerException { sessionService.getSession().save(execution); return execution; } @Override public Execution runSpecification(SystemUnderTest systemUnderTest, Specification specification, boolean implemeted, String locale) throws LivingDocServerException { specification = getOrCreateSpecification(systemUnderTest.getName(), specification.getRepository().getUid(), specification.getName()); systemUnderTest = systemUnderTestDao.getByName(systemUnderTest.getProject().getName(), systemUnderTest.getName()); if (systemUnderTest == null) { throw new LivingDocServerException(LivingDocServerErrorKey.SUT_NOT_FOUND, SYSTEM_UNDER_TEST_NOT_FOUND_MSG); } Execution exe = systemUnderTest.execute(specification, implemeted, null, locale); if (exe.wasRunned()) { if (exe.wasRemotelyExecuted()) { exe.setSpecification(getOrCreateSpecification(systemUnderTest.getName(), specification.getRepository() .getUid(), specification.getName())); exe.setSystemUnderTest(systemUnderTestDao.getByName(systemUnderTest.getProject().getName(), systemUnderTest .getName())); } specification.addExecution(exe); sessionService.getSession().save(exe); } return exe; } @Override public Reference runReference(Reference reference, String locale) throws LivingDocServerException { Reference loadedReference = get(reference); if (loadedReference == null) { throw new LivingDocServerException(LivingDocServerErrorKey.REFERENCE_NOT_FOUND, "Reference not found"); } Execution exe = loadedReference.execute(false, locale); if (exe.wasRunned()) { loadedReference.getSpecification().addExecution(exe); loadedReference.setLastExecution(exe); sessionService.getSession().save(exe); } return loadedReference; } @Override public List<Specification> getSpecifications(SystemUnderTest sut, Repository repository) { final Criteria crit = sessionService.getSession().createCriteria(Specification.class); crit.createAlias("repository", REPO); crit.add(Restrictions.eq(REPO_UID, repository.getUid())); crit.createAlias("targetedSystemUnderTests", "suts"); crit.add(Restrictions.eq("suts.name", sut.getName())); crit.createAlias("suts.project", "sp"); crit.add(Restrictions.eq("sp.name", sut.getProject().getName())); crit.addOrder(Order.asc("name")); @SuppressWarnings(SUPPRESS_UNCHECKED) List<Specification> specifications = crit.list(); HibernateLazyInitializer.initCollection(specifications); return specifications; } @Override public List<Execution> getSpecificationExecutions(Specification specification, SystemUnderTest sut, int maxResults) { final Criteria crit = sessionService.getSession().createCriteria(Execution.class); crit.add(Restrictions.eq("specification.id", specification.getId())); if (sut != null) { crit.createAlias(SYSTEM_UNDER_TEST, SUT); crit.add(Restrictions.eq(SUT_NAME, sut.getName())); } /* crit.add(Restrictions.or(Restrictions.or(Restrictions.not( * Restrictions . eq("errors", 0)), * Restrictions.not(Restrictions.eq("success", 0))), * Restrictions.or(Restrictions.not(Restrictions.eq("ignored", 0)), * Restrictions.not(Restrictions.eq("failures", 0))))); */ crit.addOrder(Order.desc("executionDate")); crit.setMaxResults(maxResults); @SuppressWarnings(SUPPRESS_UNCHECKED) List<Execution> executions = crit.list(); HibernateLazyInitializer.initCollection(executions); Collections.reverse(executions); return executions; } @Override public Execution getSpecificationExecution(Long id) { final Criteria crit = sessionService.getSession().createCriteria(Execution.class); crit.add(Restrictions.eq("id", id)); Execution execution = ( Execution ) crit.uniqueResult(); HibernateLazyInitializer.init(execution); return execution; } }
benhamidene/livingdoc-confluence
livingdoc-confluence-plugin/src/main/java/info/novatec/testit/livingdoc/server/domain/dao/hibernate/HibernateDocumentDao.java
Java
gpl-3.0
21,164
package org.lenndi.umtapo.util; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.stereotype.Component; /** * JsonViewResolver. * <p> * Created by axel on 03/01/17. */ @Component public class JsonViewResolver { /** * The interface Borrower search view. */ public interface BorrowerSearchView { } /** * Dynamic mapping mapping jackson value. * * @param jsonView the json view * @param object the object * @return the mapping jackson value */ public MappingJacksonValue dynamicMapping(String jsonView, Object object) { MappingJacksonValue wrapper = new MappingJacksonValue(object); if (jsonView.equals("BorrowerSearchView")) { wrapper.setSerializationView(BorrowerSearchView.class); } else { wrapper = null; } return wrapper; } }
Lenndi/Umtapo
back/src/main/java/org/lenndi/umtapo/util/JsonViewResolver.java
Java
gpl-3.0
912
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2016 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.lovecraftpixeldungeon.sprites; import com.shatteredpixel.lovecraftpixeldungeon.Assets; import com.shatteredpixel.lovecraftpixeldungeon.Dungeon; import com.shatteredpixel.lovecraftpixeldungeon.items.weapon.missiles.Dart; import com.watabou.noosa.TextureFilm; import com.watabou.utils.Callback; public class ScorpioSprite extends MobSprite { private int cellToAttack; public ScorpioSprite() { super(); texture( Assets.SCORPIO ); TextureFilm frames = new TextureFilm( texture, 18, 17 ); idle = new Animation( 12, true ); idle.frames( frames, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2 ); run = new Animation( 8, true ); run.frames( frames, 5, 5, 6, 6 ); attack = new Animation( 15, false ); attack.frames( frames, 0, 3, 4 ); zap = attack.clone(); die = new Animation( 12, false ); die.frames( frames, 0, 7, 8, 9, 10 ); play( idle ); } @Override public int blood() { return 0xFF44FF22; } @Override public void attack( int cell ) { if (!Dungeon.level.adjacent( cell, ch.pos )) { cellToAttack = cell; turnTo( ch.pos , cell ); play( zap ); } else { super.attack( cell ); } } @Override public void onComplete( Animation anim ) { if (anim == zap) { idle(); ((MissileSprite)parent.recycle( MissileSprite.class )). reset( ch.pos, cellToAttack, new Dart(), new Callback() { @Override public void call() { ch.onAttackComplete(); } } ); } else { super.onComplete( anim ); } } }
TypedScroll/LCPD
core/src/main/java/com/shatteredpixel/lovecraftpixeldungeon/sprites/ScorpioSprite.java
Java
gpl-3.0
2,323
/* * * * * This file is part of QuickLyric * * Created by geecko * * * * QuickLyric is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * QuickLyric is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * * along with QuickLyric. If not, see <http://www.gnu.org/licenses/>. * */ /* * * * * This file is part of QuickLyric * * Created by geecko * * * * QuickLyric is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * QuickLyric is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * * along with QuickLyric. If not, see <http://www.gnu.org/licenses/>. * */ package com.geecko.QuickLyric.provider; import com.geecko.QuickLyric.annotations.Reflection; import com.geecko.QuickLyric.model.Lyrics; import com.geecko.QuickLyric.utils.Net; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; @Reflection public class UrbanLyrics { public static final String domain = "www.urbanlyrics.com/"; @Reflection public static Lyrics fromMetaData(String artist, String song) { String htmlArtist = artist.replaceAll("[\\s'\"-]", "") .replaceAll("&", "and").replaceAll("[^A-Za-z0-9]", ""); String htmlSong = song.replaceAll("[\\s'\"-]", "") .replaceAll("&", "and").replaceAll("[^A-Za-z0-9]", ""); if (htmlArtist.toLowerCase(Locale.getDefault()).startsWith("the")) htmlArtist = htmlArtist.substring(3); String urlString = String.format( "http://www.urbanlyrics.com/lyrics/%s/%s.html", htmlArtist.toLowerCase(Locale.getDefault()), htmlSong.toLowerCase(Locale.getDefault())); return fromURL(urlString, artist, song); } public static Lyrics fromURL(String url, String artist, String song) { String html; try { Document document = Jsoup.connect(url).userAgent(Net.USER_AGENT).get(); if (document.location().contains(domain)) html = document.html(); else throw new IOException("Redirected to wrong domain " + document.location()); } catch (HttpStatusException e) { return new Lyrics(Lyrics.NO_RESULT); } catch (IOException e) { e.printStackTrace(); return new Lyrics(Lyrics.ERROR); } Pattern p = Pattern.compile( "<!-- lyrics start -->(.*)<!-- lyrics end -->", Pattern.DOTALL); Matcher matcher = p.matcher(html); if (artist == null || song == null) { Pattern metaPattern = Pattern.compile( "ArtistName = \"(.*)\";\r\nSongName = \"(.*)\";\r\n", Pattern.DOTALL); Matcher metaMatcher = metaPattern.matcher(html); if (metaMatcher.find()) { artist = metaMatcher.group(1); song = metaMatcher.group(2); song = song.substring(0, song.indexOf('"')); } else artist = song = ""; } if (matcher.find()) { Lyrics l = new Lyrics(Lyrics.POSITIVE_RESULT); l.setArtist(artist); String text = matcher.group(1); text = text.replaceAll("\\[[^\\[]*\\]", ""); l.setText(text); l.setTitle(song); l.setURL(url); l.setSource("UrbanLyrics"); return l; } else return new Lyrics(Lyrics.NEGATIVE_RESULT); } }
svenoaks/QuickLyric
QuickLyric/src/main/java/com/geecko/QuickLyric/provider/UrbanLyrics.java
Java
gpl-3.0
4,529
package ai.grakn.graql.internal.gremlin.fragment; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.util.Schema; import com.google.common.collect.ImmutableSet; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Test; import static ai.grakn.util.Schema.EdgeLabel.PLAYS; import static ai.grakn.util.Schema.EdgeLabel.SUB; import static ai.grakn.util.Schema.VertexProperty.THING_TYPE_LABEL_ID; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class InPlaysFragmentTest { private final Var start = Graql.var(); private final Var end = Graql.var(); private final Fragment fragment = Fragments.inPlays(null, start, end, false); @Test @SuppressWarnings("unchecked") public void testApplyTraversalFollowsSubsDownwards() { GraphTraversal<Vertex, Vertex> traversal = __.V(); fragment.applyTraversalInner(traversal, null, ImmutableSet.of()); // Make sure we check this is a vertex, then traverse plays and downwards subs once assertThat(traversal, is(__.V() .has(Schema.VertexProperty.ID.name()) .in(PLAYS.getLabel()) .union(__.<Vertex>not(__.has(THING_TYPE_LABEL_ID.name())).not(__.hasLabel(Schema.BaseType.SHARD.name())), __.repeat(__.in(SUB.getLabel())).emit()).unfold() )); } }
burukuru/grakn
grakn-graql/src/test/java/ai/grakn/graql/internal/gremlin/fragment/InPlaysFragmentTest.java
Java
gpl-3.0
1,537
package com.hartwig.hmftools.protect.evidence; import java.util.List; import java.util.stream.Collectors; import com.google.common.collect.Lists; import com.hartwig.hmftools.common.protect.ProtectEvidence; import com.hartwig.hmftools.common.virus.AnnotatedVirus; import com.hartwig.hmftools.common.virus.VirusConstants; import com.hartwig.hmftools.common.virus.VirusInterpreterData; import com.hartwig.hmftools.common.virus.VirusLikelihoodType; import com.hartwig.hmftools.serve.actionability.characteristic.ActionableCharacteristic; import com.hartwig.hmftools.serve.extraction.characteristic.TumorCharacteristicAnnotation; import org.jetbrains.annotations.NotNull; public class VirusEvidence { static final String HPV_POSITIVE_EVENT = "HPV positive"; static final String EBV_POSITIVE_EVENT = "EBV positive"; @NotNull private final PersonalizedEvidenceFactory personalizedEvidenceFactory; @NotNull private final List<ActionableCharacteristic> actionableViruses; public VirusEvidence(@NotNull final PersonalizedEvidenceFactory personalizedEvidenceFactory, @NotNull final List<ActionableCharacteristic> actionableCharacteristics) { this.personalizedEvidenceFactory = personalizedEvidenceFactory; this.actionableViruses = actionableCharacteristics.stream() .filter(x -> x.name() == TumorCharacteristicAnnotation.HPV_POSITIVE || x.name() == TumorCharacteristicAnnotation.EBV_POSITIVE) .collect(Collectors.toList()); } @NotNull public List<ProtectEvidence> evidence(@NotNull VirusInterpreterData virusInterpreterData) { List<AnnotatedVirus> hpv = virusesWithInterpretation(virusInterpreterData, VirusConstants.HPV); List<AnnotatedVirus> ebv = virusesWithInterpretation(virusInterpreterData, VirusConstants.EBV); boolean reportHPV = hasReportedWithHighDriverLikelihood(hpv); boolean reportEBV = hasReportedWithHighDriverLikelihood(ebv); List<ProtectEvidence> result = Lists.newArrayList(); for (ActionableCharacteristic virus : actionableViruses) { switch (virus.name()) { case HPV_POSITIVE: { if (!hpv.isEmpty()) { ProtectEvidence evidence = personalizedEvidenceFactory.somaticEvidence(virus).reported(reportHPV).event(HPV_POSITIVE_EVENT).build(); result.add(evidence); } break; } case EBV_POSITIVE: { if (!ebv.isEmpty()) { ProtectEvidence evidence = personalizedEvidenceFactory.somaticEvidence(virus).reported(reportEBV).event(EBV_POSITIVE_EVENT).build(); result.add(evidence); } break; } } } return result; } private static boolean hasReportedWithHighDriverLikelihood(@NotNull List<AnnotatedVirus> viruses) { for (AnnotatedVirus virus : viruses) { if (virus.reported() && virus.virusDriverLikelihoodType() == VirusLikelihoodType.HIGH) { return true; } } return false; } @NotNull private static List<AnnotatedVirus> virusesWithInterpretation(@NotNull VirusInterpreterData virusInterpreterData, @NotNull VirusConstants interpretationToInclude) { List<AnnotatedVirus> virusesWithInterpretation = Lists.newArrayList(); for (AnnotatedVirus virus : virusInterpreterData.reportableViruses()) { String interpretation = virus.interpretation(); if (interpretation != null && interpretation.equals(interpretationToInclude.name())) { virusesWithInterpretation.add(virus); } } for (AnnotatedVirus virus : virusInterpreterData.unreportedViruses()) { String interpretation = virus.interpretation(); if (interpretation != null && interpretation.equals(interpretationToInclude.name())) { virusesWithInterpretation.add(virus); } } return virusesWithInterpretation; } }
hartwigmedical/hmftools
protect/src/main/java/com/hartwig/hmftools/protect/evidence/VirusEvidence.java
Java
gpl-3.0
4,271
/*___Generated_by_IDEA___*/ /** Automatically generated file. DO NOT MODIFY */ package com.example.SerialTermBT; public final class BuildConfig { public final static boolean DEBUG = true; }
mekatronik-achmadi/bt_serialterm_v1
gen/com/example/SerialTermBT/BuildConfig.java
Java
gpl-3.0
195
/* * Copyright (C) 2022 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * sklintyg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.inera.intyg.webcert.integration.kundportalen.dto; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class OrganizationResponse { @JsonProperty("orgNo") private String organizationNumber; @JsonProperty("serviceCode") private List<String> serviceCodes; public String getOrganizationNumber() { return organizationNumber; } public void setOrganizationNumber(String organizationNumber) { this.organizationNumber = organizationNumber; } public List<String> getServiceCodes() { return serviceCodes; } public void setServiceCodes(List<String> serviceCodes) { this.serviceCodes = serviceCodes; } }
sklintyg/webcert
integration/kundportalen-integration/src/main/java/se/inera/intyg/webcert/integration/kundportalen/dto/OrganizationResponse.java
Java
gpl-3.0
1,490
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.ports.metadata; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Date; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import com.rapidminer.RapidMiner; import com.rapidminer.example.Attribute; import com.rapidminer.example.AttributeRole; import com.rapidminer.example.Attributes; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.Statistics; import com.rapidminer.operator.Annotations; import com.rapidminer.tools.Ontology; import com.rapidminer.tools.ParameterService; import com.rapidminer.tools.Tools; import com.rapidminer.tools.math.container.Range; /** * Meta data about an attribute * * @author Simon Fischer * */ public class AttributeMetaData implements Serializable { private static final long serialVersionUID = 1L; private ExampleSetMetaData owner = null; private String name; private int type = Ontology.ATTRIBUTE_VALUE; private String role = null; private MDInteger numberOfMissingValues = new MDInteger(0); // it has to be ensured that the appropriate value set type is constructed anyway private SetRelation valueSetRelation = SetRelation.UNKNOWN; private Range valueRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); private Set<String> valueSet = new TreeSet<String>(); private String mode; private MDReal mean = new MDReal(); private Annotations annotations = new Annotations(); public AttributeMetaData(String name, int type) { this(name, type, null); } /** * This will generate the complete meta data with all values. */ public AttributeMetaData(AttributeRole role, ExampleSet exampleSet) { this(role, exampleSet, false); } /** * This will generate the attribute meta data with the data's values shortened if the number of * values exceeds the respective property and the boolean flag is set to true. If shortened only * the first 100 characters of each nominal value is returned. */ public AttributeMetaData(AttributeRole role, ExampleSet exampleSet, boolean shortened) { this(role.getAttribute().getName(), role.getAttribute().getValueType(), role.getSpecialName()); Attribute att = role.getAttribute(); if (att.isNominal()) { int maxValues = shortened ? getMaximumNumberOfNominalValues() : Integer.MAX_VALUE; valueSet.clear(); for (String value : att.getMapping().getValues()) { if (shortened && value.length() > 100) { value = value.substring(0, 100); } valueSet.add(value); maxValues--; if (maxValues == 0) { break; } } valueSetRelation = SetRelation.EQUAL; } if (exampleSet != null) { numberOfMissingValues = new MDInteger((int) exampleSet.getStatistics(att, Statistics.UNKNOWN)); if (att.isNumerical() || Ontology.ATTRIBUTE_VALUE_TYPE.isA(att.getValueType(), Ontology.DATE_TIME)) { valueSetRelation = SetRelation.EQUAL; valueRange = new Range(exampleSet.getStatistics(att, Statistics.MINIMUM), exampleSet.getStatistics(att, Statistics.MAXIMUM)); setMean(new MDReal(exampleSet.getStatistics(att, Statistics.AVERAGE))); } if (att.isNominal()) { double modeIndex = exampleSet.getStatistics(att, Statistics.MODE); if (!Double.isNaN(modeIndex) && modeIndex >= 0 && modeIndex < att.getMapping().size()) { setMode(att.getMapping().mapIndex((int) modeIndex)); } } } else { numberOfMissingValues = new MDInteger(); if (att.isNumerical()) { setMean(new MDReal()); } if (att.isNominal()) { setMode(null); } } this.annotations.putAll(att.getAnnotations()); } public AttributeMetaData(String name, int type, String role) { this.name = name; this.type = type; this.role = role; } public AttributeMetaData(String name, String role, int nominalType, String... values) { this(name, role, values); this.type = nominalType; } public AttributeMetaData(String name, String role, String... values) { this.name = name; this.type = Ontology.NOMINAL; this.role = role; this.valueSetRelation = SetRelation.EQUAL; for (String string : values) { valueSet.add(string); } } public AttributeMetaData(String name, String role, Range range) { this.name = name; this.role = role; this.type = Ontology.REAL; this.valueRange = range; this.valueSetRelation = SetRelation.EQUAL; } public AttributeMetaData(String name, String role, int type, Range range) { this(name, role, range); this.type = type; } private AttributeMetaData(AttributeMetaData attributeMetaData) { // must not keep references on mutable objects! this.name = attributeMetaData.name; this.role = attributeMetaData.role; this.type = attributeMetaData.type; this.numberOfMissingValues = new MDInteger(attributeMetaData.numberOfMissingValues); this.mean = new MDReal(attributeMetaData.mean); this.mode = attributeMetaData.mode; this.valueSetRelation = attributeMetaData.getValueSetRelation(); this.valueRange = new Range(attributeMetaData.getValueRange()); this.valueSet = new TreeSet<String>(); this.annotations = new Annotations(attributeMetaData.annotations); valueSet.addAll(attributeMetaData.getValueSet()); } public AttributeMetaData(Attribute attribute) { this.name = attribute.getName(); this.type = attribute.getValueType(); this.annotations.putAll(attribute.getAnnotations()); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (annotations == null) { annotations = new Annotations(); } } public String getRole() { return role; } public String getName() { return name; } public void setName(String name) { String oldName = this.name; this.name = name; // informing ExampleSetMEtaData if one registered if (owner != null) { owner.attributeRenamed(this, oldName); } } public String getTypeName() { return Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(type); } public int getValueType() { return type; } /** * If you change the type, keep in mind to set the value sets and their relation */ public void setType(int type) { if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.NUMERICAL)) { valueSet.clear(); } else { setValueRange(new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), SetRelation.SUBSET); } this.type = type; } @Override public String toString() { return getDescription(); } public String getDescription() { StringBuilder buf = new StringBuilder(); if (role != null && !role.equals(Attributes.ATTRIBUTE_NAME)) { buf.append("<em>"); buf.append(role); buf.append("</em>: "); } buf.append(getName()); buf.append(" ("); buf.append(getValueTypeName()); if (valueSetRelation != SetRelation.UNKNOWN) { buf.append(" in "); appendValueSetDescription(buf); } else { if (isNominal()) { buf.append(", values unkown"); } else { buf.append(", range unknown"); } } switch (containsMissingValues()) { case NO: buf.append("; no missing values"); break; case YES: buf.append("; "); buf.append(numberOfMissingValues.toString()); buf.append(" missing values"); break; case UNKNOWN: buf.append("; may contain missing values"); break; } buf.append(")"); return buf.toString(); } public String getValueTypeName() { return Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(getValueType()); } public String getValueSetDescription() { StringBuilder buf = new StringBuilder(); appendValueSetDescription(buf); return buf.toString(); } private void appendValueSetDescription(StringBuilder buf) { if (isNominal()) { buf.append(valueSetRelation + " {"); boolean first = true; String mode = getMode(); int index = 0; for (String value : valueSet) { index++; if (first) { first = false; } else { buf.append(", "); } if (index >= 10) { buf.append("..."); break; } boolean isMode = value.equals(mode); if (isMode) { buf.append("<span style=\"text-decoration:underline\">"); } buf.append(Tools.escapeHTML(value)); if (isMode) { buf.append("</span>"); } } buf.append("}"); } if (isNumerical()) { buf.append(valueSetRelation + " ["); if (getValueRange() != null) { buf.append(Tools.formatNumber(getValueRange().getLower(), 3)); buf.append("..."); buf.append(Tools.formatNumber(getValueRange().getUpper(), 3)); buf.append("]"); } if (getMean().isKnown()) { buf.append("; mean "); buf.append(getMean().toString()); } } if (valueRange != null && Ontology.ATTRIBUTE_VALUE_TYPE.isA(getValueType(), Ontology.DATE_TIME) && !Double.isInfinite(getValueRange().getLower()) && !Double.isInfinite(getValueRange().getUpper())) { buf.append(valueSetRelation + " ["); switch (getValueType()) { case Ontology.DATE: buf.append(Tools.formatDate(new Date((long) getValueRange().getLower()))); buf.append("..."); buf.append(Tools.formatDate(new Date((long) getValueRange().getUpper()))); buf.append("]"); break; case Ontology.TIME: buf.append(Tools.formatTime(new Date((long) getValueRange().getLower()))); buf.append("..."); buf.append(Tools.formatTime(new Date((long) getValueRange().getUpper()))); buf.append("]"); break; case Ontology.DATE_TIME: buf.append(Tools.formatDateTime(new Date((long) getValueRange().getLower()))); buf.append("..."); buf.append(Tools.formatDateTime(new Date((long) getValueRange().getUpper()))); buf.append("]"); break; } } } protected String getDescriptionAsTableRow() { StringBuilder b = new StringBuilder(); b.append("<tr><td>"); String role2 = getRole(); if (role2 == null) { role2 = "-"; } b.append(role2).append("</td><td>"); b.append(Tools.escapeHTML(getName())); String unit = getAnnotations().getAnnotation(Annotations.KEY_UNIT); if (unit != null) { b.append(" <em>[").append(unit).append("]</em>"); } b.append("</td><td>"); b.append(getValueTypeName()).append("</td><td>"); if (valueSetRelation != SetRelation.UNKNOWN) { appendValueSetDescription(b); } else { if (isNominal()) { b.append("values unkown"); } else { b.append("range unknown"); } } b.append("</td><td>"); switch (containsMissingValues()) { case NO: b.append("no missing values"); break; case YES: b.append(numberOfMissingValues.toString()); b.append(" missing values"); break; case UNKNOWN: b.append("may contain missing values"); break; } final String comment = getAnnotations().getAnnotation(Annotations.KEY_COMMENT); b.append("</td><td>").append(comment != null ? comment : "-").append("</tr></tr>"); return b.toString(); } @Override public AttributeMetaData clone() { return new AttributeMetaData(this); } public boolean isNominal() { return Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.NOMINAL); } public boolean isBinominal() { return Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.BINOMINAL); } public boolean isPolynominal() { return Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.POLYNOMINAL); } public boolean isNumerical() { return Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.NUMERICAL); } /** * @return {@code true} if the type of the attribute is a {@link Ontology#DATE_TIME} (and all * it's subtypes), {@code false} otherwise * * @since 6.4.0 */ public boolean isDateTime() { return Ontology.ATTRIBUTE_VALUE_TYPE.isA(type, Ontology.DATE_TIME); } public MetaDataInfo containsMissingValues() { return numberOfMissingValues.isAtLeast(1); } public void setNumberOfMissingValues(MDInteger numberOfMissingValues) { this.numberOfMissingValues = numberOfMissingValues; } public MDInteger getNumberOfMissingValues() { return this.numberOfMissingValues; } public SetRelation getValueSetRelation() { return valueSetRelation; } public Set<String> getValueSet() { return valueSet; } public void setValueSet(Set<String> valueSet, SetRelation relation) { this.valueSetRelation = relation; this.valueSet = valueSet; } public Range getValueRange() { return valueRange; } public void setValueRange(Range range, SetRelation relation) { this.valueSetRelation = relation; this.valueRange = range; } public AttributeMetaData copy() { return new AttributeMetaData(this); } /** * Sets the role of this attribute. The name is equivalent with the names from Attributes. To * reset use null as parameter. */ public void setRole(String role) { this.role = role; } public void setRegular() { this.role = null; } public boolean isSpecial() { return role != null; } /** * This method returns a AttributeMetaData object for the prediction attribute created on * applying a model on an exampleset with the given label. */ public static AttributeMetaData createPredictionMetaData(AttributeMetaData labelMetaData) { AttributeMetaData result = labelMetaData.clone(); result.setName("prediction(" + result.getName() + ")"); result.setRole(Attributes.PREDICTION_NAME); return result; } /** * This method creates the attribute meta data for the confidence attributes in the given * exampleSetMetaData. If the values are not known precisely the attributeSet relation of the * exampleSetMetaData object is set appropriate. * * @return */ public static ExampleSetMetaData createConfidenceAttributeMetaData(ExampleSetMetaData exampleSetMD) { if (exampleSetMD.hasSpecial(Attributes.LABEL_NAME) == MetaDataInfo.YES) { AttributeMetaData labelMetaData = exampleSetMD.getLabelMetaData(); if (labelMetaData.isNominal()) { for (String value : labelMetaData.getValueSet()) { AttributeMetaData conf = new AttributeMetaData(Attributes.CONFIDENCE_NAME + "_" + value, Ontology.REAL, Attributes.CONFIDENCE_NAME); conf.setValueRange(new Range(0d, 1d), SetRelation.EQUAL); exampleSetMD.addAttribute(conf); } // setting attribute set relation according to value set relation exampleSetMD.mergeSetRelation(labelMetaData.getValueSetRelation()); return exampleSetMD; } } return exampleSetMD; } public void setValueSetRelation(SetRelation valueSetRelation) { this.valueSetRelation = valueSetRelation; } public void setMean(MDReal mean) { this.mean = mean; } public MDReal getMean() { return mean; } public void setMode(String mode) { this.mode = mode; } public String getMode() { return mode; } /** Sets types and ranges to the superset of this and the argument. */ public void merge(AttributeMetaData amd) { if (amd.isNominal() != this.isNominal()) { this.type = Ontology.ATTRIBUTE_VALUE; } if (isNominal()) { if (amd.valueSet != null && this.valueSet != null) { if (!amd.valueSet.equals(this.valueSet)) { this.valueSetRelation.merge(SetRelation.SUBSET); } this.valueSet.addAll(amd.valueSet); } this.valueSetRelation.merge(amd.valueSetRelation); } if (isNumerical()) { if (valueRange != null && amd.valueRange != null) { double min = Math.min(amd.valueRange.getLower(), this.valueRange.getLower()); double max = Math.max(amd.valueRange.getUpper(), this.valueRange.getUpper()); this.valueRange = new Range(min, max); } this.valueSetRelation.merge(amd.valueSetRelation); } } /** Returns either the value range or the value set, depending on the type of attribute. */ public String getRangeString() { if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(getValueType(), Ontology.DATE_TIME)) { if (!Double.isInfinite(getValueRange().getLower()) && !Double.isInfinite(getValueRange().getUpper())) { StringBuilder buf = new StringBuilder(); buf.append(valueSetRelation.toString()); if (valueSetRelation != SetRelation.UNKNOWN) { buf.append("["); switch (getValueType()) { case Ontology.DATE: buf.append(Tools.formatDate(new Date((long) getValueRange().getLower()))); buf.append(" \u2013 "); buf.append(Tools.formatDate(new Date((long) getValueRange().getUpper()))); break; case Ontology.TIME: buf.append(Tools.formatTime(new Date((long) getValueRange().getLower()))); buf.append(" \u2013 "); buf.append(Tools.formatTime(new Date((long) getValueRange().getUpper()))); break; case Ontology.DATE_TIME: buf.append(Tools.formatDateTime(new Date((long) getValueRange().getLower()))); buf.append(" \u2013 "); buf.append(Tools.formatDateTime(new Date((long) getValueRange().getUpper()))); break; } buf.append("]"); return buf.toString(); } else { return "Unknown date range"; } } return "Unbounded date range"; } else if (!isNominal() && valueRange != null) { return valueSetRelation.toString() + (valueSetRelation != SetRelation.UNKNOWN ? valueRange.toString() : ""); } else if (isNominal() && valueSet != null) { return valueSetRelation.toString() + (valueSetRelation != SetRelation.UNKNOWN ? valueSet.toString() : ""); } else { return "unknown"; } } /** * Throws away nominal values until the value set size is at most the value specified by * property {@link RapidMiner#PROPERTY_RAPIDMINER_GENERAL_MAX_NOMINAL_VALUES}. */ public void shrinkValueSet() { int maxSize = getMaximumNumberOfNominalValues(); shrinkValueSet(maxSize); } /** * Returns the maximum number of values to be used for meta data generation as specified by * {@link RapidMiner#PROPERTY_RAPIDMINER_GENERAL_MAX_NOMINAL_VALUES}. */ public static int getMaximumNumberOfNominalValues() { int maxSize = 100; String maxSizeString = ParameterService.getParameterValue(RapidMiner.PROPERTY_RAPIDMINER_GENERAL_MAX_NOMINAL_VALUES); if (maxSizeString != null) { maxSize = Integer.parseInt(maxSizeString); if (maxSize == 0) { maxSize = Integer.MAX_VALUE; } } return maxSize; } /** Throws away nominal values until the value set size is at most the given value. */ private void shrinkValueSet(int maxSize) { if (valueSet != null) { if (valueSet.size() > maxSize) { Set<String> newSet = new TreeSet<String>(); Iterator<String> i = valueSet.iterator(); int count = 0; while (i.hasNext() && count < maxSize) { newSet.add(i.next()); count++; } this.valueSet = newSet; valueSetRelation = valueSetRelation.merge(SetRelation.SUPERSET); if (owner != null) { owner.setNominalDataWasShrinked(true); } } } } /** * This method is only to be used by ExampleSetMetaData to register as owner of this * attributeMetaData. Returnes is this object or a clone if this object already has an owner. */ /* pp */AttributeMetaData registerOwner(ExampleSetMetaData owner) { if (this.owner == null) { this.owner = owner; return this; } else { AttributeMetaData clone = this.clone(); clone.owner = owner; return clone; } } public void setAnnotations(Annotations annotations) { if (annotations == null) { this.annotations = new Annotations(); } else { this.annotations = annotations; } } public Annotations getAnnotations() { return annotations; } }
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/ports/metadata/AttributeMetaData.java
Java
gpl-3.0
20,750
package com.mylovemhz.floordoorrecords.adapters; import com.mylovemhz.floordoorrecords.net.AlbumResponse; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; public class MockDownloadsAdapter extends DownloadsAdapter { protected Map<Integer, ViewHolder> viewHolders; public MockDownloadsAdapter(List<AlbumResponse> albumResponses) { super(albumResponses); viewHolders = new HashMap<>(); } @Override public void onBindViewHolder(ViewHolder holder, int position) { super.onBindViewHolder(holder, position); viewHolders.put(position, holder); } }
allanpichardo/Floordoor-Records-Android
app/src/test/java/com/mylovemhz/floordoorrecords/adapters/MockDownloadsAdapter.java
Java
gpl-3.0
653
// // Decompiled by Procyon v0.5.30 // package com.intenso.jira.plugins.synchronizer.entity; import java.sql.Timestamp; import net.java.ao.schema.StringLength; import net.java.ao.schema.Table; import net.java.ao.Entity; @Table("alertHistory") public interface AlertHistory extends Entity { @StringLength(-1) String getMessage(); Timestamp getLast(); void setMessage(final String p0); void setLast(final Timestamp p0); }
IrbisChaos/synchronizer
src/main/java/com/intenso/jira/plugins/synchronizer/entity/AlertHistory.java
Java
gpl-3.0
460
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.atlanta.educati.daoImp; import com.atlanta.educati.dao.UsuarioDao; import com.atlanta.educati.pojo.Usuario; import com.atlanta.educati.util.HibernateUtil; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; /** * * @author Nerio */ public class UsuarioDaoImp implements UsuarioDao{ SessionFactory sesionFactory = HibernateUtil.getSessionFactory(); @Override public int save(Usuario x) { Session sesion = sesionFactory.openSession(); Transaction tx = sesion.beginTransaction(); //Variable de respuesta int r = 0; try { sesion.save(x); tx.commit(); r++; } catch (Exception e) { System.out.println("" + e.getMessage()); tx.rollback(); } finally { sesion.close(); } return r; } @Override public Usuario get(int id) { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Criteria criteria = sesion.createCriteria(Usuario.class); Usuario x = (Usuario) criteria.add(Restrictions.eq("id", id)).uniqueResult(); sesion.close(); return x; } @Override public int update(Usuario x) { Session sesion = sesionFactory.openSession(); Transaction tx = sesion.beginTransaction(); //Variable de respuesta int r = 0; try { sesion.clear(); sesion.update(x); tx.commit(); r++; } catch (Exception e) { System.out.println("" + e.getMessage()); tx.rollback(); } finally { sesion.close(); } return r; } @Override public int drop(Usuario x) { Session sesion = sesionFactory.openSession(); Transaction tx = sesion.beginTransaction(); //Variable de respuesta int r = 0; try { sesion.delete(x); tx.commit(); r++; } catch (Exception e) { System.out.println("" + e.getMessage()); tx.rollback(); } finally { sesion.close(); } return r; } @Override public List<Usuario> findAll() { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Criteria criteria = sesion.createCriteria(Usuario.class); List<Usuario> lista = (List<Usuario>) criteria.list(); sesion.close(); return lista; } @Override public Object consultUnique(String consulta) { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Query query = sesion.createQuery(consulta); Object objeto = query.uniqueResult(); sesion.close(); return objeto; } @Override public List consultList(String consulta) { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Query query = sesion.createQuery(consulta); List lista = query.list(); sesion.close(); return lista; } @Override public Usuario CriteriaUnique(Map mapa) { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Criteria criteria = sesion.createCriteria(Usuario.class); for (String key : (List<String>) mapa.keySet()) { criteria.add(Restrictions.eq(key, mapa.get(key))); } Usuario x = (Usuario) criteria.uniqueResult(); sesion.close(); return x; } @Override public List CriteriaList(Map mapa) { Session sesion = sesionFactory.openSession(); sesion.beginTransaction().commit(); Criteria criteria = sesion.createCriteria(Usuario.class); for (String key : (List<String>) mapa.keySet()) { criteria.add(Restrictions.eq(key, mapa.get(key))); } List<Usuario> lista = (List<Usuario>) criteria.list(); sesion.close(); return lista; } }
nbaez001/educatiback
src/java/com/atlanta/educati/daoImp/UsuarioDaoImp.java
Java
gpl-3.0
4,655
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ListSystemProperties.java.java * Copyright (C) 2013-2014 University of Waikato, Hamilton, New Zealand */ package adams.flow.source; import java.util.ArrayList; import java.util.Collections; import java.util.List; import adams.core.QuickInfoHelper; import adams.core.base.BaseRegExp; /** <!-- globalinfo-start --> * Outputs the names of the currently set Java system properties. * <br><br> <!-- globalinfo-end --> * <!-- flow-summary-start --> * Input&#47;output:<br> * - generates:<br> * &nbsp;&nbsp;&nbsp;java.lang.String<br> * <br><br> <!-- flow-summary-end --> * <!-- options-start --> * Valid options are: <br><br> * * <pre>-D &lt;int&gt; (property: debugLevel) * &nbsp;&nbsp;&nbsp;The greater the number the more additional info the scheme may output to * &nbsp;&nbsp;&nbsp;the console (0 = off). * &nbsp;&nbsp;&nbsp;default: 0 * &nbsp;&nbsp;&nbsp;minimum: 0 * </pre> * * <pre>-name &lt;java.lang.String&gt; (property: name) * &nbsp;&nbsp;&nbsp;The name of the actor. * &nbsp;&nbsp;&nbsp;default: ListSystemProperties * </pre> * * <pre>-annotation &lt;adams.core.base.BaseText&gt; (property: annotations) * &nbsp;&nbsp;&nbsp;The annotations to attach to this actor. * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-skip (property: skip) * &nbsp;&nbsp;&nbsp;If set to true, transformation is skipped and the input token is just forwarded * &nbsp;&nbsp;&nbsp;as it is. * </pre> * * <pre>-stop-flow-on-error (property: stopFlowOnError) * &nbsp;&nbsp;&nbsp;If set to true, the flow gets stopped in case this actor encounters an error; * &nbsp;&nbsp;&nbsp; useful for critical actors. * </pre> * * <pre>-output-array (property: outputArray) * &nbsp;&nbsp;&nbsp;Whether to output the property names in an array rather than one by one. * </pre> * * <pre>-regexp &lt;adams.core.base.BaseRegExp&gt; (property: regExp) * &nbsp;&nbsp;&nbsp;The regular expression used for matching the property names. * &nbsp;&nbsp;&nbsp;default: .* * </pre> * * <pre>-invert (property: invert) * &nbsp;&nbsp;&nbsp;If set to true, then the matching sense is inverted. * </pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ListSystemProperties extends AbstractArrayProvider { /** for serialization. */ private static final long serialVersionUID = -3001964206807357534L; /** the regular expression to match. */ protected BaseRegExp m_RegExp; /** whether to invert the matching sense. */ protected boolean m_Invert; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Outputs the names of the currently set Java system properties."; } /** * Adds options to the internal list of options. */ @Override public void defineOptions() { super.defineOptions(); m_OptionManager.add( "regexp", "regExp", new BaseRegExp(BaseRegExp.MATCH_ALL)); m_OptionManager.add( "invert", "invert", false); } /** * Returns a quick info about the actor, which will be displayed in the GUI. * * @return null if no info available, otherwise short string */ @Override public String getQuickInfo() { String result; List<String> options; result = QuickInfoHelper.toString(this, "regExp", m_RegExp, (m_Invert ? "! " : "")); // further options options = new ArrayList<String>(); QuickInfoHelper.add(options, QuickInfoHelper.toString(this, "outputArray", getOutputArray(), "array")); result += QuickInfoHelper.flatten(options); return result; } /** * Returns the based class of the items. * * @return the class */ @Override protected Class getItemClass() { return String.class; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ @Override public String outputArrayTipText() { return "Whether to output the property names in an array rather than one by one."; } /** * Sets the regular expression to match the property names against. * * @param value the regular expression */ public void setRegExp(BaseRegExp value) { m_RegExp = value; reset(); } /** * Returns the regular expression to match the property names against. * * @return the regular expression */ public BaseRegExp getRegExp() { return m_RegExp; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String regExpTipText() { return "The regular expression used for matching the property names."; } /** * Sets whether to invert the matching sense. * * @param value true if inverting matching sense */ public void setInvert(boolean value) { m_Invert = value; reset(); } /** * Returns whether to invert the matching sense. * * @return true if matching sense is inverted */ public boolean getInvert() { return m_Invert; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String invertTipText() { return "If set to true, then the matching sense is inverted."; } /** * Executes the flow item. * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { m_Queue.clear(); if (m_RegExp.isMatchAll()) { if (!m_Invert) m_Queue.addAll(System.getProperties().stringPropertyNames()); } else { for (String name: System.getProperties().stringPropertyNames()) { if (m_Invert && !m_RegExp.isMatch(name)) m_Queue.add(name); else if (!m_Invert && m_RegExp.isMatch(name)) m_Queue.add(name); } } Collections.sort(m_Queue); return null; } }
waikato-datamining/adams-base
adams-core/src/main/java/adams/flow/source/ListSystemProperties.java
Java
gpl-3.0
6,800
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * [email protected] * * Mad is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Mad is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.mads.base.djeq.ui; import java.awt.Color; import javax.swing.JPanel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.co.modularaudio.mads.base.common.ampmeter.DPAmpMeter; import uk.co.modularaudio.util.bufferedimage.BufferedImageAllocator; import uk.co.modularaudio.util.swing.general.MigLayoutStringHelper; public class LaneStereoAmpMeter extends JPanel { private static final long serialVersionUID = 1358562457507980606L; private static Log log = LogFactory.getLog( LaneStereoAmpMeter.class.getName() ); private final DPAmpMeter leftMeter; private final AmpMeterMarks meterMarks; private final DPAmpMeter rightMeter; public LaneStereoAmpMeter( final DJEQMadUiInstance uiInstance, final BufferedImageAllocator bia, final boolean showClipBox ) { super(); setOpaque( false ); final MigLayoutStringHelper msh = new MigLayoutStringHelper(); // msh.addLayoutConstraint( "debug" ); msh.addLayoutConstraint( "filly" ); msh.addLayoutConstraint( "gap 0" ); msh.addLayoutConstraint( "insets 1" ); this.setLayout( msh.createMigLayout() ); leftMeter = new DPAmpMeter( showClipBox ); this.add( leftMeter, "gapbottom " + AmpMeterMarks.METER_LABEL_NEEDED_TOP_BOTTOM_INSET_PIXELS + ", alignx right, growy" ); meterMarks = new AmpMeterMarks( Color.BLACK, false ); this.add( meterMarks, "growy, growx 0"); rightMeter = new DPAmpMeter( showClipBox ); this.add( rightMeter, "gapbottom "+ AmpMeterMarks.METER_LABEL_NEEDED_TOP_BOTTOM_INSET_PIXELS + ", alignx left, growy" ); this.validate(); } public void receiveMeterReadingInDb( final long currentTimestamp, final int channelNum, final float meterReadingDb ) { switch( channelNum ) { case 0: { leftMeter.receiveMeterReadingInDb( currentTimestamp, meterReadingDb ); break; } case 1: { rightMeter.receiveMeterReadingInDb( currentTimestamp, meterReadingDb ); break; } default: { log.error("Oops. Which channel was this for?"); break; } } } public void receiveDisplayTick( final long currentGuiTime ) { leftMeter.receiveDisplayTick( currentGuiTime ); rightMeter.receiveDisplayTick( currentGuiTime ); } public void destroy() { leftMeter.destroy(); rightMeter.destroy(); } public void setFramesBetweenPeakReset( final int framesBetweenPeakReset ) { leftMeter.setFramesBetweenPeakReset( framesBetweenPeakReset ); rightMeter.setFramesBetweenPeakReset( framesBetweenPeakReset ); } }
danielhams/mad-java
2COMMONPROJECTS/audio-services/src/uk/co/modularaudio/mads/base/djeq/ui/LaneStereoAmpMeter.java
Java
gpl-3.0
3,265
package com.mx.fic.inventory.persistent; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table (name="address") @NamedQueries({ @NamedQuery(name="Address.getAllByCompany", query="select ad from Address ad where ad.company.id=:id") }) public class Address implements BaseEntity { private static final long serialVersionUID = 1462817466162350528L; @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @Column(name ="street") private String street; @Column(name="colony") private String colony; @Column(name="exterior_number") private Integer exteriorNumber; @Column(name="interior_number") private Integer interiorNumber; @Column(name="postal_code") private Integer postalCode; @Column(name="town") private String town; @Column(name="city") private String city; @Column(name="state") private String state; @JoinColumn(name="type_address_id", referencedColumnName="id") @ManyToOne(fetch=FetchType.LAZY) private TypeAddress typeAddress; @JoinColumn(name="status_id", referencedColumnName="id") @ManyToOne(fetch=FetchType.LAZY) private Status status; @JoinColumn(name="company_id", referencedColumnName="id") @ManyToOne(fetch=FetchType.LAZY) private Company company; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getColony() { return colony; } public void setColony(String colony) { this.colony = colony; } public Integer getExteriorNumber() { return exteriorNumber; } public void setExteriorNumber(Integer exteriorNumber) { this.exteriorNumber = exteriorNumber; } public Integer getInteriorNumber() { return interiorNumber; } public void setInteriorNumber(Integer interiorNumber) { this.interiorNumber = interiorNumber; } public Integer getPostalCode() { return postalCode; } public void setPostalCode(Integer postalCode) { this.postalCode = postalCode; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public TypeAddress getTypeAddress() { return typeAddress; } public void setTypeAddress(TypeAddress typeAddress) { this.typeAddress = typeAddress; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public String toString() { return "Address [id=" + id + ", street=" + street + ", colony=" + colony + ", exteriorNumber=" + exteriorNumber + ", interiorNumber=" + interiorNumber + ", postalCode=" + postalCode + ", town=" + town + ", city=" + city + ", state=" + state + ", typeAddress=" + typeAddress + ", status=" + status + ", company=" + company + "]"; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((city == null) ? 0 : city.hashCode()); result = prime * result + ((colony == null) ? 0 : colony.hashCode()); result = prime * result + ((company == null) ? 0 : company.hashCode()); result = prime * result + ((exteriorNumber == null) ? 0 : exteriorNumber.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((interiorNumber == null) ? 0 : interiorNumber.hashCode()); result = prime * result + ((postalCode == null) ? 0 : postalCode.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((street == null) ? 0 : street.hashCode()); result = prime * result + ((town == null) ? 0 : town.hashCode()); result = prime * result + ((typeAddress == null) ? 0 : typeAddress.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Address other = (Address) obj; if (city == null) { if (other.city != null) return false; } else if (!city.equals(other.city)) return false; if (colony == null) { if (other.colony != null) return false; } else if (!colony.equals(other.colony)) return false; if (company == null) { if (other.company != null) return false; } else if (!company.equals(other.company)) return false; if (exteriorNumber == null) { if (other.exteriorNumber != null) return false; } else if (!exteriorNumber.equals(other.exteriorNumber)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (interiorNumber == null) { if (other.interiorNumber != null) return false; } else if (!interiorNumber.equals(other.interiorNumber)) return false; if (postalCode == null) { if (other.postalCode != null) return false; } else if (!postalCode.equals(other.postalCode)) return false; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; if (street == null) { if (other.street != null) return false; } else if (!street.equals(other.street)) return false; if (town == null) { if (other.town != null) return false; } else if (!town.equals(other.town)) return false; if (typeAddress == null) { if (other.typeAddress != null) return false; } else if (!typeAddress.equals(other.typeAddress)) return false; return true; } }
modemm3/fic
fic-inventory/fic-inventory-persistent/src/main/java/com/mx/fic/inventory/persistent/Address.java
Java
gpl-3.0
6,309
/* * EuroCarbDB, a framework for carbohydrate bioinformatics * * Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * A copy of this license accompanies this distribution in the file LICENSE.txt. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * Last commit: $Rev: 1210 $ by $Author: glycoslave $ on $Date:: 2009-06-12 #$ */ package org.eurocarbdb.application.glycanbuilder; import java.util.*; /** Objects of this class are used to compute and store the position of a residue around its parent during the rendering process. @see GlycanRenderer @author Alessio Ceroni ([email protected]) */ public class PositionManager { protected static final ResAngle[] static_positions = new ResAngle[5]; static { try { static_positions[0] = new ResAngle(-90); static_positions[1] = new ResAngle(-45); static_positions[2] = new ResAngle(0); static_positions[3] = new ResAngle(45); static_positions[4] = new ResAngle(90); //static_positions[5] = new ResAngle(-135); //static_positions[6] = new ResAngle(135); } catch(Exception e) { LogUtils.report(e); } } protected HashMap<Residue,ResAngle> orientations; protected HashMap<Residue,ResAngle> rotations; protected HashMap<Residue,ResAngle> relative_positions; protected HashMap<Residue,ResAngle> absolute_positions; protected HashMap<Residue,Boolean> onborder_flags; protected HashMap<Residue,Boolean> sticky_flags; /** Default constructor. */ public PositionManager() { orientations = new HashMap<Residue,ResAngle>(); rotations = new HashMap<Residue,ResAngle>(); relative_positions = new HashMap<Residue,ResAngle>(); absolute_positions = new HashMap<Residue,ResAngle>(); onborder_flags = new HashMap<Residue,Boolean>(); sticky_flags = new HashMap<Residue,Boolean>(); } /** Clear all fields. */ public void reset() { orientations.clear(); rotations.clear(); relative_positions.clear(); absolute_positions.clear(); onborder_flags.clear(); sticky_flags.clear(); } /** Store the information about the position of a residue around its parent. @param node the residue @param parent_orientation the absolute orientation of the parent @param relative_position the position of the residue relative to its parent @param on_border <code>true</code> if the residue is rendered on the border of the parent @param sticky <code>true</code> if all the children of the current residue should be placed in position 0 */ public void add(Residue node, ResAngle parent_orientation, ResAngle relative_position, boolean on_border, boolean sticky) { if( node!=null ) { ResAngle absolute_position = parent_orientation.combine(relative_position); ResAngle rotation = (sticky) ?relative_position : new ResAngle(); ResAngle orientation = parent_orientation; if( sticky && !relative_position.equals(-45) && !relative_position.equals(45) && !on_border) //if( !relative_position.equals(-45) && !relative_position.equals(45) ) orientation = absolute_position; orientations.put(node,orientation); rotations.put(node,rotation); relative_positions.put(node,relative_position); absolute_positions.put(node,absolute_position); onborder_flags.put(node,on_border); sticky_flags.put(node,sticky); } } /** Return the absolute orientation of the parent residue */ public ResAngle getOrientation(Residue node) { return orientations.get(node); } public ResAngle getRotation(Residue node) { return rotations.get(node); } /** Return the orientation of the residue relative to its parent */ public ResAngle getRelativePosition(Residue node) { return relative_positions.get(node); } /** Return the absolute orientation of the residue */ public ResAngle getAbsolutePosition(Residue node) { return absolute_positions.get(node); } /** Return <code>true</code> if the residue is rendered on the border of its parent. */ public boolean isOnBorder(Residue node) { Boolean b = onborder_flags.get(node); if( b==null ) return false; return b; } /** Return <code>true</code> if the children of the residue should be placed all in position 0. */ public boolean isSticky(Residue node) { Boolean b = sticky_flags.get(node); if( b==null ) return false; return b; } /** Return all the possible positions of a residue around its parent. */ static public ResAngle[] getPossiblePositions() { return static_positions; } /** Return the possible positions of the residue around its parent given the current orientation. */ public ResAngle[] getAvailablePositions(Residue current, ResAngle orientation) { ResAngle[] positions = getPossiblePositions(); if( current==null ) return positions; Residue parent = current.getParent(); if( parent==null ) return positions; ResAngle cur_abs_pos = getAbsolutePosition(current); if( cur_abs_pos==null ) return positions; // check for conflicting position (e.g: +90/-90) Vector<ResAngle> vec_available_positions = new Vector<ResAngle>(); for( int i=0; i<positions.length; i++ ) { ResAngle pos = positions[i]; ResAngle abs_pos = orientation.combine(pos); if( !cur_abs_pos.isOpposite(abs_pos) ) vec_available_positions.add(pos); } // transform into array ResAngle[] available_positions = new ResAngle[vec_available_positions.size()]; vec_available_positions.copyInto(available_positions); return available_positions; } /** Return the children of the residue that have been placed in a specific position. */ public Vector<Residue> getChildrenAtPosition(Residue parent, ResAngle position) { Vector<Residue> nodes = new Vector<Residue>(); for(Iterator<Linkage> i=parent.iterator(); i.hasNext(); ) { Residue child = i.next().getChildResidue(); if( getRelativePosition(child).equals(position) ) nodes.add(child); } return nodes; } /** Return the children of the residue that have been placed in a specific position. @param on_border if <code>true</code> look at the children residues on the border of the parent */ public Vector<Residue> getChildrenAtPosition(Residue parent, ResAngle position, boolean on_border) { Vector<Residue> nodes = new Vector<Residue>(); for(Iterator<Linkage> i=parent.iterator(); i.hasNext(); ) { Residue child = i.next().getChildResidue(); if( getRelativePosition(child).equals(position) && isOnBorder(child)==on_border ) nodes.add(child); } return nodes; } /* public Vector<Residue> getChildrenCompatibleWith(Residue parent, Linkage link, Residue child) { Vector<Residue> nodes = new Vector<Residue>(); ResAngle[] child_positions = ResiduePlacementDictionary.getPlacement(parent,link,child).getPositions(); for( int i=0; i<child_positions.length; i++ ) nodes.addAll(getChildrenAtPosition(parent,child_positions[i])); return nodes; }*/ }
glycoinfo/eurocarbdb
application/GlycanBuilder/src/org/eurocarbdb/application/glycanbuilder/PositionManager.java
Java
gpl-3.0
8,136
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.sql.*; import java.util.ArrayList; /** * * @author massarmh */ public class BooksActions { /** * Adding a book * * @param bookId The book id * @param title The title * @param author The author * @param edition The edition * @param publisher The publisher * @param coverPhoto The cover photo * @param classId The class id */ public static boolean addBook(String bookId, String title , String author, int edition, String coverPhoto, String publisher, String classId) { Books newBook = new Books(bookId, title, author, edition, coverPhoto, publisher, classId); return BooksPersistence.addBook(newBook); } /** * Check Book * * @param title The title * @param author The author * @param edition The edition * @param publisher The publisher */ public static boolean checkBook(String title, String author, int edition, String publisher) { return BooksPersistence.checkBook(title, author, edition, publisher); } /** * Get book id * * @param title The title * @param author The author * @param edition The edition * @param publisher The publisher */ public static String getBookId(String title, String author, int edition, String publisher) { return BooksPersistence.getBookId(title, author, edition, publisher); } /** * Get book * * @param bookId The book id */ public static Books getBook(String bookId) { return BooksPersistence.getBook(bookId); } /** * Search Book * * @param title The title * @param author The author * @param edition The edition * @param publisher The publisher */ public static ArrayList<Books> searchBook(String title, String author, int edition, String publisher) { return BooksPersistence.searchBook(title, author, edition, publisher); } }
markdangio/final_project
JMUBookTimeMachine/src/java/model/BooksActions.java
Java
gpl-3.0
2,191
package bruno.lang.grammar; import java.nio.ByteBuffer; public class BParseTree { private final ByteBuffer lang; private final int[] rules; private final int[] starts; private final int[] ends; private final int[] levels; private final int[] indexStack = new int[50]; private int level = -1; private int top = -1; public BParseTree(ByteBuffer lang, int length) { super(); this.lang = lang; this.rules = new int[length]; this.starts = new int[length]; this.ends = new int[length]; this.levels = new int[length]; } public void push(int rule, int start) { starts[++top] = start; ends[top] = start; rules[top] = rule; level++; levels[top] = level; indexStack[level] = top; } public int end(int index) { return ends[index]; } public int start(int index) { return starts[index]; } public int level(int index) { return levels[index]; } public int rule(int index) { return rules[index]; } public int end() { return ends[0]; } public int count() { return top+1; } public void pop() { top = indexStack[level]-1; level--; } public void done(int end) { ends[indexStack[level]] = end; level--; } public void erase(int position) { while (top > 0 && ends[top] > position) { top--; } } @Override public String toString() { StringBuilder b = new StringBuilder(); for (int i = 0; i <= top; i++) { // indent for (int g = 0; g < levels[i]; g++) { b.append(' '); } // name int l = lang.get(rules[i]+1)-2; int j = rules[i] + 4; for (int h = l; h > 0; h--) { b.append((char)lang.get(j++)); } b.append(' ').append(starts[i]).append('-').append(ends[i]).append('\n'); } return b.toString(); } }
bruno-lang/alma
java/main/bruno/lang/grammar/BParseTree.java
Java
gpl-3.0
1,725
package com.grgbanking.vnc.repeater.common.util; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.mina.core.session.IoSession; public class RequestUtils { private static Logger logger = Logger.getLogger(RequestUtils.class); /** * 获取远程端的IP地址 */ public static String getRemoteIp(IoSession session){ String ip = null; try { String address = session.getRemoteAddress().toString(); ip = getIp(address); } catch (Exception ex) { logger.error("", ex); } return ip; } /** * 获取远程端的端口 */ public static int getRemotePort(IoSession session){ int port = 0; try { String address = session.getRemoteAddress().toString(); port = getPort(address); } catch (Exception ex) { logger.error("", ex); } return port; } /** * 获取本地端的IP地址 */ public static String getLocalIp(IoSession session){ String ip = null; try { String address = session.getLocalAddress().toString(); ip = getIp(address); } catch (Exception ex) { logger.error("", ex); } return ip; } /** * 获取本地端的监听端口 */ public static int getLocalPort(IoSession session){ int port = 0; try { String address = session.getLocalAddress().toString(); port = getPort(address); } catch (Exception ex) { logger.error("", ex); } return port; } private static String getIp(String address) { if(address.startsWith("/")){ address = address.substring(1); } String[] arr = address.split(":"); String ip = StringUtils.trimToEmpty(arr[0]); return ip; } private static int getPort(String address) { if(address.startsWith("/")){ address = address.substring(1); } String[] arr = address.split(":"); int port = Integer.parseInt(StringUtils.trimToEmpty(arr[1])); return port; } }
chenjumin/repeater
repeater-common/src/main/java/com/grgbanking/vnc/repeater/common/util/RequestUtils.java
Java
gpl-3.0
1,847
package net.cmikavac.autowol.services; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Random; import net.cmikavac.autowol.models.DeviceModel; import net.cmikavac.autowol.R; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.os.AsyncTask; import android.support.v4.app.NotificationCompat; import android.widget.Toast; public class WolService extends AsyncTask<DeviceModel, Void, String> { private Context mContext = null; private Boolean mNotify = false; /** * Constructor. * @param context Context entity. */ public WolService(Context context, Boolean notify) { mContext = context; mNotify = notify; } /* (non-Javadoc) * Wakes the device asynchronously. * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected String doInBackground(DeviceModel... devices) { DeviceModel device = devices[0]; return Wake(device.getName(), device.getBroadcast(), device.getMac(), device.getPort()); } /* (non-Javadoc) * Creates a notification or toast message after device WOL attempt. * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(String message) { super.onPostExecute(message); if (mNotify) createNotification(message); else Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); } /** * Creates a WOL network packet and sends it to the network. * @param name WOL device name. * @param broadcast Access point broadcast IP/FQDN. * @param mac MAC address of the device to wake. * @param port WOL port to be used. * @return Success/exception message. */ private String Wake(String name, String broadcast, String mac, int port) { try { byte[] macBytes = getMacBytes(mac); byte[] bytes = new byte[6 + 16 * macBytes.length]; for (int i = 0; i < 6; i++) { bytes[i] = (byte) 0xff; } for (int i = 6; i < bytes.length; i += macBytes.length) { System.arraycopy(macBytes, 0, bytes, i, macBytes.length); } InetAddress address = InetAddress.getByName(broadcast); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); return "WOL packet sent to " + name + "."; } catch (Exception e) { return "Failed to send WOL packet: " + e.getMessage(); } } /** * Creates a byte array from MAC address. * @param mac MAC address. * @return Byte array representing MAC address. * @throws IllegalArgumentException */ private static byte[] getMacBytes(String mac) throws IllegalArgumentException { byte[] bytes = new byte[6]; String[] hex = mac.split("(\\:|\\-)"); if (hex.length != 6) { throw new IllegalArgumentException("Invalid MAC address."); } try { for (int i = 0; i < 6; i++) { bytes[i] = (byte) Integer.parseInt(hex[i], 16); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid hex digit in MAC address."); } return bytes; } /** * Creates a new Android notification to let the user know Auto-WOL packet has been sent. * @param message Message to display. */ private void createNotification(String message) { Notification notification = new NotificationCompat.Builder(mContext) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Auto WOL") .setContentText(message) .build(); NotificationManager mNotificationManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(new Random(System.currentTimeMillis()).nextInt() , notification); } }
pootzko/auto-wol
src/net/cmikavac/autowol/services/WolService.java
Java
gpl-3.0
4,322
/* * Copyright (C) 2010-2014 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.xfl; import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler; import com.jpexs.decompiler.flash.RetryTask; import com.jpexs.decompiler.flash.RunnableIOEx; import com.jpexs.decompiler.flash.SWF; import com.jpexs.decompiler.flash.SWFCompression; import com.jpexs.decompiler.flash.SWFInputStream; import com.jpexs.decompiler.flash.action.Action; import com.jpexs.decompiler.flash.configuration.Configuration; import com.jpexs.decompiler.flash.exporters.MovieExporter; import com.jpexs.decompiler.flash.exporters.SoundExporter; import com.jpexs.decompiler.flash.exporters.commonshape.Matrix; import com.jpexs.decompiler.flash.exporters.modes.MovieExportMode; import com.jpexs.decompiler.flash.exporters.modes.ScriptExportMode; import com.jpexs.decompiler.flash.exporters.modes.SoundExportMode; import com.jpexs.decompiler.flash.helpers.HighlightedTextWriter; import com.jpexs.decompiler.flash.helpers.ImageHelper; import com.jpexs.decompiler.flash.tags.CSMTextSettingsTag; import com.jpexs.decompiler.flash.tags.DefineButton2Tag; import com.jpexs.decompiler.flash.tags.DefineButtonCxformTag; import com.jpexs.decompiler.flash.tags.DefineButtonTag; import com.jpexs.decompiler.flash.tags.DefineEditTextTag; import com.jpexs.decompiler.flash.tags.DefineFontNameTag; import com.jpexs.decompiler.flash.tags.DefineSoundTag; import com.jpexs.decompiler.flash.tags.DefineSpriteTag; import com.jpexs.decompiler.flash.tags.DefineText2Tag; import com.jpexs.decompiler.flash.tags.DefineTextTag; import com.jpexs.decompiler.flash.tags.DefineVideoStreamTag; import com.jpexs.decompiler.flash.tags.DoActionTag; import com.jpexs.decompiler.flash.tags.DoInitActionTag; import com.jpexs.decompiler.flash.tags.ExportAssetsTag; import com.jpexs.decompiler.flash.tags.FileAttributesTag; import com.jpexs.decompiler.flash.tags.FrameLabelTag; import com.jpexs.decompiler.flash.tags.SetBackgroundColorTag; import com.jpexs.decompiler.flash.tags.ShowFrameTag; import com.jpexs.decompiler.flash.tags.SoundStreamBlockTag; import com.jpexs.decompiler.flash.tags.StartSoundTag; import com.jpexs.decompiler.flash.tags.SymbolClassTag; import com.jpexs.decompiler.flash.tags.Tag; import com.jpexs.decompiler.flash.tags.base.ASMSource; import com.jpexs.decompiler.flash.tags.base.BoundedTag; import com.jpexs.decompiler.flash.tags.base.ButtonTag; import com.jpexs.decompiler.flash.tags.base.CharacterTag; import com.jpexs.decompiler.flash.tags.base.FontTag; import com.jpexs.decompiler.flash.tags.base.ImageTag; import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; import com.jpexs.decompiler.flash.tags.base.PlaceObjectTypeTag; import com.jpexs.decompiler.flash.tags.base.RemoveTag; import com.jpexs.decompiler.flash.tags.base.ShapeTag; import com.jpexs.decompiler.flash.tags.base.SoundStreamHeadTypeTag; import com.jpexs.decompiler.flash.tags.base.SoundTag; import com.jpexs.decompiler.flash.tags.base.TextTag; import com.jpexs.decompiler.flash.tags.font.CharacterRanges; import com.jpexs.decompiler.flash.types.BUTTONCONDACTION; import com.jpexs.decompiler.flash.types.BUTTONRECORD; import com.jpexs.decompiler.flash.types.CLIPACTIONRECORD; import com.jpexs.decompiler.flash.types.CLIPACTIONS; import com.jpexs.decompiler.flash.types.CXFORMWITHALPHA; import com.jpexs.decompiler.flash.types.ColorTransform; import com.jpexs.decompiler.flash.types.FILLSTYLE; import com.jpexs.decompiler.flash.types.FILLSTYLEARRAY; import com.jpexs.decompiler.flash.types.FOCALGRADIENT; import com.jpexs.decompiler.flash.types.GRADIENT; import com.jpexs.decompiler.flash.types.GRADRECORD; import com.jpexs.decompiler.flash.types.LINESTYLE; import com.jpexs.decompiler.flash.types.LINESTYLE2; import com.jpexs.decompiler.flash.types.LINESTYLEARRAY; import com.jpexs.decompiler.flash.types.MATRIX; import com.jpexs.decompiler.flash.types.RECT; import com.jpexs.decompiler.flash.types.RGB; import com.jpexs.decompiler.flash.types.RGBA; import com.jpexs.decompiler.flash.types.SOUNDENVELOPE; import com.jpexs.decompiler.flash.types.TEXTRECORD; import com.jpexs.decompiler.flash.types.filters.BEVELFILTER; import com.jpexs.decompiler.flash.types.filters.BLURFILTER; import com.jpexs.decompiler.flash.types.filters.COLORMATRIXFILTER; import com.jpexs.decompiler.flash.types.filters.DROPSHADOWFILTER; import com.jpexs.decompiler.flash.types.filters.FILTER; import com.jpexs.decompiler.flash.types.filters.GLOWFILTER; import com.jpexs.decompiler.flash.types.filters.GRADIENTBEVELFILTER; import com.jpexs.decompiler.flash.types.filters.GRADIENTGLOWFILTER; import com.jpexs.decompiler.flash.types.shaperecords.CurvedEdgeRecord; import com.jpexs.decompiler.flash.types.shaperecords.SHAPERECORD; import com.jpexs.decompiler.flash.types.shaperecords.StraightEdgeRecord; import com.jpexs.decompiler.flash.types.shaperecords.StyleChangeRecord; import com.jpexs.decompiler.flash.types.sound.MP3FRAME; import com.jpexs.decompiler.flash.types.sound.MP3SOUNDDATA; import com.jpexs.decompiler.flash.types.sound.SoundFormat; import com.jpexs.helpers.SerializableImage; import com.jpexs.helpers.utf8.Utf8Helper; import java.awt.Font; import java.awt.Point; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * * @author JPEXS */ public class XFLConverter { public static final int KEY_MODE_NORMAL = 9728; public static final int KEY_MODE_CLASSIC_TWEEN = 22017; public static final int KEY_MODE_SHAPE_TWEEN = 17922; public static final int KEY_MODE_MOTION_TWEEN = 8195; public static final int KEY_MODE_SHAPE_LAYERS = 8192; private static final Random random = new Random(123); // predictable random private XFLConverter() { } public static String convertShapeEdge(MATRIX mat, SHAPERECORD record, int x, int y) { if (record instanceof StyleChangeRecord) { StyleChangeRecord scr = (StyleChangeRecord) record; Point p = new Point(scr.moveDeltaX, scr.moveDeltaY); //p = mat.apply(p); if (scr.stateMoveTo) { return "! " + p.x + " " + p.y; } return ""; } if (record instanceof StraightEdgeRecord) { StraightEdgeRecord ser = (StraightEdgeRecord) record; if (ser.generalLineFlag || ser.vertLineFlag) { y += ser.deltaY; } if (ser.generalLineFlag || (!ser.vertLineFlag)) { x += ser.deltaX; } Point p = new Point(x, y); //p = mat.apply(p); return "| " + p.x + " " + p.y; } if (record instanceof CurvedEdgeRecord) { CurvedEdgeRecord cer = (CurvedEdgeRecord) record; int controlX = cer.controlDeltaX + x; int controlY = cer.controlDeltaY + y; int anchorX = cer.anchorDeltaX + controlX; int anchorY = cer.anchorDeltaY + controlY; Point control = new Point(controlX, controlY); //control = mat.apply(control); Point anchor = new Point(anchorX, anchorY); //anchor = mat.apply(anchor); return "[ " + control.x + " " + control.y + " " + anchor.x + " " + anchor.y; } return ""; } public static String convertShapeEdges(int startX, int startY, MATRIX mat, List<SHAPERECORD> records) { StringBuilder ret = new StringBuilder(); int x = startX; int y = startY; ret.append("!").append(startX).append(" ").append(startY); for (SHAPERECORD rec : records) { ret.append(convertShapeEdge(mat, rec, x, y)); x = rec.changeX(x); y = rec.changeY(y); } return ret.toString(); } public static String convertLineStyle(LINESTYLE ls, int shapeNum) { return "<SolidStroke weight=\"" + (((float) ls.width) / SWF.unitDivisor) + "\">" + "<fill>" + "<SolidColor color=\"" + ls.color.toHexRGB() + "\"" + (shapeNum == 3 ? " alpha=\"" + ((RGBA) ls.color).getAlphaFloat() + "\"" : "") + " />" + "</fill>" + "</SolidStroke>"; } public static String convertLineStyle(HashMap<Integer, CharacterTag> characters, LINESTYLE2 ls, int shapeNum) { StringBuilder ret = new StringBuilder(); StringBuilder params = new StringBuilder(); if (ls.pixelHintingFlag) { params.append(" pixelHinting=\"true\""); } if (ls.width == 1) { params.append(" solidStyle=\"hairline\""); } if ((!ls.noHScaleFlag) && (!ls.noVScaleFlag)) { params.append(" scaleMode=\"normal\""); } else if ((!ls.noHScaleFlag) && ls.noVScaleFlag) { params.append(" scaleMode=\"horizontal\""); } else if (ls.noHScaleFlag && (!ls.noVScaleFlag)) { params.append(" scaleMode=\"vertical\""); } switch (ls.endCapStyle) { //What about endCapStyle? case LINESTYLE2.NO_CAP: params.append(" caps=\"none\""); break; case LINESTYLE2.SQUARE_CAP: params.append(" caps=\"square\""); break; } switch (ls.joinStyle) { case LINESTYLE2.BEVEL_JOIN: params.append(" joints=\"bevel\""); break; case LINESTYLE2.MITER_JOIN: params.append(" joints=\"miter\""); float miterLimitFactor = toFloat(ls.miterLimitFactor); if (miterLimitFactor != 3.0f) { params.append(" miterLimit=\"").append(miterLimitFactor).append("\""); } break; } ret.append("<SolidStroke weight=\"").append(((float) ls.width) / SWF.unitDivisor).append("\""); ret.append(params); ret.append(">"); ret.append("<fill>"); if (!ls.hasFillFlag) { RGBA color = (RGBA) ls.color; ret.append("<SolidColor color=\"").append(color.toHexRGB()).append("\""). append(color.getAlphaFloat() != 1 ? " alpha=\"" + color.getAlphaFloat() + "\"" : ""). append(" />"); } else { ret.append(convertFillStyle(null/* FIXME */, characters, ls.fillType, shapeNum)); } ret.append("</fill>"); ret.append("</SolidStroke>"); return ret.toString(); } private static float toFloat(int i) { return ((float) i) / (1 << 16); } public static String convertFillStyle(MATRIX mat, HashMap<Integer, CharacterTag> characters, FILLSTYLE fs, int shapeNum) { /* todo: use matrix if (mat == null) { mat = new MATRIX(); }*/ StringBuilder ret = new StringBuilder(); //ret += "<FillStyle index=\"" + index + "\">"; switch (fs.fillStyleType) { case FILLSTYLE.SOLID: ret.append("<SolidColor color=\""); ret.append(fs.color.toHexRGB()); ret.append("\""); if (shapeNum >= 3) { ret.append(" alpha=\"").append(((RGBA) fs.color).getAlphaFloat()).append("\""); } ret.append(" />"); break; case FILLSTYLE.REPEATING_BITMAP: case FILLSTYLE.CLIPPED_BITMAP: case FILLSTYLE.NON_SMOOTHED_REPEATING_BITMAP: case FILLSTYLE.NON_SMOOTHED_CLIPPED_BITMAP: ret.append("<BitmapFill"); ret.append(" bitmapPath=\""); CharacterTag bitmapCh = characters.get(fs.bitmapId); if (bitmapCh instanceof ImageTag) { ImageTag it = (ImageTag) bitmapCh; ret.append("bitmap").append(bitmapCh.getCharacterId()).append(".").append(it.getImageFormat()); } else { if (bitmapCh != null) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, "Suspicious bitmapfill:" + bitmapCh.getClass().getSimpleName()); } return "<SolidColor color=\"#ffffff\" />"; } ret.append("\""); if ((fs.fillStyleType == FILLSTYLE.CLIPPED_BITMAP) || (fs.fillStyleType == FILLSTYLE.NON_SMOOTHED_CLIPPED_BITMAP)) { ret.append(" bitmapIsClipped=\"true\""); } ret.append(">"); ret.append("<matrix>").append(convertMatrix(fs.bitmapMatrix)).append("</matrix>"); ret.append("</BitmapFill>"); break; case FILLSTYLE.LINEAR_GRADIENT: case FILLSTYLE.RADIAL_GRADIENT: case FILLSTYLE.FOCAL_RADIAL_GRADIENT: if (fs.fillStyleType == FILLSTYLE.LINEAR_GRADIENT) { ret.append("<LinearGradient"); } else { ret.append("<RadialGradient"); ret.append(" focalPointRatio=\""); if (fs.fillStyleType == FILLSTYLE.FOCAL_RADIAL_GRADIENT) { ret.append(((FOCALGRADIENT) fs.gradient).focalPoint); } else { ret.append("0"); } ret.append("\""); } int interpolationMode; if (fs.fillStyleType == FILLSTYLE.FOCAL_RADIAL_GRADIENT) { interpolationMode = fs.gradient.interpolationMode; } else { interpolationMode = fs.gradient.interpolationMode; } int spreadMode; if (fs.fillStyleType == FILLSTYLE.FOCAL_RADIAL_GRADIENT) { spreadMode = fs.gradient.spreadMode; } else { spreadMode = fs.gradient.spreadMode; } if (interpolationMode == GRADIENT.INTERPOLATION_LINEAR_RGB_MODE) { ret.append(" interpolationMethod=\"linearRGB\""); } switch (spreadMode) { case GRADIENT.SPREAD_PAD_MODE: break; case GRADIENT.SPREAD_REFLECT_MODE: ret.append(" spreadMethod=\"reflect\""); break; case GRADIENT.SPREAD_REPEAT_MODE: ret.append(" spreadMethod=\"repeat\""); break; } ret.append(">"); ret.append("<matrix>").append(convertMatrix(fs.gradientMatrix)).append("</matrix>"); GRADRECORD[] records; if (fs.fillStyleType == FILLSTYLE.FOCAL_RADIAL_GRADIENT) { records = fs.gradient.gradientRecords; } else { records = fs.gradient.gradientRecords; } for (GRADRECORD rec : records) { ret.append("<GradientEntry"); ret.append(" color=\"").append(rec.color.toHexRGB()).append("\""); if (shapeNum >= 3) { ret.append(" alpha=\"").append(((RGBA) rec.color).getAlphaFloat()).append("\""); } ret.append(" ratio=\"").append(rec.getRatioFloat()).append("\""); ret.append(" />"); } if (fs.fillStyleType == FILLSTYLE.LINEAR_GRADIENT) { ret.append("</LinearGradient>"); } else { ret.append("</RadialGradient>"); } break; } //ret += "</FillStyle>"; return ret.toString(); } public static String convertMatrix(MATRIX m) { return convertMatrix(new Matrix(m)); } public static String convertMatrix(Matrix m) { StringBuilder ret = new StringBuilder(); if (m == null) { m = new Matrix(); } ret.append("<Matrix "); ret.append("tx=\"").append(((float) m.translateX) / SWF.unitDivisor).append("\" "); ret.append("ty=\"").append(((float) m.translateY) / SWF.unitDivisor).append("\" "); if (m.scaleX != 1.0 || m.scaleY != 1.0) { ret.append("a=\"").append(m.scaleX).append("\" "); ret.append("d=\"").append(m.scaleY).append("\" "); } if (m.rotateSkew0 != 0.0 || m.rotateSkew1 != 0.0) { ret.append("b=\"").append(m.rotateSkew0).append("\" "); ret.append("c=\"").append(m.rotateSkew1).append("\" "); } ret.append("/>"); return ret.toString(); } /* public static String convertShape(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, SHAPE shape) { return convertShape(characters, mat, shapeNum, shape.shapeRecords); } public static String convertShape(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, SHAPEWITHSTYLE shape,boolean morphShape) { return convertShape(characters, mat, shapeNum, shape.shapeRecords, shape.fillStyles, shape.lineStyles, morphShape); } public static String convertShape(HashMap<Integer, CharacterTag> characters, MATRIX mat, ShapeTag shape, boolean morphShape) { return convertShape(characters, mat, shape.getShapeNum(), shape.getShapes(),morphShape); } public static String convertShape(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, List<SHAPERECORD> shapeRecords,boolean useLayers) { return convertShape(characters, mat, shapeNum, shapeRecords, null, null, false,true); }*/ private static boolean shapeHasMultiLayers(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, List<SHAPERECORD> shapeRecords, FILLSTYLEARRAY fillStyles, LINESTYLEARRAY lineStyles) { List<String> layers = getShapeLayers(characters, mat, shapeNum, shapeRecords, fillStyles, lineStyles, false); return layers.size() > 1; } public static String convertShape(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, List<SHAPERECORD> shapeRecords, FILLSTYLEARRAY fillStyles, LINESTYLEARRAY lineStyles, boolean morphshape, boolean useLayers) { StringBuilder ret = new StringBuilder(); List<String> layers = getShapeLayers(characters, mat, shapeNum, shapeRecords, fillStyles, lineStyles, morphshape); if (layers.size() == 1 && !useLayers) { ret.append(layers.get(0)); } else { int layer = 1; for (int l = layers.size() - 1; l >= 0; l--) { ret.append("<DOMLayer name=\"Layer ").append(layer++).append("\">"); //color=\"#4FFF4F\" ret.append("<frames>"); ret.append("<DOMFrame index=\"0\" motionTweenScale=\"false\" keyMode=\"").append(KEY_MODE_SHAPE_LAYERS).append("\">"); ret.append("<elements>"); ret.append(layers.get(l)); ret.append("</elements>"); ret.append("</DOMFrame>"); ret.append("</frames>"); ret.append("</DOMLayer>"); } } return ret.toString(); } /** * Remove bugs in shape: * * ... straightrecord straightrecord stylechange straightrecord (-2,0) <-- * merge this with previous stylegchange * * @param shapeRecords * @return */ private static List<SHAPERECORD> smoothShape(List<SHAPERECORD> shapeRecords) { List<SHAPERECORD> ret = new ArrayList<>(shapeRecords); for (int i = 1; i < ret.size() - 1; i++) { if (ret.get(i) instanceof StraightEdgeRecord && (ret.get(i - 1) instanceof StyleChangeRecord) && (ret.get(i + 1) instanceof StyleChangeRecord)) { StraightEdgeRecord ser = (StraightEdgeRecord) ret.get(i); StyleChangeRecord scr = (StyleChangeRecord) ret.get(i - 1); StyleChangeRecord scr2 = (StyleChangeRecord) ret.get(i + 1); if ((!scr.stateMoveTo && !scr.stateNewStyles) && Math.abs(ser.deltaX) < 5 && Math.abs(ser.deltaY) < 5) { if (i >= 2) { SHAPERECORD rbef = ret.get(i - 2); if (rbef instanceof StraightEdgeRecord) { StraightEdgeRecord ser_b = (StraightEdgeRecord) rbef; ser_b.generalLineFlag = true; ser_b.deltaX = ser.changeX(ser_b.deltaX); ser_b.deltaY = ser.changeY(ser_b.deltaY); } else if (rbef instanceof CurvedEdgeRecord) { CurvedEdgeRecord cer_b = (CurvedEdgeRecord) rbef; cer_b.anchorDeltaX = ser.changeX(cer_b.anchorDeltaX); cer_b.anchorDeltaY = ser.changeY(cer_b.anchorDeltaY); } else { //??? } if (i >= 2) { ret.remove(i - 1); ret.remove(i - 1); if (scr.stateFillStyle0 && !scr2.stateFillStyle0) { scr2.stateFillStyle0 = true; scr2.fillStyle0 = scr.fillStyle0; } if (scr.stateFillStyle1 && !scr2.stateFillStyle1) { scr2.stateFillStyle1 = true; scr2.fillStyle1 = scr.fillStyle1; } if (scr.stateLineStyle && !scr2.stateLineStyle) { scr2.stateLineStyle = true; scr2.lineStyle = scr.lineStyle; } i -= 2; } } } } } return ret; } public static List<String> getShapeLayers(HashMap<Integer, CharacterTag> characters, MATRIX mat, int shapeNum, List<SHAPERECORD> shapeRecords, FILLSTYLEARRAY fillStyles, LINESTYLEARRAY lineStyles, boolean morphshape) { if (mat == null) { mat = new MATRIX(); } shapeRecords = smoothShape(shapeRecords); List<SHAPERECORD> edges = new ArrayList<>(); int lineStyleCount = 0; int fillStyle0 = -1; int fillStyle1 = -1; int strokeStyle = -1; String fillsStr = ""; String strokesStr = ""; fillsStr += "<fills>"; strokesStr += "<strokes>"; List<String> layers = new ArrayList<>(); String currentLayer = ""; int fillStyleCount = 0; if (fillStyles != null) { for (FILLSTYLE fs : fillStyles.fillStyles) { fillsStr += "<FillStyle index=\"" + (fillStyleCount + 1) + "\">"; fillsStr += convertFillStyle(mat, characters, fs, shapeNum); fillsStr += "</FillStyle>"; fillStyleCount++; } } if (lineStyles != null) { if ((shapeNum == 4) && (lineStyles.lineStyles != null)) { //(shapeNum == 4) { for (int l = 0; l < lineStyles.lineStyles.length; l++) { strokesStr += "<StrokeStyle index=\"" + (lineStyleCount + 1) + "\">"; strokesStr += convertLineStyle(characters, (LINESTYLE2) lineStyles.lineStyles[l], shapeNum); strokesStr += "</StrokeStyle>"; lineStyleCount++; } } else if (lineStyles.lineStyles != null) { for (int l = 0; l < lineStyles.lineStyles.length; l++) { strokesStr += "<StrokeStyle index=\"" + (lineStyleCount + 1) + "\">"; strokesStr += convertLineStyle(lineStyles.lineStyles[l], shapeNum); strokesStr += "</StrokeStyle>"; lineStyleCount++; } } } fillsStr += "</fills>"; strokesStr += "</strokes>"; int layer = 1; if ((fillStyleCount > 0) || (lineStyleCount > 0)) { currentLayer += "<DOMShape isFloating=\"true\">"; currentLayer += fillsStr; currentLayer += strokesStr; currentLayer += "<edges>"; } int x = 0; int y = 0; int startEdgeX = 0; int startEdgeY = 0; LINESTYLEARRAY actualLinestyles = lineStyles; int strokeStyleOrig = 0; fillStyleCount = fillStyles.fillStyles.length; for (SHAPERECORD edge : shapeRecords) { if (edge instanceof StyleChangeRecord) { StyleChangeRecord scr = (StyleChangeRecord) edge; boolean styleChange = false; int lastFillStyle1 = fillStyle1; int lastFillStyle0 = fillStyle0; int lastStrokeStyle = strokeStyle; if (scr.stateNewStyles) { fillsStr = "<fills>"; strokesStr = "<strokes>"; if (fillStyleCount > 0 || lineStyleCount > 0) { if ((fillStyle0 > 0) || (fillStyle1 > 0) || (strokeStyle > 0)) { boolean empty = false; if ((fillStyle0 <= 0) && (fillStyle1 <= 0) && (strokeStyle > 0) && morphshape) { if (shapeNum == 4) { if (strokeStyleOrig > 0) { if (!((LINESTYLE2) actualLinestyles.lineStyles[strokeStyleOrig]).hasFillFlag) { RGBA color = (RGBA) actualLinestyles.lineStyles[strokeStyleOrig].color; if (color.alpha == 0 && color.red == 0 && color.green == 0 && color.blue == 0) { empty = true; } } } } } if (!empty) { currentLayer += "<Edge"; if (fillStyle0 > -1) { currentLayer += " fillStyle0=\"" + fillStyle0 + "\""; } if (fillStyle1 > -1) { currentLayer += " fillStyle1=\"" + fillStyle1 + "\""; } if (strokeStyle > -1) { currentLayer += " strokeStyle=\"" + strokeStyle + "\""; } currentLayer += " edges=\"" + convertShapeEdges(startEdgeX, startEdgeY, mat, edges) + "\" />"; } } currentLayer += "</edges>"; currentLayer += "</DOMShape>"; if (!currentLayer.contains("<edges></edges>")) { //no empty layers, TODO:handle this better layers.add(currentLayer); } currentLayer = ""; } currentLayer += "<DOMShape isFloating=\"true\">"; //ret += convertShape(characters, null, shape); for (int f = 0; f < scr.fillStyles.fillStyles.length; f++) { fillsStr += "<FillStyle index=\"" + (f + 1) + "\">"; fillsStr += convertFillStyle(mat, characters, scr.fillStyles.fillStyles[f], shapeNum); fillsStr += "</FillStyle>"; fillStyleCount++; } lineStyleCount = 0; if (shapeNum == 4) { for (int l = 0; l < scr.lineStyles.lineStyles.length; l++) { strokesStr += "<StrokeStyle index=\"" + (lineStyleCount + 1) + "\">"; strokesStr += convertLineStyle(characters, (LINESTYLE2) scr.lineStyles.lineStyles[l], shapeNum); strokesStr += "</StrokeStyle>"; lineStyleCount++; } } else { for (int l = 0; l < scr.lineStyles.lineStyles.length; l++) { strokesStr += "<StrokeStyle index=\"" + (lineStyleCount + 1) + "\">"; strokesStr += convertLineStyle(scr.lineStyles.lineStyles[l], shapeNum); strokesStr += "</StrokeStyle>"; lineStyleCount++; } } fillsStr += "</fills>"; strokesStr += "</strokes>"; currentLayer += fillsStr; currentLayer += strokesStr; currentLayer += "<edges>"; actualLinestyles = scr.lineStyles; } if (scr.stateFillStyle0) { int fillStyle0_new = scr.fillStyle0;// == 0 ? 0 : fillStylesMap.get(fillStyleCount - lastFillStyleCount + scr.fillStyle0 - 1) + 1; if (morphshape) { //??? fillStyle1 = fillStyle0_new; } else { fillStyle0 = fillStyle0_new; } styleChange = true; } if (scr.stateFillStyle1) { int fillStyle1_new = scr.fillStyle1;// == 0 ? 0 : fillStylesMap.get(fillStyleCount - lastFillStyleCount + scr.fillStyle1 - 1) + 1; if (morphshape) { fillStyle0 = fillStyle1_new; } else { fillStyle1 = fillStyle1_new; } styleChange = true; } if (scr.stateLineStyle) { strokeStyle = scr.lineStyle;// == 0 ? 0 : lineStyleCount - lastLineStyleCount + scr.lineStyle; strokeStyleOrig = scr.lineStyle - 1; styleChange = true; } if (!edges.isEmpty()) { if ((fillStyle0 > 0) || (fillStyle1 > 0) || (strokeStyle > 0)) { boolean empty = false; if ((fillStyle0 <= 0) && (fillStyle1 <= 0) && (strokeStyle > 0) && morphshape) { if (shapeNum == 4) { if (strokeStyleOrig > 0) { if (!((LINESTYLE2) actualLinestyles.lineStyles[strokeStyleOrig]).hasFillFlag) { RGBA color = (RGBA) actualLinestyles.lineStyles[strokeStyleOrig].color; if (color.alpha == 0 && color.red == 0 && color.green == 0 && color.blue == 0) { empty = true; } } } } } if (!empty) { currentLayer += "<Edge"; if (fillStyle0 > -1) { currentLayer += " fillStyle0=\"" + lastFillStyle0 + "\""; } if (fillStyle1 > -1) { currentLayer += " fillStyle1=\"" + lastFillStyle1 + "\""; } if (strokeStyle > -1) { currentLayer += " strokeStyle=\"" + lastStrokeStyle + "\""; } currentLayer += " edges=\"" + convertShapeEdges(startEdgeX, startEdgeY, mat, edges) + "\" />"; } startEdgeX = x; startEdgeY = y; } edges.clear(); } } edges.add(edge); x = edge.changeX(x); y = edge.changeY(y); } if (!edges.isEmpty()) { if ((fillStyle0 > 0) || (fillStyle1 > 0) || (strokeStyle > 0)) { boolean empty = false; if ((fillStyle0 <= 0) && (fillStyle1 <= 0) && (strokeStyle > 0) && morphshape) { if (shapeNum == 4) { if (strokeStyleOrig > 0) { if (!((LINESTYLE2) actualLinestyles.lineStyles[strokeStyleOrig]).hasFillFlag) { RGBA color = (RGBA) actualLinestyles.lineStyles[strokeStyleOrig].color; if (color.alpha == 0 && color.red == 0 && color.green == 0 && color.blue == 0) { empty = true; } } } } } if (!empty) { currentLayer += "<Edge"; if (fillStyle0 > -1) { currentLayer += " fillStyle0=\"" + fillStyle0 + "\""; } if (fillStyle1 > -1) { currentLayer += " fillStyle1=\"" + fillStyle1 + "\""; } if (strokeStyle > -1) { currentLayer += " strokeStyle=\"" + strokeStyle + "\""; } currentLayer += " edges=\"" + convertShapeEdges(startEdgeX, startEdgeY, mat, edges) + "\" />"; } } } edges.clear(); fillsStr += "</fills>"; strokesStr += "</strokes>"; if (!currentLayer.isEmpty()) { currentLayer += "</edges>"; currentLayer += "</DOMShape>"; if (!currentLayer.contains("<edges></edges>")) { //no empty layers, TODO:handle this better layers.add(currentLayer); } } return layers; } private static int getLayerCount(List<Tag> tags) { int maxDepth = 0; for (Tag t : tags) { if (t instanceof PlaceObjectTypeTag) { int d = ((PlaceObjectTypeTag) t).getDepth(); if (d > maxDepth) { maxDepth = d; } int cd = ((PlaceObjectTypeTag) t).getClipDepth(); if (cd > maxDepth) { maxDepth = cd; } } } return maxDepth; } private static void walkShapeUsages(List<Tag> timeLineTags, HashMap<Integer, CharacterTag> characters, HashMap<Integer, Integer> usages) { for (Tag t : timeLineTags) { if (t instanceof DefineSpriteTag) { DefineSpriteTag sprite = (DefineSpriteTag) t; walkShapeUsages(sprite.subTags, characters, usages); } if (t instanceof PlaceObjectTypeTag) { PlaceObjectTypeTag po = (PlaceObjectTypeTag) t; int ch = po.getCharacterId(); if (ch > -1) { if (!usages.containsKey(ch)) { usages.put(ch, 0); } int usageCount = usages.get(ch); if (po.getInstanceName() != null) { usageCount++; } if (po.getColorTransform() != null) { usageCount++; } if (po.cacheAsBitmap()) { usageCount++; } MATRIX mat = po.getMatrix(); if (mat != null) { if (!mat.isEmpty()) { usageCount++; } } usages.put(ch, usageCount + 1); } } } } private static List<Integer> getNonLibraryShapes(List<Tag> tags, HashMap<Integer, CharacterTag> characters) { HashMap<Integer, Integer> usages = new HashMap<>(); walkShapeUsages(tags, characters, usages); List<Integer> ret = new ArrayList<>(); for (int ch : usages.keySet()) { if (usages.get(ch) < 2) { if (characters.get(ch) instanceof ShapeTag) { ShapeTag shp = (ShapeTag) characters.get(ch); if (!shapeHasMultiLayers(characters, null, shp.getShapeNum(), shp.getShapes().shapeRecords, shp.getShapes().fillStyles, shp.getShapes().lineStyles)) { ret.add(ch); } } } } return ret; } private static HashMap<Integer, CharacterTag> getCharacters(List<Tag> tags) { HashMap<Integer, CharacterTag> ret = new HashMap<>(); int maxId = 0; for (Tag t : tags) { if (t instanceof CharacterTag) { CharacterTag ct = (CharacterTag) t; if (ct.getCharacterId() > maxId) { maxId = ct.getCharacterId(); } } } for (Tag t : tags) { if (t instanceof SoundStreamHeadTypeTag) { SoundStreamHeadTypeTag ssh = (SoundStreamHeadTypeTag) t; ssh.setVirtualCharacterId(++maxId); } if (t instanceof CharacterTag) { CharacterTag ct = (CharacterTag) t; ret.put(ct.getCharacterId(), ct); } } return ret; } private static final String[] BLENDMODES = { null, null, "layer", "multiply", "screen", "lighten", "darken", "difference", "add", "subtract", "invert", "alpha", "erase", "overlay", "hardligh" }; private static double radToDeg(double rad) { return rad * 180 / Math.PI; } private static String doubleToString(double d, int precision) { double m = Math.pow(10, precision); d = Math.round(d * m) / m; return doubleToString(d); } private static String doubleToString(double d) { String ds = "" + d; if (ds.endsWith(".0")) { ds = ds.substring(0, ds.length() - 2); } return ds; } public static String convertFilter(FILTER filter) { StringBuilder ret = new StringBuilder(); if (filter instanceof DROPSHADOWFILTER) { DROPSHADOWFILTER dsf = (DROPSHADOWFILTER) filter; ret.append("<DropShadowFilter"); if (dsf.dropShadowColor.alpha != 255) { ret.append(" alpha=\"").append(doubleToString(dsf.dropShadowColor.getAlphaFloat())).append("\""); } ret.append(" angle=\"").append(doubleToString(radToDeg(dsf.angle))).append("\""); ret.append(" blurX=\"").append(doubleToString(dsf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(dsf.blurY)).append("\""); ret.append(" color=\"").append(dsf.dropShadowColor.toHexRGB()).append("\""); ret.append(" distance=\"").append(doubleToString(dsf.distance)).append("\""); if (!dsf.compositeSource) { ret.append(" hideObject=\"true\""); } if (dsf.innerShadow) { ret.append(" inner=\"true\""); } if (dsf.knockout) { ret.append(" knockout=\"true\""); } ret.append(" quality=\"").append(dsf.passes).append("\""); ret.append(" strength=\"").append(doubleToString(dsf.strength, 2)).append("\""); ret.append(" />"); } else if (filter instanceof BLURFILTER) { BLURFILTER bf = (BLURFILTER) filter; ret.append("<BlurFilter"); ret.append(" blurX=\"").append(doubleToString(bf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(bf.blurY)).append("\""); ret.append(" quality=\"").append(bf.passes).append("\""); ret.append(" />"); } else if (filter instanceof GLOWFILTER) { GLOWFILTER gf = (GLOWFILTER) filter; ret.append("<GlowFilter"); if (gf.glowColor.alpha != 255) { ret.append(" alpha=\"").append(gf.glowColor.getAlphaFloat()).append("\""); } ret.append(" blurX=\"").append(doubleToString(gf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(gf.blurY)).append("\""); ret.append(" color=\"").append(gf.glowColor.toHexRGB()).append("\""); if (gf.innerGlow) { ret.append(" inner=\"true\""); } if (gf.knockout) { ret.append(" knockout=\"true\""); } ret.append(" quality=\"").append(gf.passes).append("\""); ret.append(" strength=\"").append(doubleToString(gf.strength, 2)).append("\""); ret.append(" />"); } else if (filter instanceof BEVELFILTER) { BEVELFILTER bf = (BEVELFILTER) filter; ret.append("<BevelFilter"); ret.append(" blurX=\"").append(doubleToString(bf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(bf.blurY)).append("\""); ret.append(" quality=\"").append(bf.passes).append("\""); ret.append(" angle=\"").append(doubleToString(radToDeg(bf.angle))).append("\""); ret.append(" distance=\"").append(bf.distance).append("\""); if (bf.highlightColor.alpha != 255) { ret.append(" highlightAlpha=\"").append(bf.highlightColor.getAlphaFloat()).append("\""); } ret.append(" highlightColor=\"").append(bf.highlightColor.toHexRGB()).append("\""); if (bf.knockout) { ret.append(" knockout=\"true\""); } if (bf.shadowColor.alpha != 255) { ret.append(" shadowAlpha=\"").append(bf.shadowColor.getAlphaFloat()).append("\""); } ret.append(" shadowColor=\"").append(bf.shadowColor.toHexRGB()).append("\""); ret.append(" strength=\"").append(doubleToString(bf.strength, 2)).append("\""); if (bf.onTop && !bf.innerShadow) { ret.append(" type=\"full\""); } else if (!bf.innerShadow) { ret.append(" type=\"outer\""); } ret.append(" />"); } else if (filter instanceof GRADIENTGLOWFILTER) { GRADIENTGLOWFILTER ggf = (GRADIENTGLOWFILTER) filter; ret.append("<GradientGlowFilter"); ret.append(" angle=\"").append(doubleToString(radToDeg(ggf.angle))).append("\""); ret.append(" blurX=\"").append(doubleToString(ggf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(ggf.blurY)).append("\""); ret.append(" quality=\"").append(ggf.passes).append("\""); ret.append(" distance=\"").append(doubleToString(ggf.distance)).append("\""); if (ggf.knockout) { ret.append(" knockout=\"true\""); } ret.append(" strength=\"").append(doubleToString(ggf.strength, 2)).append("\""); if (ggf.onTop && !ggf.innerShadow) { ret.append(" type=\"full\""); } else if (!ggf.innerShadow) { ret.append(" type=\"outer\""); } ret.append(">"); for (int g = 0; g < ggf.gradientColors.length; g++) { RGBA gc = ggf.gradientColors[g]; ret.append("<GradientEntry color=\"").append(gc.toHexRGB()).append("\""); if (gc.alpha != 255) { ret.append(" alpha=\"").append(gc.getAlphaFloat()).append("\""); } ret.append(" ratio=\"").append(doubleToString(((float) ggf.gradientRatio[g]) / 255.0)).append("\""); ret.append("/>"); } ret.append("</GradientGlowFilter>"); } else if (filter instanceof GRADIENTBEVELFILTER) { GRADIENTBEVELFILTER gbf = (GRADIENTBEVELFILTER) filter; ret.append("<GradientBevelFilter"); ret.append(" angle=\"").append(doubleToString(radToDeg(gbf.angle))).append("\""); ret.append(" blurX=\"").append(doubleToString(gbf.blurX)).append("\""); ret.append(" blurY=\"").append(doubleToString(gbf.blurY)).append("\""); ret.append(" quality=\"").append(gbf.passes).append("\""); ret.append(" distance=\"").append(doubleToString(gbf.distance)).append("\""); if (gbf.knockout) { ret.append(" knockout=\"true\""); } ret.append(" strength=\"").append(doubleToString(gbf.strength, 2)).append("\""); if (gbf.onTop && !gbf.innerShadow) { ret.append(" type=\"full\""); } else if (!gbf.innerShadow) { ret.append(" type=\"outer\""); } ret.append(">"); for (int g = 0; g < gbf.gradientColors.length; g++) { RGBA gc = gbf.gradientColors[g]; ret.append("<GradientEntry color=\"").append(gc.toHexRGB()).append("\""); if (gc.alpha != 255) { ret.append(" alpha=\"").append(gc.getAlphaFloat()).append("\""); } ret.append(" ratio=\"").append(doubleToString(((float) gbf.gradientRatio[g]) / 255.0)).append("\""); ret.append("/>"); } ret.append("</GradientBevelFilter>"); } else if (filter instanceof COLORMATRIXFILTER) { COLORMATRIXFILTER cmf = (COLORMATRIXFILTER) filter; ret.append(convertAdjustColorFilter(cmf)); } return ret.toString(); } public static String convertSymbolInstance(String name, MATRIX matrix, ColorTransform colorTransform, boolean cacheAsBitmap, int blendMode, List<FILTER> filters, boolean isVisible, RGBA backgroundColor, CLIPACTIONS clipActions, CharacterTag tag, HashMap<Integer, CharacterTag> characters, List<Tag> tags, FLAVersion flaVersion) { StringBuilder ret = new StringBuilder(); if (matrix == null) { matrix = new MATRIX(); } if (tag instanceof DefineButtonTag) { DefineButtonTag bt = (DefineButtonTag) tag; for (Tag t : tags) { if (t instanceof DefineButtonCxformTag) { DefineButtonCxformTag bcx = (DefineButtonCxformTag) t; if (bcx.buttonId == bt.buttonId) { colorTransform = bcx.buttonColorTransform; } } } } ret.append("<DOMSymbolInstance libraryItemName=\"" + "Symbol ").append(tag.getCharacterId()).append("\""); if (name != null) { ret.append(" name=\"").append(xmlString(name)).append("\""); } String blendModeStr = null; if (blendMode < BLENDMODES.length) { blendModeStr = BLENDMODES[blendMode]; } if (blendModeStr != null) { ret.append(" blendMode=\"").append(blendModeStr).append("\""); } if (tag instanceof ShapeTag) { ret.append(" symbolType=\"graphic\" loop=\"loop\""); } else if (tag instanceof DefineSpriteTag) { DefineSpriteTag sprite = (DefineSpriteTag) tag; RECT spriteRect = sprite.getRect(new HashSet<BoundedTag>()); double centerPoint3DX = twipToPixel(matrix.translateX + spriteRect.getWidth() / 2); double centerPoint3DY = twipToPixel(matrix.translateY + spriteRect.getHeight() / 2); ret.append(" centerPoint3DX=\"").append(centerPoint3DX).append("\" centerPoint3DY=\"").append(centerPoint3DY).append("\""); } else if (tag instanceof ButtonTag) { ret.append(" symbolType=\"button\""); } if (cacheAsBitmap) { ret.append(" cacheAsBitmap=\"true\""); } if (!isVisible && flaVersion.ordinal() >= FLAVersion.CS5_5.ordinal()) { ret.append(" isVisible=\"false\""); } ret.append(">"); ret.append("<matrix>"); ret.append(convertMatrix(matrix)); ret.append("</matrix>"); ret.append("<transformationPoint><Point/></transformationPoint>"); if (backgroundColor != null) { ret.append("<MatteColor color=\"").append(backgroundColor.toHexRGB()).append("\""); if (backgroundColor.alpha != 255) { ret.append(" alpha=\"").append(doubleToString(backgroundColor.getAlphaFloat())).append("\""); } ret.append("/>"); } if (colorTransform != null) { ret.append("<color><Color"); if (colorTransform.getRedMulti() != 255) { ret.append(" redMultiplier=\"").append(((float) colorTransform.getRedMulti()) / 255.0f).append("\""); } if (colorTransform.getGreenMulti() != 255) { ret.append(" greenMultiplier=\"").append(((float) colorTransform.getGreenMulti()) / 255.0f).append("\""); } if (colorTransform.getBlueMulti() != 255) { ret.append(" blueMultiplier=\"").append(((float) colorTransform.getBlueMulti()) / 255.0f).append("\""); } if (colorTransform.getAlphaMulti() != 255) { ret.append(" alphaMultiplier=\"").append(((float) colorTransform.getAlphaMulti()) / 255.0f).append("\""); } if (colorTransform.getRedAdd() != 0) { ret.append(" redOffset=\"").append(colorTransform.getRedAdd()).append("\""); } if (colorTransform.getGreenAdd() != 0) { ret.append(" greenOffset=\"").append(colorTransform.getGreenAdd()).append("\""); } if (colorTransform.getBlueAdd() != 0) { ret.append(" blueOffset=\"").append(colorTransform.getBlueAdd()).append("\""); } if (colorTransform.getAlphaAdd() != 0) { ret.append(" alphaOffset=\"").append(colorTransform.getAlphaAdd()).append("\""); } ret.append("/></color>"); } if (filters != null) { ret.append("<filters>"); for (FILTER f : filters) { ret.append(convertFilter(f)); } ret.append("</filters>"); } if (tag instanceof DefineButtonTag) { ret.append("<Actionscript><script><![CDATA["); ret.append("on(press){\r\n"); ret.append(convertActionScript(((DefineButtonTag) tag))); ret.append("}"); ret.append("]]></script></Actionscript>"); } if (tag instanceof DefineButton2Tag) { DefineButton2Tag db2 = (DefineButton2Tag) tag; if (!db2.actions.isEmpty()) { ret.append("<Actionscript><script><![CDATA["); for (BUTTONCONDACTION bca : db2.actions) { ret.append(convertActionScript(bca)); } ret.append("]]></script></Actionscript>"); } } if (clipActions != null) { ret.append("<Actionscript><script><![CDATA["); for (CLIPACTIONRECORD rec : clipActions.clipActionRecords) { ret.append(convertActionScript(rec)); } ret.append("]]></script></Actionscript>"); } ret.append("</DOMSymbolInstance>"); return ret.toString(); } private static String convertActionScript(ASMSource as) { HighlightedTextWriter writer = new HighlightedTextWriter(Configuration.getCodeFormatting(), false); try { Action.actionsToSource(as, as.getActions(), as.toString(), writer); } catch (InterruptedException ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, null, ex); } return writer.toString(); } private static long getTimestamp() { return new Date().getTime() / 1000; } public static String convertLibrary(SWF swf, Map<Integer, String> characterVariables, Map<Integer, String> characterClasses, List<Integer> nonLibraryShapes, String backgroundColor, List<Tag> tags, HashMap<Integer, CharacterTag> characters, HashMap<String, byte[]> files, HashMap<String, byte[]> datfiles, FLAVersion flaVersion) { //TODO: Imported assets //linkageImportForRS="true" linkageIdentifier="xxx" linkageURL="yyy.swf" StringBuilder ret = new StringBuilder(); List<String> media = new ArrayList<>(); List<String> symbols = new ArrayList<>(); for (int ch : characters.keySet()) { CharacterTag symbol = characters.get(ch); if ((symbol instanceof ShapeTag) && nonLibraryShapes.contains(symbol.getCharacterId())) { continue; //shapes with 1 ocurrence and single layer are not added to library } if ((symbol instanceof ShapeTag) || (symbol instanceof DefineSpriteTag) || (symbol instanceof ButtonTag)) { StringBuilder symbolStr = new StringBuilder(); symbolStr.append("<DOMSymbolItem xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://ns.adobe.com/xfl/2008/\" name=\"Symbol ").append(symbol.getCharacterId()).append("\" lastModified=\"").append(getTimestamp()).append("\""); //TODO:itemID if (symbol instanceof ShapeTag) { symbolStr.append(" symbolType=\"graphic\""); } else if (symbol instanceof ButtonTag) { symbolStr.append(" symbolType=\"button\""); if (((ButtonTag) symbol).trackAsMenu()) { symbolStr.append(" trackAsMenu=\"true\""); } } boolean linkageExportForAS = false; if (characterClasses.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; symbolStr.append(" linkageClassName=\"").append(xmlString(characterClasses.get(symbol.getCharacterId()))).append("\""); } if (characterVariables.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; symbolStr.append(" linkageIdentifier=\"").append(xmlString(characterVariables.get(symbol.getCharacterId()))).append("\""); } if (linkageExportForAS) { symbolStr.append(" linkageExportForAS=\"true\""); } symbolStr.append(">"); symbolStr.append("<timeline>"); String itemIcon = null; if (symbol instanceof ButtonTag) { itemIcon = "0"; symbolStr.append("<DOMTimeline name=\"Symbol ").append(symbol.getCharacterId()).append("\" currentFrame=\"0\">"); symbolStr.append("<layers>"); ButtonTag button = (ButtonTag) symbol; List<BUTTONRECORD> records = button.getRecords(); int maxDepth = 0; for (BUTTONRECORD rec : records) { if (rec.placeDepth > maxDepth) { maxDepth = rec.placeDepth; } } for (int i = maxDepth; i >= 1; i--) { symbolStr.append("<DOMLayer name=\"Layer ").append(maxDepth - i + 1).append("\""); if (i == 1) { symbolStr.append(" current=\"true\" isSelected=\"true\""); } symbolStr.append(" color=\"").append(randomOutlineColor()).append("\">"); symbolStr.append("<frames>"); int lastFrame = 0; loopframes: for (int frame = 1; frame <= 4; frame++) { for (BUTTONRECORD rec : records) { if (rec.placeDepth == i) { boolean ok = false; switch (frame) { case 1: ok = rec.buttonStateUp; break; case 2: ok = rec.buttonStateOver; break; case 3: ok = rec.buttonStateDown; break; case 4: ok = rec.buttonStateHitTest; break; } if (!ok) { continue; } CXFORMWITHALPHA colorTransformAlpha = null; int blendMode = 0; List<FILTER> filters = new ArrayList<>(); if (button instanceof DefineButton2Tag) { colorTransformAlpha = rec.colorTransform; if (rec.buttonHasBlendMode) { blendMode = rec.blendMode; } if (rec.buttonHasFilterList) { filters = rec.filterList; } } CharacterTag character = characters.get(rec.characterId); MATRIX matrix = rec.placeMatrix; String recCharStr; if (character instanceof TextTag) { recCharStr = convertText(null, tags, (TextTag) character, matrix, filters, null); } else if (character instanceof DefineVideoStreamTag) { recCharStr = convertVideoInstance(null, matrix, (DefineVideoStreamTag) character, null); } else { recCharStr = convertSymbolInstance(null, matrix, colorTransformAlpha, false, blendMode, filters, true, null, null, characters.get(rec.characterId), characters, tags, flaVersion); } int duration = frame - lastFrame; lastFrame = frame; if (duration > 0) { if (duration > 1) { symbolStr.append("<DOMFrame index=\""); symbolStr.append((frame - duration)); symbolStr.append("\""); symbolStr.append(" duration=\"").append(duration - 1).append("\""); symbolStr.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\">"); symbolStr.append("<elements>"); symbolStr.append("</elements>"); symbolStr.append("</DOMFrame>"); } symbolStr.append("<DOMFrame index=\""); symbolStr.append((frame - 1)); symbolStr.append("\""); symbolStr.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\">"); symbolStr.append("<elements>"); symbolStr.append(recCharStr); symbolStr.append("</elements>"); symbolStr.append("</DOMFrame>"); } } } } symbolStr.append("</frames>"); symbolStr.append("</DOMLayer>"); } symbolStr.append("</layers>"); symbolStr.append("</DOMTimeline>"); } else if (symbol instanceof DefineSpriteTag) { DefineSpriteTag sprite = (DefineSpriteTag) symbol; if (sprite.subTags.isEmpty()) { //probably AS2 class continue; } symbolStr.append(convertTimeline(sprite.spriteId, nonLibraryShapes, backgroundColor, tags, sprite.getSubTags(), characters, "Symbol " + symbol.getCharacterId(), flaVersion, files)); } else if (symbol instanceof ShapeTag) { itemIcon = "1"; ShapeTag shape = (ShapeTag) symbol; symbolStr.append("<DOMTimeline name=\"Symbol ").append(symbol.getCharacterId()).append("\" currentFrame=\"0\">"); symbolStr.append("<layers>"); symbolStr.append(convertShape(characters, null, shape.getShapeNum(), shape.getShapes().shapeRecords, shape.getShapes().fillStyles, shape.getShapes().lineStyles, false, true)); symbolStr.append("</layers>"); symbolStr.append("</DOMTimeline>"); } symbolStr.append("</timeline>"); symbolStr.append("</DOMSymbolItem>"); String symbolStr2 = prettyFormatXML(symbolStr.toString()); String symbolFile = "Symbol " + symbol.getCharacterId() + ".xml"; files.put(symbolFile, Utf8Helper.getBytes(symbolStr2)); String symbLinkStr = ""; symbLinkStr += "<Include href=\"" + symbolFile + "\""; if (itemIcon != null) { symbLinkStr += " itemIcon=\"" + itemIcon + "\""; } symbLinkStr += " loadImmediate=\"false\""; if (flaVersion.ordinal() >= FLAVersion.CS5_5.ordinal()) { symbLinkStr += " lastModified=\"" + getTimestamp() + "\""; //TODO: itemID=\"518de416-00000341\" } symbLinkStr += "/>"; symbols.add(symbLinkStr); } else if (symbol instanceof ImageTag) { ImageTag imageTag = (ImageTag) symbol; ByteArrayOutputStream baos = new ByteArrayOutputStream(); SerializableImage image = imageTag.getImage(); // do not store the image in cache during xfl conversion imageTag.clearCache(); String format = imageTag.getImageFormat(); ImageHelper.write(image.getBufferedImage(), format.toUpperCase(), baos); String symbolFile = "bitmap" + symbol.getCharacterId() + "." + imageTag.getImageFormat(); files.put(symbolFile, baos.toByteArray()); String mediaLinkStr = "<DOMBitmapItem name=\"" + symbolFile + "\" sourceLastImported=\"" + getTimestamp() + "\" externalFileSize=\"" + baos.toByteArray().length + "\""; switch (format) { case "png": case "gif": mediaLinkStr += " useImportedJPEGData=\"false\" compressionType=\"lossless\" originalCompressionType=\"lossless\""; break; case "jpg": mediaLinkStr += " isJPEG=\"true\""; break; } if (characterClasses.containsKey(symbol.getCharacterId())) { mediaLinkStr += " linkageExportForAS=\"true\" linkageClassName=\"" + characterClasses.get(symbol.getCharacterId()) + "\""; } mediaLinkStr += " quality=\"50\" href=\"" + symbolFile + "\" bitmapDataHRef=\"M " + (media.size() + 1) + " " + getTimestamp() + ".dat\" frameRight=\"" + image.getWidth() + "\" frameBottom=\"" + image.getHeight() + "\"/>\n"; media.add(mediaLinkStr); } else if ((symbol instanceof SoundStreamHeadTypeTag) || (symbol instanceof DefineSoundTag)) { int soundFormat = 0; int soundRate = 0; boolean soundType = false; boolean soundSize = false; long soundSampleCount = 0; byte[] soundData = new byte[0]; int[] rateMap = {5, 11, 22, 44}; String exportFormat = "flv"; if (symbol instanceof SoundStreamHeadTypeTag) { SoundStreamHeadTypeTag sstream = (SoundStreamHeadTypeTag) symbol; soundFormat = sstream.getSoundFormatId(); soundRate = sstream.getSoundRate(); soundType = sstream.getSoundType(); soundSize = sstream.getSoundSize(); soundSampleCount = sstream.getSoundSampleCount(); boolean found = false; for (Tag t : tags) { if (found && (t instanceof SoundStreamBlockTag)) { SoundStreamBlockTag bl = (SoundStreamBlockTag) t; soundData = bl.streamSoundData.getRangeData(); break; } if (t == symbol) { found = true; } } } else if (symbol instanceof DefineSoundTag) { DefineSoundTag sound = (DefineSoundTag) symbol; soundFormat = sound.soundFormat; soundRate = sound.soundRate; soundType = sound.soundType; soundData = sound.soundData.getRangeData(); soundSize = sound.soundSize; soundSampleCount = sound.soundSampleCount; } int format = 0; int bits = 0; if ((soundFormat == SoundFormat.FORMAT_ADPCM) || (soundFormat == SoundFormat.FORMAT_UNCOMPRESSED_LITTLE_ENDIAN) || (soundFormat == SoundFormat.FORMAT_UNCOMPRESSED_NATIVE_ENDIAN)) { exportFormat = "wav"; if (soundType) { //stereo format += 1; } switch (soundRate) { case 0: format += 2; break; case 1: format += 6; break; case 2: format += 10; break; case 3: format += 14; break; } } if (soundFormat == SoundFormat.FORMAT_SPEEX) { bits = 18; } if (soundFormat == SoundFormat.FORMAT_ADPCM) { exportFormat = "wav"; try { SWFInputStream sis = new SWFInputStream(swf, soundData); int adpcmCodeSize = (int) sis.readUB(2, "adpcmCodeSize"); bits = 2 + adpcmCodeSize; } catch (IOException ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, null, ex); } } if (soundFormat == SoundFormat.FORMAT_MP3) { exportFormat = "mp3"; if (!soundType) { //mono format += 1; } format += 4; //quality best try { MP3SOUNDDATA s = new MP3SOUNDDATA(new SWFInputStream(swf, soundData), false); //sis.readSI16(); //MP3FRAME frame = new MP3FRAME(sis); MP3FRAME frame = s.frames.get(0); int bitRate = frame.getBitRate(); switch (bitRate) { case 8: bits = 6; break; case 16: bits = 7; break; case 20: bits = 8; break; case 24: bits = 9; break; case 32: bits = 10; break; case 48: bits = 11; break; case 56: bits = 12; break; case 64: bits = 13; break; case 80: bits = 14; break; case 112: bits = 15; break; case 128: bits = 16; break; case 160: bits = 17; break; } } catch (IOException ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, null, ex); } } SoundTag st = (SoundTag) symbol; SoundFormat fmt = st.getSoundFormat(); byte[] data = new byte[0]; try { data = new SoundExporter().exportSound(st, SoundExportMode.MP3_WAV); } catch (IOException ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, null, ex); } String symbolFile = "sound" + symbol.getCharacterId() + "." + exportFormat; files.put(symbolFile, data); String mediaLinkStr = "<DOMSoundItem name=\"" + symbolFile + "\" sourceLastImported=\"" + getTimestamp() + "\" externalFileSize=\"" + data.length + "\""; mediaLinkStr += " href=\"" + symbolFile + "\""; mediaLinkStr += " format=\""; mediaLinkStr += rateMap[soundRate] + "kHz"; mediaLinkStr += " " + (soundSize ? "16bit" : "8bit"); mediaLinkStr += " " + (soundType ? "Stereo" : "Mono"); mediaLinkStr += "\""; mediaLinkStr += " exportFormat=\"" + format + "\" exportBits=\"" + bits + "\" sampleCount=\"" + soundSampleCount + "\""; boolean linkageExportForAS = false; if (characterClasses.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; mediaLinkStr += " linkageClassName=\"" + characterClasses.get(symbol.getCharacterId()) + "\""; } if (characterVariables.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; mediaLinkStr += " linkageIdentifier=\"" + xmlString(characterVariables.get(symbol.getCharacterId())) + "\""; } if (linkageExportForAS) { mediaLinkStr += " linkageExportForAS=\"true\""; } mediaLinkStr += "/>\n"; media.add(mediaLinkStr); } else if (symbol instanceof DefineVideoStreamTag) { DefineVideoStreamTag video = (DefineVideoStreamTag) symbol; String videoType = "no media"; switch (video.codecID) { case 2: videoType = "h263 media"; break; case 3: videoType = "screen share media"; break; case 4: videoType = "vp6 media"; break; case 5: videoType = "vp6 alpha media"; break; } byte[] data = new byte[0]; try { data = new MovieExporter().exportMovie(video, MovieExportMode.FLV); } catch (IOException ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, null, ex); } String symbolFile = "movie" + symbol.getCharacterId() + "." + "flv"; String mediaLinkStr = ""; if (data.length == 0) { //Video has zero length, this probably means it is "Video - Actionscript-controlled" long ts = getTimestamp(); String datFileName = "M " + (datfiles.size() + 1) + " " + ts + ".dat"; mediaLinkStr = "<DOMVideoItem name=\"" + symbolFile + "\" sourceExternalFilepath=\"./LIBRARY/" + symbolFile + "\" sourceLastImported=\"" + ts + "\" videoDataHRef=\"" + datFileName + "\" channels=\"0\" isSpecial=\"true\" />"; //Use the dat file, otherwise it does not work datfiles.put(datFileName, new byte[]{ //Magic numbers, if anybody knows why, please tell me (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x59, (byte) 0x40, (byte) 0x18, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFE, (byte) 0xFF, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }); } else { files.put(symbolFile, data); mediaLinkStr = "<DOMVideoItem name=\"" + symbolFile + "\" sourceLastImported=\"" + getTimestamp() + "\" externalFileSize=\"" + data.length + "\""; mediaLinkStr += " href=\"" + symbolFile + "\""; mediaLinkStr += " videoType=\"" + videoType + "\""; mediaLinkStr += " fps=\"" + swf.frameRate + "\""; mediaLinkStr += " width=\"" + video.width + "\""; mediaLinkStr += " height=\"" + video.height + "\""; double len = ((double) video.numFrames) / ((double) swf.frameRate); mediaLinkStr += " length=\"" + len + "\""; boolean linkageExportForAS = false; if (characterClasses.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; mediaLinkStr += " linkageClassName=\"" + characterClasses.get(symbol.getCharacterId()) + "\""; } if (characterVariables.containsKey(symbol.getCharacterId())) { linkageExportForAS = true; mediaLinkStr += " linkageIdentifier=\"" + xmlString(characterVariables.get(symbol.getCharacterId())) + "\""; } if (linkageExportForAS) { mediaLinkStr += " linkageExportForAS=\"true\""; } mediaLinkStr += "/>\n"; } media.add(mediaLinkStr); } } if (!media.isEmpty()) { ret.append("<media>"); for (String m : media) { ret.append(m); } ret.append("</media>"); } if (!symbols.isEmpty()) { ret.append("<symbols>"); for (String s : symbols) { ret.append(s); } ret.append("</symbols>"); } return ret.toString(); } private static String prettyFormatXML(String input) { int indent = 5; try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) { System.err.println(input); Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, "Pretty print error", e); return input; } } private static String convertFrame(boolean shapeTween, HashMap<Integer, CharacterTag> characters, List<Tag> tags, SoundStreamHeadTypeTag soundStreamHead, StartSoundTag startSound, int frame, int duration, String actionScript, String elements, HashMap<String, byte[]> files) { StringBuilder ret = new StringBuilder(); DefineSoundTag sound = null; if (startSound != null) { for (Tag t : tags) { if (t instanceof DefineSoundTag) { DefineSoundTag s = (DefineSoundTag) t; if (s.soundId == startSound.soundId) { sound = s; break; } } } } ret.append("<DOMFrame index=\"").append(frame).append("\""); if (duration > 1) { ret.append(" duration=\"").append(duration).append("\""); } if (shapeTween) { ret.append(" tweenType=\"shape\" keyMode=\"").append(KEY_MODE_SHAPE_TWEEN).append("\""); } else { ret.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\""); } String soundEnvelopeStr = ""; if (soundStreamHead != null && startSound == null) { String soundName = "sound" + soundStreamHead.getCharacterId() + "." + soundStreamHead.getExportFormat(); ret.append(" soundName=\"").append(soundName).append("\""); ret.append(" soundSync=\"stream\""); soundEnvelopeStr += "<SoundEnvelope>"; soundEnvelopeStr += "<SoundEnvelopePoint level0=\"32768\" level1=\"32768\"/>"; soundEnvelopeStr += "</SoundEnvelope>"; } if (startSound != null && sound != null) { String soundName = "sound" + sound.soundId + "." + sound.getExportFormat(); ret.append(" soundName=\"").append(soundName).append("\""); if (startSound.soundInfo.hasInPoint) { ret.append(" inPoint44=\"").append(startSound.soundInfo.inPoint).append("\""); } if (startSound.soundInfo.hasOutPoint) { ret.append(" outPoint44=\"").append(startSound.soundInfo.outPoint).append("\""); } if (startSound.soundInfo.hasLoops) { if (startSound.soundInfo.loopCount == 32767) { ret.append(" soundLoopMode=\"loop\""); } ret.append(" soundLoop=\"").append(startSound.soundInfo.loopCount).append("\""); } if (startSound.soundInfo.syncStop) { ret.append(" soundSync=\"stop\""); } else if (startSound.soundInfo.syncNoMultiple) { ret.append(" soundSync=\"start\""); } soundEnvelopeStr += "<SoundEnvelope>"; if (startSound.soundInfo.hasEnvelope) { SOUNDENVELOPE[] envelopeRecords = startSound.soundInfo.envelopeRecords; for (SOUNDENVELOPE env : envelopeRecords) { soundEnvelopeStr += "<SoundEnvelopePoint mark44=\"" + env.pos44 + "\" level0=\"" + env.leftLevel + "\" level1=\"" + env.rightLevel + "\"/>"; } if (envelopeRecords.length == 1 && envelopeRecords[0].leftLevel == 32768 && envelopeRecords[0].pos44 == 0 && envelopeRecords[0].rightLevel == 0) { ret.append(" soundEffect=\"left channel\""); } else if (envelopeRecords.length == 1 && envelopeRecords[0].leftLevel == 0 && envelopeRecords[0].pos44 == 0 && envelopeRecords[0].rightLevel == 32768) { ret.append(" soundEffect=\"right channel\""); } else if (envelopeRecords.length == 2 && envelopeRecords[0].leftLevel == 32768 && envelopeRecords[0].pos44 == 0 && envelopeRecords[0].rightLevel == 0 && envelopeRecords[1].leftLevel == 0 && envelopeRecords[1].pos44 == sound.soundSampleCount && envelopeRecords[1].rightLevel == 32768) { ret.append(" soundEffect=\"fade left to right\""); } else if (envelopeRecords.length == 2 && envelopeRecords[0].leftLevel == 0 && envelopeRecords[0].pos44 == 0 && envelopeRecords[0].rightLevel == 32768 && envelopeRecords[1].leftLevel == 32768 && envelopeRecords[1].pos44 == sound.soundSampleCount && envelopeRecords[1].rightLevel == 0) { ret.append(" soundEffect=\"fade right to left\""); } else { ret.append(" soundEffect=\"custom\""); } //TODO: fade in, fade out } else { soundEnvelopeStr += "<SoundEnvelopePoint level0=\"32768\" level1=\"32768\"/>"; } soundEnvelopeStr += "</SoundEnvelope>"; } ret.append(">"); ret.append(soundEnvelopeStr); if (!actionScript.isEmpty()) { ret.append("<Actionscript><script><![CDATA["); ret.append(actionScript); ret.append("]]></script></Actionscript>"); } ret.append("<elements>"); ret.append(elements); ret.append("</elements>"); ret.append("</DOMFrame>"); return ret.toString(); } private static String convertVideoInstance(String instanceName, MATRIX matrix, DefineVideoStreamTag video, CLIPACTIONS clipActions) { StringBuilder ret = new StringBuilder(); ret.append("<DOMVideoInstance libraryItemName=\"movie").append(video.characterID).append(".flv\" frameRight=\"").append(20 * video.width).append("\" frameBottom=\"").append(20 * video.height).append("\""); if (instanceName != null) { ret.append(" name=\"").append(xmlString(instanceName)).append("\""); } ret.append(">"); ret.append("<matrix>"); ret.append(convertMatrix(matrix)); ret.append("</matrix>"); ret.append("<transformationPoint>"); ret.append("<Point />"); ret.append("</transformationPoint>"); ret.append("</DOMVideoInstance>"); return ret.toString(); } private static String convertFrames(String prevStr, String afterStr, List<Integer> nonLibraryShapes, List<Tag> tags, List<Tag> timelineTags, HashMap<Integer, CharacterTag> characters, int depth, FLAVersion flaVersion, HashMap<String, byte[]> files) { StringBuilder ret = new StringBuilder(); prevStr += "<frames>"; int frame = -1; String elements = ""; String lastElements = ""; int duration = 1; CharacterTag character = null; MATRIX matrix = null; String instanceName = null; ColorTransform colorTransForm = null; boolean cacheAsBitmap = false; int blendMode = 0; List<FILTER> filters = new ArrayList<>(); boolean isVisible = true; RGBA backGroundColor = null; CLIPACTIONS clipActions = null; int characterId = -1; int ratio = -1; boolean shapeTween = false; boolean lastShapeTween = false; MorphShapeTag shapeTweener = null; for (Tag t : timelineTags) { if (t instanceof PlaceObjectTypeTag) { PlaceObjectTypeTag po = (PlaceObjectTypeTag) t; if (po.getDepth() == depth) { int newCharId = po.getCharacterId(); if (newCharId == -1) { newCharId = characterId; } characterId = newCharId; if (characters.containsKey(characterId)) { character = characters.get(characterId); if (po.flagMove()) { MATRIX matrix2 = po.getMatrix(); if (matrix2 != null) { matrix = matrix2; } String instanceName2 = po.getInstanceName(); if (instanceName2 != null) { instanceName = instanceName2; } ColorTransform colorTransForm2 = po.getColorTransform(); if (colorTransForm2 != null) { colorTransForm = colorTransForm2; } CLIPACTIONS clipActions2 = po.getClipActions(); if (clipActions2 != null) { clipActions = clipActions2; } if (po.cacheAsBitmap()) { cacheAsBitmap = true; } int blendMode2 = po.getBlendMode(); if (blendMode2 > 0) { blendMode = blendMode2; } List<FILTER> filters2 = po.getFilters(); if (filters2 != null) { filters = filters2; } int ratio2 = po.getRatio(); if (ratio2 > -1) { ratio = ratio2; } } else { matrix = po.getMatrix(); instanceName = po.getInstanceName(); colorTransForm = po.getColorTransform(); cacheAsBitmap = po.cacheAsBitmap(); blendMode = po.getBlendMode(); filters = po.getFilters(); ratio = po.getRatio(); clipActions = po.getClipActions(); } } } } if (t instanceof RemoveTag) { RemoveTag rt = (RemoveTag) t; if (rt.getDepth() == depth) { if (shapeTween && character != null) { MorphShapeTag m = (MorphShapeTag) character; shapeTweener = m; shapeTween = false; } character = null; matrix = null; instanceName = null; colorTransForm = null; cacheAsBitmap = false; blendMode = 0; filters = new ArrayList<>(); isVisible = true; backGroundColor = null; characterId = -1; clipActions = null; } } if (t instanceof ShowFrameTag) { elements = ""; if ((character instanceof ShapeTag) && (nonLibraryShapes.contains(characterId) || shapeTweener != null)) { ShapeTag shape = (ShapeTag) character; elements += convertShape(characters, matrix, shape.getShapeNum(), shape.getShapes().shapeRecords, shape.getShapes().fillStyles, shape.getShapes().lineStyles, false, false); shapeTween = false; shapeTweener = null; } else if (character != null) { if (character instanceof MorphShapeTag) { MorphShapeTag m = (MorphShapeTag) character; elements += convertShape(characters, matrix, 3, m.getStartEdges().shapeRecords, m.getFillStyles().getStartFillStyles(), m.getLineStyles().getStartLineStyles(m.getShapeNum()), true, false); shapeTween = true; } else { shapeTween = false; if (character instanceof TextTag) { elements += convertText(instanceName, tags, (TextTag) character, matrix, filters, clipActions); } else if (character instanceof DefineVideoStreamTag) { elements += convertVideoInstance(instanceName, matrix, (DefineVideoStreamTag) character, clipActions); } else { elements += convertSymbolInstance(instanceName, matrix, colorTransForm, cacheAsBitmap, blendMode, filters, isVisible, backGroundColor, clipActions, character, characters, tags, flaVersion); } } } frame++; if (!elements.equals(lastElements) && frame > 0) { ret.append(convertFrame(lastShapeTween, characters, tags, null, null, frame - duration, duration, "", lastElements, files)); duration = 1; } else if (frame == 0) { duration = 1; } else { duration++; } lastShapeTween = shapeTween; lastElements = elements; } } if (!lastElements.isEmpty()) { frame++; ret.append(convertFrame(lastShapeTween, characters, tags, null, null, (frame - duration < 0 ? 0 : frame - duration), duration, "", lastElements, files)); } afterStr = "</frames>" + afterStr; String retStr = ret.toString(); if (!retStr.isEmpty()) { retStr = prevStr + retStr + afterStr; } return retStr; } public static String convertFonts(List<Tag> tags) { StringBuilder ret = new StringBuilder(); for (Tag t : tags) { if (t instanceof FontTag) { FontTag font = (FontTag) t; int fontId = font.getFontId(); String fontName = null; for (Tag t2 : tags) { if (t2 instanceof DefineFontNameTag) { if (((DefineFontNameTag) t2).fontId == fontId) { fontName = ((DefineFontNameTag) t2).fontName; } } } if (fontName == null) { fontName = font.getFontNameIntag(); } int fontStyle = font.getFontStyle(); String installedFont; if ((installedFont = FontTag.isFontFamilyInstalled(fontName)) != null) { fontName = new Font(installedFont, fontStyle, 10).getPSName(); } String embedRanges = ""; String fontChars = font.getCharacters(tags); if ("".equals(fontChars)) { continue; } String embeddedCharacters = fontChars; embeddedCharacters = embeddedCharacters.replace("\u00A0", ""); //nonbreak space embeddedCharacters = embeddedCharacters.replace(".", ""); boolean hasAllRanges = false; for (int r = 0; r < CharacterRanges.rangeCount(); r++) { int codes[] = CharacterRanges.rangeCodes(r); boolean hasAllInRange = true; for (int i = 0; i < codes.length; i++) { if (!fontChars.contains("" + (char) codes[i])) { hasAllInRange = false; break; } } if (hasAllInRange) { //remove all found characters for (int i = 0; i < codes.length; i++) { embeddedCharacters = embeddedCharacters.replace("" + (char) codes[i], ""); } if (!"".equals(embedRanges)) { embedRanges += "|"; } embedRanges += (r + 1); } else { hasAllRanges = false; } } if (hasAllRanges) { embedRanges = "9999"; } ret.append("<DOMFontItem name=\"Font ").append(fontId).append("\" font=\"").append(xmlString(fontName)).append("\" size=\"0\" id=\"").append(fontId).append("\" embedRanges=\"").append(embedRanges).append("\"").append(!"".equals(embeddedCharacters) ? " embeddedCharacters=\"" + xmlString(embeddedCharacters) + "\"" : "").append(" />"); } } String retStr = ret.toString(); if (!retStr.isEmpty()) { retStr = "<fonts>" + retStr + "</fonts>"; } return retStr; } public static String convertActionScriptLayer(int spriteId, List<Tag> tags, List<Tag> timeLineTags, String backgroundColor) { StringBuilder ret = new StringBuilder(); String script = ""; int duration = 0; int frame = 0; for (Tag t : tags) { if (t instanceof DoInitActionTag) { DoInitActionTag dia = (DoInitActionTag) t; if (dia.spriteId == spriteId) { script += convertActionScript(dia); } } } if (!script.isEmpty()) { script = "#initclip\r\n" + script + "#endinitclip\r\n"; } for (Tag t : timeLineTags) { if (t instanceof DoActionTag) { DoActionTag da = (DoActionTag) t; script += convertActionScript(da); } if (t instanceof ShowFrameTag) { if (script.isEmpty()) { duration++; } else { if (duration > 0) { ret.append("<DOMFrame index=\"").append(frame - duration).append("\""); if (duration > 1) { ret.append(" duration=\"").append(duration).append("\""); } ret.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\">"); ret.append("<elements>"); ret.append("</elements>"); ret.append("</DOMFrame>"); } ret.append("<DOMFrame index=\"").append(frame).append("\""); ret.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\">"); ret.append("<Actionscript><script><![CDATA["); ret.append(script); ret.append("]]></script></Actionscript>"); ret.append("<elements>"); ret.append("</elements>"); ret.append("</DOMFrame>"); script = ""; duration = 0; } frame++; } } String retStr = ret.toString(); if (!retStr.isEmpty()) { retStr = "<DOMLayer name=\"Script Layer\" color=\"" + randomOutlineColor() + "\">" + "<frames>" + retStr + "</frames>" + "</DOMLayer>"; } return retStr; } public static String convertLabelsLayer(int spriteId, List<Tag> tags, List<Tag> timeLineTags, String backgroundColor) { StringBuilder ret = new StringBuilder(); int duration = 0; int frame = 0; String frameLabel = ""; boolean isAnchor = false; for (Tag t : timeLineTags) { if (t instanceof FrameLabelTag) { FrameLabelTag fl = (FrameLabelTag) t; frameLabel = fl.getLabelName(); isAnchor = fl.isNamedAnchor(); } if (t instanceof ShowFrameTag) { if (frameLabel.isEmpty()) { duration++; } else { if (duration > 0) { ret.append("<DOMFrame index=\"").append(frame - duration).append("\""); if (duration > 1) { ret.append(" duration=\"").append(duration).append("\""); } ret.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\">"); ret.append("<elements>"); ret.append("</elements>"); ret.append("</DOMFrame>"); } ret.append("<DOMFrame index=\"").append(frame).append("\""); ret.append(" keyMode=\"").append(KEY_MODE_NORMAL).append("\""); ret.append(" name=\"").append(frameLabel).append("\""); if (isAnchor) { ret.append(" labelType=\"anchor\" bookmark=\"true\""); } else { ret.append(" labelType=\"name\""); } ret.append(">"); ret.append("<elements>"); ret.append("</elements>"); ret.append("</DOMFrame>"); frameLabel = ""; duration = 0; } frame++; } } String retStr = ret.toString(); if (!retStr.isEmpty()) { retStr = "<DOMLayer name=\"Labels Layer\" color=\"" + randomOutlineColor() + "\">" + "<frames>" + retStr + "</frames>" + "</DOMLayer>"; } return retStr; } public static String convertSoundLayer(int layerIndex, String backgroundColor, HashMap<Integer, CharacterTag> characters, List<Tag> tags, List<Tag> timeLineTags, HashMap<String, byte[]> files) { StringBuilder ret = new StringBuilder(); StartSoundTag lastStartSound = null; SoundStreamHeadTypeTag lastSoundStreamHead = null; StartSoundTag startSound = null; SoundStreamHeadTypeTag soundStreamHead = null; int duration = 1; int frame = 0; for (Tag t : timeLineTags) { if (t instanceof StartSoundTag) { startSound = (StartSoundTag) t; for (Tag ta : tags) { if (ta instanceof DefineSoundTag) { DefineSoundTag s = (DefineSoundTag) ta; if (s.soundId == startSound.soundId) { if (!files.containsKey("sound" + s.soundId + "." + s.getExportFormat())) { //Sound was not exported startSound = null; //ignore } break; } } } } if (t instanceof SoundStreamHeadTypeTag) { soundStreamHead = (SoundStreamHeadTypeTag) t; if (!files.containsKey("sound" + soundStreamHead.getCharacterId() + "." + soundStreamHead.getExportFormat())) { //Sound was not exported soundStreamHead = null; //ignore } } if (t instanceof ShowFrameTag) { if (soundStreamHead != null || startSound != null) { if (lastSoundStreamHead != null || lastStartSound != null) { ret.append(convertFrame(false, characters, tags, lastSoundStreamHead, lastStartSound, frame, duration, "", "", files)); } frame += duration; duration = 1; lastSoundStreamHead = soundStreamHead; lastStartSound = startSound; soundStreamHead = null; startSound = null; } else { duration++; } } } if (lastSoundStreamHead != null || lastStartSound != null) { if (frame < 0) { frame = 0; duration = 1; } ret.append(convertFrame(false, characters, tags, lastSoundStreamHead, lastStartSound, frame, duration, "", "", files)); } String retStr = ret.toString(); if (!retStr.isEmpty()) { retStr = "<DOMLayer name=\"Layer " + layerIndex + "\" color=\"" + randomOutlineColor() + "\">" + "<frames>" + retStr + "</frames>" + "</DOMLayer>"; } return retStr; } private static String randomOutlineColor() { RGB outlineColor = new RGB(); do { outlineColor.red = random.nextInt(256); outlineColor.green = random.nextInt(256); outlineColor.blue = random.nextInt(256); } while ((outlineColor.red + outlineColor.green + outlineColor.blue) / 3 < 128); return outlineColor.toHexRGB(); } public static String convertTimeline(int spriteId, List<Integer> nonLibraryShapes, String backgroundColor, List<Tag> tags, List<Tag> timelineTags, HashMap<Integer, CharacterTag> characters, String name, FLAVersion flaVersion, HashMap<String, byte[]> files) { StringBuilder ret = new StringBuilder(); ret.append("<DOMTimeline name=\"").append(name).append("\">"); ret.append("<layers>"); String labelsLayer = convertLabelsLayer(spriteId, tags, timelineTags, backgroundColor); ret.append(labelsLayer); String scriptLayer = convertActionScriptLayer(spriteId, tags, timelineTags, backgroundColor); ret.append(scriptLayer); int index = 0; if (!labelsLayer.isEmpty()) { index++; } if (!scriptLayer.isEmpty()) { index++; } int layerCount = getLayerCount(timelineTags); Stack<Integer> parentLayers = new Stack<>(); for (int d = layerCount; d >= 1; d--, index++) { for (Tag t : timelineTags) { if (t instanceof PlaceObjectTypeTag) { PlaceObjectTypeTag po = (PlaceObjectTypeTag) t; if (po.getClipDepth() == d) { for (int m = po.getDepth(); m < po.getClipDepth(); m++) { parentLayers.push(index); } ret.append("<DOMLayer name=\"Layer ").append(index + 1).append("\" color=\"").append(randomOutlineColor()).append("\" "); ret.append(" layerType=\"mask\" locked=\"true\""); ret.append(">"); ret.append(convertFrames("", "", nonLibraryShapes, tags, timelineTags, characters, po.getDepth(), flaVersion, files)); ret.append("</DOMLayer>"); index++; break; } } } boolean hasClipDepth = false; for (Tag t : timelineTags) { if (t instanceof PlaceObjectTypeTag) { PlaceObjectTypeTag po = (PlaceObjectTypeTag) t; if (po.getDepth() == d) { if (po.getClipDepth() != -1) { hasClipDepth = true; break; } } } } if (hasClipDepth) { index--; continue; } int parentLayer = -1; if (!parentLayers.isEmpty()) { parentLayer = parentLayers.pop(); } String layerPrev = ""; layerPrev += "<DOMLayer name=\"Layer " + (index + 1) + "\" color=\"" + randomOutlineColor() + "\" "; if (d == 1) { layerPrev += " current=\"true\" isSelected=\"true\""; } if (parentLayer != -1) { if (parentLayer != d) { layerPrev += " parentLayerIndex=\"" + (parentLayer) + "\" locked=\"true\""; } } layerPrev += ">"; String layerAfter = "</DOMLayer>"; String cf = convertFrames(layerPrev, layerAfter, nonLibraryShapes, tags, timelineTags, characters, d, flaVersion, files); if (cf.isEmpty()) { index--; } ret.append(cf); } int soundLayerIndex = layerCount; layerCount++; ret.append(convertSoundLayer(soundLayerIndex, backgroundColor, characters, tags, timelineTags, files)); ret.append("</layers>"); ret.append("</DOMTimeline>"); return ret.toString(); } private static void writeFile(AbortRetryIgnoreHandler handler, final byte[] data, final String file) throws IOException { new RetryTask(new RunnableIOEx() { @Override public void run() throws IOException { try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(data); } } }, handler).run(); } private static Map<Integer, String> getCharacterClasses(List<Tag> tags) { Map<Integer, String> ret = new HashMap<>(); for (Tag t : tags) { if (t instanceof SymbolClassTag) { SymbolClassTag sc = (SymbolClassTag) t; for (int i = 0; i < sc.tags.length; i++) { if (!ret.containsKey(sc.tags[i]) && !ret.containsValue(sc.names[i])) { ret.put(sc.tags[i], sc.names[i]); } } } } return ret; } private static Map<Integer, String> getCharacterVariables(List<Tag> tags) { Map<Integer, String> ret = new HashMap<>(); for (Tag t : tags) { if (t instanceof ExportAssetsTag) { ExportAssetsTag ea = (ExportAssetsTag) t; for (int i = 0; i < ea.tags.size(); i++) { if (!ret.containsKey(ea.tags.get(i))) { ret.put(ea.tags.get(i), ea.names.get(i)); } } } } return ret; } public static String convertText(String instanceName, List<Tag> tags, TextTag tag, MATRIX m, List<FILTER> filters, CLIPACTIONS clipActions) { StringBuilder ret = new StringBuilder(); if (m == null) { m = new MATRIX(); } Matrix matrix = new Matrix(m); CSMTextSettingsTag csmts = null; String filterStr = ""; if (filters != null) { filterStr += "<filters>"; for (FILTER f : filters) { filterStr += convertFilter(f); } filterStr += "</filters>"; } for (Tag t : tags) { if (t instanceof CSMTextSettingsTag) { CSMTextSettingsTag c = (CSMTextSettingsTag) t; if (c.textID == tag.getCharacterId()) { csmts = c; break; } } } String fontRenderingMode = "standard"; String antiAlias = ""; if (csmts != null) { if (csmts.thickness == 0 & csmts.sharpness == 0) { fontRenderingMode = null; } else { fontRenderingMode = "customThicknessSharpness"; } antiAlias = " antiAliasSharpness=\"" + doubleToString(csmts.sharpness) + "\" antiAliasThickness=\"" + doubleToString(csmts.thickness) + "\""; } String matStr = ""; matStr += "<matrix>"; String left = ""; RECT bounds = tag.getBounds(); if ((tag instanceof DefineTextTag) || (tag instanceof DefineText2Tag)) { MATRIX textMatrix = tag.getTextMatrix(); left = " left=\"" + doubleToString((textMatrix.translateX) / SWF.unitDivisor) + "\""; } matStr += convertMatrix(matrix); matStr += "</matrix>"; if ((tag instanceof DefineTextTag) || (tag instanceof DefineText2Tag)) { List<TEXTRECORD> textRecords = new ArrayList<>(); if (tag instanceof DefineTextTag) { textRecords = ((DefineTextTag) tag).textRecords; } else if (tag instanceof DefineText2Tag) { textRecords = ((DefineText2Tag) tag).textRecords; } looprec: for (TEXTRECORD rec : textRecords) { if (rec.styleFlagsHasFont) { for (Tag t : tags) { if (t instanceof FontTag) { FontTag ft = (FontTag) t; if (ft.getFontId() == rec.fontId) { if (ft.isSmall()) { fontRenderingMode = "bitmap"; break looprec; } } } } } } ret.append("<DOMStaticText"); ret.append(left); if (fontRenderingMode != null) { ret.append(" fontRenderingMode=\"").append(fontRenderingMode).append("\""); } if (instanceName != null) { ret.append(" instanceName=\"").append(xmlString(instanceName)).append("\""); } ret.append(antiAlias); Map<String, Object> attrs = TextTag.getTextRecordsAttributes(textRecords, tags); ret.append(" width=\"").append(tag.getBounds().getWidth() / 2).append("\" height=\"").append(tag.getBounds().getHeight()).append("\" autoExpand=\"true\" isSelectable=\"false\">"); ret.append(matStr); ret.append("<textRuns>"); int fontId = -1; FontTag font = null; String fontName = null; String psFontName = null; int textHeight = -1; RGB textColor = null; RGBA textColorA = null; boolean newline = false; boolean firstRun = true; @SuppressWarnings("unchecked") List<Integer> leftMargins = (List<Integer>) attrs.get("allLeftMargins"); @SuppressWarnings("unchecked") List<Integer> letterSpacings = (List<Integer>) attrs.get("allLetterSpacings"); for (int r = 0; r < textRecords.size(); r++) { TEXTRECORD rec = textRecords.get(r); if (rec.styleFlagsHasColor) { if (tag instanceof DefineTextTag) { textColor = rec.textColor; } else { textColorA = rec.textColorA; } } if (rec.styleFlagsHasFont) { fontId = rec.fontId; fontName = null; textHeight = rec.textHeight; font = null; for (Tag t : tags) { if (t instanceof FontTag) { if (((FontTag) t).getFontId() == fontId) { font = (FontTag) t; } } if (t instanceof DefineFontNameTag) { if (((DefineFontNameTag) t).fontId == fontId) { fontName = ((DefineFontNameTag) t).fontName; } } } if ((fontName == null) && (font != null)) { fontName = font.getFontNameIntag(); } int fontStyle = 0; if (font != null) { fontStyle = font.getFontStyle(); } String installedFont; if ((installedFont = FontTag.isFontFamilyInstalled(fontName)) != null) { psFontName = new Font(installedFont, fontStyle, 10).getPSName(); } else { psFontName = fontName; } } newline = false; if (!firstRun && rec.styleFlagsHasYOffset) { newline = true; } firstRun = false; if (font != null) { ret.append("<DOMTextRun>"); ret.append("<characters>").append(xmlString((newline ? "\r" : "") + rec.getText(font))).append("</characters>"); ret.append("<textAttrs>"); ret.append("<DOMTextAttrs aliasText=\"false\" rotation=\"true\" size=\"").append(twipToPixel(textHeight)).append("\" bitmapSize=\"").append(textHeight).append("\""); ret.append(" letterSpacing=\"").append(doubleToString(twipToPixel(letterSpacings.get(r)))).append("\""); ret.append(" indent=\"").append(doubleToString(twipToPixel((int) attrs.get("indent")))).append("\""); ret.append(" leftMargin=\"").append(doubleToString(twipToPixel(leftMargins.get(r)))).append("\""); ret.append(" lineSpacing=\"").append(doubleToString(twipToPixel((int) attrs.get("lineSpacing")))).append("\""); ret.append(" rightMargin=\"").append(doubleToString(twipToPixel((int) attrs.get("rightMargin")))).append("\""); if (textColor != null) { ret.append(" fillColor=\"").append(textColor.toHexRGB()).append("\""); } else if (textColorA != null) { ret.append(" fillColor=\"").append(textColorA.toHexRGB()).append("\" alpha=\"").append(textColorA.getAlphaFloat()).append("\""); } ret.append(" face=\"").append(psFontName).append("\""); ret.append("/>"); ret.append("</textAttrs>"); ret.append("</DOMTextRun>"); } } ret.append("</textRuns>"); ret.append(filterStr); ret.append("</DOMStaticText>"); } else if (tag instanceof DefineEditTextTag) { DefineEditTextTag det = (DefineEditTextTag) tag; String tagName; for (Tag t : tags) { if (t instanceof FontTag) { FontTag ft = (FontTag) t; if (ft.getFontId() == det.fontId) { if (ft.isSmall()) { fontRenderingMode = "bitmap"; break; } } } } if (!det.useOutlines) { fontRenderingMode = "device"; } if (det.wasStatic) { tagName = "DOMStaticText"; } else if (det.readOnly) { tagName = "DOMDynamicText"; } else { tagName = "DOMInputText"; } ret.append("<").append(tagName); if (fontRenderingMode != null) { ret.append(" fontRenderingMode=\"").append(fontRenderingMode).append("\""); } if (instanceName != null) { ret.append(" name=\"").append(xmlString(instanceName)).append("\""); } ret.append(antiAlias); double width = twipToPixel(bounds.getWidth()); double height = twipToPixel(bounds.getHeight()); //There is usually 4px difference between width/height and XML width/height //If somebody knows what that means, tell me double padding = 2; width -= 2 * padding; height -= 2 * padding; if (det.hasLayout) { width -= twipToPixel(det.rightMargin); width -= twipToPixel(det.leftMargin); } ret.append(" width=\"").append(width).append("\""); ret.append(" height=\"").append(height).append("\""); if (det.border) { ret.append(" border=\"true\""); } if (det.html) { ret.append(" renderAsHTML=\"true\""); } if (det.noSelect) { ret.append(" isSelectable=\"false\""); } if (det.multiline && det.wordWrap) { ret.append(" lineType=\"multiline\""); } else if (det.multiline && (!det.wordWrap)) { ret.append(" lineType=\"multiline no wrap\""); } else if (det.password) { ret.append(" lineType=\"password\""); } if (det.hasMaxLength) { ret.append(" maxCharacters=\"").append(det.maxLength).append("\""); } if (!det.variableName.isEmpty()) { ret.append(" variableName=\"").append(det.variableName).append("\""); } ret.append(">"); ret.append(matStr); ret.append("<textRuns>"); String txt = ""; if (det.hasText) { txt = det.initialText; } if (det.html) { ret.append(convertHTMLText(tags, det, txt)); } else { ret.append("<DOMTextRun>"); ret.append("<characters>").append(xmlString(txt)).append("</characters>"); int leftMargin = -1; int rightMargin = -1; int indent = -1; int lineSpacing = -1; String alignment = null; boolean italic = false; boolean bold = false; String fontFace = null; int size = -1; RGBA textColor = null; if (det.hasTextColor) { textColor = det.textColor; } if (det.hasFont) { String fontName = null; FontTag ft = null; for (Tag u : tags) { if (u instanceof DefineFontNameTag) { if (((DefineFontNameTag) u).fontId == det.fontId) { fontName = ((DefineFontNameTag) u).fontName; } } if (u instanceof FontTag) { if (((FontTag) u).getFontId() == det.fontId) { ft = (FontTag) u; } } if (fontName != null && ft != null) { break; } } if (ft != null) { if (fontName == null) { fontName = ft.getFontNameIntag(); } italic = ft.isItalic(); bold = ft.isBold(); size = det.fontHeight; fontFace = fontName; String installedFont = null; if ((installedFont = FontTag.isFontFamilyInstalled(fontName)) != null) { fontName = installedFont; fontFace = new Font(installedFont, (italic ? Font.ITALIC : 0) | (bold ? Font.BOLD : 0) | (!italic && !bold ? Font.PLAIN : 0), size < 0 ? 10 : size).getPSName(); } } } if (det.hasLayout) { leftMargin = det.leftMargin; rightMargin = det.rightMargin; indent = det.indent; lineSpacing = det.leading; String[] alignNames = {"left", "right", "center", "justify"}; if (det.align < alignNames.length) { alignment = alignNames[det.align]; } else { alignment = "unknown"; } } ret.append("<textAttrs>"); ret.append("<DOMTextAttrs"); if (alignment != null) { ret.append(" alignment=\"").append(alignment).append("\""); } ret.append(" rotation=\"true\""); //? if (indent > -1) { ret.append(" indent=\"").append(twipToPixel(indent)).append("\""); } if (leftMargin > -1) { ret.append(" leftMargin=\"").append(twipToPixel(leftMargin)).append("\""); } if (lineSpacing > -1) { ret.append(" lineSpacing=\"").append(twipToPixel(lineSpacing)).append("\""); } if (rightMargin > -1) { ret.append(" rightMargin=\"").append(twipToPixel(rightMargin)).append("\""); } if (size > -1) { ret.append(" size=\"").append(twipToPixel(size)).append("\""); ret.append(" bitmapSize=\"").append(size).append("\""); } if (fontFace != null) { ret.append(" face=\"").append(fontFace).append("\""); } if (textColor != null) { ret.append(" fillColor=\"").append(textColor.toHexRGB()).append("\" alpha=\"").append(textColor.getAlphaFloat()).append("\""); } ret.append("/>"); ret.append("</textAttrs>"); ret.append("</DOMTextRun>"); } ret.append("</textRuns>"); ret.append(filterStr); ret.append("</").append(tagName).append(">"); } return ret.toString(); } public static void convertSWF(AbortRetryIgnoreHandler handler, SWF swf, String swfFileName, String outfile, boolean compressed, String generator, String generatorVerName, String generatorVersion, boolean parallel, FLAVersion flaVersion) throws IOException { FileAttributesTag fa = swf.fileAttributes; boolean useAS3 = false; boolean useNetwork = false; if (fa != null) { useAS3 = fa.actionScript3; useNetwork = fa.useNetwork; } if (!useAS3 && flaVersion.minASVersion() > 2) { throw new IllegalArgumentException("FLA version " + flaVersion + " does not support AS1/2"); } File file = new File(outfile); File outDir = file.getParentFile(); if (!outDir.exists()) { if (!outDir.mkdirs()) { if (!outDir.exists()) { throw new IOException("cannot create directory " + outDir); } } } StringBuilder domDocument = new StringBuilder(); String baseName = swfFileName; File f = new File(baseName); baseName = f.getName(); if (baseName.contains(".")) { baseName = baseName.substring(0, baseName.lastIndexOf('.')); } final HashMap<String, byte[]> files = new HashMap<>(); final HashMap<String, byte[]> datfiles = new HashMap<>(); HashMap<Integer, CharacterTag> characters = getCharacters(swf.tags); List<Integer> nonLibraryShapes = getNonLibraryShapes(swf.tags, characters); Map<Integer, String> characterClasses = getCharacterClasses(swf.tags); Map<Integer, String> characterVariables = getCharacterVariables(swf.tags); String backgroundColor = "#ffffff"; for (Tag t : swf.tags) { if (t instanceof SetBackgroundColorTag) { SetBackgroundColorTag sbc = (SetBackgroundColorTag) t; backgroundColor = sbc.backgroundColor.toHexRGB(); } } domDocument.append("<DOMDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://ns.adobe.com/xfl/2008/\" currentTimeline=\"1\" xflVersion=\"").append(flaVersion.xflVersion()).append("\" creatorInfo=\"").append(generator).append("\" platform=\"Windows\" versionInfo=\"Saved by ").append(generatorVerName).append("\" majorVersion=\"").append(generatorVersion).append("\" buildNumber=\"\" nextSceneIdentifier=\"2\" playOptionsPlayLoop=\"false\" playOptionsPlayPages=\"false\" playOptionsPlayFrameActions=\"false\" autoSaveHasPrompted=\"true\""); domDocument.append(" backgroundColor=\"").append(backgroundColor).append("\""); domDocument.append(" frameRate=\"").append(swf.frameRate).append("\""); double width = twipToPixel(swf.displayRect.getWidth()); double height = twipToPixel(swf.displayRect.getHeight()); if (Double.compare(width, 550) != 0) { domDocument.append(" width=\"").append(doubleToString(width)).append("\""); } if (Double.compare(height, 400) != 0) { domDocument.append(" height=\"").append(doubleToString(height)).append("\""); } domDocument.append(">"); domDocument.append(convertFonts(swf.tags)); domDocument.append(convertLibrary(swf, characterVariables, characterClasses, nonLibraryShapes, backgroundColor, swf.tags, characters, files, datfiles, flaVersion)); domDocument.append("<timelines>"); domDocument.append(convertTimeline(0, nonLibraryShapes, backgroundColor, swf.tags, swf.tags, characters, "Scene 1", flaVersion, files)); domDocument.append("</timelines>"); domDocument.append("</DOMDocument>"); String domDocumentStr = prettyFormatXML(domDocument.toString()); for (Tag t : swf.tags) { if (t instanceof DoInitActionTag) { DoInitActionTag dia = (DoInitActionTag) t; int chid = dia.getCharacterId(); if (characters.containsKey(chid)) { if (characters.get(chid) instanceof DefineSpriteTag) { DefineSpriteTag sprite = (DefineSpriteTag) characters.get(chid); if (sprite.subTags.isEmpty()) { String data = convertActionScript(dia); String expPath = dia.getExportName(); final String prefix = "__Packages."; if (expPath.startsWith(prefix)) { expPath = expPath.substring(prefix.length()); } String expDir = ""; if (expPath.contains(".")) { expDir = expPath.substring(0, expPath.lastIndexOf('.')); expDir = expDir.replace(".", File.separator); } expPath = expPath.replace(".", File.separator); File cdir = new File(outDir.getAbsolutePath() + File.separator + expDir); if (!cdir.exists()) { if (!cdir.mkdirs()) { if (!cdir.exists()) { throw new IOException("cannot create directory " + cdir); } } } writeFile(handler, Utf8Helper.getBytes(data), outDir.getAbsolutePath() + File.separator + expPath + ".as"); } } } } } int flaSwfVersion = swf.version > flaVersion.maxSwfVersion() ? flaVersion.maxSwfVersion() : swf.version; boolean greaterThanCC = flaVersion.ordinal() >= FLAVersion.CC.ordinal(); StringBuilder publishSettings = new StringBuilder(); publishSettings.append("<flash_profiles>\n"); publishSettings.append("<flash_profile version=\"1.0\" name=\"Default\" current=\"true\">\n"); publishSettings.append(" <PublishFormatProperties enabled=\"true\">\n"); publishSettings.append(" <defaultNames>1</defaultNames>\n"); publishSettings.append(" <flash>1</flash>\n"); publishSettings.append(" <projectorWin>0</projectorWin>\n"); publishSettings.append(" <projectorMac>0</projectorMac>\n"); publishSettings.append(" <html>1</html>\n"); publishSettings.append(" <gif>0</gif>\n"); publishSettings.append(" <jpeg>0</jpeg>\n"); publishSettings.append(" <png>0</png>\n"); publishSettings.append(greaterThanCC ? " <svg>0</svg>\n" : " <qt>0</qt>\n"); publishSettings.append(" <rnwk>0</rnwk>\n"); publishSettings.append(" <swc>0</swc>\n"); publishSettings.append(" <flashDefaultName>1</flashDefaultName>\n"); publishSettings.append(" <projectorWinDefaultName>1</projectorWinDefaultName>\n"); publishSettings.append(" <projectorMacDefaultName>1</projectorMacDefaultName>\n"); publishSettings.append(" <htmlDefaultName>1</htmlDefaultName>\n"); publishSettings.append(" <gifDefaultName>1</gifDefaultName>\n"); publishSettings.append(" <jpegDefaultName>1</jpegDefaultName>\n"); publishSettings.append(" <pngDefaultName>1</pngDefaultName>\n"); publishSettings.append(greaterThanCC ? " <svgDefaultName>1</svgDefaultName>\n" : " <qtDefaultName>1</qtDefaultName>\n"); publishSettings.append(" <rnwkDefaultName>1</rnwkDefaultName>\n"); publishSettings.append(" <swcDefaultName>1</swcDefaultName>\n"); publishSettings.append(" <flashFileName>").append(baseName).append(".swf</flashFileName>\n"); publishSettings.append(" <projectorWinFileName>").append(baseName).append(".exe</projectorWinFileName>\n"); publishSettings.append(" <projectorMacFileName>").append(baseName).append(".app</projectorMacFileName>\n"); publishSettings.append(" <htmlFileName>").append(baseName).append(".html</htmlFileName>\n"); publishSettings.append(" <gifFileName>").append(baseName).append(".gif</gifFileName>\n"); publishSettings.append(" <jpegFileName>").append(baseName).append(".jpg</jpegFileName>\n"); publishSettings.append(" <pngFileName>").append(baseName).append(".png</pngFileName>\n"); publishSettings.append(greaterThanCC ? " <svgFileName>1</svgFileName>\n" : " <qtFileName>1</qtFileName>\n"); publishSettings.append(" <rnwkFileName>").append(baseName).append(".smil</rnwkFileName>\n"); publishSettings.append(" <swcFileName>").append(baseName).append(".swc</swcFileName>\n"); publishSettings.append(" </PublishFormatProperties>\n"); publishSettings.append(" <PublishHtmlProperties enabled=\"true\">\n"); publishSettings.append(" <VersionDetectionIfAvailable>0</VersionDetectionIfAvailable>\n"); publishSettings.append(" <VersionInfo>12,0,0,0;11,2,0,0;11,1,0,0;10,3,0,0;10,2,153,0;10,1,52,0;9,0,124,0;8,0,24,0;7,0,14,0;6,0,79,0;5,0,58,0;4,0,32,0;3,0,8,0;2,0,1,12;1,0,0,1;</VersionInfo>\n"); publishSettings.append(" <UsingDefaultContentFilename>1</UsingDefaultContentFilename>\n"); publishSettings.append(" <UsingDefaultAlternateFilename>1</UsingDefaultAlternateFilename>\n"); publishSettings.append(" <ContentFilename>").append(baseName).append("_content.html</ContentFilename>\n"); publishSettings.append(" <AlternateFilename>").append(baseName).append("_alternate.html</AlternateFilename>\n"); publishSettings.append(" <UsingOwnAlternateFile>0</UsingOwnAlternateFile>\n"); publishSettings.append(" <OwnAlternateFilename></OwnAlternateFilename>\n"); publishSettings.append(" <Width>").append(width).append("</Width>\n"); publishSettings.append(" <Height>").append(height).append("</Height>\n"); publishSettings.append(" <Align>0</Align>\n"); publishSettings.append(" <Units>0</Units>\n"); publishSettings.append(" <Loop>1</Loop>\n"); publishSettings.append(" <StartPaused>0</StartPaused>\n"); publishSettings.append(" <Scale>0</Scale>\n"); publishSettings.append(" <HorizontalAlignment>1</HorizontalAlignment>\n"); publishSettings.append(" <VerticalAlignment>1</VerticalAlignment>\n"); publishSettings.append(" <Quality>4</Quality>\n"); publishSettings.append(" <DeblockingFilter>0</DeblockingFilter>\n"); publishSettings.append(" <WindowMode>0</WindowMode>\n"); publishSettings.append(" <DisplayMenu>1</DisplayMenu>\n"); publishSettings.append(" <DeviceFont>0</DeviceFont>\n"); publishSettings.append(" <TemplateFileName></TemplateFileName>\n"); publishSettings.append(" <showTagWarnMsg>1</showTagWarnMsg>\n"); publishSettings.append(" </PublishHtmlProperties>\n"); publishSettings.append(" <PublishFlashProperties enabled=\"true\">\n"); publishSettings.append(" <TopDown></TopDown>\n"); publishSettings.append(" <FireFox></FireFox>\n"); publishSettings.append(" <Report>0</Report>\n"); publishSettings.append(" <Protect>0</Protect>\n"); publishSettings.append(" <OmitTraceActions>0</OmitTraceActions>\n"); publishSettings.append(" <Quality>80</Quality>\n"); publishSettings.append(" <DeblockingFilter>0</DeblockingFilter>\n"); publishSettings.append(" <StreamFormat>0</StreamFormat>\n"); publishSettings.append(" <StreamCompress>7</StreamCompress>\n"); publishSettings.append(" <EventFormat>0</EventFormat>\n"); publishSettings.append(" <EventCompress>7</EventCompress>\n"); publishSettings.append(" <OverrideSounds>0</OverrideSounds>\n"); publishSettings.append(" <Version>").append(flaSwfVersion).append("</Version>\n"); publishSettings.append(" <ExternalPlayer>").append(FLAVersion.swfVersionToPlayer(flaSwfVersion)).append("</ExternalPlayer>\n"); publishSettings.append(" <ActionScriptVersion>").append(useAS3 ? "3" : "2").append("</ActionScriptVersion>\n"); publishSettings.append(" <PackageExportFrame>1</PackageExportFrame>\n"); publishSettings.append(" <PackagePaths></PackagePaths>\n"); publishSettings.append(" <AS3PackagePaths>.</AS3PackagePaths>\n"); publishSettings.append(" <AS3ConfigConst>CONFIG::FLASH_AUTHORING=&quot;true&quot;;</AS3ConfigConst>\n"); publishSettings.append(" <DebuggingPermitted>0</DebuggingPermitted>\n"); publishSettings.append(" <DebuggingPassword></DebuggingPassword>\n"); publishSettings.append(" <CompressMovie>").append(swf.compression == SWFCompression.NONE ? "0" : "1").append("</CompressMovie>\n"); publishSettings.append(" <CompressionType>").append(swf.compression == SWFCompression.LZMA ? "1" : "0").append("</CompressionType>\n"); publishSettings.append(" <InvisibleLayer>1</InvisibleLayer>\n"); publishSettings.append(" <DeviceSound>0</DeviceSound>\n"); publishSettings.append(" <StreamUse8kSampleRate>0</StreamUse8kSampleRate>\n"); publishSettings.append(" <EventUse8kSampleRate>0</EventUse8kSampleRate>\n"); publishSettings.append(" <UseNetwork>").append(useNetwork ? 1 : 0).append("</UseNetwork>\n"); publishSettings.append(" <DocumentClass>").append(xmlString(characterClasses.containsKey(0) ? characterClasses.get(0) : "")).append("</DocumentClass>\n"); publishSettings.append(" <AS3Strict>2</AS3Strict>\n"); publishSettings.append(" <AS3Coach>4</AS3Coach>\n"); publishSettings.append(" <AS3AutoDeclare>4096</AS3AutoDeclare>\n"); publishSettings.append(" <AS3Dialect>AS3</AS3Dialect>\n"); publishSettings.append(" <AS3ExportFrame>1</AS3ExportFrame>\n"); publishSettings.append(" <AS3Optimize>1</AS3Optimize>\n"); publishSettings.append(" <ExportSwc>0</ExportSwc>\n"); publishSettings.append(" <ScriptStuckDelay>15</ScriptStuckDelay>\n"); publishSettings.append(" <IncludeXMP>1</IncludeXMP>\n"); publishSettings.append(" <HardwareAcceleration>0</HardwareAcceleration>\n"); publishSettings.append(" <AS3Flags>4102</AS3Flags>\n"); publishSettings.append(" <DefaultLibraryLinkage>rsl</DefaultLibraryLinkage>\n"); publishSettings.append(" <RSLPreloaderMethod>wrap</RSLPreloaderMethod>\n"); publishSettings.append(" <RSLPreloaderSWF>$(AppConfig)/ActionScript 3.0/rsls/loader_animation.swf</RSLPreloaderSWF>\n"); if (greaterThanCC) { publishSettings.append(" <LibraryPath>\n"); publishSettings.append(" <library-path-entry>\n"); publishSettings.append(" <swc-path>$(AppConfig)/ActionScript 3.0/libs</swc-path>\n"); publishSettings.append(" <linkage>merge</linkage>\n"); publishSettings.append(" </library-path-entry>\n"); publishSettings.append(" <library-path-entry>\n"); publishSettings.append(" <swc-path>$(FlexSDK)/frameworks/libs/flex.swc</swc-path>\n"); publishSettings.append(" <linkage>merge</linkage>\n"); publishSettings.append(" <rsl-url>textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" </library-path-entry>\n"); publishSettings.append(" <library-path-entry>\n"); publishSettings.append(" <swc-path>$(FlexSDK)/frameworks/libs/core.swc</swc-path>\n"); publishSettings.append(" <linkage>merge</linkage>\n"); publishSettings.append(" <rsl-url>textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" </library-path-entry>\n"); publishSettings.append(" </LibraryPath>\n"); publishSettings.append(" <LibraryVersions>\n"); publishSettings.append(" </LibraryVersions> "); } else { publishSettings.append(" <LibraryPath>\n"); publishSettings.append(" <library-path-entry>\n"); publishSettings.append(" <swc-path>$(AppConfig)/ActionScript 3.0/libs</swc-path>\n"); publishSettings.append(" <linkage>merge</linkage>\n"); publishSettings.append(" </library-path-entry>\n"); publishSettings.append(" <library-path-entry>\n"); publishSettings.append(" <swc-path>$(AppConfig)/ActionScript 3.0/libs/11.0/textLayout.swc</swc-path>\n"); publishSettings.append(" <linkage usesDefault=\"true\">rsl</linkage>\n"); publishSettings.append(" <rsl-url>http://fpdownload.adobe.com/pub/swz/tlf/2.0.0.232/textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" <policy-file-url>http://fpdownload.adobe.com/pub/swz/crossdomain.xml</policy-file-url>\n"); publishSettings.append(" <rsl-url>textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" </library-path-entry>\n"); publishSettings.append(" </LibraryPath>\n"); publishSettings.append(" <LibraryVersions>\n"); publishSettings.append(" <library-version>\n"); publishSettings.append(" <swc-path>$(AppConfig)/ActionScript 3.0/libs/11.0/textLayout.swc</swc-path>\n"); publishSettings.append(" <feature name=\"tlfText\" majorVersion=\"2\" minorVersion=\"0\" build=\"232\"/>\n"); publishSettings.append(" <rsl-url>http://fpdownload.adobe.com/pub/swz/tlf/2.0.0.232/textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" <policy-file-url>http://fpdownload.adobe.com/pub/swz/crossdomain.xml</policy-file-url>\n"); publishSettings.append(" <rsl-url>textLayout_2.0.0.232.swz</rsl-url>\n"); publishSettings.append(" </library-version>\n"); publishSettings.append(" </LibraryVersions>\n"); } publishSettings.append(" </PublishFlashProperties>\n"); publishSettings.append(" <PublishJpegProperties enabled=\"true\">\n"); publishSettings.append(" <Width>").append(width).append("</Width>\n"); publishSettings.append(" <Height>").append(height).append("</Height>\n"); publishSettings.append(" <Progressive>0</Progressive>\n"); publishSettings.append(" <DPI>4718592</DPI>\n"); publishSettings.append(" <Size>0</Size>\n"); publishSettings.append(" <Quality>80</Quality>\n"); publishSettings.append(" <MatchMovieDim>1</MatchMovieDim>\n"); publishSettings.append(" </PublishJpegProperties>\n"); publishSettings.append(" <PublishRNWKProperties enabled=\"true\">\n"); publishSettings.append(" <exportFlash>1</exportFlash>\n"); publishSettings.append(" <flashBitRate>0</flashBitRate>\n"); publishSettings.append(" <exportAudio>1</exportAudio>\n"); publishSettings.append(" <audioFormat>0</audioFormat>\n"); publishSettings.append(" <singleRateAudio>0</singleRateAudio>\n"); publishSettings.append(" <realVideoRate>100000</realVideoRate>\n"); publishSettings.append(" <speed28K>1</speed28K>\n"); publishSettings.append(" <speed56K>1</speed56K>\n"); publishSettings.append(" <speedSingleISDN>0</speedSingleISDN>\n"); publishSettings.append(" <speedDualISDN>0</speedDualISDN>\n"); publishSettings.append(" <speedCorporateLAN>0</speedCorporateLAN>\n"); publishSettings.append(" <speed256K>0</speed256K>\n"); publishSettings.append(" <speed384K>0</speed384K>\n"); publishSettings.append(" <speed512K>0</speed512K>\n"); publishSettings.append(" <exportSMIL>1</exportSMIL>\n"); publishSettings.append(" </PublishRNWKProperties>\n"); publishSettings.append(" <PublishGifProperties enabled=\"true\">\n"); publishSettings.append(" <Width>").append(width).append("</Width>\n"); publishSettings.append(" <Height>").append(height).append("</Height>\n"); publishSettings.append(" <Animated>0</Animated>\n"); publishSettings.append(" <MatchMovieDim>1</MatchMovieDim>\n"); publishSettings.append(" <Loop>1</Loop>\n"); publishSettings.append(" <LoopCount></LoopCount>\n"); publishSettings.append(" <OptimizeColors>1</OptimizeColors>\n"); publishSettings.append(" <Interlace>0</Interlace>\n"); publishSettings.append(" <Smooth>1</Smooth>\n"); publishSettings.append(" <DitherSolids>0</DitherSolids>\n"); publishSettings.append(" <RemoveGradients>0</RemoveGradients>\n"); publishSettings.append(" <TransparentOption></TransparentOption>\n"); publishSettings.append(" <TransparentAlpha>128</TransparentAlpha>\n"); publishSettings.append(" <DitherOption></DitherOption>\n"); publishSettings.append(" <PaletteOption></PaletteOption>\n"); publishSettings.append(" <MaxColors>255</MaxColors>\n"); publishSettings.append(" <PaletteName></PaletteName>\n"); publishSettings.append(" </PublishGifProperties>\n"); publishSettings.append(" <PublishPNGProperties enabled=\"true\">\n"); publishSettings.append(" <Width>").append(width).append("</Width>\n"); publishSettings.append(" <Height>").append(height).append("</Height>\n"); publishSettings.append(" <OptimizeColors>1</OptimizeColors>\n"); publishSettings.append(" <Interlace>0</Interlace>\n"); publishSettings.append(" <Transparent>0</Transparent>\n"); publishSettings.append(" <Smooth>1</Smooth>\n"); publishSettings.append(" <DitherSolids>0</DitherSolids>\n"); publishSettings.append(" <RemoveGradients>0</RemoveGradients>\n"); publishSettings.append(" <MatchMovieDim>1</MatchMovieDim>\n"); publishSettings.append(" <DitherOption></DitherOption>\n"); publishSettings.append(" <FilterOption></FilterOption>\n"); publishSettings.append(" <PaletteOption></PaletteOption>\n"); publishSettings.append(" <BitDepth>24-bit with Alpha</BitDepth>\n"); publishSettings.append(" <MaxColors>255</MaxColors>\n"); publishSettings.append(" <PaletteName></PaletteName>\n"); publishSettings.append(" </PublishPNGProperties>\n"); if (!greaterThanCC) { publishSettings.append(" <PublishQTProperties enabled=\"true\">\n"); publishSettings.append(" <Width>").append(width).append("</Width>\n"); publishSettings.append(" <Height>").append(height).append("</Height>\n"); publishSettings.append(" <MatchMovieDim>1</MatchMovieDim>\n"); publishSettings.append(" <UseQTSoundCompression>0</UseQTSoundCompression>\n"); publishSettings.append(" <AlphaOption></AlphaOption>\n"); publishSettings.append(" <LayerOption></LayerOption>\n"); publishSettings.append(" <QTSndSettings>00000000</QTSndSettings>\n"); publishSettings.append(" <ControllerOption>0</ControllerOption>\n"); publishSettings.append(" <Looping>0</Looping>\n"); publishSettings.append(" <PausedAtStart>0</PausedAtStart>\n"); publishSettings.append(" <PlayEveryFrame>0</PlayEveryFrame>\n"); publishSettings.append(" <Flatten>1</Flatten>\n"); publishSettings.append(" </PublishQTProperties>\n"); } publishSettings.append("</flash_profile>\n"); publishSettings.append("</flash_profiles>"); String publishSettingsStr = publishSettings.toString(); if (compressed) { final String domDocumentF = domDocumentStr; final String publishSettingsF = publishSettingsStr; final String outfileF = outfile; new RetryTask(new RunnableIOEx() { @Override public void run() throws IOException { try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outfileF))) { out.putNextEntry(new ZipEntry("DOMDocument.xml")); out.write(Utf8Helper.getBytes(domDocumentF)); out.putNextEntry(new ZipEntry("PublishSettings.xml")); out.write(Utf8Helper.getBytes(publishSettingsF)); for (String fileName : files.keySet()) { out.putNextEntry(new ZipEntry("LIBRARY/" + fileName)); out.write(files.get(fileName)); } for (String fileName : datfiles.keySet()) { out.putNextEntry(new ZipEntry("bin/" + fileName)); out.write(datfiles.get(fileName)); } } } }, handler).run(); } else { if (!outDir.exists()) { if (!outDir.mkdirs()) { if (!outDir.exists()) { throw new IOException("cannot create directory " + outDir); } } } writeFile(handler, Utf8Helper.getBytes(domDocumentStr), outDir.getAbsolutePath() + File.separator + "DOMDocument.xml"); writeFile(handler, Utf8Helper.getBytes(publishSettingsStr), outDir.getAbsolutePath() + File.separator + "PublishSettings.xml"); File libraryDir = new File(outDir.getAbsolutePath() + File.separator + "LIBRARY"); libraryDir.mkdir(); File binDir = new File(outDir.getAbsolutePath() + File.separator + "bin"); binDir.mkdir(); for (String fileName : files.keySet()) { writeFile(handler, files.get(fileName), libraryDir.getAbsolutePath() + File.separator + fileName); } for (String fileName : datfiles.keySet()) { writeFile(handler, datfiles.get(fileName), binDir.getAbsolutePath() + File.separator + fileName); } writeFile(handler, Utf8Helper.getBytes("PROXY-CS5"), outfile); } if (useAS3) { try { swf.exportActionScript(handler, outDir.getAbsolutePath(), ScriptExportMode.AS, parallel); } catch (Exception ex) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, "Error during ActionScript3 export", ex); } } } private static int normHue(double h) { if (Double.isNaN(h)) { h = -Math.PI; } int ret = (int) Math.round(h * 180 / Math.PI); while (ret > 180) { ret -= 360; } while (ret < -180) { ret += 360; } return ret; } private static int normBrightness(double b) { if (Double.isNaN(b)) { b = -100; } return (int) Math.round(b); } private static int normSaturation(double s) { if (Double.isNaN(s)) { return -100; } else if (s == 1) { return 0; } else if (s - 1 < 0) { return (int) Math.round((s - 1) * 100); } else { return (int) Math.round(((s - 1) * 100) / 3); } } private static int normContrast(double c) { double[] ctrMap = { // 0 1 2 3 4 5 6 7 8 9 /*0*/0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11, /*1*/ 0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24, /*2*/ 0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42, /*3*/ 0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68, /*4*/ 0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98, /*5*/ 1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54, /*6*/ 1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25, /*7*/ 2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8, /*8*/ 4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0, /*9*/ 7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8, /*10*/ 10.0}; if (c == 127) { return 0; } else if (c - 127 < 0) { return (int) Math.round((c - 127) * 100.0 / 127.0); } else { c = (c - 127) / 127; for (int i = 0; i < ctrMap.length; i++) { if (ctrMap[i] >= c) { return i; } } } return ctrMap.length - 1; } private static boolean sameDouble(double a, double b) { final double EPSILON = 0.00001; return a == b ? true : Math.abs(a - b) < EPSILON; } public static String convertAdjustColorFilter(COLORMATRIXFILTER filter) { float[][] matrix = new float[5][5]; int index = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { matrix[j][i] = filter.matrix[index]; index++; } } double a11 = matrix[0][0], a12 = matrix[0][1], a13 = matrix[0][2], a21 = matrix[1][0], a22 = matrix[1][1], a23 = matrix[1][2], a31 = matrix[2][0], a32 = matrix[2][1], a33 = matrix[2][2], a41 = matrix[4][0]; double b, c, h, s; b = (24872168661075.0 * a11 * a11 - 151430415740925.0 * a12 + 341095051289483.0 * a12 * a12 - 15302094789450.0 * a13 + 82428663495404.0 * a12 * a13 - 4592294873812.0 * a13 * a13 + 43556251470.0 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13)) + 2384730956550.0 * a12 * a41 + 240977870700.0 * a13 * a41 - 685925220 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13)) * a41 + 465 * a11 * (466201717582.0 * a12 + 55756962908.0 * a13 + 764132175 * (-127 + 2 * a41))) / (391687695450.0 * a11 * a11 + 5371575610858.0 * a12 * a12 + 1298089188904.0 * a12 * a13 - 72319604312.0 * a13 * a13 + 1860 * a11 * (1835439833 * a12 + 219515602 * a13)); c = (127 * (495225 * a11 + 1661845 * a12 + 167930 * a13 + 478 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13)))) / 717495; h = 2 * (Math.atan((-465 * a11 + 287 * a12 + 178 * a13 + Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13))) / (500. * (a12 - a13))) + Math.PI/*+ Pi*C(1)*/); s = (1543 * (-103355550 * a11 * a11 - 158872382 * a12 * a12 + 190161784 * a12 * a13 - 134644952 * a13 * a13 + 1661845 * a12 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13)) + 167930 * a13 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13)) + 465 * a11 * (274372 * a12 + 170168 * a13 + 1065 * Math.sqrt(216225 * a11 * a11 + 332369 * a12 * a12 - 397828 * a12 * a13 + 281684 * a13 * a13 - 930 * a11 * (287 * a12 + 178 * a13))))) / (195843847725.0 * a11 * a11 + 2685787805429.0 * a12 * a12 + 649044594452.0 * a12 * a13 - 36159802156.0 * a13 * a13 + 930 * a11 * (1835439833 * a12 + 219515602 * a13)); if (sameDouble(410 * a12, 1543 * a31) && sameDouble(410 * a12, 1543 * a32) && sameDouble(3047 * a12, 1543 * a21) && sameDouble(3047 * a12, 1543 * a23) && sameDouble(a22, a11 + (1504 * a12) / 1543.) && sameDouble((1133 * a12) / 1543. + a33, a11) /*&& (b == (195961 * a11 + 439039 * a12 + 1543 * (-127 + 2 * a41)) / (3086 * a11 + 6914 * a12)) && (c == 127 * a11 + (439039 * a12) / 1543.) && (s == (1543 * (a11 - a12)) / (1543 * a11 + 3457 * a12)) */ && !sameDouble(a11, a12) && !sameDouble(1543 * a11 + 3457 * a12, 0)) { h = 0; } return "<AdjustColorFilter brightness=\"" + normBrightness(b) + "\" contrast=\"" + normContrast(c) + "\" saturation=\"" + normSaturation(s) + "\" hue=\"" + normHue(h) + "\"/>"; } private static String convertHTMLText(List<Tag> tags, DefineEditTextTag det, String html) { HTMLTextParser tparser = new HTMLTextParser(tags, det); XMLReader parser; try { SAXParserFactory factory = SAXParserFactory.newInstance(); parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(tparser); parser.setErrorHandler(tparser); html = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE some_name [ \n" + "<!ENTITY nbsp \"&#160;\"> \n" + "]><html>" + html + "</html>"; try { parser.parse(new InputSource(new StringReader(html))); } catch (SAXParseException spe) { System.out.println(html); System.err.println(tparser.result); } } catch (SAXException | IOException e) { Logger.getLogger(XFLConverter.class.getName()).log(Level.SEVERE, "Error while converting HTML", e); } return tparser.result; } private static String xmlString(String s) { return s.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("&", "&amp;").replace("\r\n", "&#xD;").replace("\r", "&#xD;").replace("\n", "&#xD;"); } private static double twipToPixel(double tw) { return tw / SWF.unitDivisor; } private static class HTMLTextParser extends DefaultHandler { public String result = ""; private String fontFace = ""; private String color = ""; private int size = -1; private int indent = -1; private int leftMargin = -1; private int rightMargin = -1; private int lineSpacing = -1; private double letterSpacing = -1; private String alignment = null; private final List<Tag> tags; private boolean bold = false; private boolean italic = false; private boolean underline = false; private boolean li = false; private String url = null; private String target = null; @Override public void error(SAXParseException e) throws SAXException { } @Override public void fatalError(SAXParseException e) throws SAXException { } @Override public void warning(SAXParseException e) throws SAXException { } public HTMLTextParser(List<Tag> tags, DefineEditTextTag det) { if (det.hasFont) { String fontName = null; FontTag ft = null; for (Tag u : tags) { if (u instanceof DefineFontNameTag) { if (((DefineFontNameTag) u).fontId == det.fontId) { fontName = ((DefineFontNameTag) u).fontName; } } if (u instanceof FontTag) { if (((FontTag) u).getFontId() == det.fontId) { ft = (FontTag) u; } } if (fontName != null && ft != null) { break; } } if (ft != null) { if (fontName == null) { fontName = ft.getFontNameIntag(); } italic = ft.isItalic(); bold = ft.isBold(); size = det.fontHeight; fontFace = new Font(fontName, (italic ? Font.ITALIC : 0) | (bold ? Font.BOLD : 0) | (!italic && !bold ? Font.PLAIN : 0), size < 0 ? 10 : size).getPSName(); } } if (det.hasLayout) { leftMargin = det.leftMargin; rightMargin = det.rightMargin; indent = det.indent; lineSpacing = det.leading; String[] alignNames = {"left", "right", "center", "justify"}; if (det.align < alignNames.length) { alignment = alignNames[det.align]; } else { alignment = "unknown"; } } this.tags = tags; } @Override public void startDocument() throws SAXException { } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch (qName) { case "a": String href = attributes.getValue("href"); if (href != null) { url = href; } String t = attributes.getValue("target"); if (t != null) { target = t; } break; case "b": bold = true; break; case "i": italic = true; break; case "u": underline = true; break; case "li": li = true; break; case "p": String a = attributes.getValue("align"); if (a != null) { alignment = a; } if (!result.isEmpty()) { putText("\r\n"); } break; case "font": //kerning ? String ls = attributes.getValue("letterSpacing"); if (ls != null) { letterSpacing = Double.parseDouble(ls); } String s = attributes.getValue("size"); if (s != null) { size = Integer.parseInt(s); } String c = attributes.getValue("color"); if (c != null) { color = c; } String f = attributes.getValue("face"); if (f != null) { for (Tag tag : tags) { if (tag instanceof FontTag) { FontTag ft = (FontTag) tag; String fontName = null; if (f.equals(ft.getFontNameIntag())) { for (Tag u : tags) { if (u instanceof DefineFontNameTag) { if (((DefineFontNameTag) u).fontId == ft.getFontId()) { fontName = ((DefineFontNameTag) u).fontName; } } } if (fontName == null) { fontName = ft.getFontNameIntag(); } String installedFont; if ((installedFont = FontTag.isFontFamilyInstalled(fontName)) != null) { fontFace = new Font(installedFont, (italic ? Font.ITALIC : 0) | (bold ? Font.BOLD : 0) | (!italic && !bold ? Font.PLAIN : 0), size < 0 ? 10 : size).getPSName(); } else { fontFace = fontName; } break; } } } } break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("a")) { url = null; target = null; } if (qName.equals("b")) { bold = false; } if (qName.equals("i")) { italic = false; } if (qName.equals("u")) { underline = false; } if (qName.equals("li")) { li = false; } } private void putText(String txt) { result += "<DOMTextRun>"; result += "<characters>" + xmlString(txt) + "</characters>"; result += "<textAttrs>"; result += "<DOMTextAttrs"; if (alignment != null) { result += " alignment=\"" + alignment + "\""; } result += " rotation=\"true\""; //? if (indent > -1) { result += " indent=\"" + twipToPixel(indent) + "\""; } if (leftMargin > -1) { result += " leftMargin=\"" + twipToPixel(leftMargin) + "\""; } if (letterSpacing > -1) { result += " letterSpacing=\"" + letterSpacing + "\""; } if (lineSpacing > -1) { result += " lineSpacing=\"" + twipToPixel(lineSpacing) + "\""; } if (rightMargin > -1) { result += " rightMargin=\"" + twipToPixel(rightMargin) + "\""; } if (size > -1) { result += " size=\"" + size + "\""; result += " bitmapSize=\"" + (size * 20) + "\""; } if (fontFace != null) { result += " face=\"" + fontFace + "\""; } if (color != null) { result += " fillColor=\"" + color + "\""; } if (url != null) { result += " url=\"" + url + "\""; } if (target != null) { result += " target=\"" + target + "\""; } result += "/>"; result += "</textAttrs>"; result += "</DOMTextRun>"; } @Override public void characters(char[] ch, int start, int length) throws SAXException { putText(new String(ch, start, length)); } @Override public void endDocument() { if (this.result.isEmpty()) { putText(""); } } } }
realmaster42/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/xfl/XFLConverter.java
Java
gpl-3.0
170,715
/** * barsuift-simlife is a life simulator program * * Copyright (C) 2010 Cyrille GACHOT * * This file is part of barsuift-simlife. * * barsuift-simlife is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * barsuift-simlife is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with barsuift-simlife. If not, see * <http://www.gnu.org/licenses/>. */ package barsuift.simLife.environment; import org.testng.annotations.Test; import barsuift.simLife.CoreDataCreatorForTests; import barsuift.simLife.j3d.environment.Sun3D; import barsuift.simLife.universe.MockUniverse; import static org.fest.assertions.Assertions.assertThat; public class BasicSkyTest { @Test public void testGetState() { SkyState state = CoreDataCreatorForTests.createRandomSkyState(); BasicSky sky = new BasicSky(state); sky.init(new MockUniverse()); assertThat(sky.getState()).isEqualTo(state); assertThat(sky.getState()).isSameAs(state); Sun3D sun3D = sky.getSun().getSun3D(); assertThat(sun3D.getEarthRevolution()).isEqualTo(state.getSunState().getSun3DState().getEarthRevolution()); sun3D.setEarthRevolution(sun3D.getEarthRevolution() / 2); assertThat(sky.getState()).isEqualTo(state); assertThat(sky.getState()).isSameAs(state); assertThat(sun3D.getEarthRevolution()).isEqualTo(state.getSunState().getSun3DState().getEarthRevolution()); } }
sdp0et/barsuift-simlife
simLifeCore/src/test/java/barsuift/simLife/environment/BasicSkyTest.java
Java
gpl-3.0
1,920
/* * Navigation bar function expansion module * Copyright (C) 2017 egguncle [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.egguncle.xposednavigationbar; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.Log; import com.egguncle.xposednavigationbar.util.SPUtil; import org.litepal.LitePalApplication; import java.util.Locale; /** * Created by egguncle on 17-6-16. */ public class MyApplication extends LitePalApplication { private static Context mContext; @Override public void onCreate() { super.onCreate(); Resources resources = getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); Configuration config = resources.getConfiguration(); // 应用用户选择语言 String language = SPUtil.getInstance(this).getLanguage(); if ("".equals(language)){ language =Locale.getDefault().getLanguage(); } if (language.equals(SPUtil.LANGUAGE_CHINESE)) { config.setLocale(Locale.getDefault()); } else { config.setLocale(Locale.ENGLISH); } resources.updateConfiguration(config, dm); mContext=getApplicationContext(); } public static Context getContext(){ return mContext; } }
EggUncle/XposedNavigationBar
app/src/main/java/com/egguncle/xposednavigationbar/MyApplication.java
Java
gpl-3.0
2,071
package com.beimin.eveapi.eve.character; import com.beimin.eveapi.core.AbstractApiParser; import com.beimin.eveapi.core.AbstractContentHandler; import com.beimin.eveapi.core.ApiAuth; import com.beimin.eveapi.core.ApiPage; import com.beimin.eveapi.core.ApiPath; import com.beimin.eveapi.exception.ApiException; public class CharacterInfoParser extends AbstractApiParser<CharacterInfoResponse> { public CharacterInfoParser() { super(CharacterInfoResponse.class, 2, ApiPath.EVE, ApiPage.CHARACTER_INFO); } @Override protected AbstractContentHandler getContentHandler() { return new CharacterInfoHandler(); } public static CharacterInfoParser getInstance() { return new CharacterInfoParser(); } public CharacterInfoResponse getResponse(long characterID) throws ApiException { return super.getResponse("characterID", Long.toString(characterID)); } @Override public CharacterInfoResponse getResponse(ApiAuth<?> auth) throws ApiException { return super.getResponse(auth); } }
Claudweb/EveTool
EveApi/eveapi-5.1.3-sources/com/beimin/eveapi/eve/character/CharacterInfoParser.java
Java
gpl-3.0
996
/* * License Agreement for OpenSearchServer * <p> * Copyright (C) 2010-2017 Emmanuel Keller / Jaeksoft * <p> * http://www.open-search-server.com * <p> * This file is part of OpenSearchServer. * <p> * OpenSearchServer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * OpenSearchServer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with OpenSearchServer. If not, see <http://www.gnu.org/licenses/>. */ package com.jaeksoft.searchlib.web.controller.crawler.web; import com.jaeksoft.searchlib.SearchLibException; import com.jaeksoft.searchlib.crawler.web.database.HostUrlList.ListType; import com.jaeksoft.searchlib.crawler.web.process.WebCrawlThread; import com.jaeksoft.searchlib.crawler.web.spider.DownloadItem; import com.jaeksoft.searchlib.function.expression.SyntaxError; import com.jaeksoft.searchlib.query.ParseException; import com.jaeksoft.searchlib.util.LinkUtils; import com.jaeksoft.searchlib.web.controller.AlertController; import com.jaeksoft.searchlib.web.controller.CommonController; import com.jaeksoft.searchlib.webservice.crawler.webcrawler.WebCrawlerImpl; import org.json.JSONException; import org.zkoss.bind.annotation.AfterCompose; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zk.ui.event.InputEvent; import org.zkoss.zul.Filedownload; import org.zkoss.zul.Messagebox; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; @AfterCompose(superclass = true) public class ManualWebCrawlController extends CommonController { private transient String url; private transient WebCrawlThread currentCrawlThread; public ManualWebCrawlController() throws SearchLibException { super(); } @Override protected void reset() { url = null; currentCrawlThread = null; } /** * @param url the url to set */ @NotifyChange("*") public void setUrl(String url) { this.url = url; } @Command @NotifyChange({ "crawlJsonApi", "crawlXmlApi" }) public void onChanging(@ContextParam(ContextType.TRIGGER_EVENT) InputEvent event) throws SearchLibException { setUrl(event.getValue()); } /** * @return the url */ public String getUrl() { return url; } public WebCrawlThread getCrawlThread() { synchronized (this) { return currentCrawlThread; } } private boolean checkNotRunning() throws InterruptedException { if (!isCrawlRunning()) return true; new AlertController("A crawl is already running", Messagebox.ERROR); return false; } private boolean checkCrawlCacheEnabled() throws InterruptedException, SearchLibException { if (isCrawlCache()) return true; new AlertController("The crawl cache is disabled", Messagebox.ERROR); return false; } @Command public void onCrawl() throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { synchronized (this) { if (!checkNotRunning()) return; currentCrawlThread = getClient().getWebCrawlMaster().manualCrawl(LinkUtils.newEncodedURL(url), ListType.MANUAL); currentCrawlThread.waitForStart(60); reload(); } } @Command public void onFlushCache() throws SearchLibException, MalformedURLException, IOException, URISyntaxException, InterruptedException { synchronized (this) { if (!checkNotRunning()) return; if (!checkCrawlCacheEnabled()) return; boolean deleted = getClient().getCrawlCacheManager().getItem(LinkUtils.newEncodedURI(url)).flush(); new AlertController(deleted ? "Content deleted" : "Nothing to delete", Messagebox.INFORMATION); } } @Command public void onDownload() throws IOException, InterruptedException, SearchLibException, URISyntaxException, JSONException { synchronized (this) { if (!checkNotRunning()) return; if (!checkCrawlCacheEnabled()) return; DownloadItem downloadItem = getClient().getCrawlCacheManager().getItem(LinkUtils.newEncodedURI(url)).load(); if (downloadItem == null) { new AlertController("No content", Messagebox.EXCLAMATION); return; } Filedownload.save(downloadItem.getContentInputStream(), downloadItem.getContentBaseType(), "crawl.cache"); } } public boolean isCrawlComplete() { synchronized (this) { if (currentCrawlThread == null) return false; if (currentCrawlThread.isRunning()) return false; return true; } } public boolean isCrawlCache() throws SearchLibException { synchronized (this) { return getClient().getCrawlCacheManager().isEnabled(); } } @Command public void onTimer() throws SearchLibException { reload(); } public boolean isCrawlRunning() { synchronized (this) { if (currentCrawlThread == null) return false; return currentCrawlThread.isRunning(); } } public boolean isRefresh() { return isCrawlRunning(); } public String getCrawlXmlApi() throws UnsupportedEncodingException, SearchLibException { return WebCrawlerImpl.getCrawlXML(getLoggedUser(), getClient(), getUrl()); } public String getCrawlJsonApi() throws UnsupportedEncodingException, SearchLibException { return WebCrawlerImpl.getCrawlJSON(getLoggedUser(), getClient(), getUrl()); } }
emmanuel-keller/opensearchserver
src/main/java/com/jaeksoft/searchlib/web/controller/crawler/web/ManualWebCrawlController.java
Java
gpl-3.0
5,841
package com.eliaswalyba.m1sir.tutorials.practice1.exercise3; public class ValidHarmonicDegreException extends Exception { public ValidHarmonicDegreException() { System.out.print("Error: a harmonic series degree can't be less than 1"); } public ValidHarmonicDegreException(String errorMessage) { System.out.print(errorMessage); } }
eliaswalyba/java-training-m1sir
src/com/eliaswalyba/m1sir/tutorials/practice1/exercise3/ValidHarmonicDegreException.java
Java
gpl-3.0
364
package slimeknights.tconstruct.shared.worldgen; import net.minecraft.block.state.pattern.BlockMatcher; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.WorldProviderHell; import net.minecraft.world.chunk.IChunkGenerator; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random; import slimeknights.tconstruct.common.config.Config; import slimeknights.tconstruct.shared.TinkerCommons; import slimeknights.tconstruct.shared.block.BlockOre; public class NetherOreGenerator implements IWorldGenerator { public static NetherOreGenerator INSTANCE = new NetherOreGenerator(); public WorldGenMinable cobaltGen; public WorldGenMinable arditeGen; public NetherOreGenerator() { cobaltGen = new WorldGenMinable(TinkerCommons.blockOre.getStateFromMeta(BlockOre.OreTypes.COBALT.getMeta()), 5, BlockMatcher.forBlock(Blocks.NETHERRACK)); arditeGen = new WorldGenMinable(TinkerCommons.blockOre.getStateFromMeta(BlockOre.OreTypes.ARDITE.getMeta()), 5, BlockMatcher.forBlock(Blocks.NETHERRACK)); } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { if(world.provider instanceof WorldProviderHell) { if(Config.genArdite) { generateNetherOre(arditeGen, Config.arditeRate, random, chunkX, chunkZ, world); } if(Config.genCobalt) { generateNetherOre(cobaltGen, Config.cobaltRate, random, chunkX, chunkZ, world); } } } public void generateNetherOre(WorldGenMinable gen, int rate, Random random, int chunkX, int chunkZ, World world) { BlockPos pos; for(int i = 0; i < rate; i += 2) { pos = new BlockPos(chunkX * 16, 32, chunkZ * 16); pos = pos.add(random.nextInt(16), random.nextInt(64), random.nextInt(16)); gen.generate(world, random, pos); pos = new BlockPos(chunkX * 16, 0, chunkZ * 16); pos = pos.add(random.nextInt(16), random.nextInt(128), random.nextInt(16)); gen.generate(world, random, pos); } } }
VosDerrick/Volsteria
src/main/java/slimeknights/tconstruct/shared/worldgen/NetherOreGenerator.java
Java
gpl-3.0
2,372
/* * Copyright (C) 2009-2011 RtcNbClient Team (http://rtcnbclient.wmi.amu.edu.pl/) * * This file is part of RtcNbClient. * * RtcNbClient is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RtcNbClient is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RtcNbClient. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.amu.wmi.kino.netbeans.view.customview.impl.table; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import org.openide.nodes.Node; /** * * @author Patryk Żywica */ public class CustomViewTableModel implements TableModel { private CustomViewNodeGroup rootGroup; private Set<TableModelListener> listeners = Collections.synchronizedSet(new HashSet<TableModelListener>(5)); private Object modelUpdateLock=new Object(); public CustomViewTableModel(Node rootNode) { rootGroup = new CustomViewNodeGroup(new CustomViewRootNodeGroupParent(rootNode), rootNode,modelUpdateLock); } @Override public int getRowCount() { return rootGroup.getGroupSize(); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int columnIndex) { return "CustomViewMainColumn"; } @Override public Class<?> getColumnClass(int columnIndex) { return CustomViewNodeGroup.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } @Override public CustomViewNodeGroup getValueAt(int rowIndex, int columnIndex) { return rootGroup.getNodeAt(rowIndex); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { // } @Override public void addTableModelListener(TableModelListener l) { listeners.add(l); } @Override public void removeTableModelListener(TableModelListener l) { listeners.remove(l); } protected void fireEvent() { synchronized (listeners) { TableModelEvent e = new TableModelEvent(this); for (TableModelListener l : listeners) { l.tableChanged(e); } } } /** * this class is used to obtain set modified event from root group */ class CustomViewRootNodeGroupParent extends CustomViewNodeGroup { public CustomViewRootNodeGroupParent(Node rootNode) { super(null, rootNode, modelUpdateLock); } @Override protected void setModified() { super.setModified(); fireEvent(); } } }
RtcNbClient/RtcNbClient
KinoNbUtilities/src/main/java/pl/edu/amu/wmi/kino/netbeans/view/customview/impl/table/CustomViewTableModel.java
Java
gpl-3.0
3,186
package com.example.planefight3d; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; public class ExplodeManager { public static ArrayList<Explode> explode_list=new ArrayList<Explode>(); public static void drawself(GL10 gl) { for(int i=0;i<explode_list.size();i++) { gl.glPushMatrix(); Explode tmp=explode_list.get(i); tmp.drawself(gl); gl.glPopMatrix(); } } }
xc-fighting/word-plane-project
src/com/example/planefight3d/ExplodeManager.java
Java
gpl-3.0
439
package Transport.aspects.interfaces; import Values.physicsValues.interfaces.Length; public interface WithPosition { // SELECTORS public Length pos(); }
MesutKoc/uni-haw
2. Semester/PR2/Aufgabe_3_Igor/src/Transport/aspects/interfaces/WithPosition.java
Java
gpl-3.0
162
/* * Pixel Dungeon: Rebalanced * Copyright (C) 2012-2015 Oleg Dolya * Copyright (C) 2015 Peter Cassetta * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.petercassetta.pdrebalanced.actors.mobs.npcs; import java.util.HashSet; import com.petercassetta.pdrebalanced.Dungeon; import com.petercassetta.pdrebalanced.actors.Char; import com.petercassetta.pdrebalanced.actors.buffs.Poison; import com.petercassetta.pdrebalanced.actors.mobs.Mob; import com.petercassetta.pdrebalanced.levels.Level; import com.petercassetta.pdrebalanced.sprites.BeeSprite; import com.petercassetta.pdrebalanced.utils.Utils; import com.petercassetta.utils.Bundle; import com.petercassetta.utils.Random; public class Bee extends NPC { { name = "golden bee"; spriteClass = BeeSprite.class; viewDistance = 4; WANDERING = new Wandering(); flying = true; state = WANDERING; } private int level; private static final String LEVEL = "level"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( LEVEL, level ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); spawn( bundle.getInt( LEVEL ) ); } public void spawn( int level ) { this.level = level; HT = (3 + level) * 5; defenseSkill = 9 + level; } @Override public int attackSkill( Char target ) { return defenseSkill; } @Override public int damageRoll() { return Random.NormalIntRange( HT / 10, HT / 4 ); } @Override public int attackProc( Char enemy, int damage ) { if (enemy instanceof Mob) { ((Mob)enemy).aggro( this ); } return damage; } @Override protected boolean act() { HP--; if (HP <= 0) { die( null ); return true; } else { return super.act(); } } protected Char chooseEnemy() { if (enemy == null || !enemy.isAlive()) { HashSet<Mob> enemies = new HashSet<Mob>(); for (Mob mob:Dungeon.level.mobs) { if (mob.hostile && Level.fieldOfView[mob.pos]) { enemies.add( mob ); } } return enemies.size() > 0 ? Random.element( enemies ) : null; } else { return enemy; } } @Override public String description() { return "Despite their small size, golden bees tend " + "to protect their master fiercely. They don't live long though."; } @Override public void interact() { int curPos = pos; moveSprite( pos, Dungeon.hero.pos ); move( Dungeon.hero.pos ); Dungeon.hero.sprite.move( Dungeon.hero.pos, curPos ); Dungeon.hero.move( curPos ); Dungeon.hero.spend( 1 / Dungeon.hero.speed() ); Dungeon.hero.busy(); } private static final HashSet<Class<?>> IMMUNITIES = new HashSet<Class<?>>(); static { IMMUNITIES.add( Poison.class ); } @Override public HashSet<Class<?>> immunities() { return IMMUNITIES; } private class Wandering implements AiState { @Override public boolean act( boolean enemyInFOV, boolean justAlerted ) { if (enemyInFOV) { enemySeen = true; notice(); state = HUNTING; target = enemy.pos; } else { enemySeen = false; int oldPos = pos; if (getCloser( Dungeon.hero.pos )) { spend( 1 / speed() ); return moveSprite( oldPos, pos ); } else { spend( TICK ); } } return true; } @Override public String status() { return Utils.format( "This %s is wandering", name ); } } }
PeterCassetta/pixel-dungeon-rebalanced
java/com/petercassetta/pdrebalanced/actors/mobs/npcs/Bee.java
Java
gpl-3.0
4,040
/* * Created by Khanh Tran on 10/9/16. */ import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import static java.lang.Math.toIntExact; import static java.lang.Thread.sleep; @SuppressWarnings({"unchecked", "InfiniteLoopStatement"}) class serverStart implements Runnable { static private String appKey, PASS, Authorization; private Connection conn; private DataOutputStream out; private String sql; private PreparedStatement ps; private ResultSet rs; private JSONObject obj; serverStart(JSONObject pobj, DataOutputStream pout, String key, String pass, String auth) { obj = pobj; out = pout; appKey = key; PASS = pass; Authorization = auth; } public void run() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/Butterfly", "root", PASS); conn.getMetaData().getCatalogs(); conn.createStatement(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } switch ((String) obj.get("function")) { case "addCommunity": addCommunity(obj); break; case "addCommunityUser": addCommunityUser(obj); break; case "addCrew": addCrew(obj); break; case "addEvent": addEvent(obj); break; case "addHangout": addHangout(obj); break; case "addHangoutUser": addHangoutUser(obj); break; case "addMessage": addMessage(obj); break; case "addUser": addUser(obj); break; case "communityInvite": communityInvite(obj); break; case "communitySearch": communitySearch((String) obj.get("type"), (String) obj.get("value")); break; case "checkIn": checkIn(obj); break; case "checkInCheck": checkInCheck(obj); break; case "deleteEvent": deleteEvent(obj); break; case "editEvent": editEvent(obj); break; case "editHangout": editHangout(obj); break; case "emailInvite": emailInvite("user", (String) obj.get("to")); break; case "getCheckIns": getCheckIns(obj); break; case "getCommunities": getCommunities(); break; case "getCommunityUsers": getCommunityUsers((String) obj.get("communityName")); break; case "getCommunityUsersWithID": getCommunityUsersWithID((String) obj.get("communityName")); break; case "getCrewUsers": getCrewUsers((String) obj.get("communityName"), (long) obj.get("idCrew")); break; case "getCrewMessages": getCrewMessages(obj); break; case "getEvents": getEvents((String) obj.get("communityName")); break; case "getHangouts": getHangouts((String) obj.get("communityName")); break; case "getMessages": getMessages((String) obj.get("communityName")); break; case "getNeighborhoodEvents": getNeighborhoodEvents(); break; case "getrsvp": getrsvp((String) obj.get("communityName"), (String) obj.get("eventName")); break; case "getUserCommunities": getUserCommunities((String) obj.get("googleID")); break; case "getUserCommunityEvents": getUserCommunityEvents((String) obj.get("googleID")); break; case "getUserCrews": getUserCrews((String) obj.get("communityName"), (String) obj.get("googleID")); break; case "getUserHangouts": getUserHangouts((String) obj.get("googleID")); break; case "getUserName": getUserName((String) obj.get("googleID")); break; case "getUserModerator": getUserModerator((String) obj.get("googleID")); break; case "getUserProfile": getUserProfile((String) obj.get("googleID")); break; case "groupNotification": groupNotification(obj); break; case "inviteNotification": inviteNotification(obj); break; case "isPrivate": isPrivate((String) obj.get("communityName")); break; case "leaveCommunityUser": case "removeCommunityUser": leaveCommunityUser(obj); break; case "leaveHangoutUser": leaveHangoutUser(obj); break; case "removeAllCommunities": removeAllCommunities(); break; case "removeCommunity": removeCommunity((String) obj.get("communityName")); break; case "removeCheckIn": removeCheckIn(obj); break; case "rsvpEvent": rsvpEvent(obj); break; case "rsvpCheck": rsvpCheck(obj); break; case "rsvpEventRemove": rsvpEventRemove(obj); break; case "updateInstanceID": updateInstanceID(obj); break; case "updateUserProfile": updateUserProfile(obj); break; case "wipe": wipe(); break; default: System.out.println("NO FUNCTION FOUND " + obj.toString()); } } /* Function which adds a new user created community into the database, inserts the new community into the Communities table and creates four new tables. Function calls createCommunityBoardTable, createCommunityEventTable, createCommunityUserTable, and createHCommunityHangouts. */ private void addCommunity(JSONObject obj) { String neighborhoodID = "purdue"; String name = (String) obj.get("name"); try { sql = "SELECT count(*) from Communities WHERE name = ?"; ps = conn.prepareStatement(sql); ps.setString(1, name); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 0) { sql = "INSERT INTO Communities (neighborhoodID, category, subcategory, name, " + "description, numMembers, numUpcomingEvents, dateCreated, private) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, neighborhoodID); ps.setString(2, (String) obj.get("category")); ps.setString(3, (String) obj.get("subCategory")); ps.setString(4, name); ps.setString(5, (String) obj.get("description")); ps.setString(6, "1"); ps.setString(7, "0"); ps.setString(8, (String) obj.get("dateCreated")); ps.setString(9, (String) obj.get("private")); System.out.println(ps); ps.executeUpdate(); name = name.replaceAll("\\s", "_"); createCommunityUsersTable(name); createCommunityBoardTable(name); createCommunityCrewsTable(name); createCommunityEventsTable(name); createCommunityHangoutsTable(name); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which adds a new user into the specified community users table if they are not already there. Updates the communitiesList of the user in Users table and if the new user is a moderator, update the moderatorOf list in the Users table. */ private void addCommunityUser(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Users"; String googleID = (String) obj.get("googleID"); try { sql = "SELECT count(*) FROM " + communityName + " WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 0) { sql = "INSERT INTO " + communityName + " (googleID) VALUES (?)"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); ps.executeUpdate(); sql = "UPDATE " + communityName + " SET isLeader = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("isLeader")); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); if (Integer.parseInt((String) obj.get("isLeader")) == 1) { sql = "UPDATE Users SET moderatorOf = " + "CONCAT(?, moderatorOf) WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, obj.get("communityName") + ", "); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } sql = "UPDATE Users SET communitiesList = " + "CONCAT(?, communitiesList) WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, obj.get("communityName") + ", "); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void addCrew(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); String list = (String) obj.get("list"); String crewName = (String) obj.get("crewName"); try { ArrayList<String> members; members = new ArrayList<>(Arrays.asList(list.split(", "))); String crewsTable = communityName + "_Crews"; sql = "INSERT INTO " + crewsTable + " (crewName, numMembers, listMembers) VALUES (?, ?, ?)"; ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, crewName); ps.setInt(2, members.size()); ps.setString(3, list); ps.executeUpdate(); rs = ps.getGeneratedKeys(); if (rs.next()) { int idCrew = rs.getInt(1); String crewTable = communityName + "_" + crewName.replaceAll("\\s", "_") + "_" + idCrew + "_Board"; String newTable = "CREATE TABLE " + crewTable + " (" + "idMessage INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, " + "pinned INT(4), name VARCHAR(255), date DATE, " + "message TEXT CHARACTER SET latin1 COLLATE latin1_general_cs)"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); out.write(idCrew); System.out.println("idCrew " + idCrew); } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } } /* Function which adds a new event into the specified community calendar table. */ private void addEvent(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; String eventName = (String) obj.get("eventName"); try { sql = "SELECT count(*) FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 0) { sql = "INSERT INTO " + communityName + " (eventName, description, date, time, city, " + "state, address, zip, locationName, numAttendees, notified, listAttendees) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("eventName")); ps.setString(2, (String) obj.get("description")); ps.setString(3, (String) obj.get("date")); ps.setString(4, (String) obj.get("time")); ps.setString(5, (String) obj.get("city")); ps.setString(6, (String) obj.get("state")); ps.setString(7, (String) obj.get("address")); ps.setString(8, (String) obj.get("zip")); ps.setString(9, (String) obj.get("locationName")); ps.setString(10, (String) obj.get("numAttendees")); ps.setString(11, ""); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates a new hangout in the specified community hangout table. */ private void addHangout(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Hangouts"; String hangoutName = (String) obj.get("hangoutName"); try { sql = "SELECT count(*) FROM " + communityName + " WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, hangoutName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 0) { sql = "INSERT INTO " + communityName + " (creator, hangoutName, startTime, " + "endTime, date, address, locationName, listAttendees, minUsers, maxUsers, " + "numUsers) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("creator")); ps.setString(2, hangoutName); ps.setString(3, (String) obj.get("startTime")); ps.setString(4, (String) obj.get("endTime")); ps.setString(5, (String) obj.get("date")); ps.setString(6, (String) obj.get("address")); ps.setString(7, (String) obj.get("locationName")); ps.setString(8, (String) obj.get("listAttendees")); ps.setInt(9, toIntExact((long) obj.get("minUsers"))); ps.setInt(10, toIntExact((long) obj.get("maxUsers"))); ps.setInt(11, 1); System.out.println(ps); ps.executeUpdate(); sql = "UPDATE Users Set listHangOuts = CONCAT(?, listHangOuts) WHERE googleID = ?"; ps = conn.prepareStatement(sql); String listHangOut = obj.get("communityName") + "_" + hangoutName; ps.setString(1, listHangOut); String googleID = (String) obj.get("listAttendees"); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which adds a user to specified hangout. First checks the string listAttendees of hangout name for user googleID. If not found then concatenates the user googleID into the communitiesList for the hangout. */ private void addHangoutUser(JSONObject obj) { //this "works" String name = (String) obj.get("communityName"); name = name.replaceAll("\\s", "_"); String communityName = name + "_Hangouts"; String googleID = (String) obj.get("googleID"); String hangoutName = (String) obj.get("hangoutName"); int idHangout; try { sql = "SELECT listAttendees, idHangouts, numUsers FROM " + communityName + " WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, hangoutName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { idHangout = rs.getInt("idHangouts"); boolean found = false; String list = rs.getString("listAttendees"); ArrayList<String> users; users = new ArrayList<>(Arrays.asList(list.split(", "))); for (String user : users) { if (user.equals(googleID)) { found = true; break; } } if (!found) { sql = "UPDATE " + communityName + " Set listAttendees = CONCAT(?, listAttendees) WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); googleID += ", "; ps.setString(1, googleID); ps.setInt(2, idHangout); System.out.println(ps); ps.executeUpdate(); sql = "UPDATE " + communityName + " SET numUsers = ? WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, rs.getInt("numUsers") + 1); ps.setInt(2, rs.getInt("idHangouts")); System.out.println(ps); ps.executeUpdate(); sql = "UPDATE Users Set listHangOuts = CONCAT(?, listHangOuts) WHERE googleID = ?"; ps = conn.prepareStatement(sql); String listHangOut = obj.get("communityName") + "_" + hangoutName; ps.setString(1, listHangOut); ps.setString(2, (String) obj.get("googleID")); System.out.println(ps); ps.executeUpdate(); } sql = "SELECT maxUsers, numUsers, listAttendees FROM " + communityName + " WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, idHangout); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt("numUsers") == rs.getInt("maxUsers")) { sql = "DELETE FROM " + communityName + " WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, idHangout); ps.executeUpdate(); String crewsTable = name + "_Crews"; sql = "INSERT INTO " + crewsTable + " (crewName, numMembers, listMembers) " + "VALUES (?, ?, ?)"; ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, hangoutName); ps.setInt(2, rs.getInt("numUsers")); ps.setString(3, rs.getString("listAttendees")); System.out.println(ps); ps.executeUpdate(); rs = ps.getGeneratedKeys(); if (rs.next()) { int idCrew = rs.getInt(1); String crewName = name + "_" + hangoutName.replaceAll("\\s", "_") + "_" + idCrew + "_Board"; String newTable = "CREATE TABLE " + crewName + " (" + "idMessage INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, " + "pinned INT(4), name VARCHAR(255), date DATE, " + "message TEXT CHARACTER SET latin1 COLLATE latin1_general_cs)"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } } } catch (SQLException e) { e.printStackTrace(); System.out.println("failed"); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which adds a new message into the specified community board table. After adding the message into the table calls function to send a notification. Calls newBoardNotification. */ private void addMessage(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Board"; String message = (String) obj.get("message"); String name = message.split(":")[0]; try { sql = "INSERT INTO " + communityName + " (pinned, name, date, message) VALUES(?, ?, ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("pinned")); ps.setString(2, name); ps.setString(3, (String) obj.get("date")); ps.setString(4, message); System.out.println(ps); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } newBoardNotification((String) obj.get("communityName"), name, message); } /* Function which adds a new user to the Users table if user is not already there. */ private void addUser(JSONObject obj) { String googleID = (String) obj.get("googleID"); try { sql = "SELECT count(*) from Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 0) { sql = "INSERT INTO Users (firstName, lastName, googleID, communitiesList, " + "moderatorOf, pictureURL, listHangOuts) VALUES (?, ?, ?, ?, ?, ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("firstName")); ps.setString(2, (String) obj.get("lastName")); ps.setString(3, googleID); ps.setString(4, ""); ps.setString(5, ""); ps.setString(6, (String) obj.get("pictureURL")); ps.setString(7, ""); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates the Firebase JSON with a message that a user is inviting another to specified community. */ private void communityInvite(JSONObject obj) { //TODO test JSONObject data = new JSONObject(); JSONObject notification = new JSONObject(); JSONObject parent = new JSONObject(); notification.put("body", "You have received an invitation to join a community"); notification.put("title", "New Community Invitation"); data.put("body", obj.get("user") + " has invited you to join " + obj.get("communityName")); data.put("title", "New community invitation by " + obj.get("user")); data.put("communityName", obj.get("communityName")); parent.put("notification", notification); parent.put("data", data); parent.put("priority", "high"); messageWrite(parent); } /* Function which searches the Communities for the specified value in provided variable type. If any communities are found, then write to client a comma separated string of all found communities, otherwise returns an empty string. */ private String communitySearch(String type, String value) { StringBuilder communities = new StringBuilder(); communities.append(""); try { sql = "SELECT name FROM Communities WHERE " + type + " = ?"; ps = conn.prepareStatement(sql); ps.setString(1, value); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { communities.append(rs.getString("name")); communities.append(", "); } out.writeUTF(communities.toString()); System.out.println(communities); } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return ""; } /* Function which concatenates a user into the list of users who have checked into the event. */ private void checkIn(JSONObject obj) { //TODO test String communityName = (String) obj.get("communityName"); String eventName = (String) obj.get("eventName"); String googleID = (String) obj.get("googleID"); String listCheckedIn; try { sql = "SELECT ideventCheckIns, listCheckedIn FROM eventsCheckIn " + "WHERE (communityName = ? AND eventName = ?)"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); ps.setString(2, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { listCheckedIn = rs.getString("listCheckedIn"); boolean found = false; ArrayList<String> users; users = new ArrayList<>(Arrays.asList(listCheckedIn.split(", "))); for (String user : users) { if (user.equals(googleID)) { found = true; break; } } if (!found) { int id = rs.getInt("ideventCheckIns"); listCheckedIn += googleID + ", "; sql = "UPDATE eventsCheckIn SET numCheckedIn = numCheckedIn + 1, listCheckedIn = ? " + "WHERE idEventCheckIns = ?"; ps = conn.prepareStatement(sql); ps.setString(1, listCheckedIn); ps.setInt(2, id); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates a new board table for newly added community. Called by addCommunity. */ private void createCommunityBoardTable(String communityName) { communityName += "_Board"; String newTable = "CREATE TABLE " + communityName + " (" + "idMessage INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, " + "pinned INT(4), name VARCHAR(255), date DATE, " + "message TEXT CHARACTER SET latin1 COLLATE latin1_general_cs)"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void createCommunityCrewsTable(String communityName) { communityName += "_Crews"; String newTable = "CREATE TABLE " + communityName + " (" + "idCrew INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, crewName VARCHAR(45), " + "numMembers INT(11), listMembers TEXT CHARACTER SET latin1 COLLATE latin1_general_cs)"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates a new calendar table for newly added community. Called by addCommunity. */ private void createCommunityEventsTable(String communityName) { //DATETIME: YYYY-MM-DD HH:MM:SS, DATE: YYYY-MM-DD communityName += "_Calendar"; String newTable = "CREATE TABLE " + communityName + " (" + "idEvents INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, eventName VARCHAR(255), " + "description VARCHAR(255), date DATE, time TIME, city VARCHAR(255), " + "state VARCHAR(255), address VARCHAR(255), zip VARCHAR(255), idCheckIn INT(4), " + "locationName VARCHAR(255), numAttendees INT(4), notified INT(1), " + "listAttendees TEXT CHARACTER SET latin1 COLLATE latin1_general_cs, " + "FOREIGN KEY (idCheckIn) REFERENCES eventsCheckIn (ideventCheckIns))"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates a new hangout table for newly added community. Called by addCommunity. */ private void createCommunityHangoutsTable(String communityName) { communityName += "_Hangouts"; String newTable = "CREATE TABLE " + communityName + " (" + "idHangouts INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, creator VARCHAR(255), " + "hangoutName VARCHAR(255), startTime TIME, endTime TIME, date DATE, minUsers INT(11), " + "maxUsers INT(11), numUsers INT(11), address VARCHAR(255), locationName VARCHAR(255), " + "listAttendees TEXT CHARACTER SET latin1 COLLATE latin1_general_cs)"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which creates a new users table for newly added community. Called by addCommunity. */ private void createCommunityUsersTable(String communityName) { communityName += "_Users"; String newTable = "CREATE TABLE " + communityName + " (" + "idUsers INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, googleID VARCHAR(255), " + "isLeader TINYINT(1), subscribed INT(1))"; System.out.println(newTable); try { ps = conn.prepareStatement(newTable); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which deletes an event from the community calendar table. */ private void deleteEvent(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; try { sql = "DELETE FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("eventName")); System.out.println(ps); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which edits the values of an event in the calendar table for the specified community. */ private void editEvent(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; String eventName = (String) obj.get("eventName"); try { sql = "SELECT * FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { sql = "UPDATE Users SET (eventName, description, date, time, city, state, address, " + "zip, locationName, numAttendees) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(11, rs.getString("eventName")); if (obj.get("eventName") != rs.getString("eventName") && obj.get("eventName") != null) { ps.setString(1, (String) obj.get("eventName")); } else { ps.setString(1, rs.getString("eventName")); } if (obj.get("description") != rs.getString("description") && obj.get("description") != null) { ps.setString(2, (String) obj.get("description")); } else { ps.setString(2, rs.getString("description")); } if (obj.get("date") != null && obj.get("date") != rs.getString("date")) { ps.setString(3, (String) obj.get("date")); } else { ps.setString(3, rs.getString("date")); } if (obj.get("time") != null && obj.get("time") != rs.getString("time")) { ps.setString(4, (String) obj.get("time")); } else { ps.setString(4, rs.getString("time")); } if (obj.get("city") != null && obj.get("city") != rs.getString("city")) { ps.setString(5, (String) obj.get("city")); } else { ps.setString(5, rs.getString("city")); } if (obj.get("state") != null && obj.get("state") != rs.getString("state")) { ps.setString(6, (String) obj.get("state")); } else { ps.setString(6, rs.getString("state")); } if (obj.get("address") != null && obj.get("address") != rs.getString("address")) { ps.setString(7, (String) obj.get("address")); } else { ps.setString(7, rs.getString("address")); } if (obj.get("zip") != null && obj.get("zip") != rs.getString("zip")) { ps.setString(8, (String) obj.get("zip")); } else { ps.setString(8, rs.getString("zip")); } if (obj.get("locationName") != rs.getString("locationName") && obj.get("locationName") != null) { ps.setString(9, (String) obj.get("locationName")); } else { ps.setString(9, rs.getString("locationName")); } if (obj.get("numAttendees") != rs.getString("numAttendees") && obj.get("numAttendees") != null) { ps.setString(10, (String) obj.get("numAttendees")); } else { ps.setString(10, rs.getString("numAttendees")); } System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which edits the values of a hangout in the hangout table for the specified community. */ private void editHangout(JSONObject obj) { //TODO test String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Hangout"; String hangoutName = (String) obj.get("hangoutName"); try { sql = "SELECT * FROM " + communityName + " WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, hangoutName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { sql = "UPDATE Users SET (hangoutName, startTime, endTime, date, address, locationName, " + "listAttendees) VALUES (?, ?, ?, ?, ?, ?, ?) WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(8, rs.getString("hangoutName")); if (obj.get("hangoutName") != rs.getString("hangoutName") && obj.get("hangoutName") != null) { ps.setString(1, (String) obj.get("hangoutName")); } else { ps.setString(1, rs.getString("hangoutName")); } if (obj.get("startTime") != rs.getString("startTime") && obj.get("startTime") != null) { ps.setString(2, (String) obj.get("startTime")); } else { ps.setString(2, rs.getString("startTime")); } if (obj.get("endTime") != null && obj.get("endTime") != rs.getString("endTime")) { ps.setString(3, (String) obj.get("endTime")); } else { ps.setString(3, rs.getString("endTime")); } if (obj.get("date") != null && obj.get("date") != rs.getString("date")) { ps.setString(4, (String) obj.get("date")); } else { ps.setString(4, rs.getString("date")); } if (obj.get("address") != null && obj.get("address") != rs.getString("address")) { ps.setString(5, (String) obj.get("address")); } else { ps.setString(5, rs.getString("address")); } if (obj.get("locationName") != rs.getString("locationName") && obj.get("locationName") != null ) { ps.setString(6, (String) obj.get("locationName")); } else { ps.setString(6, rs.getString("locationName")); } if (obj.get("listAttendees") != rs.getString("listAttendees") && obj.get("listAttendees") != null) { ps.setString(7, (String) obj.get("listAttendees")); } else { ps.setString(7, rs.getString("listAttendees")); } System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which sends an email to provided email address from the [email protected] gmail account with a link to the app download page. Some email accounts cannot be sent to for whatever reason. */ private void emailInvite(String fromName, String to) { final String password = appKey; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication("[email protected]", password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Butterfly Invite"); message.setText("A wants you to use Butterfly"); Transport.send(message); System.out.println("Invite Sent from: [email protected] to: " + to); } catch (MessagingException e) { e.printStackTrace(); } } private void getCheckIns(JSONObject obj) { String communityName = (String) obj.get("communityName"); String eventName = (String) obj.get("eventName"); try { sql = "SELECT listCheckedIn FROM eventsCheckIn " + "WHERE (communityName = ? AND eventName = ?)"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); ps.setString(2, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { StringBuilder namesList = new StringBuilder(); String listCheckedIn = rs.getString("listCheckedIn"); ArrayList<String> users; users = new ArrayList<>(Arrays.asList(listCheckedIn.split(", "))); for (String user : users) { sql = "SELECT firstName, lastName FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, user); System.out.println(ps); ResultSet result = ps.executeQuery(); if (result.next()) { namesList.append(result.getString("firstName")); namesList.append(" "); namesList.append(result.getString("lastName")); namesList.append(", "); } try { result.close(); } catch (SQLException e) { e.printStackTrace(); } } out.writeUTF(namesList.toString()); System.out.println(namesList.toString()); sleep(10); out.writeUTF(rs.getString("listCheckedIn")); System.out.println(rs.getString("listCheckedIn")); } } catch (SQLException | IOException | InterruptedException e) { e.printStackTrace(); } finally { try { ps.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client a string of communities in the Communities table which are not marked as private. */ private void getCommunities() { StringBuilder communities = new StringBuilder(); try { sql = "SELECT name, private FROM Communities"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { if (rs.getInt("private") == 0) { communities.append(rs.getString("name")); communities.append(", "); } } out.writeUTF(communities.toString()); System.out.println(communities); } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client JSON strings of users in specified community. First function writes number of following strings to send. JSON strings include first and last names of user. */ private void getCommunityUsers(String communityName) { communityName = communityName.replaceAll("\\s", "_"); communityName += "_Users"; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) > 0) { out.writeUTF(Integer.toString(rs.getInt(1))); sql = "SELECT googleID FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); JSONObject obj; while (rs.next()) { sql = "SELECT firstName, lastName FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, rs.getString("googleID")); System.out.println(ps); ResultSet result = ps.executeQuery(); if (result.next()) { obj = new JSONObject(); obj.put("firstName", result.getString("firstName")); obj.put("lastName", result.getString("lastName")); out.writeUTF(obj.toString()); System.out.println(obj.toString()); } } } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client JSON strings of users in specified community. First function writes number of following strings to send. JSON strings include first and last names of user and googleID. */ private void getCommunityUsersWithID(String communityName) { communityName = communityName.replaceAll("\\s", "_"); communityName += "_Users"; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) > 0) { System.out.println("Users in community " + Integer.toString(rs.getInt(1))); out.writeUTF(Integer.toString(rs.getInt(1))); sql = "SELECT googleID FROM " + communityName; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); JSONObject obj; while (rs.next()) { sql = "SELECT firstName, lastName, googleID FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, rs.getString("googleID")); ResultSet result = ps.executeQuery(); if (result.next()) { obj = new JSONObject(); obj.put("firstName", result.getString("firstName")); obj.put("lastName", result.getString("lastName")); obj.put("googleID", result.getString("googleID")); out.writeUTF(obj.toString()); System.out.println(obj.toString()); } } } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void getCrewMessages(JSONObject obj) { //TODO test String communityName = (String) obj.get("communityName"); String crewName = (String) obj.get("crewName"); long idCrew = (long) obj.get("idCrew"); System.out.println("id number " + idCrew); communityName = communityName.replaceAll("\\s", "_") + "_" + crewName.replaceAll("\\s", "_"); communityName += "_" + idCrew + "_Board"; JSONObject returnObj; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { out.writeUTF(Integer.toString(rs.getInt(1))); sql = "SELECT * FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { returnObj = new JSONObject(); returnObj.put("pinned", rs.getString("pinned")); returnObj.put("name", rs.getString("name")); returnObj.put("date", rs.getString("date")); returnObj.put("message", rs.getString("message")); out.writeUTF(returnObj.toString()); System.out.println(returnObj); } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void getCrewUsers(String communityName, long idCrew) { //TODO test communityName = communityName.replaceAll("\\s", "_"); communityName += "_Crews"; try { sql = "SELECT numMembers, listMembers FROM " + communityName + " WHERE idCrew = ?"; ps = conn.prepareStatement(sql); ps.setLong(1, idCrew); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { out.writeUTF(Integer.toString(rs.getInt("numMembers"))); System.out.println("numMembers " + rs.getInt("numMembers")); ArrayList<String> ids = new ArrayList<>(Arrays.asList( rs.getString("listMembers").split(", "))); JSONObject obj; for (String id : ids) { sql = "SELECT firstName, lastName, googleID FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, id); System.out.println(ps); ResultSet result = ps.executeQuery(); if (result.next()) { obj = new JSONObject(); obj.put("firstName", result.getString("firstName")); obj.put("lastName", result.getString("lastName")); obj.put("googleID", result.getString("googleID")); out.writeUTF(obj.toString()); System.out.println(obj.toString()); } } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client a string number of how many events in the community table then JSON strings of all rows in the provided community's calendar table. */ private void getEvents(String communityName) { String community = communityName; communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) > 0) { out.writeUTF(Integer.toString(rs.getInt(1))); sql = "SELECT * FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); JSONObject obj; while (rs.next()) { obj = new JSONObject(); obj.put("eventName", rs.getString("eventName")); obj.put("city", rs.getString("city")); obj.put("date", rs.getString("date")); obj.put("time", rs.getString("time")); obj.put("address", rs.getString("address")); obj.put("state", rs.getString("state")); obj.put("zip", rs.getString("zip")); obj.put("description", rs.getString("description")); obj.put("communityName", community); obj.put("locationName", rs.getString("locationName")); obj.put("numAttendees", rs.getString("numAttendees")); out.writeUTF(obj.toString()); System.out.println(obj.toString()); } } else { out.writeUTF("0"); } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client a string containing the primary key idUsers associated with the googleID. */ private String getIdUsers(String googleID) { try { sql = "SELECT idUsers FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { System.out.println(rs.getString("idUsers")); return rs.getString("idUsers"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return "0"; } /* Function which writes to client a string containing the Firebase provided instanceID associated with the googleID. */ private String getInstanceID(String googleID) { //function passed to genericNotification try { sql = "SELECT instanceID FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { return rs.getString("instanceID"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return ""; } /* Function which writes to client JSON strings of hangouts in the specified community. First writes to client number of strings to be written. */ private void getHangouts(String communityName) { //TODO test communityName = communityName.replaceAll("\\s", "_"); communityName += "_Hangouts"; JSONObject obj; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { out.writeUTF(Integer.toString(rs.getInt(1))); sql = "SELECT * FROM " + communityName; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { obj = new JSONObject(); obj.put("creator", rs.getString("creator")); System.out.println("name " + rs.getString("hangoutName")); obj.put("hangoutName", rs.getString("hangoutName")); System.out.println("put " + obj.get("hangoutName")); obj.put("startTime", rs.getString("startTime")); obj.put("endTime", rs.getString("endTime")); obj.put("date", rs.getString("date")); obj.put("address", rs.getString("address")); obj.put("locationName", rs.getString("locationName")); obj.put("listIds", rs.getString("listAttendees")); obj.put("minUsers", rs.getInt("minUsers")); obj.put("maxUsers", rs.getInt("maxUsers")); String list = rs.getString("listAttendees"); System.out.println(list); ArrayList<String> ids = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder names = new StringBuilder(); for (String id : ids) { sql = "SELECT firstName, lastName FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, id); rs = ps.executeQuery(); if (rs.next()) { names.append(rs.getString("firstName")); names.append(" "); names.append(rs.getString("lastName")); names.append(", "); } } obj.put("listNames", names.toString()); out.writeUTF(obj.toString()); System.out.println(obj); } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client the number of messages stored in the community board table and then all rows in the table in JSON format. */ private void getMessages(String communityName) { communityName = communityName.replaceAll("\\s", "_"); communityName += "_Board"; JSONObject obj; try { sql = "SELECT COUNT(*) FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { out.writeUTF(Integer.toString(rs.getInt(1))); System.out.println("total messages " + rs.getInt(1)); sql = "SELECT * FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { obj = new JSONObject(); obj.put("pinned", rs.getString("pinned")); obj.put("name", rs.getString("name")); obj.put("date", rs.getString("date")); obj.put("message", rs.getString("message")); out.writeUTF(obj.toString()); System.out.println(obj); } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which loops through every community in the neighborhood table and writes to client number of communities in the neighborhood and then calls a function to write all events from the list of communities. Calls getEvents. */ private void getNeighborhoodEvents() { try { sql = "SELECT name FROM Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { ArrayList<String> communities = new ArrayList<>(); communities.add(rs.getString("name")); out.writeUTF(Integer.toString(communities.size())); System.out.println(communities.size()); communities.forEach(this::getEvents); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client string list of users which have rsvp'ed to specified event from specified community. If there are no users who have rsvp'ed then send write back empty string. */ private void getrsvp(String communityName, String eventName) { communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; try { sql = "SELECT listAttendees FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); String list; if (rs.next()) { list = rs.getString("listAttendees"); StringBuilder namesList = new StringBuilder(); ArrayList<String> ids = new ArrayList<>(Arrays.asList(list.split(", "))); //out.writeUTF(Integer.toString(ids.size())); for (String id : ids) { sql = "SELECT firstName, lastName FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, id); System.out.println(ps); ResultSet result = ps.executeQuery(); if (result.next()) { namesList.append(result.getString("firstName")); namesList.append(" "); namesList.append(result.getString("lastName")); namesList.append(", "); } try { result.close(); } catch (SQLException e) { e.printStackTrace(); } } out.writeUTF(namesList.toString()); System.out.println("sent " + namesList.toString() + "!"); out.writeUTF(list); System.out.println("sent " + list + "!"); } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client string of community names that the user is a part of from the communitiesList column in Users table. If user is not in any communities then write empty string. */ private void getUserCommunities(String googleID) { try { sql = "SELECT communitiesList FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); String list; if (rs.next()) { list = rs.getString("communitiesList"); out.writeUTF(list); System.out.println("sent " + list); } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void getUserCrews(String communityName, String googleID) { communityName = communityName.replaceAll("\\s", "_"); communityName += "_Crews"; try { sql = "SELECT idCrew, crewName, listMembers FROM " + communityName; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); JSONObject returnObj; while (rs.next()) { String list = rs.getString("listMembers"); ArrayList<String> users = new ArrayList<>(Arrays.asList(list.split(", "))); for (String user : users) { if (user.equals(googleID)) { returnObj = new JSONObject(); returnObj.put("crewName", rs.getString("crewName")); returnObj.put("idCrew", rs.getInt("idCrew")); out.writeUTF(returnObj.toString()); System.out.println(returnObj.toString()); break; } } } returnObj = new JSONObject(); returnObj.put("crewName", "END"); returnObj.put("idCrew", -1); out.writeUTF(returnObj.toString()); System.out.println(returnObj.toString()); } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client the number of communities the user is in then the community name and calls a function to get all events of that community. If user is not in any communities then write empty string. Calls getEvents. */ private void getUserCommunityEvents(String googleID) { try { sql = "SELECT communitiesList FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); String list; if (rs.next()) { list = rs.getString("communitiesList"); if (!list.equals("")) { ArrayList<String> communities = new ArrayList<>(Arrays.asList(list.split(", "))); out.writeUTF(Integer.toString(communities.size())); for (String community : communities) { out.writeUTF(community); getEvents(community); } } } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void getUserHangouts(String googleID) { try { sql = "SELECT listHangOuts FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { out.writeUTF(rs.getString("listHangOuts")); } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client a string that contains the first and last name of the user associated with the provided googleID. */ private void getUserName(String googleID) { try { sql = "SELECT firstName, lastName FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String name = rs.getString("firstName"); name += " "; name += rs.getString("lastName"); out.writeUTF(name); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client string of community names where the user is a moderator of. Writes an empty string if user is not a moderator of any communities. */ private void getUserModerator(String googleID) { try { sql = "SELECT moderatorOf FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); String list; if (rs.next()) { list = rs.getString("moderatorOf"); out.writeUTF(list); System.out.println("sent " + list); } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which writes to client a JSON which holds all variable fields for a user in the Users table. */ private void getUserProfile(String googleID) { try { sql = "SELECT * FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { JSONObject returnJSON = new JSONObject(); returnJSON.put("firstName", rs.getString("firstName")); returnJSON.put("lastName", rs.getString("lastName")); returnJSON.put("googleID", rs.getString("googleID")); returnJSON.put("communitiesList", rs.getString("communitiesList")); returnJSON.put("moderatorOf", rs.getString("moderatorOf")); returnJSON.put("pictureURL", rs.getString("pictureURL")); out.writeUTF(returnJSON.toString()); System.out.println("sent " + returnJSON.toString()); } else { out.writeUTF(""); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which builds the Firebase JSON for a notification that a user has pinged members of the community. Calls messageWrite. */ private void groupNotification(JSONObject obj) { String name = (String) obj.get("name"); String community = (String) obj.get("communityName"); String message = (String) obj.get("message"); JSONObject data = new JSONObject(); JSONObject notification = new JSONObject(); JSONObject parent = new JSONObject(); notification.put("body", name + " pinged the group"); notification.put("title", "New ping in " + community + " by " + name); //data.put("body", message); data.put("title", "New ping in " + community + " by " + name); data.put("communityName", community); parent.put("to", "/topics/" + community.replaceAll("\\s", "_")); parent.put("notification", notification); parent.put("data", data); parent.put("priority", "high"); messageWrite(parent); } /* Function which builds the Firebase JSON for inviting a user who uses the app to the community. Calls messageWrite. */ private void inviteNotification(JSONObject obj) { String name = (String) obj.get("name"); String community = (String) obj.get("communityName"); String message = (String) obj.get("message"); String googleID = (String) obj.get("googleID"); System.out.println(googleID); JSONObject data = new JSONObject(); JSONObject notification = new JSONObject(); JSONObject parent = new JSONObject(); notification.put("body", name + " wants you to join " + community); notification.put("title", "Community Invite"); data.put("body", message); data.put("title", "Community Invite"); data.put("communityName", community); //community.replaceAll("\\s", "_"); parent.put("to", getInstanceID(googleID)); parent.put("notification", notification); parent.put("data", data); parent.put("priority", "high"); messageWrite(parent); } private void isPrivate(String communityName) { try { sql = "SELECT private FROM Communities WHERE name = ?"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt("private") == 0) { out.writeUTF("FALSE"); } else { out.writeUTF("TRUE"); } } } catch (SQLException |IOException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which removes the user from the community users table, updates the communitiesList for the user in the Users table, if the user was a moderator for the community left, then also updates the moderatorOf for the user in the Users table. */ private void leaveCommunityUser(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Users"; String googleID = (String) obj.get("googleID"); try { sql = "SELECT COUNT(*) FROM " + communityName + " WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 1) { sql = "DELETE FROM " + communityName + " WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); ps.executeUpdate(); sql = "SELECT communitiesList FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); String list; if (rs.next()) { list = rs.getString("communitiesList"); ArrayList<String> communities; communities = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder communitiesList = new StringBuilder(); for (String community : communities) { if (community.equals(obj.get("communityName"))) { System.out.println("found " + community); } else { communitiesList.append(community); communitiesList.append(", "); } } sql = "UPDATE Users SET communitiesList = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, communitiesList.toString()); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } sql = "SELECT moderatorOf FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { list = rs.getString("moderatorOf"); ArrayList<String> communities; communities = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder communitiesList = new StringBuilder(); for (String community : communities) { if (community.equals(obj.get("communityName"))) { System.out.println("found " + community); } else { communitiesList.append(community); if (!community.equals(" ")) { communitiesList.append(", "); } } } sql = "UPDATE Users SET moderatorOf = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, communitiesList.toString()); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which removes the user from a hangout in the specified community at the specified hangout name. */ private void leaveHangoutUser(JSONObject obj) { //TODO test String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Hangouts"; String googleID = (String) obj.get("googleID"); String hangoutName = (String) obj.get("hangoutName"); try { sql = "SELECT listAttendees, idHangouts, numUsers FROM " + communityName + " WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, hangoutName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String list = rs.getString("listAttendees"); ArrayList<String> attendees; attendees = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder string = new StringBuilder(); for (String attendee : attendees) { if (attendee.equals(googleID)) { System.out.println("found " + attendee); } else { string.append(attendee); string.append(", "); } } if (rs.getInt("numUsers") - 1 == 0) { sql = "DELETE FROM " + communityName + " WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, rs.getInt("idHangouts")); System.out.println(ps); ps.executeUpdate(); } else { sql = "UPDATE " + communityName + " SET (listAttendees, numUsers) VALUES (?, ?) " + "WHERE hangoutName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, string.toString()); ps.setInt(2, rs.getInt("numUsers") - 1); ps.setString(3, hangoutName); System.out.println(ps); ps.executeUpdate(); } sql = "SELECT listHangOuts FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); rs = ps.executeQuery(); if (rs.next()) { list = rs.getString("listHangOuts"); ArrayList<String> hangouts; hangouts = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder listHangOuts = new StringBuilder(); for (String hangout : hangouts) { if (hangout.equals(obj.get("communityName") + "_" + hangoutName)) { System.out.println("found hangout"); } else { listHangOuts.append(hangout); if (!hangout.equals(" ")) { listHangOuts.append(", "); } } } sql = "UPDATE Users SET listHangOuts = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, listHangOuts.toString()); ps.setString(2, googleID); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which sends a http POST request to FireBaseIO and receives a response JSON back from FireBaseIO. Called by genericNotification and newBoardNotification. */ private void messageWrite(JSONObject parent) { System.out.println(parent.toString()); try { URL url = new URL("https://fcm.googleapis.com/fcm/send"); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setDoOutput(true); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json"); http.setRequestProperty("Authorization", Authorization); OutputStream os = http.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); osw.write(parent.toString()); osw.flush(); osw.close(); BufferedReader is = new BufferedReader(new InputStreamReader(http.getInputStream())); String response; while ((response = is.readLine()) != null) { System.out.println(response); } is.close(); } catch (IOException e) { e.printStackTrace(); } } /* Function which builds the JSON for notification when a new board message has been added. Uses FireBase topic messaging. Called by addMessage and calls messageWrite. */ private void newBoardNotification(String community, String name, String message) { JSONObject data = new JSONObject(); JSONObject notification = new JSONObject(); JSONObject parent = new JSONObject(); notification.put("body", name + " has posted a new message"); notification.put("title", "New Message in " + community + " by " + name); data.put("body", message); data.put("title", "New Message in " + community + " by " + name); data.put("communityName", community); parent.put("to", "/topics/" + community.replaceAll("\\s", "_")); parent.put("notification", notification); parent.put("data", data); parent.put("priority", "high"); messageWrite(parent); } /* Function which removes all communities from the database. Loops through the Communities table and drops all created tables associated with community name. Loops through Users table and truncates the rows for communitiesList and moderatorOf. */ private void removeAllCommunities() { try { sql = "SELECT name FROM Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { String communityName = rs.getString("name"); sql = "DROP TABLE " + communityName + "_Board, " + communityName + "_Calendar, " + communityName + "_Hangouts, " + communityName + "_Users"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); } sql = "SELECT googleID FROM Users"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { sql = "UPDATE Users SET (communitiesList, moderatorOf) VALUES (?, ?) " + "WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, ""); ps.setString(2, ""); ps.setString(3, rs.getString("googleID")); System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which removes a community from the database. Removes the community from the Communities table. Loops through any users still in the community and removes the community from respective communitiesList. Drops all created tables associated from database. */ private void removeCommunity(String communityName) { String name = communityName; ResultSet result; try { sql = "DELETE FROM Communities WHERE name = ?"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); System.out.println(ps); ps.executeUpdate(); communityName = communityName.replaceAll("\\s", "_"); sql = "SELECT googleID FROM " + communityName + "_Users"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { sql = "SELECT communitiesList FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, rs.getString("googleID")); System.out.println(ps); result = ps.executeQuery(); if (result.next()) { ArrayList<String> communities = new ArrayList<>( Arrays.asList(result.getString("communitiesList").split(", "))); StringBuilder string = new StringBuilder(); for (String community : communities) { if (community.equals(name)) { System.out.println("found " + community); } else { string.append(community); string.append(", "); } } sql = "UPDATE Users SET communitiesList = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, string.toString()); ps.setString(2, rs.getString("googleID")); System.out.println(ps); ps.executeUpdate(); try { result.close(); } catch (SQLException e) { e.printStackTrace(); } } } sql = "DROP TABLE " + communityName + "_Board, " + communityName + "_Calendar, " + communityName + "_Hangouts, " + communityName + "_Users"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which adds the user to listAttendees in community calendar table for specified event. */ private void rsvpEvent(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; String googleID = (String) obj.get("googleID"); String eventName = (String) obj.get("eventName"); try { sql = "SELECT count(*) FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 1) { sql = "UPDATE " + communityName + " SET listAttendees = " + "CONCAT(?, listAttendees) WHERE eventName = ?"; ps = conn.prepareStatement(sql); googleID += ", "; ps.setString(1, googleID); ps.setString(2, eventName); System.out.println(ps); ps.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void checkInCheck(JSONObject obj) { String communityName = (String) obj.get("communityName"); String eventName = (String) obj.get("eventName"); String googleID = (String) obj.get("googleID"); try { sql = "SELECT listCheckedIn FROM eventsCheckIn " + "WHERE (communityName = ? AND eventName = ?)"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); ps.setString(2, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String list = rs.getString("listCheckedIn"); ArrayList<String> attendees; attendees = new ArrayList<>(Arrays.asList(list.split(", "))); for (String attendee : attendees) { if (attendee.equals(googleID)) { out.writeUTF("1"); System.out.println("found " + attendee); return; } } out.writeUTF("0"); System.out.println("0"); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { ps.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which selects from the community calendar table and checks whether the user has already rsvp'ed to the specified event. Returns string "1" if found and "0" otherwise. */ private void rsvpCheck(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; String googleID = (String) obj.get("googleID"); String eventName = (String) obj.get("eventName"); try { sql = "SELECT listAttendees FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String list = rs.getString("listAttendees"); ArrayList<String> attendees; attendees = new ArrayList<>(Arrays.asList(list.split(", "))); for (String attendee : attendees) { if (attendee.equals(googleID)) { out.writeUTF("1"); System.out.println("found " + attendee); return; } } out.writeUTF("0"); System.out.println("0"); } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void removeCheckIn(JSONObject obj) { String communityName = (String) obj.get("communityName"); String eventName = (String) obj.get("eventName"); String googleID = (String) obj.get("googleID"); try { sql = "SELECT listCheckedIn FROM eventsCheckIn " + "WHERE (communityName = ? AND eventName = ?)"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); ps.setString(2, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String list = rs.getString("listCheckedIn"); ArrayList<String> attendees; attendees = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder string = new StringBuilder(); for (String attendee : attendees) { if (attendee.equals(googleID)) { System.out.println("found " + attendee); } else { string.append(attendee); string.append(", "); } } sql = "UPDATE eventsCheckIn SET listAttendees = ? WHERE (communityName = ? AND eventName = ?)"; ps = conn.prepareStatement(sql); ps.setString(1, string.toString()); ps.setString(2, communityName); ps.setString(3, eventName); System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Updates listAttendees in the community calendar table for an event if a user removes rsvp from event. */ private void rsvpEventRemove(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Calendar"; String googleID = (String) obj.get("googleID"); String eventName = (String) obj.get("eventName"); try { sql = "SELECT listAttendees FROM " + communityName + " WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, eventName); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String list = rs.getString("listAttendees"); ArrayList<String> attendees; attendees = new ArrayList<>(Arrays.asList(list.split(", "))); StringBuilder string = new StringBuilder(); for (String attendee : attendees) { if (attendee.equals(googleID)) { System.out.println("found " + attendee); } else { string.append(attendee); string.append(", "); } } sql = "UPDATE " + communityName + " SET listAttendees = ? WHERE eventName = ?"; ps = conn.prepareStatement(sql); ps.setString(1, string.toString()); ps.setString(2, eventName); System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Updates the Users table with the current instanceID provided by FireBaseIO because instanceIDs can change depending on something. */ private void updateInstanceID(JSONObject obj) { try { sql = "UPDATE Users SET instanceID = ? WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("instanceID")); ps.setString(2, (String) obj.get("googleID")); System.out.println(ps); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Updates the Users table with any different information from JSON which is sent from client. */ private void updateUserProfile(JSONObject obj) { String googleID = (String) obj.get("googleID"); try { sql = "SELECT * FROM Users WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, googleID); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { sql = "UPDATE Users SET (firstName, lastName, birthDate) " + "VALUES (?, ?, ?) WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(4, googleID); if (obj.get("firstName") != null && obj.get("firstName") != rs.getString("firstName")) { ps.setString(1, (String) obj.get("firstName")); } else { ps.setString(1, rs.getString("firstName")); } if (obj.get("lastName") != null && obj.get("lastName") != rs.getString("lastName")) { ps.setString(2, (String) obj.get("lastName")); } else { ps.setString(2, rs.getString("lastName")); } if (obj.get("birthDate") != null && obj.get("birthDate") != rs.getString("birthDate")) { ps.setString(3, (String) obj.get("birthDate")); } else { ps.setString(3, rs.getString("birthDate")); } System.out.println(ps); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* Function which drops all created tables and truncates the required tables Users, Communities, and eventsCheckIn. */ private void wipe() { try { //sql = "SELECT " sql = "SELECT name FROM Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { String communityName = rs.getString("name"); communityName = communityName.replaceAll("\\s", "_"); sql = "SELECT idCrew, crewName FROM " + communityName + "_Crews"; ps = conn.prepareStatement(sql); System.out.println(ps); ResultSet result = ps.executeQuery(); while (result.next()) { String crewName = communityName + "_" + result.getString("crewName").replaceAll("\\s", "_") + "_" + result.getInt("idCrew") + "_Board"; sql = "DROP TABLE " + crewName; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); } sql = "DROP TABLE " + communityName + "_Board, " + communityName + "_Calendar, " + communityName + "_Hangouts, " + communityName + "_Users, " + communityName + "_Crews"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); } sql = "TRUNCATE TABLE Users"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); sql = "TRUNCATE TABLE Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); sql = "TRUNCATE TABLE eventsCheckIn"; ps = conn.prepareStatement(sql); System.out.println(ps); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } /*private boolean checkIfLeader(JSONObject obj) { String communityName = (String) obj.get("communityName"); communityName = communityName.replaceAll("\\s", "_"); communityName += "_Users"; try { sql = "SELECT isLeader from " + communityName + " WHERE googleID = ?"; ps = conn.prepareStatement(sql); ps.setString(1, (String) obj.get("googleID")); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { if (rs.getInt(1) == 1) { return true; } } } catch (SQLException e) { e.printStackTrace(); } return false; }*/ /*private ArrayList<String> getSubscribedMembers(String communityName) { ArrayList<String> subscribedGoogleIDs = new ArrayList<>(); try { sql = "SELECT * from " + communityName + "_Users WHERE subscribed = '1'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs.next()) { subscribedGoogleIDs.add(rs.getString("googleID")); } } catch (SQLException e) { e.printStackTrace(); } return subscribedGoogleIDs; }*/ } @SuppressWarnings({"unchecked", "InfiniteLoopStatement"}) class eventCheck implements Runnable { static private String Authorization; private Connection conn; private String sql; private PreparedStatement ps; private ResultSet rs; eventCheck(String PASS, String auth) { Authorization = auth; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/Butterfly", "root", PASS); conn.getMetaData().getCatalogs(); conn.createStatement(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public void run() { // called by upcomingEventNotification // TIME: HH:MM:SS, DATE: YYYY-MM-DD while (true) { try { sql = "SELECT name FROM Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); ArrayList<String> communities = new ArrayList<>(); while (rs.next()) { communities.add(rs.getString("name")); } communities.forEach(this::timeCheckEvents); communities.clear(); } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); Thread.sleep(30000); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } } } /* Function which loops through rows in the community calendar table and if the startDate for an event is within 24 hours then send out a notification to all subscribed members of the community and creates a new row into eventsCheckIn. */ private void timeCheckEvents(String communityName) { // called by upcomingEventNotification // TIME: HH:MM:SS, DATE: YYYY-MM-DD String communityReplaced = communityName.replaceAll("\\s", "_"); String communityCalendar = communityReplaced; communityCalendar += "_Calendar"; try { sql = "SELECT idEvents, eventName, notified, date FROM " + communityCalendar; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { if (rs.getInt("notified") == 0) { sql = "UPDATE " + communityCalendar + " SET notified = 1 WHERE idEvents = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, rs.getInt("idEvents")); System.out.println(ps); ps.executeUpdate(); String eventDate = rs.getString("date"); ArrayList<String> dateSplit = new ArrayList<>(Arrays.asList(eventDate.split("-"))); Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int currYear = cal.get(Calendar.YEAR); int currMonth = cal.get(Calendar.MONTH); int currDay = cal.get(Calendar.DAY_OF_MONTH); int eventYear = Integer.parseInt(dateSplit.get(0)); int eventMonth = Integer.parseInt(dateSplit.get(1)); if (eventMonth > 0) { eventMonth--; } int eventDay = Integer.parseInt(dateSplit.get(2)); if (currYear == eventYear && currMonth == eventMonth && eventDay - currDay < 1) { String topic = "/topics/"; topic += communityReplaced; eventNotification(topic, "A Community event is upcoming", "Upcoming Event", communityName); sql = "INSERT INTO eventsCheckIn (communityName, eventName, numCheckedIn, " + "listCheckedIn) VALUES(?, ?, ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, communityName); ps.setString(2, rs.getString("eventName")); ps.setInt(3, 0); ps.setString(4, ""); System.out.println(ps); ps.executeUpdate(); } } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void eventNotification(String to, String message, String title, String community) { JSONObject parent = new JSONObject(); JSONObject notification = new JSONObject(); JSONObject data = new JSONObject(); data.put("body", "message"); data.put("title", title); data.put("communityName", community); parent.put("data", data); notification.put("body", message); notification.put("title", title); parent.put("to", to); parent.put("notification", notification); parent.put("priority", "high"); messageWrite(parent); } private void messageWrite(JSONObject parent) { System.out.println(parent.toString()); try { URL url = new URL("https://fcm.googleapis.com/fcm/send"); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setDoOutput(true); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json"); http.setRequestProperty("Authorization", Authorization); OutputStream os = http.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); osw.write(parent.toString()); osw.flush(); osw.close(); BufferedReader is = new BufferedReader(new InputStreamReader(http.getInputStream())); String response; while ((response = is.readLine()) != null) { System.out.println(response); } is.close(); } catch (IOException e) { e.printStackTrace(); } } } @SuppressWarnings("InfiniteLoopStatement") class hangoutCheck implements Runnable { private Connection conn; private String sql; private PreparedStatement ps; private ResultSet rs; hangoutCheck(String PASS) { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/Butterfly", "root", PASS); conn.getMetaData().getCatalogs(); conn.createStatement(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public void run() { ArrayList<String> communities = new ArrayList<>(); while (true) { try { sql = "SELECT name FROM Communities"; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); if (rs.next()) { String temp = rs.getString("name").replaceAll("\\s", "_"); temp += "_Hangouts"; communities.add(temp); communities.forEach(this::timeCheckHangouts); communities.clear(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); Thread.sleep(60000); } catch (SQLException | InterruptedException e) { e.printStackTrace(); } } } } /* Function which loops through rows in the community hangouts table and removes the hangouts which have passed. */ private void timeCheckHangouts(String communityHangout) { try { sql = "SELECT date, endTime, idHangouts FROM " + communityHangout; ps = conn.prepareStatement(sql); System.out.println(ps); rs = ps.executeQuery(); while (rs.next()) { String eventDate = rs.getString("date"); String eventTime = rs.getString("endTime"); ArrayList<String> dateSplit; dateSplit = new ArrayList<>(Arrays.asList(eventDate.split("-"))); ArrayList<String> timeSplit; timeSplit = new ArrayList<>(Arrays.asList(eventTime.split(":"))); Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int currYear = cal.get(Calendar.YEAR); int currMonth = cal.get(Calendar.MONTH); int currDay = cal.get(Calendar.DAY_OF_MONTH); int currHour = cal.get(Calendar.HOUR_OF_DAY); int currMinute = cal.get(Calendar.MINUTE); int hangoutYear = Integer.parseInt(dateSplit.get(0)); int hangoutMonth = Integer.parseInt(dateSplit.get(1)); if (hangoutMonth > 0) { hangoutMonth--; } int hangoutDay = Integer.parseInt(dateSplit.get(2)); int hangoutHour = Integer.parseInt(timeSplit.get(0)); int hangoutMinute = Integer.parseInt(timeSplit.get(1)); if (currYear == hangoutYear && currMonth == hangoutMonth && hangoutDay - currDay == 1) { if (currHour - hangoutHour >= 0 && currMinute - hangoutMinute >= 0) { sql = "DELETE FROM " + communityHangout + " WHERE idHangouts = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, rs.getInt("idHangouts")); System.out.println("Events Thread " + ps); ps.executeUpdate(); } } } } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } @SuppressWarnings("InfiniteLoopStatement") public class Server { public static void main(String[] args) { Date currentDate = Calendar.getInstance().getTime(); System.out.println(currentDate); try { FirebaseOptions options = new FirebaseOptions.Builder() .setServiceAccount(new FileInputStream("/home/khanh/Butterfly-40ec2c75b546.json")) .setDatabaseUrl("butterfly-145620.firebaseio.com/") .build(); FirebaseApp.initializeApp(options); ServerSocket serverSocket = new ServerSocket(3300); JSONParser parser = new JSONParser(); String appKey, PASS, Authorization; FileInputStream fileIn = new FileInputStream("/home/khanh/keys.txt"); InputStreamReader isr = new InputStreamReader(fileIn, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); appKey = br.readLine(); PASS = br.readLine(); Authorization = br.readLine(); br.close(); isr.close(); new Thread(new eventCheck(PASS, Authorization)).start(); new Thread(new hangoutCheck(PASS)).start(); while (true) { System.out.println("Waiting on port " + serverSocket.getLocalPort() + "..."); try { Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); sleep(100); if (in.available() > 0) { Object parsed = parser.parse(in.readUTF()); JSONObject obj = (JSONObject) parsed; System.out.println("TIMESTAMP " + currentDate + " " + obj.get("function")); new Thread(new serverStart(obj, out, appKey, PASS, Authorization)).start(); } } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); } catch (ParseException | InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } }
Hamza141/Butterfly
Server/src/Server.java
Java
gpl-3.0
124,016
/*- Package Declaration ------------------------------------------------------*/ package org.epics.ca.impl; /*- Imported packages --------------------------------------------------------*/ import org.epics.ca.util.logging.LibraryLogManager; import java.net.InetSocketAddress; import java.util.logging.Logger; /*- Interface Declaration ----------------------------------------------------*/ /*- Class Declaration --------------------------------------------------------*/ /** * Beacon handler. */ public class BeaconHandler { /*- Public attributes --------------------------------------------------------*/ /*- Private attributes -------------------------------------------------------*/ private static final Logger logger = LibraryLogManager.getLogger( BeaconHandler.class ); /** * Context instance. */ private final ContextImpl context; /* * Remote address for this handler. */ //private final InetSocketAddress responseFrom; /** * Average period. */ private long averagePeriod = Long.MIN_VALUE; /** * Period stabilization flag. * If beacon monitoring began when server is being (re)started, * beacon period increases by factor 2. This case is handled by this flag. */ private boolean periodStabilized = false; /** * Last beacon sequence ID. */ private long lastBeaconSequenceID; /** * Last beacon timestamp. */ private long lastBeaconTimeStamp = Long.MIN_VALUE; /*- Main ---------------------------------------------------------------------*/ /*- Constructor --------------------------------------------------------------*/ /** * Constructor. * * @param context the context. * @param responseFrom server to handle. */ public BeaconHandler( ContextImpl context, InetSocketAddress responseFrom ) { this.context = context; //this.responseFrom = responseFrom; } /*- Public methods -----------------------------------------------------------*/ /** * Update beacon period and do analytical checks (server re-started, routing problems, etc.) * * @param remoteTransportRevision the EPICS CA protocol revision number. * @param timestamp the timestamp. * @param sequentialID the ID. */ public void beaconNotify( short remoteTransportRevision, long timestamp, long sequentialID ) { final boolean networkChanged = updateBeaconPeriod( remoteTransportRevision, timestamp, sequentialID ); if ( networkChanged ) { logger.fine( "The network topology has changed." ); // what to do here?!! // report changedTransport } } /*- Private methods ----------------------------------------------------------*/ /** * Update beacon period. * * @param remoteTransportRevision the EPICS CA protocol revision number. * @param timestamp the timestamp. * @param sequentialID the ID. * @return network change (server restarted) detected. */ private synchronized boolean updateBeaconPeriod( short remoteTransportRevision, long timestamp, long sequentialID ) { // first beacon notification check if ( lastBeaconTimeStamp == Long.MIN_VALUE ) { // new server up... context.beaconAnomalyNotify(); if ( remoteTransportRevision >= 10 ) { lastBeaconSequenceID = sequentialID; } lastBeaconTimeStamp = timestamp; return false; } // v4.10+ support beacon sequential IDs and additional checks are possible: // - detect beacon duplications due to redundant routes // - detect lost beacons due to input queue overrun or damage if ( remoteTransportRevision >= 10 ) { final long beaconSeqAdvance; if ( sequentialID >= lastBeaconSequenceID ) { beaconSeqAdvance = sequentialID - lastBeaconSequenceID; } else { beaconSeqAdvance = (0x00000000FFFFFFFFL - lastBeaconSequenceID) + sequentialID; } lastBeaconSequenceID = sequentialID; // throw out sequence numbers just prior to, or the same as, the last one received // (this situation is probably caused by a temporary duplicate route ) if ( beaconSeqAdvance == 0 || beaconSeqAdvance > 0x00000000FFFFFFFFL - 256 ) { return false; } // throw out sequence numbers that jump forward by only a few numbers // (this situation is probably caused by a duplicate route // or a beacon due to input queue overrun) if ( beaconSeqAdvance > 1 && beaconSeqAdvance < 4 ) { return false; } } boolean networkChange = false; long currentPeriod = timestamp - lastBeaconTimeStamp; // second beacon, period can be calculated now if ( averagePeriod < 0 ) { averagePeriod = currentPeriod; } else { // is this a server seen because of a restored network segment? if ( currentPeriod >= (averagePeriod * 1.25) ) { if ( currentPeriod >= (averagePeriod * 3.25) ) { context.beaconAnomalyNotify (); // trigger network change on any 3 contiguous missing beacons networkChange = true; } else if ( !periodStabilized ) { // boost current period averagePeriod = currentPeriod; } else { // something might be wrong... context.beaconAnomalyNotify(); } } // is this a server seen because of reboot // (beacons come at a higher rate just after the) else if ( currentPeriod <= (averagePeriod * 0.8) ) { // server restarted... context.beaconAnomalyNotify(); networkChange = true; } // all OK else { periodStabilized = true; } if ( networkChange ) { // reset periodStabilized = false; averagePeriod = -1; } else { // update a running average period averagePeriod = (long) (currentPeriod * 0.125 + averagePeriod * 0.875); } } lastBeaconTimeStamp = timestamp; return networkChange; } /*- Nested classes -----------------------------------------------------------*/ }
channelaccess/ca
src/main/java/org/epics/ca/impl/BeaconHandler.java
Java
gpl-3.0
6,554
package org.aauc.urticariapp; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
aauc/urticariapp
android/app/src/androidTest/java/org/aauc/urticariapp/ApplicationTest.java
Java
gpl-3.0
351
package com.ipac.app.model; import java.util.Date; public interface Switch { public Integer getVersion(); public Date getDateCreated(); public Date getDateUpdated(); public Integer getBladeCount(); public void setBladeCount(Integer bladeCount); public String getDescr(); public void setDescr(String descr); public Integer getId(); public void setId(Integer id); public String getModel(); public void setModel(String model); public String getName(); public void setName(String name); public String getCreatedBy(); public void setCreatedBy(String createdBy); public Integer getSiteId(); public void setSiteId(Integer siteId); }
rob-murray/ipac
WEBAPP/src/main/java/com/ipac/app/model/Switch.java
Java
gpl-3.0
714
/* Copyright 2007-2009 QSpin - www.qspin.be This file is part of QTaste framework. QTaste is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QTaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with QTaste. If not, see <http://www.gnu.org/licenses/>. */ package com.qspin.qtaste.testsuite; /** * QTasteDataException represents a error related to the test data. * Nothing about the test behavior or the testAPI, just test data. * If there is a problem related to an invalid data type or an unexpected value. * For example, if a test expects a value between 0 and 10 but the data is not present in the csv file, then a QTasteDataException will be thrown. * @author dergo */ @SuppressWarnings("serial") public class QTasteDataException extends QTasteException { /** Creates a new instance of QTasteDataException */ public QTasteDataException(String message) { super(message); } public QTasteDataException(String message, Throwable e) { super(message, e); } }
remybaranx/qtaste
kernel/src/main/java/com/qspin/qtaste/testsuite/QTasteDataException.java
Java
gpl-3.0
1,507
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers.tunnel; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.List; import org.pepsoft.minecraft.Constants; import org.pepsoft.minecraft.Material; import org.pepsoft.util.MathUtils; import org.pepsoft.util.PerlinNoise; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.MixedMaterial; import org.pepsoft.worldpainter.exporting.AbstractLayerExporter; import org.pepsoft.worldpainter.exporting.Fixup; import org.pepsoft.worldpainter.exporting.MinecraftWorld; import org.pepsoft.worldpainter.exporting.SecondPassLayerExporter; import org.pepsoft.worldpainter.heightMaps.NoiseHeightMap; /** * * @author SchmitzP */ public class TunnelLayerExporter extends AbstractLayerExporter<TunnelLayer> implements SecondPassLayerExporter<TunnelLayer> { public TunnelLayerExporter(TunnelLayer layer) { super(layer); if (layer.getFloorNoise() != null) { floorNoise = new NoiseHeightMap(layer.getFloorNoise().getRange() * 2, layer.getFloorNoise().getScale() / 5, layer.getFloorNoise().getRoughness() + 1, FLOOR_NOISE_SEED_OFFSET); floorNoiseOffset = layer.getFloorNoise().getRange(); } else { floorNoise = null; floorNoiseOffset = 0; } if (layer.getRoofNoise()!= null) { roofNoise = new NoiseHeightMap(layer.getRoofNoise().getRange() * 2, layer.getRoofNoise().getScale() / 5, layer.getRoofNoise().getRoughness() + 1, ROOF_NOISE_SEED_OFFSET); roofNoiseOffset = layer.getRoofNoise().getRange(); } else { roofNoise = null; roofNoiseOffset = 0; } // if (layer.getWallNoise() != null) { // wallNoise = new PerlinNoise(layer.getWallNoise().getSeed()); // } else { // wallNoise = null; // } } @Override public List<Fixup> render(Dimension dimension, Rectangle area, Rectangle exportedArea, MinecraftWorld world) { final TunnelLayer.Mode floorMode = layer.getFloorMode(), roofMode = layer.getRoofMode(); final int floorWallDepth = layer.getFloorWallDepth(), roofWallDepth = layer.getRoofWallDepth(), floorLevel = layer.getFloorLevel(), roofLevel = layer.getRoofLevel(), maxWallDepth = Math.max(floorWallDepth, roofWallDepth) + 1, floorMin = layer.getFloorMin(), floorMax = layer.getFloorMax(), roofMin = layer.getRoofMin(), roofMax = layer.getRoofMax(), floodLevel = layer.getFloodLevel(); final int minZ = dimension.isBottomless() ? 0 : 1, maxZ = dimension.getMaxHeight() - 1; final boolean removeWater = layer.isRemoveWater(), floodWithLava = layer.isFloodWithLava(); final MixedMaterial floorMaterial = layer.getFloorMaterial(), wallMaterial = layer.getWallMaterial(), roofMaterial = layer.getRoofMaterial(); if (floorNoise != null) { floorNoise.setSeed(dimension.getSeed()); } if (roofNoise != null) { roofNoise.setSeed(dimension.getSeed()); } if ((floorMaterial == null) && (wallMaterial == null) && (roofMaterial == null)) { // One pass: just remove blocks for (int x = area.x; x < area.x + area.width; x++) { for (int y = area.y; y < area.y + area.height; y++) { if (dimension.getBitLayerValueAt(layer, x, y)) { final int terrainHeight = dimension.getIntHeightAt(x, y); int actualFloorLevel = calculateLevel(floorMode, floorLevel, terrainHeight, floorMin, floorMax, minZ, maxZ, (floorNoise != null) ? ((int) floorNoise.getHeight(x, y) - floorNoiseOffset) : 0); int actualRoofLevel = calculateLevel(roofMode, roofLevel, terrainHeight, roofMin, roofMax, minZ, maxZ, (roofNoise != null) ? ((int) roofNoise.getHeight(x, y) - roofNoiseOffset) : 0); if (actualRoofLevel <= actualFloorLevel) { continue; } final float distanceToWall = dimension.getDistanceToEdge(layer, x, y, maxWallDepth) - 1; final int floorLedgeHeight = calculateLedgeHeight(floorWallDepth, distanceToWall); final int roofLedgeHeight = calculateLedgeHeight(roofWallDepth, distanceToWall); actualFloorLevel += floorLedgeHeight; actualRoofLevel -= roofLedgeHeight; if (actualRoofLevel <= actualFloorLevel) { continue; } final int waterLevel = dimension.getWaterLevelAt(x, y); for (int z = Math.min(removeWater ? Math.max(terrainHeight, waterLevel) : terrainHeight, actualRoofLevel); z > actualFloorLevel; z--) { if (removeWater || (z <= terrainHeight) || (z > waterLevel)) { if (z <= floodLevel) { world.setMaterialAt(x, y, z, floodWithLava ? Material.LAVA : Material.WATER); } else { world.setMaterialAt(x, y, z, Material.AIR); } } } if (actualFloorLevel == 0) { // Bottomless world, and cave extends all the way to // the bottom. Remove the floor block, as that is // probably what the user wants if ((floodLevel > 0) && (0 <= floodLevel)) { world.setMaterialAt(x, y, 0, floodWithLava ? Material.LAVA : Material.WATER); } else { world.setMaterialAt(x, y, 0, Material.AIR); } } } } } } else { // Two passes: first place floor, wall and roof materials, then // excavate the interior for (int x = area.x; x < area.x + area.width; x++) { for (int y = area.y; y < area.y + area.height; y++) { if (dimension.getBitLayerValueAt(layer, x, y)) { int terrainHeight = dimension.getIntHeightAt(x, y); int actualFloorLevel = calculateLevel(floorMode, floorLevel, terrainHeight, floorMin, floorMax, minZ, maxZ, (floorNoise != null) ? ((int) floorNoise.getHeight(x, y) - floorNoiseOffset) : 0); int actualRoofLevel = calculateLevel(roofMode, roofLevel, terrainHeight, roofMin, roofMax, minZ, maxZ, (roofNoise != null) ? ((int) roofNoise.getHeight(x, y) - roofNoiseOffset) : 0); if (actualRoofLevel <= actualFloorLevel) { continue; } final float distanceToWall = dimension.getDistanceToEdge(layer, x, y, maxWallDepth) - 1; final int floorLedgeHeight = calculateLedgeHeight(floorWallDepth, distanceToWall); final int roofLedgeHeight = calculateLedgeHeight(roofWallDepth, distanceToWall); actualFloorLevel += floorLedgeHeight; actualRoofLevel -= roofLedgeHeight; if (actualRoofLevel <= actualFloorLevel) { continue; } int waterLevel = dimension.getWaterLevelAt(x, y); boolean flooded = waterLevel > terrainHeight; final int startZ = Math.min(removeWater ? Math.max(terrainHeight, waterLevel) : terrainHeight, actualRoofLevel); for (int z = startZ; z > actualFloorLevel; z--) { if ((floorLedgeHeight == 0) && (floorMaterial != null)) { setIfSolid(world, x, y, z - 1, minZ, maxZ, floorMaterial, flooded, terrainHeight, waterLevel, removeWater); } if (wallMaterial != null) { if (floorLedgeHeight > 0) { setIfSolid(world, x, y, z - 1, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } if (roofLedgeHeight > 0) { setIfSolid(world, x, y, z + 1, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } } if ((roofLedgeHeight == 0) && (roofMaterial != null)) { setIfSolid(world, x, y, z + 1, minZ, maxZ, roofMaterial, flooded, terrainHeight, waterLevel, removeWater); } } if (wallMaterial != null) { terrainHeight = dimension.getIntHeightAt(x - 1, y); waterLevel = dimension.getWaterLevelAt(x - 1, y); flooded = waterLevel > terrainHeight; for (int z = startZ; z > actualFloorLevel; z--) { setIfSolid(world, x - 1, y, z, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } terrainHeight = dimension.getIntHeightAt(x, y - 1); waterLevel = dimension.getWaterLevelAt(x, y - 1); flooded = waterLevel > terrainHeight; for (int z = startZ; z > actualFloorLevel; z--) { setIfSolid(world, x, y - 1, z, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } terrainHeight = dimension.getIntHeightAt(x + 1, y); waterLevel = dimension.getWaterLevelAt(x + 1, y); flooded = waterLevel > terrainHeight; for (int z = startZ; z > actualFloorLevel; z--) { setIfSolid(world, x + 1, y, z, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } terrainHeight = dimension.getIntHeightAt(x, y + 1); waterLevel = dimension.getWaterLevelAt(x, y + 1); flooded = waterLevel > terrainHeight; for (int z = startZ; z > actualFloorLevel; z--) { setIfSolid(world, x, y + 1, z, minZ, maxZ, wallMaterial, flooded, terrainHeight, waterLevel, removeWater); } } } } } // Second pass: excavate interior for (int x = area.x; x < area.x + area.width; x++) { for (int y = area.y; y < area.y + area.height; y++) { if (dimension.getBitLayerValueAt(layer, x, y)) { final int terrainHeight = dimension.getIntHeightAt(x, y); int actualFloorLevel = calculateLevel(floorMode, floorLevel, terrainHeight, floorMin, floorMax, minZ, maxZ, (floorNoise != null) ? ((int) floorNoise.getHeight(x, y) - floorNoiseOffset) : 0); int actualRoofLevel = calculateLevel(roofMode, roofLevel, terrainHeight, roofMin, roofMax, minZ, maxZ, (roofNoise != null) ? ((int) roofNoise.getHeight(x, y) - roofNoiseOffset) : 0); if (actualRoofLevel <= actualFloorLevel) { continue; } final float distanceToWall = dimension.getDistanceToEdge(layer, x, y, maxWallDepth) - 1; final int floorLedgeHeight = calculateLedgeHeight(floorWallDepth, distanceToWall); final int roofLedgeHeight = calculateLedgeHeight(roofWallDepth, distanceToWall); actualFloorLevel += floorLedgeHeight; actualRoofLevel -= roofLedgeHeight; if (actualRoofLevel <= actualFloorLevel) { continue; } final int waterLevel = dimension.getWaterLevelAt(x, y); for (int z = actualRoofLevel; z > actualFloorLevel; z--) { if (removeWater || (z <= terrainHeight) || (z > waterLevel)) { if (z <= floodLevel) { world.setMaterialAt(x, y, z, floodWithLava ? Material.LAVA : Material.WATER); } else { world.setMaterialAt(x, y, z, Material.AIR); } } } if (actualFloorLevel == 0) { // Bottomless world, and cave extends all the way to // the bottom. Remove the floor block, as that is // probably what the user wants if ((floodLevel > 0) && (0 <= floodLevel)) { world.setMaterialAt(x, y, 0, floodWithLava ? Material.LAVA : Material.WATER); } else { world.setMaterialAt(x, y, 0, Material.AIR); } } } } } } return null; } // private void excavateDisc(final MinecraftWorld world, final int x, final int y, final int z, int r, final Material materialAbove, final Material materialBesides, final Material materialBelow) { // GeometryUtil.visitFilledCircle(r, new GeometryVisitor() { // @Override // public boolean visit(int dx, int dy, float d) { // world.setMaterialAt(x + dx, y + dy, z, Material.AIR); // if (materialAbove != null) { // setIfSolid(world, x + dx, y + dy, z - 1, 0, Integer.MAX_VALUE, materialAbove); // } // if (materialBesides != null) { // setIfSolid(world, x + dx - 1, y + dy, z, 0, Integer.MAX_VALUE, materialBesides); // setIfSolid(world, x + dx, y + dy - 1, z, 0, Integer.MAX_VALUE, materialBesides); // setIfSolid(world, x + dx + 1, y + dy, z, 0, Integer.MAX_VALUE, materialBesides); // setIfSolid(world, x + dx, y + dy + 1, z, 0, Integer.MAX_VALUE, materialBesides); // } // if (materialBelow != null) { // setIfSolid(world, x + dx, y + dy, z + 1, 0, Integer.MAX_VALUE, materialBelow); // } // return true; // } // }); // } public BufferedImage generatePreview(int width, int height, int waterLevel, int baseHeight, int heightDifference) { final TunnelLayer.Mode floorMode = layer.getFloorMode(), roofMode = layer.getRoofMode(); final int floorWallDepth = layer.getFloorWallDepth(), roofWallDepth = layer.getRoofWallDepth(), floorLevel = layer.getFloorLevel(), roofLevel = layer.getRoofLevel(), tunnelExtent = width - 24, floorMin = layer.getFloorMin(), floorMax = layer.getFloorMax(), roofMin = layer.getRoofMin(), roofMax = layer.getRoofMax(), floodLevel = layer.getFloodLevel(); final boolean removeWater = layer.isRemoveWater(), floodWithLava = layer.isFloodWithLava(); final PerlinNoise noise = new PerlinNoise(0); final BufferedImage preview = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { // Clear the sky final int terrainHeight = MathUtils.clamp(0, (int) (Math.sin((x / (double) width * 1.5 + 1.25) * Math.PI) * heightDifference / 2 + heightDifference / 2 + baseHeight + noise.getPerlinNoise(x / 20.0) * 32 + noise.getPerlinNoise(x / 10.0) * 16 + noise.getPerlinNoise(x / 5.0) * 8), baseHeight + heightDifference - 1); for (int z = height - 1; z > terrainHeight; z--) { preview.setRGB(x, height - 1 - z, (z <= waterLevel) ? 0x0000ff : 0xffffff); } if (x <= tunnelExtent) { // Draw the tunnel int actualFloorLevel = calculateLevel(floorMode, floorLevel, terrainHeight, floorMin, floorMax, 1, height - 1, (floorNoise != null) ? ((int) floorNoise.getHeight(x, 0) - floorNoiseOffset) : 0); int actualRoofLevel = calculateLevel(roofMode, roofLevel, terrainHeight, roofMin, roofMax, 1, height - 1, (roofNoise != null) ? ((int) roofNoise.getHeight(x, 0) - roofNoiseOffset) : 0); if (actualRoofLevel > actualFloorLevel) { final float distanceToWall = tunnelExtent - x; final int floorLedgeHeight = calculateLedgeHeight(floorWallDepth, distanceToWall); final int roofLedgeHeight = calculateLedgeHeight(roofWallDepth, distanceToWall); actualFloorLevel += floorLedgeHeight; actualRoofLevel = Math.min(actualRoofLevel - roofLedgeHeight, Math.max(terrainHeight, 62)); for (int z = actualFloorLevel + 1; z <= actualRoofLevel; z++) { if (z <= floodLevel) { if (floodWithLava) { preview.setRGB(x, height - 1 - z, 0xff8000); } else { preview.setRGB(x, height - 1 - z, 0x0000ff); } } else { if (z > terrainHeight) { if (removeWater) { preview.setRGB(x, height - 1 - z, 0x7f7fff); } } else { preview.setRGB(x, height - 1 - z, 0x7f7f7f); } } } } } } return preview; } private int calculateLevel(TunnelLayer.Mode mode, int level, int terrainHeight, int minLevel, int maxLevel, int minZ, int maxZ, int offset) { switch (mode) { case CONSTANT_DEPTH: return MathUtils.clamp(minZ, MathUtils.clamp(minLevel, terrainHeight - level, maxLevel) + offset, maxZ); case FIXED_HEIGHT: return MathUtils.clamp(minZ, level + offset, maxZ); case INVERTED_DEPTH: return MathUtils.clamp(minZ, MathUtils.clamp(minLevel, level - (terrainHeight - level), maxLevel) + offset, maxZ); default: throw new InternalError(); } } private int calculateLedgeHeight(int wallDepth, float distanceToWall) { if (distanceToWall > wallDepth) { return 0; } else { final float a = wallDepth - distanceToWall; return (int) (wallDepth - Math.sqrt(wallDepth * wallDepth - a * a) + 0.5); } } private void setIfSolid(MinecraftWorld world, int x, int y, int z, int minZ, int maxZ, MixedMaterial material, boolean flooded, int terrainHeight, int waterLevel, boolean removeWater) { if ((z >= minZ) && (z <= maxZ)) { if (removeWater || (! flooded) || (z <= terrainHeight) || (z > waterLevel)) { final int existingBlock = world.getBlockTypeAt(x, y, z); if ((existingBlock != Constants.BLK_AIR) && (! Constants.INSUBSTANTIAL_BLOCKS.contains(existingBlock))) { // The coordinates are within bounds and the existing block is solid world.setMaterialAt(x, y, z, material.getMaterial(MATERIAL_SEED, x, y, z)); } } } } private final NoiseHeightMap floorNoise, roofNoise; private final int floorNoiseOffset, roofNoiseOffset; // private final PerlinNoise wallNoise; private static final long MATERIAL_SEED = 0x688b2af137c77e0cL; private static final long FLOOR_NOISE_SEED_OFFSET = 177766561L; private static final long ROOF_NOISE_SEED_OFFSET = 184818453L; enum RenderState {AIR, WATER, LAVA, UNDERGROUND} }
nfloersch/wpgis
org/pepsoft/worldpainter/layers/tunnel/TunnelLayerExporter.java
Java
gpl-3.0
20,924
package com.lghead.timeclockexpert; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.lghead.timeclockexpert.base.BaseFragment; import com.lghead.timeclockexpert.common.IGenericResult; import com.lghead.timeclockexpert.enums.ClockActionType; import com.lghead.timeclockexpert.enums.ClockType; import com.lghead.timeclockexpert.event.ClockListChangedMessageEvent; import com.lghead.timeclockexpert.event.TickNextMinuteMessageEvent; import com.lghead.timeclockexpert.model.ClockModel; import com.lghead.timeclockexpert.model.ShiftDetailModel; import com.lghead.timeclockexpert.model.ShiftModel; import com.lghead.timeclockexpert.repository.ShiftRepository; import org.greenrobot.eventbus.EventBus; import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.lghead.timeclockexpert.util.LogUtil.LOGI; import static com.lghead.timeclockexpert.util.LogUtil.makeLogTag; public class CurrentShiftFragment extends BaseFragment { public static CurrentShiftFragment getInstance() { return new CurrentShiftFragment(); } private static final String TAG = makeLogTag(CurrentShiftFragment.class); private enum ButtonAction { START_SHIFT, PUSH_IN, PUSH_OUT_END_SHIFT } private static Handler mHandler = new Handler(); private boolean mMinuteTickStarted = false; private ShiftModel mShiftModel; private ButtonAction mButtonAction; @BindView(R.id.current_shift_button) Button mButton; @BindView(R.id.current_shift_total_text) TextView mTotalShiftText; @BindView(R.id.current_shift_exit_text) TextView mExitEstimatedText; @BindView(R.id.current_shift_lefting_text) TextView mShiftLeftingText; @BindView(R.id.current_shift_overtime_text) TextView mShiftOvertimeText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initShiftModel(); } private void initShiftModel() { ShiftRepository shiftRepository = new ShiftRepository(getRealmInstance()); ShiftModel realmShiftModel = shiftRepository.findUnfinishedShift(); if (realmShiftModel != null) { mShiftModel = getRealmInstance().copyFromRealm(realmShiftModel); } else { mShiftModel = new ShiftModel(); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_current_shift, container, false); ButterKnife.bind(this, rootView); updateTextButtons(); updateShiftDetail(); return rootView; } @Override public void onResume() { super.onResume(); checkInitMinuteTickHandler(); } @Override public void onPause() { super.onPause(); mHandler.removeCallbacksAndMessages(null); } private void updateTextButtons() { boolean startedShift = mShiftModel.getClockModelList().size() > 0; @StringRes int buttonText = R.string.start_shift; mButtonAction = ButtonAction.START_SHIFT; if (startedShift) { boolean canFinishOrPushOut = canFinishOrPushOut(); if (canFinishOrPushOut) { buttonText = R.string.push_out_end_shift; mButtonAction = ButtonAction.PUSH_OUT_END_SHIFT; } else { buttonText = R.string.push_in; mButtonAction = ButtonAction.PUSH_IN; } } mButton.setText(buttonText); } private void updateShiftDetail() { ShiftDetailModel shiftDetailModel = mShiftModel.getShiftDetailModel(getRealmInstance()); mTotalShiftText.setText(shiftDetailModel.getWorkedHours().toString()); mExitEstimatedText.setText(shiftDetailModel.getEstimatedExitHours().toString()); mShiftLeftingText.setText(shiftDetailModel.getLeftingToExitHours().toString()); } /** * Method used to handle the START/END shift now. */ @OnClick(R.id.current_shift_button) void onActionButtonClick() { final IGenericResult<DateTimePickerDialog.DateTimePickerDialogResult> genericResult = new IGenericResult<DateTimePickerDialog.DateTimePickerDialogResult>() { @Override public void onResult(DateTimePickerDialog.DateTimePickerDialogResult result) { addNewClock(result.date); ClockModel lastClockModel = mShiftModel.getClockModelList().get(mShiftModel.getClockModelList().size() - 1); if (lastClockModel.getType() == ClockType.OUT) { // TODO: Close the shift. } stuffToDoAfterAddClock(); } }; new DateTimePickerDialog(getActivity(), mShiftModel, new Date(), genericResult); } private void stuffToDoAfterAddClock() { updateTextButtons(); updateShiftDetail(); checkInitMinuteTickHandler(); } private void checkInitMinuteTickHandler() { LOGI(TAG, "checkInitMinuteTickHandler - Can init?"); if (mMinuteTickStarted || mShiftModel.isFinished() || mShiftModel.getClockModelList().size() == 0) { mHandler.removeCallbacksAndMessages(null); mMinuteTickStarted = false; return; } mMinuteTickStarted = true; long tickToNextMinute = DateUtils.MINUTE_IN_MILLIS - System.currentTimeMillis() % DateUtils.MINUTE_IN_MILLIS; mHandler.postDelayed(new Runnable() { @Override public void run() { updateShiftDetail(); LOGI(TAG, "checkInitMinuteTickHandler - Tick minute"); long tickToNextNextMinute = DateUtils.MINUTE_IN_MILLIS - System.currentTimeMillis() % DateUtils.MINUTE_IN_MILLIS; EventBus.getDefault().post(new TickNextMinuteMessageEvent()); mHandler.postDelayed(this, tickToNextNextMinute); } }, tickToNextMinute); } private void addNewClock(Date date) { ClockType clockType = canFinishOrPushOut() ? ClockType.OUT : ClockType.IN; ClockModel clockModel = new ClockModel(date, clockType); clockModel.setId(clockModel.getNextPrimaryKeyValue(getRealmInstance())); mShiftModel.getClockModelList().add(clockModel); saveNewClock(clockModel); } private void saveNewClock(ClockModel clockModel) { new ShiftRepository(getRealmInstance()).createOrUpdate(mShiftModel); EventBus.getDefault().post(new ClockListChangedMessageEvent(clockModel, ClockActionType.INSERT)); } private boolean canFinishOrPushOut() { return mShiftModel.getClockModelList().size() % 2 != 0; } @Override protected @StringRes int getFragmentTitle() { return R.string.current_shift_fragment_title; } }
luanalbineli/time-clock-expert
app/src/main/java/com/lghead/timeclockexpert/CurrentShiftFragment.java
Java
gpl-3.0
7,262
package dna.metrics.shortestPaths; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import dna.graph.IElement; import dna.graph.edges.UndirectedEdge; import dna.graph.nodes.UndirectedNode; import dna.updates.batch.Batch; import dna.updates.update.EdgeAddition; import dna.updates.update.EdgeRemoval; import dna.updates.update.NodeAddition; import dna.updates.update.NodeRemoval; import dna.updates.update.Update; import dna.util.ArrayUtils; public class UndirectedShortestPathsU extends UndirectedShortestPaths { public UndirectedShortestPathsU() { super("UndirectedShortestPathsU", ApplicationType.BeforeUpdate); } protected HashMap<UndirectedNode, HashMap<UndirectedNode, UndirectedNode>> parents; protected HashMap<UndirectedNode, HashMap<UndirectedNode, Integer>> heights; @Override public boolean applyBeforeBatch(Batch b) { return false; } @Override public boolean applyAfterBatch(Batch b) { return false; } @Override public boolean applyBeforeUpdate(Update u) { if (u instanceof NodeAddition) { // TODO implement SP update node addition return false; } else if (u instanceof NodeRemoval) { // TODO implement SP update node removal return false; } else if (u instanceof EdgeAddition) { UndirectedEdge e = (UndirectedEdge) ((EdgeAddition) u).getEdge(); UndirectedNode n1 = (UndirectedNode) e.getNode1(); UndirectedNode n2 = (UndirectedNode) e.getNode2(); for (IElement sUncasted : g.getNodes()) { UndirectedNode s = (UndirectedNode) sUncasted; HashMap<UndirectedNode, UndirectedNode> parent = this.parents .get(s); HashMap<UndirectedNode, Integer> height = this.heights.get(s); if (n1.equals(s)) { this.check(n1, n2, parent, height); continue; } if (n2.equals(s)) { this.check(n2, n1, parent, height); continue; } if (!parent.containsKey(n1) && !parent.containsKey(n2)) { continue; } this.check(n1, n2, parent, height); this.check(n2, n1, parent, height); } this.spl = ArrayUtils.truncate(this.spl, 0); this.diam = spl.length - 1; } else if (u instanceof EdgeRemoval) { // TODO implement SP update edge removal return false; } return true; } protected void check(UndirectedNode a, UndirectedNode b, HashMap<UndirectedNode, UndirectedNode> parent, HashMap<UndirectedNode, Integer> height) { int h_a = height.get(a); int h_b = height.get(b); if (h_a == Integer.MAX_VALUE || h_a + 1 >= h_b) { return; } if (h_b != Integer.MAX_VALUE) { this.spl = ArrayUtils.decr(this.spl, h_b); } if (!parent.containsKey(b)) { this.existingPaths++; } parent.put(b, a); h_b = h_a + 1; height.put(b, h_b); this.spl = ArrayUtils.incr(this.spl, h_b); for (IElement eUncasted : b.getEdges()) { UndirectedEdge e = (UndirectedEdge) eUncasted; UndirectedNode c = e.getDifferingNode(b); this.check(b, c, parent, height); } } @Override public boolean applyAfterUpdate(Update u) { return false; } @Override public boolean compute() { for (IElement sUncasted : g.getNodes()) { UndirectedNode s = (UndirectedNode) sUncasted; HashMap<UndirectedNode, UndirectedNode> parent = new HashMap<UndirectedNode, UndirectedNode>(); HashMap<UndirectedNode, Integer> height = new HashMap<UndirectedNode, Integer>(); for (IElement tUncasted : g.getNodes()) { UndirectedNode t = (UndirectedNode) tUncasted; if (t.equals(s)) { height.put(s, 0); } else { height.put(t, Integer.MAX_VALUE); } } Queue<UndirectedNode> q = new LinkedList<UndirectedNode>(); q.add(s); while (!q.isEmpty()) { UndirectedNode current = q.poll(); for (IElement eUncasted : current.getEdges()) { UndirectedEdge e = (UndirectedEdge) eUncasted; UndirectedNode neighbor = e.getDifferingNode(current); if (height.get(neighbor) != Integer.MAX_VALUE) { continue; } height.put(neighbor, height.get(current) + 1); parent.put(neighbor, current); this.spl = ArrayUtils.incr(this.spl, height.get(neighbor)); q.add(neighbor); this.existingPaths++; } } this.parents.put(s, parent); this.heights.put(s, height); } this.cpl = -1; this.diam = this.spl.length - 1; return true; } public void init_() { super.init_(); this.parents = new HashMap<UndirectedNode, HashMap<UndirectedNode, UndirectedNode>>(); this.heights = new HashMap<UndirectedNode, HashMap<UndirectedNode, Integer>>(); } public void reset_() { super.reset_(); this.parents = null; this.heights = null; } }
Rwilmes/DNA3
src/dna/metrics/shortestPaths/UndirectedShortestPathsU.java
Java
gpl-3.0
4,593
package ro.roda.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ro.roda.domain.City; @Service @Transactional public class CityServiceImpl implements CityService { public long countAllCitys() { return City.countCitys(); } public void deleteCity(City city) { city.remove(); } public City findCity(Integer id) { return City.findCity(id); } public List<City> findAllCitys() { return City.findAllCitys(); } public List<City> findCityEntries(int firstResult, int maxResults) { return City.findCityEntries(firstResult, maxResults); } public void saveCity(City city) { city.persist(); } public City updateCity(City city) { return city.merge(); } }
cosminrentea/roda
src/main/java/ro/roda/service/CityServiceImpl.java
Java
gpl-3.0
782
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.pixeldungeon.sprites; import com.watabou.noosa.Animation; import com.watabou.noosa.TextureFilm; import com.watabou.pixeldungeon.Assets; import com.watabou.utils.Random; public class SeniorSprite extends MobSprite { private Animation kick; public SeniorSprite() { super(); texture( Assets.MONK ); TextureFilm frames = new TextureFilm( texture, 15, 14 ); idle = new Animation( 6, true ); idle.frames( frames, 18, 17, 18, 19 ); run = new Animation( 15, true ); run.frames( frames, 28, 29, 30, 31, 32, 33 ); attack = new Animation( 12, false ); attack.frames( frames, 20, 21, 20, 21 ); kick = new Animation( 10, false ); kick.frames( frames, 22, 23, 22 ); die = new Animation( 15, false ); die.frames( frames, 18, 24, 25, 25, 26, 27 ); play( idle ); } @Override public void attack( int cell ) { super.attack( cell ); if (Random.Float() < 0.3f) { play( kick ); } } @Override public void onComplete( Animation anim ) { super.onComplete( anim == kick ? attack : anim ); } }
NYRDS/pixel-dungeon-remix
RemixedDungeon/src/main/java/com/watabou/pixeldungeon/sprites/SeniorSprite.java
Java
gpl-3.0
1,780
package com.notman.repository; import com.notman.domain.User; import java.time.ZonedDateTime; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; /** * Spring Data JPA repository for the User entity. */ public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findOneByActivationKey(String activationKey); List<User> findAllByActivatedIsFalseAndCreatedDateBefore(ZonedDateTime dateTime); Optional<User> findOneByResetKey(String resetKey); Optional<User> findOneByEmail(String email); Optional<User> findOneByLogin(String login); Optional<User> findOneById(Long userId); @Override void delete(User t); }
swainsoftware/salvo
src/main/java/com/notman/repository/UserRepository.java
Java
gpl-3.0
735
package org.fox.ttrss.types; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; // TODO: serialize Labels public class Article implements Parcelable { public int id; public boolean unread; public boolean marked; public boolean published; public int score; public int updated; public boolean is_updated; public String title; public String link; public int feed_id; public List<String> tags; public List<Attachment> attachments; public String content; public String excerpt; public List<List<String>> labels; public String feed_title; public int comments_count; public String comments_link; public boolean always_display_attachments; public String author; public String note; public boolean selected; /* not serialized */ public Document articleDoc; public Element flavorImage; public String flavorImageUri; public String flavorStreamUri; public String youtubeVid; //public int flavorImageCount; public List<Element> mediaList = new ArrayList<>(); public Article(Parcel in) { readFromParcel(in); } public Article() { } public void cleanupExcerpt() { if (excerpt != null) { excerpt = excerpt.replace("&hellip;", "…"); excerpt = excerpt.replace("]]>", ""); excerpt = Jsoup.parse(excerpt).text(); } } public void collectMediaInfo() { articleDoc = Jsoup.parse(content); if (articleDoc != null) { mediaList = articleDoc.select("img,video,iframe[src*=youtube.com/embed/]"); for (Element e : mediaList) { if ("iframe".equals(e.tagName().toLowerCase())) { flavorImage = e; break; } else if ("video".equals(e.tagName().toLowerCase())) { flavorImage = e; break; } } if (flavorImage == null) { for (Element e : mediaList) { flavorImage = e; break; } } if (flavorImage != null) { try { if ("video".equals(flavorImage.tagName().toLowerCase())) { Element source = flavorImage.select("source").first(); flavorStreamUri = source.attr("src"); flavorImageUri = flavorImage.attr("poster"); } else if ("iframe".equals(flavorImage.tagName().toLowerCase())) { String srcEmbed = flavorImage.attr("src"); if (srcEmbed.length() > 0) { Pattern pattern = Pattern.compile("/embed/([\\w-]+)"); Matcher matcher = pattern.matcher(srcEmbed); if (matcher.find()) { youtubeVid = matcher.group(1); flavorImageUri = "https://img.youtube.com/vi/" + youtubeVid + "/mqdefault.jpg"; flavorStreamUri = "https://youtu.be/" + youtubeVid; } } } else { flavorImageUri = flavorImage.attr("src"); if (flavorImageUri != null && flavorImageUri.startsWith("//")) { flavorImageUri = "https:" + flavorImageUri; } flavorStreamUri = null; } } catch (Exception e) { e.printStackTrace(); flavorImage = null; flavorImageUri = null; flavorStreamUri = null; } } } //Log.d("Article", "collectMediaInfo: " + flavorImage); } public Article(int id) { this.id = id; this.title = ""; this.link = ""; this.tags = new ArrayList<String>(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(id); out.writeInt(unread ? 1 : 0); out.writeInt(marked ? 1 : 0); out.writeInt(published ? 1 : 0); out.writeInt(score); out.writeInt(updated); out.writeInt(is_updated ? 1 : 0); out.writeString(title); out.writeString(link); out.writeInt(feed_id); out.writeStringList(tags); out.writeString(content); out.writeString(excerpt); out.writeList(attachments); out.writeString(feed_title); out.writeInt(comments_count); out.writeString(comments_link); out.writeInt(always_display_attachments ? 1 : 0); out.writeString(author); out.writeString(note); out.writeInt(selected ? 1 : 0); } public void readFromParcel(Parcel in) { id = in.readInt(); unread = in.readInt() == 1; marked = in.readInt() == 1; published = in.readInt() == 1; score = in.readInt(); updated = in.readInt(); is_updated = in.readInt() == 1; title = in.readString(); link = in.readString(); feed_id = in.readInt(); if (tags == null) tags = new ArrayList<String>(); in.readStringList(tags); content = in.readString(); excerpt = in.readString(); attachments = new ArrayList<Attachment>(); in.readList(attachments, Attachment.class.getClassLoader()); feed_title = in.readString(); comments_count = in.readInt(); comments_link = in.readString(); always_display_attachments = in.readInt() == 1; author = in.readString(); note = in.readString(); selected = in.readInt() == 1; } @SuppressWarnings("rawtypes") public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Article createFromParcel(Parcel in) { return new Article(in); } public Article[] newArray(int size) { return new Article[size]; } }; }
tribut/Tiny-Tiny-RSS-for-Honeycomb
org.fox.ttrss/src/main/java/org/fox/ttrss/types/Article.java
Java
gpl-3.0
5,315
/* stocks is client-server program to manage a household's food stock * Copyright (C) 2019 The stocks developers * * This file is part of the stocks program suite. * * stocks is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * stocks is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.njsm.stocks.common.util; @FunctionalInterface public interface FunctionWithExceptions<T, R, E extends Exception> { R apply(T t) throws E; }
F1rst-Unicorn/stocks
common/src/main/java/de/njsm/stocks/common/util/FunctionWithExceptions.java
Java
gpl-3.0
967
/* * @(#)ParameterOptgroupService.java * @author xichao.dong * Copyright (c) 2013 Glacier SoftWare Company Limited. All Rights Reserved. */ package com.glacier.netloan.service.basicdatas; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.glacier.basic.util.JackJson; import com.glacier.basic.util.RandomGUID; import com.glacier.jqueryui.util.JqReturnJson; import com.glacier.jqueryui.util.Tree; import com.glacier.netloan.dao.basicdatas.ParameterOptgroupMapper; import com.glacier.netloan.dao.basicdatas.ParameterOptgroupValueMapper; import com.glacier.netloan.dao.system.UserMapper; import com.glacier.netloan.entity.basicdatas.ParameterOptgroup; import com.glacier.netloan.entity.basicdatas.ParameterOptgroupExample; import com.glacier.netloan.entity.basicdatas.ParameterOptgroupValueExample; import com.glacier.netloan.entity.system.User; import com.glacier.netloan.util.MethodLog; /** * @ClassName: ParameterOptgroupService * @Description: TODO(下拉项业务类) * @author xichao.dong * @email [email protected] * @date 2014-1-21 下午2:22:22 */ @Service @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public class ParameterOptgroupService { @Autowired private ParameterOptgroupMapper optgroupMapper; @Autowired private ParameterOptgroupValueMapper optgroupValueMapper; @Autowired private UserMapper userMapper; /** * @Title: getOptgroup * @Description: TODO(根据下拉项Id获取下拉项信息) * @param @param optgroupId * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object getOptgroup(String optgroupId) { return optgroupMapper.selectByPrimaryKey(optgroupId); } /** * @Title: listAsTree * @Description: TODO(获取下拉项下的树结构的所有下拉项数据) * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object listAsTree() { ParameterOptgroupExample OptgroupExample=new ParameterOptgroupExample(); OptgroupExample.setOrderByClause("temp_parameter_optgroup.optgroup_num asc"); List<ParameterOptgroup> optgroupList = optgroupMapper.selectByExample(OptgroupExample); return optgroupList; } /** * @Title: addOptgroup * @Description: TODO(新增下拉项) * @param @param optgroup * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) @MethodLog(opera = "OptgroupTree_add") public Object addOptgroup(ParameterOptgroup optgroup) { Subject pricipalSubject = SecurityUtils.getSubject(); User pricipalUser = (User) pricipalSubject.getPrincipal(); JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false ParameterOptgroupExample optgroupExample = new ParameterOptgroupExample(); int count = 0; // 防止下拉项名称重复 optgroupExample.createCriteria().andOptgroupNameEqualTo(optgroup.getOptgroupName()); count = optgroupMapper.countByExample(optgroupExample);// 查找相同名称的下拉项数量 if (count > 0) { returnResult.setMsg("下拉项名称重复"); return returnResult; } optgroup.setOptgroupId(RandomGUID.getRandomGUID()); if (optgroup.getOptgroupPid().equals("ROOT") || optgroup.getOptgroupPid().equals("")) {// 如果父级下拉项的Id为"ROOT"或为空,则将父级下拉项的值设置为null保存到数据库 optgroup.setOptgroupPid(null); } optgroup.setCreater(pricipalUser.getUserId()); optgroup.setCreateTime(new Date()); optgroup.setUpdater(pricipalUser.getUserId()); optgroup.setUpdateTime(new Date()); count = optgroupMapper.insert(optgroup); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("[" + optgroup.getOptgroupName() + "] 下拉项信息已保存"); } else { returnResult.setMsg("发生未知错误,下拉项信息保存失败"); } return returnResult; } /** * @Title: getAllTreeOptgroupNode * @Description: TODO(获取全部的下拉项数据组装成EasyUI树节点JSON) * @param @param virtualRoot 是否构建虚拟ROOT -> 系统下拉项作为导航 * @param @return 设定文件 * @return String 返回类型 * @throws */ public String getAllTreeOptgroupNode(boolean virtualRoot) { List<Tree> items = new ArrayList<Tree>(); if (virtualRoot) { Tree optgroupItem = new Tree();// 增加总的树节点作为下拉项导航 optgroupItem.setId("ROOT"); optgroupItem.setText("下拉项导航"); items.add(optgroupItem); } ParameterOptgroupExample optgroupExample = new ParameterOptgroupExample(); optgroupExample.setOrderByClause("temp_parameter_optgroup.optgroup_num asc"); List<ParameterOptgroup> optgroupList = optgroupMapper.selectByExample(optgroupExample); if (null != optgroupList && optgroupList.size() > 0) { for (ParameterOptgroup optgroup : optgroupList) { Tree item = new Tree();// 将查询到的下拉项记录某些属性值设置在ComboTreeItem中,用于页面的ComboTree的数据绑定 item.setId(optgroup.getOptgroupId()); item.setText(optgroup.getOptgroupName()); if (StringUtils.isNotBlank(optgroup.getOptgroupPid())) { item.setPid(optgroup.getOptgroupPid()); } else if (virtualRoot) { item.setPid("ROOT");// 如果父节点为空说明上一级为总节点 } items.add(item); } } return JackJson.fromObjectToJson(items); } /** * @Title: editOptgroup * @Description: TODO(修改下拉项) * @param @param optgroup * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) @MethodLog(opera = "OptgroupTree_edit") public Object editOptgroup(ParameterOptgroup optgroup) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false List<String> retrunOptgroupList = new ArrayList<String>();// 修改上级所属下拉项时,禁止选择下拉项本身及子级下拉项作为下拉项的父级下拉项 retrunOptgroupList = getOptgroupChild(optgroup.getOptgroupId(), retrunOptgroupList);// 查找下拉项本身及子级下拉项 retrunOptgroupList.add(optgroup.getOptgroupId()); if (retrunOptgroupList.contains(optgroup.getOptgroupPid())) {// 如果用户是选择下拉项本身及子级下拉项作为下拉项的父级下拉项,则返回错误提示信息 returnResult.setMsg("禁止选择该下拉项本身以及子下拉项作为上级下拉项"); return returnResult; } ParameterOptgroupExample optgroupExample = new ParameterOptgroupExample(); int count = 0; // 防止下拉项名称重复 optgroupExample.createCriteria().andOptgroupIdNotEqualTo(optgroup.getOptgroupId()).andOptgroupNameEqualTo(optgroup.getOptgroupName()); count = optgroupMapper.countByExample(optgroupExample);// 查找相同名称的下拉项数量 if (count > 0) { returnResult.setMsg("下拉项名称重复"); return returnResult; } if (optgroup.getOptgroupPid().equals("ROOT") || optgroup.getOptgroupPid().equals("")) {// 如果父级下拉项的Id为"ROOT"或为空,则将父级下拉项的值设置为null保存到数据库 optgroup.setOptgroupPid(null); } ParameterOptgroup oldOptgroup = optgroupMapper.selectByPrimaryKey(optgroup.getOptgroupId()) ; optgroup.setCreater(oldOptgroup.getCreater()); optgroup.setCreateTime(oldOptgroup.getCreateTime()); Subject pricipalSubject = SecurityUtils.getSubject(); User pricipalUser = (User) pricipalSubject.getPrincipal(); optgroup.setUpdater(pricipalUser.getUserId()); optgroup.setUpdateTime(new Date()); count = optgroupMapper.updateByPrimaryKey(optgroup); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("[" + optgroup.getOptgroupName() + "] 下拉项信息已修改"); } else { returnResult.setMsg("发生未知错误,下拉项信息修改失败"); } return returnResult; } /** * @Title: getOptgroupChild * @Description: TODO(递归获取下拉项和下拉项子节点) * @param @param optgroupId * @param @param retrunOptgroupList 返回的所有下拉项信息 * @param @return 设定文件 * @return List<String> 返回类型 * @throws */ private List<String> getOptgroupChild(String optgroupId, List<String> retrunOptgroupList) { ParameterOptgroupExample optgroupExample = new ParameterOptgroupExample(); optgroupExample.createCriteria().andOptgroupPidEqualTo(optgroupId);// 查询子下拉项 List<ParameterOptgroup> optgroupList = optgroupMapper.selectByExample(optgroupExample); if (optgroupList.size() > 0) {// 如果存在子下拉项则遍历 for (ParameterOptgroup optgroup : optgroupList) { this.getOptgroupChild(optgroup.getOptgroupId(), retrunOptgroupList);// 递归查询是否存在子下拉项 } } retrunOptgroupList.add(optgroupId); return retrunOptgroupList; } /** * @Title: delArea * @Description: TODO(删除下拉项) * @param @param optgroupId * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) @MethodLog(opera = "OptgroupTree_del") public Object delOptgroup(String optgroupId) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false if (StringUtils.isBlank(optgroupId)) {// 判断是否选择一条下拉项信息 returnResult.setMsg("请选择一条下拉项信息,再进行删除"); return returnResult; } ParameterOptgroupExample parameterOptgroupExample = new ParameterOptgroupExample(); parameterOptgroupExample.createCriteria().andOptgroupPidEqualTo(optgroupId); if (optgroupMapper.countByExample(parameterOptgroupExample) > 0) {// 判断该下拉项是否存在子级下拉项,有则不能删除 returnResult.setMsg("该下拉项存在子级下拉项,如需删除请先删除子下拉项"); }else { ParameterOptgroupValueExample parameterOptgroupValueExample = new ParameterOptgroupValueExample(); parameterOptgroupValueExample.createCriteria().andOptgroupIdEqualTo(optgroupId); if (optgroupValueMapper.countByExample(parameterOptgroupValueExample)>0) {// 判断该下拉项是否存在所属下拉值,有则不能删除 returnResult.setMsg("该下拉项存在所属下拉值,如需删除请先删除所属下拉值"); }else { ParameterOptgroup optgroup= optgroupMapper.selectByPrimaryKey(optgroupId); int result = optgroupMapper.deleteByPrimaryKey(optgroupId);//根据下拉项Id,进行删除下拉项 if (result == 1) { returnResult.setSuccess(true); returnResult.setMsg("[" + optgroup.getOptgroupName() + "] 下拉项信息已删除"); } else { returnResult.setMsg("发生未知错误,下拉项信息删除失败"); } } } return returnResult; } }
GlacierSoft/netloan-project
netloan-module/src/main/java/com/glacier/netloan/service/basicdatas/ParameterOptgroupService.java
Java
gpl-3.0
12,560
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.kisti.science.platform.app.service; import com.liferay.portal.service.InvokableLocalService; /** * @author Jerry H. Seo & Young Suh * @generated */ public class PortTypeLocalServiceClp implements PortTypeLocalService { public PortTypeLocalServiceClp(InvokableLocalService invokableLocalService) { _invokableLocalService = invokableLocalService; _methodName0 = "addPortType"; _methodParameterTypes0 = new String[] { "com.kisti.science.platform.app.model.PortType" }; _methodName1 = "createPortType"; _methodParameterTypes1 = new String[] { "long" }; _methodName2 = "deletePortType"; _methodParameterTypes2 = new String[] { "long" }; _methodName3 = "deletePortType"; _methodParameterTypes3 = new String[] { "com.kisti.science.platform.app.model.PortType" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "dynamicQueryCount"; _methodParameterTypes9 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "com.liferay.portal.kernel.dao.orm.Projection" }; _methodName10 = "fetchPortType"; _methodParameterTypes10 = new String[] { "long" }; _methodName11 = "fetchPortTypeByUuidAndCompanyId"; _methodParameterTypes11 = new String[] { "java.lang.String", "long" }; _methodName12 = "getPortType"; _methodParameterTypes12 = new String[] { "long" }; _methodName13 = "getPersistedModel"; _methodParameterTypes13 = new String[] { "java.io.Serializable" }; _methodName14 = "getPortTypeByUuidAndCompanyId"; _methodParameterTypes14 = new String[] { "java.lang.String", "long" }; _methodName15 = "getPortTypes"; _methodParameterTypes15 = new String[] { "int", "int" }; _methodName16 = "getPortTypesCount"; _methodParameterTypes16 = new String[] { }; _methodName17 = "updatePortType"; _methodParameterTypes17 = new String[] { "com.kisti.science.platform.app.model.PortType" }; _methodName18 = "getBeanIdentifier"; _methodParameterTypes18 = new String[] { }; _methodName19 = "setBeanIdentifier"; _methodParameterTypes19 = new String[] { "java.lang.String" }; _methodName21 = "createPortType"; _methodParameterTypes21 = new String[] { "java.lang.String", "com.liferay.portal.service.ServiceContext" }; _methodName22 = "existPortType"; _methodParameterTypes22 = new String[] { "java.lang.String" }; _methodName23 = "setPortTypeInputdeckForm"; _methodParameterTypes23 = new String[] { "long", "java.lang.String" }; } @Override public com.kisti.science.platform.app.model.PortType addPortType( com.kisti.science.platform.app.model.PortType portType) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName0, _methodParameterTypes0, new Object[] { ClpSerializer.translateInput(portType) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType createPortType( long portTypeId) { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName1, _methodParameterTypes1, new Object[] { portTypeId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType deletePortType( long portTypeId) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName2, _methodParameterTypes2, new Object[] { portTypeId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType deletePortType( com.kisti.science.platform.app.model.PortType portType) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName3, _methodParameterTypes3, new Object[] { ClpSerializer.translateInput(portType) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName4, _methodParameterTypes4, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.kernel.dao.orm.DynamicQuery)ClpSerializer.translateOutput(returnObj); } @Override @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName5, _methodParameterTypes5, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @Override @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName6, _methodParameterTypes6, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @Override @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName7, _methodParameterTypes7, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end, ClpSerializer.translateInput(orderByComparator) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @Override public long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName8, _methodParameterTypes8, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Long)returnObj).longValue(); } @Override public long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, com.liferay.portal.kernel.dao.orm.Projection projection) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName9, _methodParameterTypes9, new Object[] { ClpSerializer.translateInput(dynamicQuery), ClpSerializer.translateInput(projection) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Long)returnObj).longValue(); } @Override public com.kisti.science.platform.app.model.PortType fetchPortType( long portTypeId) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName10, _methodParameterTypes10, new Object[] { portTypeId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType fetchPortTypeByUuidAndCompanyId( java.lang.String uuid, long companyId) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName11, _methodParameterTypes11, new Object[] { ClpSerializer.translateInput(uuid), companyId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType getPortType( long portTypeId) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName12, _methodParameterTypes12, new Object[] { portTypeId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public com.liferay.portal.model.PersistedModel getPersistedModel( java.io.Serializable primaryKeyObj) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName13, _methodParameterTypes13, new Object[] { ClpSerializer.translateInput(primaryKeyObj) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.model.PersistedModel)ClpSerializer.translateOutput(returnObj); } @Override public com.kisti.science.platform.app.model.PortType getPortTypeByUuidAndCompanyId( java.lang.String uuid, long companyId) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName14, _methodParameterTypes14, new Object[] { ClpSerializer.translateInput(uuid), companyId }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public java.util.List<com.kisti.science.platform.app.model.PortType> getPortTypes( int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName15, _methodParameterTypes15, new Object[] { start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List<com.kisti.science.platform.app.model.PortType>)ClpSerializer.translateOutput(returnObj); } @Override public int getPortTypesCount() throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName16, _methodParameterTypes16, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Integer)returnObj).intValue(); } @Override public com.kisti.science.platform.app.model.PortType updatePortType( com.kisti.science.platform.app.model.PortType portType) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName17, _methodParameterTypes17, new Object[] { ClpSerializer.translateInput(portType) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public java.lang.String getBeanIdentifier() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName18, _methodParameterTypes18, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.lang.String)ClpSerializer.translateOutput(returnObj); } @Override public void setBeanIdentifier(java.lang.String beanIdentifier) { try { _invokableLocalService.invokeMethod(_methodName19, _methodParameterTypes19, new Object[] { ClpSerializer.translateInput(beanIdentifier) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } } @Override public java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { throw new UnsupportedOperationException(); } @Override public com.kisti.science.platform.app.model.PortType createPortType( java.lang.String portTypeName, com.liferay.portal.service.ServiceContext sc) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName21, _methodParameterTypes21, new Object[] { ClpSerializer.translateInput(portTypeName), ClpSerializer.translateInput(sc) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.kisti.science.platform.app.model.PortType)ClpSerializer.translateOutput(returnObj); } @Override public boolean existPortType(java.lang.String portTypeName) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName22, _methodParameterTypes22, new Object[] { ClpSerializer.translateInput(portTypeName) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Boolean)returnObj).booleanValue(); } @Override public void setPortTypeInputdeckForm(long portTypeId, java.lang.String inputdeckForm) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { try { _invokableLocalService.invokeMethod(_methodName23, _methodParameterTypes23, new Object[] { portTypeId, ClpSerializer.translateInput(inputdeckForm) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } } private InvokableLocalService _invokableLocalService; private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName16; private String[] _methodParameterTypes16; private String _methodName17; private String[] _methodParameterTypes17; private String _methodName18; private String[] _methodParameterTypes18; private String _methodName19; private String[] _methodParameterTypes19; private String _methodName21; private String[] _methodParameterTypes21; private String _methodName22; private String[] _methodParameterTypes22; private String _methodName23; private String[] _methodParameterTypes23; }
queza85/edison
edison-portal-framework/edison-board-2016-portlet/ScienceApp-portlet/docroot/WEB-INF/service/com/kisti/science/platform/app/service/PortTypeLocalServiceClp.java
Java
gpl-3.0
25,890
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.sql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLStatementImpl; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; import com.alibaba.druid.sql.visitor.SQLASTVisitor; import java.util.ArrayList; import java.util.List; public class SQLReplaceStatement extends SQLStatementImpl { protected boolean lowPriority = false; protected boolean delayed = false; protected SQLExprTableSource tableSource; protected final List<SQLExpr> columns = new ArrayList<SQLExpr>(); protected List<SQLInsertStatement.ValuesClause> valuesList = new ArrayList<SQLInsertStatement.ValuesClause>(); protected SQLQueryExpr query; public SQLName getTableName() { if (tableSource == null) { return null; } return (SQLName) tableSource.getExpr(); } public void setTableName(SQLName tableName) { this.setTableSource(new SQLExprTableSource(tableName)); } public SQLExprTableSource getTableSource() { return tableSource; } public void setTableSource(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSource = tableSource; } public List<SQLExpr> getColumns() { return columns; } public void addColumn(SQLExpr column) { if (column != null) { column.setParent(this); } this.columns.add(column); } public boolean isLowPriority() { return lowPriority; } public void setLowPriority(boolean lowPriority) { this.lowPriority = lowPriority; } public boolean isDelayed() { return delayed; } public void setDelayed(boolean delayed) { this.delayed = delayed; } public SQLQueryExpr getQuery() { return query; } public void setQuery(SQLQueryExpr query) { if (query != null) { query.setParent(this); } this.query = query; } public List<SQLInsertStatement.ValuesClause> getValuesList() { return valuesList; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, tableSource); acceptChild(visitor, columns); acceptChild(visitor, valuesList); acceptChild(visitor, query); } visitor.endVisit(this); } }
zuonima/sql-utils
src/main/java/com/alibaba/druid/sql/ast/statement/SQLReplaceStatement.java
Java
gpl-3.0
3,169
/* * Copyright 2011-2014 Will Tipton, Richard Hennig, Ben Revard, Stewart Wenner This file is part of the Genetic Algorithm for Structure and Phase Prediction (GASP). GASP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GASP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GASP. If not, see <http://www.gnu.org/licenses/>. */ package ga; import java.util.ArrayList; import java.util.List; import crystallography.Cell; import crystallography.Site; import pdvisual.PDAnalyzer; import utility.Utility; import utility.Vect; import vasp.VaspOut; public class ClusterObjFcn extends ObjectiveFunction { List<String> objFcnArgs; StructureOrg org; double padding; public ClusterObjFcn(List<String> subArray, Organism o) { padding = Double.parseDouble(subArray.get(0)); objFcnArgs = Utility.subList(subArray, 1); org = (StructureOrg)o; } private void padOrg() { Cell oldCell = org.getCell(); List<Vect> basis = new ArrayList<Vect>(); basis.add(new Vect(padding, 0.0, 0.0)); basis.add(new Vect(0.0, padding, 0.0)); basis.add(new Vect(0.0, 0.0, padding)); List<Site> newSites = new ArrayList<Site>(); for (Site s : oldCell.getSites()) newSites.add(new Site(s.getElement(), s.getCoords().plus(new Vect(padding/2, padding/2, padding/2)))); Cell newCell = new Cell(basis, newSites, oldCell.getLabel()); org.setCell(newCell, false); } private void unpadOrg() { Cell oldCell = org.getCell(); if (oldCell == null) return; double mid = GAParameters.getParams().getMinInteratomicDistance(); // get a bounding box for the atoms double minx = Double.MAX_VALUE; double miny = Double.MAX_VALUE; double minz = Double.MAX_VALUE; double maxx = Double.MIN_VALUE; double maxy = Double.MIN_VALUE; double maxz = Double.MIN_VALUE; for (Site s : oldCell.getSites()) { List<Double> cartComps = s.getCoords().getCartesianComponents(); minx = Math.min(minx, cartComps.get(0)); miny = Math.min(miny, cartComps.get(1)); minz = Math.min(minz, cartComps.get(2)); maxx = Math.max(maxx, cartComps.get(0)); maxy = Math.max(maxy, cartComps.get(1)); maxz = Math.max(maxz, cartComps.get(2)); } double xlen = maxx - minx; double ylen = maxy - miny; double zlen = maxz - minz; // make new list of sites where we subtract (minx,miny,minz) off all the old ones List<Site> newSites = new ArrayList<Site>(); Vect minv = new Vect(minx - mid/2, miny - mid/2, minz - mid/2); for (Site s : oldCell.getSites()) newSites.add(new Site(s.getElement(), s.getCoords().subtract(minv))); // make a new box which is xlen x ylen x zlen plus the min interatomic distance List<Vect> newBasis = new ArrayList<Vect>(); newBasis.add(new Vect(xlen + mid, 0.0, 0.0)); newBasis.add(new Vect(0.0, ylen + mid, 0.0)); newBasis.add(new Vect(0.0, 0.0, zlen + mid)); Cell newCell = new Cell(newBasis, newSites, oldCell.getLabel()); org.setCell(newCell, false); } public void run() { padOrg(); ObjectiveFunction energyFcn = ObjFcnFactory.getObjectiveFunctionInstance(org, objFcnArgs); // relax the cell - have to wait for it to finish before using results Thread t = energyFcn.evaluate(); try { if (t != null) t.join(); } catch (InterruptedException x) { GAOut.out().stdout("InterruptedException in energy calc thread in ClusterObjFcn: " + x.getMessage(), GAOut.NOTICE, org.getID()); } // updating structure w/ relaxed version is this done in EPA already //org.setValue((new PDAnalyzer(pdbuilder.getPDData())).getEnergyPerAtomAboveHull(org)); unpadOrg(); } // dont update numCalculations when implementing this.. the underlying objfcn will do it public Thread evaluate() { // short circuit here if we've done the calculation already if (org.knowsValue()) return null; // start the calculation and return the Thread Thread t = new Thread(this); t.start(); return t; } // an ObjectiveFunction should also overload toString(); public String toString() { return "ClusterObjFcn"; // TODO: more? } // for testing public static void main(String args[]) { /* String arg[] = {"20", "hi"}; StructureOrg c = new StructureOrg(VaspOut.getPOSCAR("/home/wtipton/POSCAR")); ClusterObjFcn cof = new ClusterObjFcn(arg, c); cof.padOrg(); c.getCell().writeCIF("/home/wtipton/POSCAR.padded.cif"); cof.unpadOrg(); c.getCell().writeCIF("/home/wtipton/POSCAR.unpadded.cif"); */ } }
henniggroup/gasp
src/ga/ClusterObjFcn.java
Java
gpl-3.0
4,940
/************************************************************************************************** * Copyright 2009 Chris Maguire ([email protected]) * * * * Flexmud is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * Flexmud is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with flexmud. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************************************/ package flexmud.engine.cmd.game; import flexmud.engine.cmd.Command; import flexmud.engine.context.ClientContextHandler; import flexmud.engine.exec.Executor; import flexmud.net.Client; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; public class InvalidGameCommandCommand extends Command { private static final Logger LOGGER = Logger.getLogger(InvalidGameCommandCommand.class); @Override public void run() { List<Command> commands = new ArrayList<Command>(); Client client = getClient(); ClientContextHandler clientContextHandler = client.getClientContextHandler(); client.sendTextLn("Huh?"); Command promptCommand = clientContextHandler.getPromptCommand(); promptCommand.setClient(client); Executor.exec(promptCommand); } }
cwmaguire/flexmud
src/flexmud/engine/cmd/game/InvalidGameCommandCommand.java
Java
gpl-3.0
2,485
/* * Copyright (C) 2017 The Android Open Source Project * * 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.enrico.launcher3; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.view.View.AccessibilityDelegate; public abstract class BaseActivity extends Activity { protected DeviceProfile mDeviceProfile; public DeviceProfile getDeviceProfile() { return mDeviceProfile; } public AccessibilityDelegate getAccessibilityDelegate() { return null; } public boolean isInMultiWindowModeCompat() { return AndroidVersion.isAtLeastNougat && isInMultiWindowMode(); } public static BaseActivity fromContext(Context context) { if (context instanceof BaseActivity) { return (BaseActivity) context; } return ((BaseActivity) ((ContextWrapper) context).getBaseContext()); } }
enricocid/LaunchEnr
Launcher3-O-r12/src/main/java/com/enrico/launcher3/BaseActivity.java
Java
gpl-3.0
1,450
package Input; import org.lwjgl.glfw.GLFWCursorPosCallback; public class MousePos extends GLFWCursorPosCallback{ public static double x, y; @Override public void invoke(long window, double xP, double yP) { // TODO Auto-generated method stub x = xP; y = yP; } }
AlronDerRe/LWJGL3_basic_code
basic lwjgl3/src/Input/MousePos.java
Java
gpl-3.0
280
/* * Copyright (C) 2010---2013 星星(wuweixing)<[email protected]> * * This file is part of Wabacus * * Wabacus is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.wabacus.system.component.application.report.configbean.editablereport; import com.wabacus.config.component.application.report.ColBean; import com.wabacus.util.Consts; public class EditableReportDeleteDataBean extends AbsEditableReportEditDataBean { private String deleteConfirmMessage=null; public EditableReportDeleteDataBean(IEditableReportEditGroupOwnerBean owner) { super(owner); } public String getDeleteConfirmMessage() { return deleteConfirmMessage; } public void setDeleteConfirmMessage(String deleteConfirmMessage) { this.deleteConfirmMessage=deleteConfirmMessage; } protected void setParamBeanInfoOfColBean(ColBean cbUpdateSrc,EditableReportParamBean paramBean,String configColProperty,String reportTypeKey) { if(Consts.COL_DISPLAYTYPE_HIDDEN.equals(cbUpdateSrc.getDisplaytype())) { if(configColProperty.endsWith("__old")) configColProperty=configColProperty.substring(0,configColProperty.length()-"__old".length()); }else if(configColProperty.endsWith("__old")) { EditableReportColBean ercbeanUpdated=(EditableReportColBean)cbUpdateSrc.getExtendConfigDataForReportType(reportTypeKey); if(ercbeanUpdated==null||ercbeanUpdated.getEditableWhenUpdate()<=0) { configColProperty=configColProperty.substring(0,configColProperty.length()-"__old".length()); } } paramBean.setParamname(configColProperty); } }
foxerfly/Wabacus4.1src
src/com/wabacus/system/component/application/report/configbean/editablereport/EditableReportDeleteDataBean.java
Java
gpl-3.0
2,305
package com.howmuchof.squirrels.android; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /* * How many squirrels: tool for young naturalist * * This application is created within the internship * in the Education Department of Tomsksoft, http://tomsksoft.com * Idea and leading: Sergei Borisov * * This software is licensed under a GPL v3 * http://www.gnu.org/licenses/gpl.txt * * Created by Viacheslav Voronov on 4/13/2014 */ public class MainActivity extends Activity { ActionBar.Tab mainTab, graphViewTab, listViewTab; Fragment mainFragment = new MainFragmentActivity(); Fragment listViewFragment = new ListViewFragment(); Fragment graphViewFragment = new GraphViewFragment(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } mainTab = actionBar.newTab().setText(R.string.mainTabName); graphViewTab = actionBar.newTab().setText(R.string.graphViewTabName); listViewTab = actionBar.newTab().setText(R.string.listViewTabName); mainTab.setTabListener(new TabListener(mainFragment)); graphViewTab.setTabListener(new TabListener(graphViewFragment)); listViewTab.setTabListener(new TabListener(listViewFragment)); actionBar.addTab(mainTab); actionBar.addTab(listViewTab); actionBar.addTab(graphViewTab); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0,1,0,R.string.settingsPageTitle); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(this, SettingsActivity.class); int tabNumber = 0; ActionBar actionBar = this.getActionBar(); if (null != actionBar) { tabNumber = actionBar.getSelectedTab().getPosition(); } startActivityForResult(intent, tabNumber); onResume(); return true; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { ActionBar actionBar = this.getActionBar(); if (null != actionBar) { ActionBar.Tab tab = actionBar.getTabAt(requestCode); actionBar.selectTab(tab); } } public class TabListener implements ActionBar.TabListener { Fragment fragment; public TabListener(Fragment fragment) { this.fragment = fragment; } public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { ft.replace(R.id.fragment_container, fragment); } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { ft.remove(fragment); } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // nothing done here } } }
tomsksoft/how-many-squirrels-android
app/src/main/java/com/howmuchof/squirrels/android/MainActivity.java
Java
gpl-3.0
3,345
/* * DefaultDatabaseProcedure.java * * Copyright (C) 2002-2017 Takis Diakoumis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.executequery.databaseobjects.impl; import org.executequery.databaseobjects.DatabaseMetaTag; import org.executequery.databaseobjects.DatabaseProcedure; /** * Default database procedure implementation. * * @author Takis Diakoumis */ public class DefaultDatabaseProcedure extends DefaultDatabaseExecutable implements DatabaseProcedure { /** * Creates a new instance of DefaultDatabaseProcedure. */ public DefaultDatabaseProcedure() {} /** * Creates a new instance of DefaultDatabaseProcedure */ public DefaultDatabaseProcedure(DatabaseMetaTag metaTagParent, String name) { super(metaTagParent, name); } /** * Creates a new instance of DefaultDatabaseProcedure with * the specified values. */ public DefaultDatabaseProcedure(String schema, String name) { setName(name); setSchemaName(schema); } /** * Returns the database object type. * * @return the object type */ public int getType() { return PROCEDURE; } /** * Returns the meta data key name of this object. * * @return the meta data key name. */ public String getMetaDataKey() { return META_TYPES[PROCEDURE]; } }
takisd123/executequery
src/org/executequery/databaseobjects/impl/DefaultDatabaseProcedure.java
Java
gpl-3.0
2,038
package jademula; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Input implements KeyListener, Serializable { private static final long serialVersionUID = 1L; private int button; private List<Key> keys = new ArrayList<Key>(); //wird in Control-Config konfiguriert //private List<Integer> emitters = new ArrayList<Integer>(); //wird in Handy-Config konfiguriert public Input(int button) { this.button = button; } public void keyPressed() { Handy.getCurrent().keyPressed(button); } public void keyReleased() { Handy.getCurrent().keyReleased(button); } public void add(Key key) { if (keys.contains(key)) return; key.addButtonListener(this); keys.add(key); } /*public void addEmitter(int emitter) { emitters.add(emitter); } public List<Integer> getEmitters() { return emitters; }*/ public void clearKeys() { for (Key key : keys) key.removeButtonListener(this); keys.clear(); } /*public void clearEmitters() { emitters.clear(); }*/ public String toString() { if (keys.size() == 0) return " "; String ret = ""; boolean first = true; for (Key key : keys) { if (first) { ret += key.toString(); first = false; } else ret += ", " + key.toString(); } return ret; } public void checkKey(Key key) { //können Keys übrigbleiben for (Key k : keys) { if (k.equals(key)) { keys.remove(k); keys.add(key); key.addButtonListener(this); return; } } } }
RobDangerous/Jademula
src/jademula/Input.java
Java
gpl-3.0
1,572
/* * Copyright (C) 2008 Universidade Federal de Campina Grande * * This file is part of Commune. * * Commune is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package br.edu.ufcg.lsd.commune.functionaltests.data.parametersdeployment; import br.edu.ufcg.lsd.commune.api.Remote; @Remote public interface MyInterface12 { public void hereIsParameter(MyParameter7 myParameter); }
OurGrid/commune
src/main/test/br/edu/ufcg/lsd/commune/functionaltests/data/parametersdeployment/MyInterface12.java
Java
gpl-3.0
1,005
package org.asamk.signal.commands; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import org.asamk.signal.commands.exceptions.CommandException; import org.asamk.signal.manager.Manager; import org.asamk.signal.output.OutputWriter; import org.asamk.signal.util.CommandUtil; public class RemoveContactCommand implements JsonRpcLocalCommand { @Override public String getName() { return "removeContact"; } @Override public void attachToSubparser(final Subparser subparser) { subparser.help("Remove the details of a given contact"); subparser.addArgument("recipient").help("Contact number"); subparser.addArgument("--forget") .action(Arguments.storeTrue()) .help("Delete all data associated with this contact, including identity keys and sessions."); } @Override public void handleCommand( final Namespace ns, final Manager m, final OutputWriter outputWriter ) throws CommandException { var recipientString = ns.getString("recipient"); var recipient = CommandUtil.getSingleRecipientIdentifier(recipientString, m.getSelfNumber()); var forget = Boolean.TRUE == ns.getBoolean("forget"); if (forget) { m.deleteRecipient(recipient); } else { m.deleteContact(recipient); } } }
AsamK/signal-cli
src/main/java/org/asamk/signal/commands/RemoveContactCommand.java
Java
gpl-3.0
1,461
package io.github.mbarre.schemacrawler.tool.linter; /*- * #%L * Additional SchemaCrawler Lints * %% * Copyright (C) 2015 - 2019 github * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import io.github.mbarre.schemacrawler.test.utils.LintWrapper; import io.github.mbarre.schemacrawler.test.utils.PostgreSqlDatabase; import schemacrawler.schemacrawler.SchemaCrawlerOptions; import schemacrawler.schemacrawler.SchemaCrawlerOptionsBuilder; import schemacrawler.schemacrawler.SchemaInfoLevelBuilder; import schemacrawler.tools.lint.LinterRegistry; public class LinterTimeStampWithOutTimeZoneColumnTest extends BaseLintTest { private static final String CHANGE_LOG_TIMESTAMP_CHECK = "src/test/db/liquibase/LinterTimeStampWithOutTimeZoneColumn/db.changelog.xml"; private static PostgreSqlDatabase database; @BeforeClass public static void init(){ database = new PostgreSqlDatabase(); database.setUp(CHANGE_LOG_TIMESTAMP_CHECK); } @Test public void testLint() throws Exception{ final LinterRegistry registry = new LinterRegistry(); Assert.assertTrue(registry.hasLinter(LinterTimeStampWithOutTimeZoneColumn.class.getName())); final SchemaCrawlerOptions options = SchemaCrawlerOptionsBuilder.builder().withSchemaInfoLevel(SchemaInfoLevelBuilder.standard()).toOptions(); Connection connection = DriverManager.getConnection(PostgreSqlDatabase.CONNECTION_STRING, PostgreSqlDatabase.USER_NAME, database.getPostgresPassword()); List<LintWrapper> lints = executeToJsonAndConvertToLintList(LinterTimeStampWithOutTimeZoneColumn.class.getSimpleName(), options, connection); Assert.assertEquals(1,lints.size()); int index = 0; Assert.assertEquals(LinterTimeStampWithOutTimeZoneColumn.class.getName(), lints.get(index).getId()); Assert.assertEquals("public.test_timetsamp_type.created_at", lints.get(index).getValue()); Assert.assertEquals("Timestamp without time zone (timestamp) is not a permitted data type. Use timestamp with time zone (timestamptz)", lints.get(index).getDescription()); Assert.assertEquals("critical", lints.get(index).getSeverity()); } }
mbarre/schemacrawler-additionnallints
src/test/java/io/github/mbarre/schemacrawler/tool/linter/LinterTimeStampWithOutTimeZoneColumnTest.java
Java
gpl-3.0
2,889
/* * Created on 07-sep-2007 * * gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * [email protected] * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * [email protected] */ /* CVS MESSAGES: * * $Id: * $Log: * */ package org.gvsig.topology.topologyrules; import java.awt.Color; import java.util.ArrayList; import java.util.List; import org.gvsig.fmap.core.FGeometryUtil; import org.gvsig.fmap.core.NewFConverter; import org.gvsig.jts.SnapLineStringSelfIntersectionChecker; import org.gvsig.topology.AbstractTopologyRule; import org.gvsig.topology.IRuleWithClusterTolerance; import org.gvsig.topology.ITopologyErrorFix; import org.gvsig.topology.Messages; import org.gvsig.topology.Topology; import org.gvsig.topology.TopologyError; import org.gvsig.topology.TopologyRuleDefinitionException; import org.gvsig.topology.errorfixes.SplitSelfIntersectingLineFix; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.iver.cit.gvsig.fmap.core.FShape; import com.iver.cit.gvsig.fmap.core.IFeature; import com.iver.cit.gvsig.fmap.core.IGeometry; import com.iver.cit.gvsig.fmap.core.ShapeFactory; import com.iver.cit.gvsig.fmap.core.SymbologyFactory; import com.iver.cit.gvsig.fmap.core.symbols.MultiShapeSymbol; import com.iver.cit.gvsig.fmap.layers.FLyrVect; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.LineString; /** *Lines of a layer must not have self intersections. *JTS allows this. This is one of the restrictions that must *not have pseudonodos checks. * */ public class LineMustNotSelfIntersect extends AbstractTopologyRule implements IRuleWithClusterTolerance { final static String RULE_NAME = Messages.getText("line_must_not_self_intersect"); private static List<ITopologyErrorFix> automaticErrorFixes = new ArrayList<ITopologyErrorFix>(); static{ automaticErrorFixes.add(new SplitSelfIntersectingLineFix()); } private static final Color DEFAULT_ERROR_COLOR = Color.YELLOW; private static final MultiShapeSymbol DEFAULT_ERROR_SYMBOL = (MultiShapeSymbol) SymbologyFactory.createDefaultSymbolByShapeType(FShape.MULTI, DEFAULT_ERROR_COLOR); static{ DEFAULT_ERROR_SYMBOL.setDescription(RULE_NAME); DEFAULT_ERROR_SYMBOL.setSize(3); } private double clusterTolerance; /** * Symbol for topology errors caused by a violation of this rule. */ private MultiShapeSymbol errorSymbol = DEFAULT_ERROR_SYMBOL; public LineMustNotSelfIntersect(Topology topology, FLyrVect originLyr, double clusterTolerance) { super(topology, originLyr); setClusterTolerance(clusterTolerance); } public LineMustNotSelfIntersect(){} public String getName() { return RULE_NAME; } public void checkPreconditions() throws TopologyRuleDefinitionException { try { if( FGeometryUtil.getDimensions(this.originLyr.getShapeType()) == 0){ throw new TopologyRuleDefinitionException("Capa con tipo de geometria incorrecto para la regla "+this.getClassName()); } } catch (ReadDriverException e) { throw new TopologyRuleDefinitionException("Error de driver al verificar el tipo de geometria de la capa "+originLyr.getName()); } } public void validateFeature(IFeature feature) { IGeometry geometry = feature.getGeometry(); Geometry jtsGeometry = NewFConverter.toJtsGeometry(geometry); process(jtsGeometry, feature); } private void process(Geometry geometry, IFeature feature){ if( ! (geometry instanceof LineString) && ! (geometry instanceof GeometryCollection)) return; if(geometry instanceof GeometryCollection){ GeometryCollection geomCol = (GeometryCollection) geometry; for(int i = 0; i < geomCol.getNumGeometries(); i++){ Geometry geom = geomCol.getGeometryN(i); process(geom, feature); } }else{ LineString lineString = (LineString) geometry; SnapLineStringSelfIntersectionChecker checker = new SnapLineStringSelfIntersectionChecker(lineString, clusterTolerance); if(checker.hasSelfIntersections()){ Coordinate[] coords = checker.getSelfIntersections(); double[] x = new double[coords.length]; double[] y = new double[coords.length]; for(int i = 0; i < coords.length; i++){ x[i] = coords[i].x; y[i] = coords[i].y; } IGeometry errorGeometry = ShapeFactory.createMultipoint2D(x, y); TopologyError topologyError = new TopologyError(errorGeometry, this, feature, topology); topologyError.setID(errorContainer.getErrorFid()); addTopologyError(topologyError); }//if selfintersections } } public double getClusterTolerance() { return clusterTolerance; } public void setClusterTolerance(double clusterTolerance) { this.clusterTolerance = clusterTolerance; } public boolean acceptsOriginLyr(FLyrVect lyr) { try { return (FGeometryUtil.getDimensions(lyr.getShapeType()) != 0); } catch (ReadDriverException e) { e.printStackTrace(); return false; } } public List<ITopologyErrorFix> getAutomaticErrorFixes() { return automaticErrorFixes; } public MultiShapeSymbol getDefaultErrorSymbol() { return DEFAULT_ERROR_SYMBOL; } public MultiShapeSymbol getErrorSymbol() { return errorSymbol; } public void setErrorSymbol(MultiShapeSymbol errorSymbol) { this.errorSymbol = errorSymbol; } public ITopologyErrorFix getDefaultFixFor(TopologyError topologyError){ return automaticErrorFixes.get(0); } }
iCarto/siga
libTopology/src/org/gvsig/topology/topologyrules/LineMustNotSelfIntersect.java
Java
gpl-3.0
6,577
package domain.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import domain.model.PlaneStatus; public class TestDaoPlaneStatus { private static final String ERROR_REMOVING = "Error removing one planeStatus from database"; private static final String ERROR_LOAD = "Error load all planeStatus from database"; private static final String ERROR_INSERT = "Error insert planeStatus into database"; @Test public void testInsertPlaneStatusIntoDB() { PlaneStatus planeStatus = Initializer.initPlaneStatus(); boolean result = HibernateGeneric.saveObject(planeStatus); assertEquals(ERROR_INSERT, true, result); } @Test public void testInsertPlaneStatusWithoutNameIntoDB() { boolean result = HibernateGeneric.saveObject(new PlaneStatus()); assertEquals(ERROR_INSERT, false, result); } @Test public void testLoadAllStates() { assertNotNull(ERROR_LOAD, HibernateGeneric.loadAllObjects(new PlaneStatus())); } @Test public void testRemoveOneSpecificPlaneStatus() { PlaneStatus planeStatus = Initializer.initPlaneStatus(); HibernateGeneric.saveObject(planeStatus); PlaneStatus s = (PlaneStatus) HibernateGeneric.loadAllObjects(new PlaneStatus()).get(0); boolean result = HibernateGeneric.deleteObject(s); assertEquals(ERROR_REMOVING, true, result); } }
Maracars/POPBL5
tests/domain/dao/TestDaoPlaneStatus.java
Java
gpl-3.0
1,361
/******************************************************************************* * Copyright (c) 2014, 2015 Scott Clarke ([email protected]). * * This file is part of Dawg6's Demon Hunter DPS Calculator. * * Dawg6's Demon Hunter DPS Calculator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dawg6's Demon Hunter DPS Calculator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.dawg6.web.dhcalc.client; import java.util.Collections; import java.util.Map; import java.util.Vector; import com.dawg6.web.dhcalc.shared.calculator.ActiveSkill; import com.dawg6.web.dhcalc.shared.calculator.Build; import com.dawg6.web.dhcalc.shared.calculator.Rune; import com.dawg6.web.dhcalc.shared.calculator.Util; import com.dawg6.web.dhcalc.shared.calculator.stats.DBStatistics; import com.dawg6.web.dhcalc.shared.calculator.stats.DpsTableEntry; import com.dawg6.web.dhcalc.shared.calculator.stats.StatCategory; import com.dawg6.web.dhcalc.shared.calculator.stats.StatHolder; import com.dawg6.web.dhcalc.shared.calculator.stats.StatSorter; import com.dawg6.web.dhcalc.shared.calculator.stats.Statistics; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CaptionPanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SimpleCheckBox; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; public class StatsPanel extends Composite { private final Label totalLabel; private final FlexTable mainTable; private final FlexTable filterTable; private final SimpleCheckBox sentry; private final ListBox sentryRune; private final ListBox skill1; // private final ListBox rune3; // private final ListBox skill3; private final ListBox rune2; private final ListBox skill2; private final ListBox rune1; private final FlexTable buildTable; private final ListBox[] skills; private final ListBox[] runes; private boolean disableListeners = false; private DBStatistics stats; private Vector<StatHolder> statList; private ActionListener actionListener; public StatsPanel() { CaptionPanel cptnpnlNewPanel = new CaptionPanel("Statistics"); initWidget(cptnpnlNewPanel); cptnpnlNewPanel.setSize("1005px", "619px"); FlexTable flexTable = new FlexTable(); SimplePanel panel = new SimplePanel(); panel.setWidget(flexTable); flexTable.setHeight("554px"); cptnpnlNewPanel.setContentWidget(panel); panel.setSize("100%", "100%"); Label lblNewLabel = new Label("Total # of Profiles Analyzed:"); lblNewLabel.setStyleName("boldText"); lblNewLabel.setWordWrap(false); flexTable.setWidget(0, 0, lblNewLabel); totalLabel = new Label("Loading..."); flexTable.setWidget(0, 1, totalLabel); CaptionPanel cptnpnlNewPanel_1 = new CaptionPanel("Global Statistics"); flexTable.setWidget(1, 0, cptnpnlNewPanel_1); mainTable = new FlexTable(); mainTable.setStyleName("statsTable"); SimplePanel panel2 = new SimplePanel(); panel2.setWidget(mainTable); cptnpnlNewPanel_1.setContentWidget(panel2); Label lblStatistic = new Label("Statistic"); lblStatistic.setStyleName("boldText"); lblStatistic.setWordWrap(false); mainTable.setWidget(0, 0, lblStatistic); Label lblAverage = new Label("Average DPS"); lblAverage.setWordWrap(false); lblAverage.setStyleName("boldText"); mainTable.setWidget(0, 1, lblAverage); Label lblNewLabel_1 = new Label("Max DPS"); lblNewLabel_1.setStyleName("boldText"); lblNewLabel_1.setWordWrap(false); mainTable.setWidget(0, 2, lblNewLabel_1); Label lblProfile = new Label("Link to Profile"); lblProfile.setWordWrap(false); lblProfile.setStyleName("boldText"); mainTable.setWidget(0, 3, lblProfile); mainTable.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); mainTable.getCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT); mainTable.getCellFormatter().setHorizontalAlignment(0, 3, HasHorizontalAlignment.ALIGN_RIGHT); Label lblImport = new Label("Import"); lblImport.setWordWrap(false); lblImport.setStyleName("boldText"); mainTable.setWidget(0, 4, lblImport); mainTable.getCellFormatter().setHorizontalAlignment(0, 4, HasHorizontalAlignment.ALIGN_CENTER); flexTable.getFlexCellFormatter().setColSpan(1, 0, 2); CaptionPanel cptnpnlNewPanel_2 = new CaptionPanel("Build Statistics"); flexTable.setWidget(2, 0, cptnpnlNewPanel_2); cptnpnlNewPanel_2.setHeight("367px"); VerticalPanel verticalPanel = new VerticalPanel(); cptnpnlNewPanel_2.setContentWidget(verticalPanel); filterTable = new FlexTable(); SimplePanel panel3 = new SimplePanel(); panel3.setWidget(filterTable); verticalPanel.add(panel3); panel3.setHeight("80px"); Label sentryLabel = new Label("Sentry:"); sentryLabel.setWordWrap(false); sentryLabel.setStyleName("boldText"); filterTable.setWidget(0, 0, sentryLabel); sentry = new SimpleCheckBox(); filterTable.setWidget(0, 1, sentry); Label lblNewLabel_2 = new Label("Rune:"); lblNewLabel_2.setWordWrap(false); lblNewLabel_2.setStyleName("boldText"); filterTable.setWidget(0, 2, lblNewLabel_2); sentryRune = new ListBox(); filterTable.setWidget(0, 3, sentryRune); Label lblSkill = new Label("Skill 1:"); lblSkill.setWordWrap(false); lblSkill.setStyleName("boldText"); filterTable.setWidget(0, 2, lblSkill); skill1 = new ListBox(); filterTable.setWidget(0, 3, skill1); Label lblSkill_1 = new Label("Skill 2:"); lblSkill_1.setWordWrap(false); lblSkill_1.setStyleName("boldText"); filterTable.setWidget(0, 4, lblSkill_1); skill2 = new ListBox(); filterTable.setWidget(0, 5, skill2); // Label lblSkill_2 = new Label("Skill 3:"); // lblSkill_2.setWordWrap(false); // lblSkill_2.setStyleName("boldText"); // filterTable.setWidget(0, 6, lblSkill_2); // // skill3 = new ListBox(); // filterTable.setWidget(0, 7, skill3); // Button button = new Button("Copy My Build"); filterTable.setWidget(0, 6, button); button.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { copyBuild(); } }); Button btnNewButton = new Button("Update"); btnNewButton.setText("Filter/Refresh"); filterTable.setWidget(1, 0, btnNewButton); btnNewButton.setWidth("100%"); btnNewButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { updateStats(); } }); Label lblRune = new Label("Rune 1:"); lblRune.setWordWrap(false); lblRune.setStyleName("boldText"); filterTable.setWidget(1, 2, lblRune); rune1 = new ListBox(); filterTable.setWidget(1, 3, rune1); Label lblRune_1 = new Label("Rune 2:"); lblRune_1.setWordWrap(false); lblRune_1.setStyleName("boldText"); filterTable.setWidget(1, 4, lblRune_1); rune2 = new ListBox(); filterTable.setWidget(1, 5, rune2); // Label lblRune_2 = new Label("Rune 3:"); // lblRune_2.setWordWrap(false); // lblRune_2.setStyleName("boldText"); // filterTable.setWidget(1, 6, lblRune_2); // // rune3 = new ListBox(); // filterTable.setWidget(1, 7, rune3); // filterTable.getFlexCellFormatter().setColSpan(1, 0, 2); buildTable = new FlexTable(); buildTable.setStyleName("statsTable"); ScrollPanel scroll = new ScrollPanel(); scroll.setWidget(buildTable); verticalPanel.add(scroll); scroll.setSize("975px", "269px"); Anchor lblSentryRune = new Anchor("Sentry Rune"); lblSentryRune.setWordWrap(false); lblSentryRune.setStyleName("boldText"); lblSentryRune.setHref("javascript:void(0);"); buildTable.setWidget(0, 0, lblSentryRune); lblSentryRune.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { // sortStats(StatSorter.SENTRY_RUNE); } }); Anchor lblSkill_3 = new Anchor("Skills/Runes"); lblSkill_3.setHref("javascript:void(0);"); lblSkill_3.setWordWrap(false); lblSkill_3.setStyleName("boldText"); buildTable.setWidget(0, 1, lblSkill_3); lblSkill_3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { // sortStats(StatSorter.SKILLS); } }); buildTable.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_CENTER); Anchor lblCount = new Anchor("Count"); lblCount.setHref("javascript:void(0);"); lblCount.setWordWrap(false); lblCount.setStyleName("boldText"); buildTable.setWidget(0, 2, lblCount); lblCount.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { sortStats(StatSorter.COUNT); } }); flexTable.getFlexCellFormatter().setColSpan(2, 0, 2); flexTable.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT); flexTable.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); disableListeners = true; int row = 1; int col = 3; for (StatCategory c : StatCategory.values()) { Label label = new Label(c.getDescription()); label.setWordWrap(false); if ((row % 2) == 0) mainTable.getRowFormatter().addStyleName(row, "even"); else mainTable.getRowFormatter().addStyleName(row, "odd"); for (int i = 0; i < 4; i++) { Label label3 = new Label("Loading..."); label3.addStyleName("right"); mainTable.setWidget(row, i + 1, label3); } mainTable.setWidget(row++, 0, label); FlexTable table = new FlexTable(); buildTable.setWidget(0, col, table); Anchor avg = new Anchor("Avg"); avg.setWordWrap(false); avg.setHref("javascript:void(0);"); avg.setStyleName("boldText"); Anchor max = new Anchor("Max"); max.setWordWrap(false); max.setHref("javascript:void(0);"); max.setStyleName("boldText"); Label split = new Label("/"); split.setWordWrap(false); split.setStyleName("boldText"); table.setWidget(0, 0, avg); table.setWidget(0, 1, split); table.setWidget(0, 2, max); table.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); table.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_CENTER); table.getFlexCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_CENTER); Label label2 = new Label(c.getDescription()); label2.setWordWrap(true); label2.setStyleName("boldText"); table.setWidget(1, 0, label2); table.getFlexCellFormatter().setColSpan(1, 0, 3); table.getFlexCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER); buildTable.getFlexCellFormatter().setHorizontalAlignment(0, col, HasHorizontalAlignment.ALIGN_CENTER); final StatCategory cat = c; avg.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { sortStats(new StatSorter.AverageCategorySorter(cat)); } }); max.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { sortStats(new StatSorter.MaxCategorySorter(cat)); } }); col++; } skills = new ListBox[] { skill1, skill2 }; //, skill3 }; runes = new ListBox[] { rune1, rune2 }; //, rune3 }; for (int i = 0; i < skills.length; i++) { populateSkillsAndRunes(i); final int j = i; skills[i].addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { if (!disableListeners) { skillChanged(j); } } }); } disableListeners = false; } protected void copyBuild() { if (this.actionListener != null) { Build build = this.actionListener.getBuild(); setBuild(build); } } private void setBuild(Build build) { // this.selectRune(this.sentryRune, build.getSentryRune()); // this.sentry.setValue(build.isSentry()); this.disableListeners = true; for (int i = 0; i < skills.length; i++) { this.selectSkill(this.skills[i], null); this.populateRunes(this.runes[i], null); } int n = 0; // for (SkillAndRune sk : build.getSkills()) { // this.selectSkill(skills[n], sk.getSkill()); // this.populateRunes(runes[n], sk.getSkill()); // this.selectRune(runes[n], sk.getRune()); // n++; // } this.disableListeners = false; } private void selectRune(ListBox list, Rune rune) { for (int i = 0; i < list.getItemCount(); i++) { String value = list.getValue(i); if (value.equals(rune.name())) { list.setSelectedIndex(i); return; } } list.setSelectedIndex(0); } private void selectSkill(ListBox list, ActiveSkill skill) { for (int i = 0; i < list.getItemCount(); i++) { String value = list.getValue(i); if (skill != null) { if (value.equals(skill.name())) { list.setSelectedIndex(i); return; } } else { if ((value == null) || (value.trim().length() == 0)) { list.setSelectedIndex(i); return; } } } list.setSelectedIndex(0); } public void updateStats() { Rune sentryRune = getSelectedRune(this.sentryRune); ActiveSkill[] skills = new ActiveSkill[2]; Rune[] runes = new Rune[2]; for (int i = 0; i < skills.length; i++) { skills[i] = getSelectedSkill(i); runes[i] = getSelectedRune(i); } // Service.getInstance().getStats(sentryRune, skills, runes, // new DefaultCallback<DBStatistics>() { // // @Override // protected void doOnSuccess(DBStatistics result) { // showStats(result); // } // }); } protected void sortStats(StatSorter sorter) { Collections.sort(statList, sorter); while (buildTable.getRowCount() > 1) buildTable.removeRow(1); int row = 1; for (StatHolder h : statList) { for (int n = 0; n < 4; n++) { if ((row % 2) == 0) { buildTable.getRowFormatter() .addStyleName((row * 4) - n, "even"); } else { buildTable.getRowFormatter().addStyleName((row * 4) - n, "odd"); } buildTable.getRowFormatter().setVerticalAlign((row * 4) - n, HasVerticalAlignment.ALIGN_TOP); } final Build build = h.build; Statistics s = h.stats; // Rune r = build.getSentryRune(); // Anchor runeLabel = new Anchor(r.getLongName()); // runeLabel.setWordWrap(false); // runeLabel.addStyleName("center"); // runeLabel.setTarget("_blank"); // // if (r != Rune.None) // runeLabel.setHref(ActiveSkill.SENTRY.getUrl() + "#" // + r.getSlug() + "+"); // else // runeLabel.setHref(ActiveSkill.SENTRY.getUrl()); // buildTable.setWidget((row * 4) - 3, 0, runeLabel); // buildTable.getFlexCellFormatter().setRowSpan((row * 4) - 3, 0, 4); // buildTable.getFlexCellFormatter().setHorizontalAlignment((row * 4) - 3, 0, HasHorizontalAlignment.ALIGN_CENTER); // // SkillAndRune[] slist = build.getSkillsAsArray(); // // int col = 1; // int subRow = 3; // // for (int n = 0; n < 3; n++) { // // if (n < slist.length) { // ActiveSkill skill = slist[n].getSkill(); // Rune rune = slist[n].getRune(); // // String url = skill.getUrl(); // // if ((rune != null) && (rune != Rune.None)) { // url += ("#" + rune.getSlug() + "+"); // } // // Anchor slabel = new Anchor(slist[n].getSkill() // .getShortName() + "/" + rune.getLongName()); // slabel.setWordWrap(false); // slabel.addStyleDependentName("center"); // slabel.setTarget("_blank"); // slabel.setHref(url); // buildTable.setWidget((row * 4) - subRow, (n == 0) ? 1 : 0, slabel); // // } else if (n == 0) { // Label slabel = new Label("None"); // slabel.setWordWrap(false); // slabel.addStyleDependentName("center"); // buildTable.setWidget((row * 4) - subRow, (n == 0) ? 1 : 0, slabel); // } // // buildTable.getFlexCellFormatter().setHorizontalAlignment((row * 4) - subRow, (n == 0) ? 1 : 0, HasHorizontalAlignment.ALIGN_CENTER); // // subRow--; // } Anchor copy = new Anchor("copy this build"); copy.setHref("javascript:void(0);"); copy.setWordWrap(false); copy.setTitle("Copy this build"); copy.addStyleName("center"); buildTable.setWidget(row * 4, 0, copy); buildTable.getFlexCellFormatter().setHorizontalAlignment( row * 4, 0, HasHorizontalAlignment.ALIGN_CENTER); copy.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (actionListener != null) actionListener.setBuild(build); } }); // // col++; // Label label = new Label(Util.format(s.total)); // label.addStyleName("right"); // buildTable.setWidget((row * 4) - 3, col, label); // buildTable.getFlexCellFormatter().setRowSpan((row * 4) - 3, col, 4); // // col++; // for (StatCategory c : StatCategory.values()) { // // Double avg = s.average.get(c); // Label valueLabel1 = new Label(Util.format(Math.round(avg)) + "(avg)"); // valueLabel1.addStyleName("right"); // buildTable.setWidget((row * 4) - 3, col, valueLabel1); // // final DpsTableEntry entry = s.max.get(c); // double value = c.getValue(entry); // Label valueLabel = new Label(Util.format(Math.round(value)) + "(max)"); // valueLabel.addStyleName("right"); // buildTable.setWidget((row * 4) - 2, col - 2, valueLabel); // // String name = entry.getRealm() + "/" + entry.getProfile() + "-" + entry.getTag(); // Anchor anchor = new Anchor(name); // anchor.setWordWrap(false); // anchor.setTitle("View this profile on battle.net"); // anchor.setTarget("_blank"); // anchor.addStyleName("center"); // anchor.setHref(ClientUtils.getProfileUrl(entry)); // buildTable.setWidget((row * 4) - 1, col - 2, anchor); // buildTable.getFlexCellFormatter().setHorizontalAlignment( // (row * 4) - 1, col - 2, // HasHorizontalAlignment.ALIGN_CENTER); // // Anchor imp = new Anchor("import"); // imp.setWordWrap(false); // imp.setTitle("Import this profile"); // imp.setHref("javascript:void(0);"); // imp.addStyleName("center"); // buildTable.setWidget(row * 4, col - 2, imp); // buildTable.getFlexCellFormatter().setHorizontalAlignment( // row * 4, col - 2, HasHorizontalAlignment.ALIGN_CENTER); // // imp.addClickHandler(new ClickHandler() { // // @Override // public void onClick(ClickEvent event) { // importEntry(entry); // // } // }); // col++; // } row++; } } protected void showStats(DBStatistics stats) { this.statList = new Vector<StatHolder>(stats.builds.size()); for (Map.Entry<Build, Statistics> e : stats.builds.entrySet()) { StatHolder h = new StatHolder(); h.build = e.getKey(); h.stats = e.getValue(); statList.add(h); } totalLabel.setText(Util.format(stats.stats.total)); int row = 1; for (StatCategory c : StatCategory.values()) { final DpsTableEntry entry = stats.stats.max.get(c); Double average = stats.stats.average.get(c); double max = c.getValue(entry); Label label1 = new Label(Util.format(Math.round(average))); label1.addStyleName("right"); Label label2 = new Label(Util.format(Math.round(max))); label2.addStyleName("right"); mainTable.setWidget(row, 1, label1); mainTable.setWidget(row, 2, label2); Anchor anchor = new Anchor(entry.getRealm().name() + "/" + entry.getProfile() + "-" + entry.getTag()); anchor.setTarget("_blank"); anchor.setTitle("View this profile on battle.net"); anchor.setHref(ClientUtils.getProfileUrl(entry)); mainTable.setWidget(row, 3, anchor); Anchor imp = new Anchor("import"); imp.setTitle("Import this profile"); imp.setHref("javascript:void(0);"); imp.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { importEntry(entry); } }); mainTable.setWidget(row, 4, imp); row++; } sortStats(StatSorter.COUNT); } protected void importEntry(DpsTableEntry entry) { if (this.actionListener != null) { this.actionListener.closePanel(); this.actionListener.importEntry(entry); } } public void setActionListener(ActionListener actionListener) { this.actionListener = actionListener; } public interface ActionListener { void importEntry(DpsTableEntry entry); void setBuild(Build build); Build getBuild(); void closePanel(); } protected void skillChanged(int j) { populateRunes(j); } private void populateSkillsAndRunes(int i) { populateSkills(i); populateRunes(i); populateRunes(sentryRune, ActiveSkill.SENTRY); } private final ActiveSkill[] spenders = { ActiveSkill.CA, ActiveSkill.CHAK, ActiveSkill.EA, ActiveSkill.IMP, ActiveSkill.MS, ActiveSkill.HA, ActiveSkill.ES, ActiveSkill.BOLAS, ActiveSkill.EF, ActiveSkill.GRENADE }; private void populateSkills(int i) { ListBox list = skills[i]; list.clear(); list.addItem(ActiveSkill.Any.getLongName(), ActiveSkill.Any.name()); list.addItem("None", ""); for (ActiveSkill a : spenders) list.addItem(a.getLongName(), a.name()); list.setSelectedIndex(0); } ActiveSkill getSelectedSkill(int i) { ListBox list = skills[i]; int index = list.getSelectedIndex(); if (index < 0) return null; String value = list.getValue(index); if ((value == null) || (value.trim().length() == 0)) return null; return ActiveSkill.valueOf(value); } Rune getSelectedRune(int i) { ListBox list = runes[i]; return getSelectedRune(list); } Rune getSelectedRune(ListBox list) { int index = list.getSelectedIndex(); if (index < 0) return null; String value = list.getValue(index); if ((value == null) || (value.trim().length() == 0)) return null; return Rune.valueOf(value); } private void populateRunes(int i) { ListBox list = runes[i]; ActiveSkill skill = getSelectedSkill(i); populateRunes(list, skill); } private void populateRunes(ListBox list, ActiveSkill skill) { list.clear(); if (skill == null) { list.addItem(Rune.None.getLongName(), Rune.None.name()); } else { list.addItem(Rune.All_Runes.getLongName(), Rune.All_Runes.name()); if (skill != ActiveSkill.Any) { for (Rune r : skill.getRunes()) { list.addItem(r.getLongName(), r.name()); } } } list.setSelectedIndex(0); } }
dawg6/dhcalc
src/com/dawg6/web/dhcalc/client/StatsPanel.java
Java
gpl-3.0
23,198
package com.dsh105.echopet.api.pet.type; import com.dsh105.echopet.compat.api.entity.EntityPetType; import com.dsh105.echopet.compat.api.entity.PetType; import com.dsh105.echopet.compat.api.entity.type.pet.ICodPet; import org.bukkit.entity.Player; /** * @author Arnah * @since Aug 2, 2018 */ @EntityPetType(petType = PetType.COD) public class CodPet extends FishPet implements ICodPet{ public CodPet(Player owner){ super(owner); } }
Borlea/EchoPet
modules/EchoPet/src/com/dsh105/echopet/api/pet/type/CodPet.java
Java
gpl-3.0
444
package net.dericbourg.fuzzywallhack.descriptors; import net.dericbourg.fuzzywallhack.descriptors.type.array.ArrayType; public class ArrayDescriptor extends Descriptor { private final ArrayType arrayType; ArrayDescriptor(ArrayType arrayType) { this.arrayType = arrayType; } public ArrayType getArrayType() { return arrayType; } public static class Builder { public ArrayDescriptor of(ArrayType arrayType) { return new ArrayDescriptor(arrayType); } } }
adericbourg/fuzzy-wallhack
src/main/java/net/dericbourg/fuzzywallhack/descriptors/ArrayDescriptor.java
Java
gpl-3.0
529
package com.csy.mission.domain.emus; public enum MissionCodeTypeEn { INIT((byte)0,"自动生成"),IMPORT((byte)1,"导入"); private Byte code; private String mean; public static MissionCodeTypeEn toEnum(Byte id) { MissionCodeTypeEn[] values = values(); for (MissionCodeTypeEn en : values) { if (en.getCode() == id) { return en; } } return null; } MissionCodeTypeEn(Byte code, String mean) { this.code = code; this.mean = mean; } public Byte getCode() { return code; } public String getMean() { return mean; } }
csycurry/cloud.group
cloud.group.websys/src/main/java/com/csy/mission/domain/emus/MissionCodeTypeEn.java
Java
gpl-3.0
555
/******************************************************************************* * Copyright (c) 2006-2011 Gluster, Inc. <http://www.gluster.com> * This file is part of Gluster Management Console. * * Gluster Management Console is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Gluster Management Console is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.gluster.storage.management.console; import org.eclipse.swt.graphics.Image; import org.gluster.storage.management.console.utils.GUIHelper; import org.gluster.storage.management.console.views.pages.GlusterServersPage.GLUSTER_SERVER_TABLE_COLUMN_INDICES; import org.gluster.storage.management.core.model.GlusterServer; import org.gluster.storage.management.core.model.Server.SERVER_STATUS; import org.gluster.storage.management.core.utils.NumberUtil; public class GlusterServerTableLabelProvider extends TableLabelProviderAdapter { private GUIHelper guiHelper = GUIHelper.getInstance(); @Override public Image getColumnImage(Object element, int columnIndex) { if (!(element instanceof GlusterServer)) { return null; } GlusterServer server = (GlusterServer) element; if(columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal()) { SERVER_STATUS status = server.getStatus(); if(status == SERVER_STATUS.ONLINE) { return guiHelper.getImage(IImageKeys.STATUS_ONLINE_16x16); } else { return guiHelper.getImage(IImageKeys.STATUS_OFFLINE_16x16); } } return null; } @Override public String getColumnText(Object element, int columnIndex) { if (!(element instanceof GlusterServer)) { return null; } GlusterServer server = (GlusterServer) element; if (server.getStatus() == SERVER_STATUS.OFFLINE && columnIndex != GLUSTER_SERVER_TABLE_COLUMN_INDICES.NAME.ordinal() && columnIndex != GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal()) { return "NA"; } return (columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.NAME.ordinal() ? server.getName() : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal() ? server.getStatusStr() // : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.PREFERRED_NETWORK.ordinal() ? server.getPreferredNetworkInterface().getName() : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.NUM_OF_CPUS.ordinal() ? "" + server.getNumOfCPUs() //: columnIndex == SERVER_DISK_TABLE_COLUMN_INDICES.CPU_USAGE.ordinal() ? "" + server.getCpuUsage() : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_MEMORY.ordinal() ? "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024)) //: columnIndex == SERVER_DISK_TABLE_COLUMN_INDICES.MEMORY_IN_USE.ordinal() ? "" + server.getMemoryInUse() : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_FREE_SPACE.ordinal() ? NumberUtil.formatNumber((server.getFreeDiskSpace() / 1024)) : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.IP_ADDRESSES.ordinal() ? server.getIpAddressesAsString() : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_DISK_SPACE.ordinal() ? NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)) : "Invalid"); } }
gluster/gmc
src/org.gluster.storage.management.console/src/org/gluster/storage/management/console/GlusterServerTableLabelProvider.java
Java
gpl-3.0
3,728
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * FixedFilenameGenerator.java * Copyright (C) 2011-2014 University of Waikato, Hamilton, New Zealand */ package adams.core.io; import java.io.File; /** <!-- globalinfo-start --> * Simple concatenates directory, provided name and extension. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre>-D &lt;int&gt; (property: debugLevel) * &nbsp;&nbsp;&nbsp;The greater the number the more additional info the scheme may output to * &nbsp;&nbsp;&nbsp;the console (0 = off). * &nbsp;&nbsp;&nbsp;default: 0 * &nbsp;&nbsp;&nbsp;minimum: 0 * </pre> * * <pre>-dir &lt;adams.core.io.PlaceholderDirectory&gt; (property: directory) * &nbsp;&nbsp;&nbsp;The parent directory of the generated filename. * &nbsp;&nbsp;&nbsp;default: ${CWD} * </pre> * * <pre>-extension &lt;java.lang.String&gt; (property: extension) * &nbsp;&nbsp;&nbsp;The extension to use (including the dot). * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-name &lt;java.lang.String&gt; (property: name) * &nbsp;&nbsp;&nbsp;The name to use, excluding the extension. * &nbsp;&nbsp;&nbsp;default: * </pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 9229 $ */ public class FixedFilenameGenerator extends AbstractFilenameGeneratorWithDirectory { /** for serialization. */ private static final long serialVersionUID = -5985801362418398850L; /** the name to use. */ protected String m_Name; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Simple concatenates directory, provided name and extension."; } /** * Adds options to the internal list of options. */ @Override public void defineOptions() { super.defineOptions(); m_OptionManager.add( "name", "name", ""); } /** * Sets the name to use. * * @param value the name */ public void setName(String value) { m_Name = value; reset(); } /** * Returns the suffix in use. * * @return the suffix */ public String getName() { return m_Name; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String nameTipText() { return "The name to use, including the extension."; } /** * Returns whether we actually need an object to generate the filename. * * @return true if object required */ @Override public boolean canHandleNullObject() { return true; } /** * Performs the actual generation of the filename. * * @param obj the object to generate the filename for * @return the generated filename */ @Override protected String doGenerate(Object obj) { return m_Directory.getAbsolutePath() + File.separator + FileUtils.createFilename(m_Name, "_"); } }
automenta/adams-core
src/main/java/adams/core/io/FixedFilenameGenerator.java
Java
gpl-3.0
3,682
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CerrarSeion */ @WebServlet(description = "Cierra la sesión de usuario", urlPatterns = { "/CerrarSeion" }) public class CerrarSesion extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CerrarSesion() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String resultado="/Welcome"; request.getSession().invalidate(); getServletContext().getRequestDispatcher(resultado).forward(request, response); } }
RafaV56/MiEscuelaDeInformatica
MiEscuelaDeInformatica/src/servlet/CerrarSesion.java
Java
gpl-3.0
1,287
/* * #%L * gitools-ui-platform * %% * Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package org.gitools.ui.platform.os; public class OSXProperties extends OSProperties { public OSXProperties() { super(); metaKey = "⌘"; altKey = "⌥"; } @Override public int getCtrlMask() { //fix mapping of OSX keyboard return metaMask; } @Override public String getCtrlKey() { //fix mapping of OSX keyboard return metaKey; } @Override public String getMetaKey() { //fix mapping of OSX keyboard return ctrlKey; } @Override public int getMetaMask() { //fix mapping of OSX keyboard return ctrlMask; } }
gitools/gitools
org.gitools.ui.platform/src/main/java/org/gitools/ui/platform/os/OSXProperties.java
Java
gpl-3.0
1,453
/** * Copyright (C) 2009 STMicroelectronics * * This file is part of "Mind Compiler" is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: [email protected] * * Authors: Matthieu Leclercq * Contributors: */ package org.ow2.mind.adl; import org.objectweb.fractal.adl.Definition; import org.ow2.mind.VoidVisitor; public interface DefinitionSourceGenerator extends VoidVisitor<Definition> { }
MIND-Tools/mind-compiler
adl-backend/src/main/java/org/ow2/mind/adl/DefinitionSourceGenerator.java
Java
gpl-3.0
1,013
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example; import com.rapidminer.tools.Tools; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Formats an example as specified by the format string. The dollar sign '$' is an escape character. * Squared brackets '[' and ']' have a special meaning. The following escape sequences are * interpreted: * <dl> * <dt>$a:</dt> * <dd>All attributes separated by the default separator</dd> * <dt>$a[separator]:</dt> * <dd>All attributes separated by separator</dd> * <dt>$s[separator][indexSeparator]:</dt> * <dd>Sparse format. For all non 0 attributes the following strings are concatenated: the column * index, the value of indexSeparator, the attribute value. Attributes are separated by separator.</dd> * <dt>$v[name]:</dt> * <dd>The value of the attribute with the given name (both regular and special attributes)</dd> * <dt>$k[index]:</dt> * <dd>The value of the attribute with the given index in the example set</dd> * <dt>$l:</dt> * <dd>The label</dd> * <dt>$p:</dt> * <dd>The predicted label</dd> * <dt>$d:</dt> * <dd>All prediction confidences for all classes in the form conf(class)=value</dd> * <dt>$d[class]:</dt> * <dd>The prediction confidence for the defined class as a simple number</dd> * <dt>$i:</dt> * <dd>The id</dd> * <dt>$w:</dt> * <dd>The weight</dd> * <dt>$c:</dt> * <dd>The cluster</dd> * <dt>$b:</dt> * <dd>The batch</dd> * <dt>$n:</dt> * <dd>The newline character</dd> * <dt>$t:</dt> * <dd>The tabulator character</dd> * <dt>$$:</dt> * <dd>The dollar sign</dd> * <dt>$[:</dt> * <dd>The '[' character</dd> * <dt>$]:</dt> * <dd>The ']' character</dd> * </dl> * * @author Simon Fischer, Ingo Mierswa Exp $ */ public class ExampleFormatter { /** Represents one piece of formatting. */ public static interface FormatCommand { public String format(Example example); } /** * Implements some simple format commands like 'a' for all attributes or 'l' for the label. */ public static class SimpleCommand implements FormatCommand { private char command; private String[] arguments; private int fractionDigits = -1; private boolean quoteNominal; private SimpleCommand(ExampleSet exampleSet, char command, String[] arguments, int fractionDigits, boolean quoteNominal) throws FormatterException { this.command = command; this.fractionDigits = fractionDigits; this.quoteNominal = quoteNominal; if ((command != 'a') && (command != 's') && (command != 'l') && (command != 'p') && (command != 'd') && (command != 'i') && (command != 'w') && (command != 'c') && (command != 'b')) { throw new FormatterException("Unknown command: '" + command + "'"); } switch (command) { case 'a': if (arguments.length == 0) { arguments = new String[] { Example.SEPARATOR }; } break; case 's': if (arguments.length == 0) { arguments = new String[] { Example.SEPARATOR, Example.SPARSE_SEPARATOR }; } if (arguments.length == 1) { arguments = new String[] { arguments[0], Example.SPARSE_SEPARATOR }; } if (arguments.length == 2) { arguments = new String[] { arguments[0], arguments[1] }; } if (arguments.length > 2) { throw new FormatterException( "For command 's' only up to two arguments (separator and sparse separator) are allowed."); } break; case 'l': if (exampleSet.getAttributes().getLabel() == null) { throw new FormatterException("Example set does not provide 'label' attribute, $l will not work."); } break; case 'p': if (exampleSet.getAttributes().getPredictedLabel() == null) { throw new FormatterException( "Example set does not provide 'predicted label' attribute, $p will not work."); } break; case 'i': if (exampleSet.getAttributes().getId() == null) { throw new FormatterException("Example set does not provide 'id' attribute, $i will not work."); } break; case 'w': if (exampleSet.getAttributes().getWeight() == null) { throw new FormatterException("Example set does not provide 'weight' attribute, $w will not work."); } break; case 'c': if (exampleSet.getAttributes().getCluster() == null) { throw new FormatterException("Example set does not provide 'cluster' attribute, $c will not work."); } break; case 'b': if (exampleSet.getAttributes().getSpecial(Attributes.BATCH_NAME) == null) { throw new FormatterException("Example set does not provide 'batch' attribute, $b will not work."); } break; case 'd': if (exampleSet.getAttributes().getPredictedLabel() == null) { throw new FormatterException( "Example set does not provide 'confidence' attributes, $d will not work."); } break; default: break; } this.arguments = arguments; } @Override public String format(Example example) { switch (command) { case 'a': StringBuffer str = new StringBuffer(); boolean first = true; for (Attribute attribute : example.getAttributes()) { if (!first) { str.append(arguments[0]); } str.append(example.getValueAsString(attribute, fractionDigits, quoteNominal)); first = false; } return str.toString(); case 's': return example.getAttributesAsSparseString(arguments[0], arguments[1], fractionDigits, quoteNominal); case 'l': return example.getValueAsString(example.getAttributes().getLabel(), fractionDigits, quoteNominal); case 'p': return example.getValueAsString(example.getAttributes().getPredictedLabel(), fractionDigits, quoteNominal); case 'i': return example.getValueAsString(example.getAttributes().getId(), fractionDigits, quoteNominal); case 'w': return example.getValueAsString(example.getAttributes().getWeight(), fractionDigits, quoteNominal); case 'c': return example.getValueAsString(example.getAttributes().getCluster(), fractionDigits, quoteNominal); case 'b': return example.getValueAsString(example.getAttributes().getSpecial(Attributes.BATCH_NAME), fractionDigits, quoteNominal); case 'd': if (arguments.length == 0) { Iterator i = example.getAttributes().getPredictedLabel().getMapping().getValues().iterator(); StringBuffer result = new StringBuffer(); int index = 0; while (i.hasNext()) { String value = (String) i.next(); if (index != 0) { result.append(Example.SEPARATOR); } result.append("conf(" + value + ")=" + Tools.formatNumber(example.getConfidence(value), fractionDigits)); index++; } return result.toString(); } else { return Tools.formatNumber(example.getConfidence(arguments[0]), fractionDigits); } default: return command + ""; } } } /** Returns the value of an argument which must be an attribute's name. */ public static class ValueCommand implements FormatCommand { private Attribute attribute; private int fractionDigits = -1; private boolean quoteWhitespace = false; public ValueCommand(char command, String[] arguments, ExampleSet exampleSet, int fractionDigits, boolean quoteWhitespace) throws FormatterException { this.fractionDigits = fractionDigits; this.quoteWhitespace = quoteWhitespace; if (arguments.length < 1) { throw new FormatterException("Command 'v' needs argument!"); } switch (command) { case 'v': attribute = exampleSet.getAttributes().get(arguments[0]); if (attribute == null) { throw new FormatterException("Unknown attribute: '" + arguments[0] + "'!"); } break; case 'k': int column = -1; try { column = Integer.parseInt(arguments[0]); } catch (NumberFormatException e) { throw new FormatterException("Argument for 'k' must be an integer!"); } if ((column < 0) || (column >= exampleSet.getAttributes().size())) { throw new FormatterException("Illegal column: '" + arguments[0] + "'!"); } int counter = 0; for (Attribute attribute : exampleSet.getAttributes()) { if (counter >= column) { this.attribute = attribute; break; } counter++; } if (attribute == null) { throw new FormatterException("Attribute #" + column + " not found."); } break; default: throw new FormatterException("Illegal command for ValueCommand: '" + command + "'"); } } @Override public String format(Example example) { return example.getValueAsString(attribute, fractionDigits, quoteWhitespace); } } /** Returns simply the given text. */ public static class TextCommand implements FormatCommand { private String text; private TextCommand(String text) { this.text = text; } @Override public String format(Example example) { return text; } } /** The commands used subsequently to format the example. */ private FormatCommand[] formatCommands; /** * Constructs a new ExampleFormatter that executes the given array of formatting commands. The * preferred way of creating an instance of ExampleFormatter is to * {@link ExampleFormatter#compile(String, ExampleSet, int, boolean)} a format string. */ public ExampleFormatter(FormatCommand[] formatCommands) { this.formatCommands = formatCommands; } /** * Factory method that compiles a format string and creates an instance of ExampleFormatter. */ public static ExampleFormatter compile(String formatString, ExampleSet exampleSet, int fractionDigits, boolean quoteWhitespace) throws FormatterException { List<FormatCommand> commandList = new LinkedList<FormatCommand>(); compile(formatString, exampleSet, commandList, fractionDigits, quoteWhitespace); FormatCommand[] commands = new FormatCommand[commandList.size()]; commandList.toArray(commands); return new ExampleFormatter(commands); } /** Adds all commands to the <code>commandList</code>. */ private static void compile(String formatString, ExampleSet exampleSet, List<FormatCommand> commandList, int fractionDigits, boolean quoteWhitespace) throws FormatterException { int start = 0; while (true) { int tagStart = formatString.indexOf("$", start); if (tagStart == -1) { commandList.add(new TextCommand(formatString.substring(start))); break; } if (tagStart == formatString.length() - 1) { throw new FormatterException("Format string ends in '$'."); } commandList.add(new TextCommand(formatString.substring(start, tagStart))); char command = formatString.charAt(tagStart + 1); if ((command == '$') || (command == '[') || (command == ']')) { commandList.add(new TextCommand("" + command)); start = tagStart + 2; continue; } else if (command == 'n') { commandList.add(new TextCommand(Tools.getLineSeparator())); start = tagStart + 2; continue; } else if (command == 't') { commandList.add(new TextCommand("\t")); start = tagStart + 2; continue; } start = tagStart + 2; List<String> argumentList = new LinkedList<String>(); while ((start < formatString.length()) && (formatString.charAt(start) == '[')) { int end = formatString.indexOf(']', start); if (end == -1) { throw new FormatterException("Unclosed '['!"); } argumentList.add(formatString.substring(start + 1, end)); start = end + 1; } String[] arguments = new String[argumentList.size()]; argumentList.toArray(arguments); switch (command) { case 'v': case 'k': commandList.add(new ValueCommand(command, arguments, exampleSet, fractionDigits, quoteWhitespace)); break; default: commandList.add(new SimpleCommand(exampleSet, command, arguments, fractionDigits, quoteWhitespace)); break; } } } /** Formats a single example. */ public String format(Example example) { StringBuffer str = new StringBuffer(); for (int i = 0; i < formatCommands.length; i++) { str.append(formatCommands[i].format(example)); } return str.toString(); } }
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/example/ExampleFormatter.java
Java
gpl-3.0
13,327
/* * Copyright 2012 Amazon Technologies, Inc. * * Licensed under the Amazon Software License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/asl * * This file 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.amazonaws.mturk.cmd.summary; /** * Thrown when a quorum-based technique (where answer with max votes wins) cannot * be used to determine the correct answer. */ public class UnresolvedAnswerException extends Exception { private ErrorReason reason; /** * Constructor with error message. * @param message error message. * @param reason error reason */ public UnresolvedAnswerException(String message, ErrorReason reason) { super(message); this.reason = reason; } public ErrorReason getErrorReason() { return this.reason; } public static enum ErrorReason { InProgress("in progress"), NoAgreement("no agreement"); private String reason; private ErrorReason(String reason) { this.reason = reason; } public String getReason() { return this.reason; } } }
ucberkeley/moocchat
turk/src/com/amazonaws/mturk/cmd/summary/UnresolvedAnswerException.java
Java
gpl-3.0
1,449
/** * Copyright (C) 2011 The Serval Project * * This file is part of Serval Software (http://www.servalproject.org) * * Serval Software is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This source code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.servalproject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.servalproject.account.AccountService; import org.servalproject.batphone.BatPhone; import org.servalproject.messages.ShowConversationActivity; import org.servalproject.servald.Peer; import org.servalproject.servald.PeerListService; import org.servalproject.servald.SubscriberId; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; /** * * @author jeremy * * Peer List fetches a list of known peers from the PeerListService. * When a peer is received from the service this activity will attempt * to resolve the peer by calling ServalD in an async task. */ public class PeerList extends ListActivity { Adapter listAdapter; boolean displayed = false; private static final String TAG = "PeerList"; public static final String PICK_PEER_INTENT = "org.servalproject.PICK_FROM_PEER_LIST"; public static final String CONTACT_NAME = "org.servalproject.PeerList.contactName"; public static final String CONTACT_ID = "org.servalproject.PeerList.contactId"; public static final String DID = "org.servalproject.PeerList.did"; public static final String SID = "org.servalproject.PeerList.sid"; public static final String NAME = "org.servalproject.PeerList.name"; public static final String RESOLVED = "org.servalproject.PeerList.resolved"; private boolean returnResult = false; private List<Peer> peers = new ArrayList<Peer>(); class Adapter extends ArrayAdapter<Peer> { public Adapter(Context context) { super(context, R.layout.peer, R.id.Number, peers); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View ret = super.getView(position, convertView, parent); Peer p = listAdapter.getItem(position); TextView displaySid = (TextView) ret.findViewById(R.id.sid); displaySid.setText(p.sid.abbreviation()); View chat = ret.findViewById(R.id.chat); chat.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Peer p = listAdapter.getItem(position); // Send MeshMS by SID Intent intent = new Intent( ServalBatPhoneApplication.context, ShowConversationActivity.class); intent.putExtra("recipient", p.sid.toString()); PeerList.this.startActivity(intent); } }); View call = ret.findViewById(R.id.call); if (p.sid.isBroadcast()) { call.setVisibility(View.INVISIBLE); } View contact = ret.findViewById(R.id.add_contact); if (p.contactId >= 0) { contact.setVisibility(View.INVISIBLE); } else { contact.setVisibility(View.VISIBLE); contact.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Peer p = listAdapter.getItem(position); // Create contact if required if (p.contactId == -1) { if ("".equals(p.getContactName())) p.setContactName(p.name); p.contactId = AccountService.addContact( PeerList.this, p.getContactName(), p.sid, p.did); } v.setVisibility(View.INVISIBLE); // now display/edit contact // Work out how to get the contact id from here, and // then open it for editing. // Intent intent = new Intent(Intent.ACTION_VIEW, // Uri.parse( // "content://contacts/people/" + p.contactId)); // PeerList.this.startActivity(intent); } }); } return ret; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(); Intent intent = getIntent(); if (intent != null) { if (PICK_PEER_INTENT.equals(intent.getAction())) { returnResult = true; } } listAdapter = new Adapter(this); listAdapter.setNotifyOnChange(false); this.setListAdapter(listAdapter); ListView lv = getListView(); // TODO Long click listener for more options, eg text message lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { Peer p = listAdapter.getItem(position); if (returnResult) { Log.i(TAG, "returning selected peer " + p); Intent returnIntent = new Intent(); returnIntent.putExtra( CONTACT_NAME, p.getContactName()); returnIntent.putExtra(SID, p.sid.toString()); returnIntent.putExtra(CONTACT_ID, p.contactId); returnIntent.putExtra(DID, p.did); returnIntent.putExtra(NAME, p.name); returnIntent.putExtra(RESOLVED, p.cacheUntil > SystemClock.elapsedRealtime()); setResult(Activity.RESULT_OK, returnIntent); finish(); } else if (!p.sid.isBroadcast()) { Log.i(TAG, "calling selected peer " + p); BatPhone.callPeer(p); } } catch (Exception e) { ServalBatPhoneApplication.context.displayToastMessage(e .getMessage()); Log.e("BatPhone", e.getMessage(), e); } } }); } @Override protected void onNewIntent(Intent intent) { // TODO Auto-generated method stub super.onNewIntent(intent); if (intent != null) { if (PICK_PEER_INTENT.equals(intent.getAction())) { returnResult = true; } } } private IPeerListListener listener = new IPeerListListener() { @Override public void peerChanged(final Peer p) { if (p.cacheUntil <= SystemClock.elapsedRealtime()) { unresolved.put(p.sid, p); handler.post(refresh); } // if we haven't seen recent active network confirmation for the // existence of this peer, don't add to the UI if (!p.stillAlive()) return; int pos = peers.indexOf(p); if (pos < 0) { peers.add(p); } Collections.sort(peers, new PeerComparator()); runOnUiThread(new Runnable() { @Override public void run() { listAdapter.notifyDataSetChanged(); } }); } }; ConcurrentMap<SubscriberId, Peer> unresolved = new ConcurrentHashMap<SubscriberId, Peer>(); private Handler handler; private boolean searching = false; private Runnable refresh = new Runnable() { @Override public void run() { handler.removeCallbacks(refresh); if (searching || (!displayed)) return; searching = true; new AsyncTask<Void, Peer, Void>() { @Override protected void onPostExecute(Void result) { searching = false; } @Override protected Void doInBackground(Void... params) { for (Peer p : unresolved.values()) { PeerListService.resolve(p); unresolved.remove(p.sid); } return null; } }.execute(); } }; @Override protected void onPause() { super.onPause(); displayed = false; handler.removeCallbacks(refresh); PeerListService.removeListener(listener); } @Override protected void onResume() { super.onResume(); displayed = true; PeerListService.peerCount(this); PeerListService.addListener(this, listener); } }
aiQon/crowdshare
src/org/servalproject/PeerList.java
Java
gpl-3.0
8,396
package com.billooms.indexercontrol; import com.billooms.indexerprefs.api.Preferences; import com.billooms.indexwheel.api.IndexWheel; import com.billooms.indexwheel.api.IndexWheelMgr; import com.billooms.stepperboard.api.StepperBoard; import com.billooms.stepperboard.api.StepperBoard.Stepper; import java.awt.BorderLayout; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.Lookup; import org.openide.util.Utilities; import org.openide.util.lookup.Lookups; /** * Top component for controlling the stepper motor. * @author Bill Ooms Copyright (c) 2011 Studio of Bill Ooms all rights reserved * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ @ConvertAsProperties(dtd = "-//com.billooms.indexercontrol//Control//EN", autostore = false) @TopComponent.Description(preferredID = "ControlTopComponent", iconBase="com/billooms/indexercontrol/icons/Control16.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS) @TopComponent.Registration(mode = "control", openAtStartup = true) @ActionID(category = "Window", id = "com.billooms.indexercontrol.ControlTopComponent") @ActionReference(path = "Menu/Window" /*, position = 333 */) @TopComponent.OpenActionRegistration(displayName = "#CTL_ControlAction", preferredID = "ControlTopComponent") public final class ControlTopComponent extends TopComponent { private RotationStage cStage; // This is the hardware interface private ControlPanel panel; private Lookup.Result result = null; // global selection of IndexWheel private StepperBoard stepBoard = null; private IndexWheelMgr idxMgr = null; private Preferences prefs = null; /** * Create a new window for controlling the stepper motor. */ public ControlTopComponent() { initComponents(); setName(NbBundle.getMessage(ControlTopComponent.class, "CTL_ControlTopComponent")); setToolTipText(NbBundle.getMessage(ControlTopComponent.class, "HINT_ControlTopComponent")); putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE); putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE); cStage = new RotationStage(Stepper.values()[Lookup.getDefault().lookup(Preferences.class).getWiredTo()]); panel = new ControlPanel(cStage); this.add(panel, BorderLayout.CENTER); this.associateLookup(Lookups.fixed(panel, cStage)); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setLayout(new java.awt.BorderLayout()); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables @Override public void componentOpened() { // TODO add custom code on component opening stepBoard = Lookup.getDefault().lookup(StepperBoard.class); stepBoard.addPropertyChangeListener(panel); // panel listens to the StepperBoard idxMgr = Lookup.getDefault().lookup(IndexWheelMgr.class); idxMgr.addPropertyChangeListener(panel); // panel listens for READXML prefs = Lookup.getDefault().lookup(Preferences.class); prefs.addPropertyChangeListener(cStage); // stage listens for setup changes result = Utilities.actionsGlobalContext().lookupResult(IndexWheel.class); result.addLookupListener(panel); // panel listens for changes in the selection } @Override public void componentClosed() { // TODO add custom code on component closing stepBoard.removePropertyChangeListener(panel); // quit listening when window closes stepBoard = null; idxMgr.removePropertyChangeListener(panel); idxMgr = null; prefs.removePropertyChangeListener(cStage); prefs = null; result.removeLookupListener(panel); // remove the listener when the window closes result = null; } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } }
billooms/Indexer
IndexerControl/src/com/billooms/indexercontrol/ControlTopComponent.java
Java
gpl-3.0
5,140
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.graph; import java.beans.PropertyChangeListener; import java.util.*; /** * Implements a graph allowing nodes in the getModel time lag to have parents * taken from previous time lags. This is intended to be interpreted as a * repeating time series graph for purposes of simulation. * * @author Joseph Ramsey */ public class LagGraph implements Graph { static final long serialVersionUID = 23L; private Dag graph = new Dag(); private List<String> variables = new ArrayList<>(); private int numLags = 0; private Map<String, List<Node>> laggedVariables = new HashMap<>(); private boolean pag; private boolean pattern; private Map<String,Object> attributes = new HashMap<>(); // New methods. public boolean addVariable(String variable) { if (variables.contains(variable)) { return false; } for (String _variable : variables) { if (variable.equals(_variable)) { return false; } } variables.add(variable); laggedVariables.put(variable, new ArrayList<Node>()); for (String node : variables) { List<Node> _lags = laggedVariables.get(node); GraphNode _newNode = new GraphNode(node + "." + _lags.size()); _lags.add(_newNode); _newNode.setCenter(5, 5); addNode(_newNode); } return true; } /** * Generates a simple exemplar of this class to test serialization. */ public static LagGraph serializableInstance() { return new LagGraph(); } // Modified methods from graph. public boolean addDirectedEdge(Node node1, Node node2) { return getGraph().addDirectedEdge(node1, node2); } public boolean addNode(Node node) { throw new UnsupportedOperationException(); } // Wrapped methods from graph. public boolean addBidirectedEdge(Node node1, Node node2) { throw new UnsupportedOperationException(); } public boolean addUndirectedEdge(Node node1, Node node2) { throw new UnsupportedOperationException(); } public boolean addNondirectedEdge(Node node1, Node node2) { throw new UnsupportedOperationException(); } public boolean addPartiallyOrientedEdge(Node node1, Node node2) { throw new UnsupportedOperationException(); } public boolean addEdge(Edge edge) { throw new UnsupportedOperationException(); } public void addPropertyChangeListener(PropertyChangeListener e) { getGraph().addPropertyChangeListener(e); } public void clear() { getGraph().clear(); } public boolean containsEdge(Edge edge) { return getGraph().containsEdge(edge); } public boolean containsNode(Node node) { return getGraph().containsNode(node); } public boolean existsDirectedCycle() { return getGraph().existsDirectedCycle(); } public boolean existsDirectedPathFromTo(Node node1, Node node2) { return getGraph().existsDirectedPathFromTo(node1, node2); } public boolean existsUndirectedPathFromTo(Node node1, Node node2) { return getGraph().existsUndirectedPathFromTo(node1, node2); } public boolean existsSemiDirectedPathFromTo(Node node1, Set<Node> nodes) { return getGraph().existsSemiDirectedPathFromTo(node1, nodes); } public boolean existsInducingPath(Node node1, Node node2) { return getGraph().existsInducingPath(node1, node2); } public boolean existsTrek(Node node1, Node node2) { return getGraph().existsTrek(node1, node2); } public void fullyConnect(Endpoint endpoint) { throw new UnsupportedOperationException(); } public void reorientAllWith(Endpoint endpoint) { getGraph().reorientAllWith(endpoint); } public List<Node> getAdjacentNodes(Node node) { return getGraph().getAdjacentNodes(node); } public List<Node> getAncestors(List<Node> nodes) { return getGraph().getAncestors(nodes); } public List<Node> getChildren(Node node) { return getGraph().getChildren(node); } public int getConnectivity() { return getGraph().getConnectivity(); } public List<Node> getDescendants(List<Node> nodes) { return getGraph().getDescendants(nodes); } public Edge getEdge(Node node1, Node node2) { return getGraph().getEdge(node1, node2); } public Edge getDirectedEdge(Node node1, Node node2) { return getGraph().getDirectedEdge(node1, node2); } public List<Edge> getEdges(Node node) { return getGraph().getEdges(node); } public List<Edge> getEdges(Node node1, Node node2) { return getGraph().getEdges(node1, node2); } public Set<Edge> getEdges() { return getGraph().getEdges(); } public Endpoint getEndpoint(Node node1, Node node2) { return getGraph().getEndpoint(node1, node2); } public Endpoint[][] getEndpointMatrix() { return getGraph().getEndpointMatrix(); } public int getIndegree(Node node) { return getGraph().getIndegree(node); } @Override public int getDegree(Node node) { return getGraph().getDegree(node); } public Node getNode(String name) { return getGraph().getNode(name); } public List<Node> getNodes() { return getGraph().getNodes(); } public List<String> getNodeNames() { return getGraph().getNodeNames(); } public int getNumEdges() { return getGraph().getNumEdges(); } public int getNumEdges(Node node) { return getGraph().getNumEdges(node); } public int getNumNodes() { return getGraph().getNumNodes(); } public int getOutdegree(Node node) { return getGraph().getOutdegree(node); } public List<Node> getParents(Node node) { return getGraph().getParents(node); } public boolean isAdjacentTo(Node node1, Node node2) { return getGraph().isAdjacentTo(node1, node2); } public boolean isAncestorOf(Node node1, Node node2) { return getGraph().isAncestorOf(node1, node2); } public boolean possibleAncestor(Node node1, Node node2) { return getGraph().possibleAncestor(node1, node2); } public boolean isChildOf(Node node1, Node node2) { return getGraph().isChildOf(node2, node2); } public boolean isParentOf(Node node1, Node node2) { return getGraph().isParentOf(node1, node2); } public boolean isProperAncestorOf(Node node1, Node node2) { return getGraph().isProperAncestorOf(node1, node2); } public boolean isProperDescendentOf(Node node1, Node node2) { return getGraph().isProperDescendentOf(node1, node2); } public boolean isDescendentOf(Node node1, Node node2) { return getGraph().isDescendentOf(node1, node2); } public boolean defNonDescendent(Node node1, Node node2) { return getGraph().defNonDescendent(node1, node2); } public boolean isDefNoncollider(Node node1, Node node2, Node node3) { return getGraph().isDefNoncollider(node1, node2, node3); } public boolean isDefCollider(Node node1, Node node2, Node node3) { return getGraph().isDefCollider(node1, node2, node3); } public boolean isDConnectedTo(Node node1, Node node2, List<Node> z) { return getGraph().isDConnectedTo(node1, node2, z); } public boolean isDSeparatedFrom(Node node1, Node node2, List<Node> z) { return getGraph().isDSeparatedFrom(node1, node2, z); } public boolean possDConnectedTo(Node node1, Node node2, List<Node> z) { return getGraph().possDConnectedTo(node1, node2, z); } public boolean isDirectedFromTo(Node node1, Node node2) { return getGraph().isDirectedFromTo(node1, node2); } public boolean isUndirectedFromTo(Node node1, Node node2) { return getGraph().isUndirectedFromTo(node1, node2); } public boolean defVisible(Edge edge) { return getGraph().defVisible(edge); } public boolean isExogenous(Node node) { return getGraph().isExogenous(node); } public List<Node> getNodesInTo(Node node, Endpoint n) { return getGraph().getNodesInTo(node, n); } public List<Node> getNodesOutTo(Node node, Endpoint n) { return getGraph().getNodesOutTo(node, n); } public boolean removeEdge(Edge edge) { return getGraph().removeEdge(edge); } public boolean removeEdge(Node node1, Node node2) { return getGraph().removeEdge(node1, node2); } public boolean removeEdges(Node node1, Node node2) { return getGraph().removeEdges(node1, node2); } public boolean removeEdges(Collection<Edge> edges) { return getGraph().removeEdges(edges); } public boolean removeNode(Node node) { return getGraph().removeNode(node); } public boolean removeNodes(List<Node> nodes) { return getGraph().removeNodes(nodes); } public boolean setEndpoint(Node from, Node to, Endpoint endPoint) { return getGraph().setEndpoint(from, to, endPoint); } public Graph subgraph(List<Node> nodes) { return getGraph().subgraph(nodes); } public void transferNodesAndEdges(Graph graph) throws IllegalArgumentException { this.getGraph().transferNodesAndEdges(graph); } public void transferAttributes(Graph graph) throws IllegalArgumentException { this.getGraph().transferAttributes(graph); } public Set<Triple> getAmbiguousTriples() { return getGraph().getAmbiguousTriples(); } public Set<Triple> getUnderLines() { return getGraph().getUnderLines(); } public Set<Triple> getDottedUnderlines() { return getGraph().getDottedUnderlines(); } public boolean isAmbiguousTriple(Node x, Node y, Node z) { return getGraph().isAmbiguousTriple(x, y, z); } public boolean isUnderlineTriple(Node x, Node y, Node z) { return getGraph().isUnderlineTriple(x, y, z); } public boolean isDottedUnderlineTriple(Node x, Node y, Node z) { return getGraph().isDottedUnderlineTriple(x, y, z); } public void addAmbiguousTriple(Node x, Node y, Node Z) { getGraph().addAmbiguousTriple(x, y, Z); } public void addUnderlineTriple(Node x, Node y, Node Z) { getGraph().addUnderlineTriple(x, y, Z); } public void addDottedUnderlineTriple(Node x, Node y, Node Z) { getGraph().addDottedUnderlineTriple(x, y, Z); } public void removeAmbiguousTriple(Node x, Node y, Node z) { getGraph().removeAmbiguousTriple(x, y, z); } public void removeUnderlineTriple(Node x, Node y, Node z) { getGraph().removeUnderlineTriple(x, y, z); } public void removeDottedUnderlineTriple(Node x, Node y, Node z) { getGraph().removeDottedUnderlineTriple(x, y, z); } public void setAmbiguousTriples(Set<Triple> triples) { getGraph().setAmbiguousTriples(triples); } public void setUnderLineTriples(Set<Triple> triples) { getGraph().setUnderLineTriples(triples); } public void setDottedUnderLineTriples(Set<Triple> triples) { getGraph().setDottedUnderLineTriples(triples); } public List<Node> getCausalOrdering() { return getGraph().getCausalOrdering(); } public void setHighlighted(Edge edge, boolean highlighted) { getGraph().setHighlighted(edge, highlighted); } public boolean isHighlighted(Edge edge) { return getGraph().isHighlighted(edge); } public boolean isParameterizable(Node node) { return getGraph().isParameterizable(node); } public boolean isTimeLagModel() { return false; } public TimeLagGraph getTimeLagGraph() { return null; } @Override public void removeTriplesNotInGraph() { throw new UnsupportedOperationException(); } @Override public List<Node> getSepset(Node n1, Node n2) { throw new UnsupportedOperationException(); } @Override public void setNodes(List<Node> nodes) { graph.setNodes(nodes); } private Dag getGraph() { return graph; } public void setGraph(Dag graph) { this.graph = graph; } @Override public List<String> getTriplesClassificationTypes() { return null; } @Override public List<List<Triple>> getTriplesLists(Node node) { return null; } @Override public boolean isPag() { return pag; } @Override public void setPag(boolean pag) { this.pag = pag; } @Override public boolean isPattern() { return pattern; } @Override public void setPattern(boolean pattern) { this.pattern = pattern; } @Override public Map<String, Object> getAllAttributes() { return attributes; } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public void addAttribute(String key, Object value) { attributes.put(key, value); } }
bd2kccd/tetradR
java/edu/cmu/tetrad/graph/LagGraph.java
Java
gpl-3.0
15,013
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; public class PlayerBedLeaveEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } @Override public HandlerList getHandlerList() { return getHandlers(); } private final Block bed; public PlayerBedLeaveEvent(Player player, Block bed) { this.player = player; this.bed = bed; } public Block getBed() { return bed; } }
boy0001/Nukkit
src/main/java/cn/nukkit/event/player/PlayerBedLeaveEvent.java
Java
gpl-3.0
625
package ar.edu.taco.stryker.exceptions; /** * This exception is thrown if a fatal error has occurred while executing a * stryker stage. This exception or any of its subclasses indicate that * the execution of the stryker stage as well as the rest of the stages * should be aborted. */ @SuppressWarnings("serial") public class FatalStrykerStageException extends Exception { public FatalStrykerStageException(String msg) { super(msg); } }
zeminlu/comitaco
src/ar/edu/taco/stryker/exceptions/FatalStrykerStageException.java
Java
gpl-3.0
449
package org.runnerup.db.entities; import android.content.ContentValues; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import org.runnerup.common.util.Constants; import java.util.Arrays; import java.util.List; public abstract class AbstractBaseValues { private final ContentValues mContentValues = new ContentValues(); protected abstract List<String> getValidColumns(); protected abstract String getTableName(); protected abstract String getNullColumnHack(); /** * Returns the {@code ContentValues} wrapped by this object. */ protected final ContentValues values() { return mContentValues; } public Long getId() { if (mContentValues.keySet().contains(Constants.DB.PRIMARY_KEY)) { return mContentValues.getAsLong(Constants.DB.PRIMARY_KEY); } return null; } public void insert(SQLiteDatabase db) { db.insert(getTableName(), getNullColumnHack(), values()); } public void update(SQLiteDatabase db) { if (getId() != null) { db.update(getTableName(), values(), Constants.DB.PRIMARY_KEY + " = ?", new String[]{Long.toString(getId())}); } else { throw new IllegalArgumentException("Entity has no primary key"); } } protected void toContentValues(Cursor c) { if (c.isClosed() || c.isAfterLast() || c.isBeforeFirst()) { throw new CursorIndexOutOfBoundsException("Cursor not readable"); } if (getValidColumns().containsAll(Arrays.asList(c.getColumnNames()))) { DatabaseUtils.cursorRowToContentValues(c, values()); } else { throw new IllegalArgumentException("Cursor " + c.toString() + " is incompatible with the Entity " + this.getClass().getName()); } } }
netmackan/runnerup
app/src/org/runnerup/db/entities/AbstractBaseValues.java
Java
gpl-3.0
1,934
package com.pix.mind.screens; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.Shape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.pix.mind.BodyEditorLoader; import com.pix.mind.PixMindGame; public class MainMenuScreen implements Screen { private Drawable[] candiesDrawables = new Drawable[4] ; static final float candySize = 0.2f; private PixMindGame game; Stage mainMenuStage; Image playImageS2D, optionsImageS2D, exitImageS2D, titleImageS2D, backgroundImage, background; World world; Image sweet, mind, sweetes; private OrthographicCamera camera; private Box2DDebugRenderer debugRenderer; private ArrayList<Body> candies; public MainMenuScreen(PixMindGame game) { super(); this.game = game; } float time = 0; float randomTime = 0; @Override public void render(float delta) { // TODO Auto-generated method stub Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); // we only need to draw and not to act because we always want to show exactly the same, and anything modify it along the time mainMenuStage.act(); mainMenuStage.draw(); world.step(delta, 6, 2); //debugRenderer.render(world, camera.combined); for(Body b : candies){ Image im = (Image)b.getFixtureList().get(0).getUserData(); im.setPosition((b.getPosition().x - candySize)*PixMindGame.BOX_TO_WORLD, (b.getPosition().y-candySize)*PixMindGame.BOX_TO_WORLD); im.setRotation(-45+(float) (b.getAngle()*360/(2*Math.PI))); } time = time + delta; if(time >0.7f && randomTime ==0){ randomTime = (float) Math.random(); } if(time>0.7f && randomTime!=0){ float randomPosition = (float) Math.random()*PixMindGame.w*PixMindGame.WORLD_TO_BOX; float randomRotation = (float) Math.random()*90; float randomCandy = (float) Math.random()*4; // System.out.print(randomCandy+ " - "); // System.out.println((int) randomCandy); generateCandy(world,randomPosition,6.8f,randomRotation, candiesDrawables[(int) randomCandy]); time=0; randomTime = 0; } //remove candy if its out of screen for(int i = 0; i<candies.size();i++){ if(candies.get(i).getFixtureList().get(0).getBody().getPosition().y < 0){ Image image = (Image) candies.get(i).getFixtureList().get(0).getUserData(); image.remove(); world.destroyBody(candies.get(i)); candies.remove(i); } /* Image im = (Image)b.getFixtureList().get(0).getUserData(); im.setPosition((b.getPosition().x - 0.2f)*PixMindGame.BOX_TO_WORLD, (b.getPosition().y-0.2f)*PixMindGame.BOX_TO_WORLD); im.setRotation((float) (b.getAngle()*360/(2*Math.PI)));*/ } // System.out.print("size: " + candies.size()); } @Override public void resize(int width, int height) { // TODO Auto-generated method stub } @Override public void show() { // TODO Auto-generated method stub // creating actors (image) mainMenuStage = new Stage(PixMindGame.w, PixMindGame.h, true); Gdx.input.setInputProcessor(mainMenuStage); // for to catch BACK Android button events Gdx.input.setCatchBackKey(true); //to move according to the resolutuion, we create a group to put inside all menu elements Group menuGroup = new Group(); //to move according to the resolutuion background = new Image(PixMindGame.getSkin().getDrawable("emptyscreen")); background.setColor(Color.valueOf("ff8000AA")); //backgroundImage = new Image(PixMindGame.getSkin().getDrawable("personaje fondo")); playImageS2D = new Image(PixMindGame.getSkin().getDrawable("play no selec")); optionsImageS2D = new Image(PixMindGame.getSkin().getDrawable("options no selec")); exitImageS2D = new Image(PixMindGame.getSkin().getDrawable("exit no selec")); //titleImageS2D = new Image(PixMindGame.getSkin().getDrawable("sweetmind")); sweet = new Image(PixMindGame.getSkin().getDrawable("sweet")); mind = new Image(PixMindGame.getSkin().getDrawable("mind")); sweetes = new Image(PixMindGame.getSkin().getDrawable("caramelos1")); // adding actor listeners playImageS2D.addListener(new ActorGestureListener(){ boolean selected = true; public void touchDown (InputEvent event, float x, float y, int pointer, int button) { playImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("play selec")); selected = true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if(selected){ System.out.println("PLAY TOUCHED"); if(PixMindGame.infoFx) PixMindGame.getMenuClick().play(0.3f); game.changeLevel(game.getLevelSelector1Screen()); } } @Override public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) { // TODO Auto-generated method stub System.out.println("x " + x + " y " + y); System.out.println("x " + playImageS2D.getWidth() + " y "+ playImageS2D.getHeight()); if(x<0 || x>playImageS2D.getWidth() || y<0 || y>playImageS2D.getHeight()){ playImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("play no selec")); selected= false; } } }); optionsImageS2D.addListener(new ActorGestureListener(){ boolean selected = true; public void touchDown (InputEvent event, float x, float y, int pointer, int button) { optionsImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("options selec")); selected = true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if(selected){ System.out.println("PLAY TOUCHED"); if(PixMindGame.infoFx) PixMindGame.getMenuClick().play(0.3f); game.changeLevel(game.getOptionsMenuScreen()); } } @Override public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) { // TODO Auto-generated method stub System.out.println("x " + x + " y " + y); System.out.println("x " + playImageS2D.getWidth() + " y "+ playImageS2D.getHeight()); if(x<0 || x>optionsImageS2D.getWidth() || y<0 || y>optionsImageS2D.getHeight()){ optionsImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("options no selec")); selected= false; } } }); exitImageS2D.addListener(new ActorGestureListener(){ boolean selected = true; public void touchDown (InputEvent event, float x, float y, int pointer, int button) { exitImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("exit selec")); selected = true; } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if(selected){ System.out.println("PLAY TOUCHED"); if(PixMindGame.infoFx) PixMindGame.getMenuClick().play(0.3f); Gdx.app.exit(); } } @Override public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) { // TODO Auto-generated method stub System.out.println("x " + x + " y " + y); System.out.println("x " + playImageS2D.getWidth() + " y "+ playImageS2D.getHeight()); if(x<0 || x>exitImageS2D.getWidth() || y<0 || y>exitImageS2D.getHeight()){ exitImageS2D.setDrawable(PixMindGame.getSkin().getDrawable("exit no selec")); selected= false; } } }); // setting actors positions playImageS2D.setPosition((PixMindGame.w/2)-playImageS2D.getWidth()/2-200, 330); optionsImageS2D.setPosition((PixMindGame.w/2)-optionsImageS2D.getWidth()/2, 330); exitImageS2D.setPosition((PixMindGame.w/2)-exitImageS2D.getWidth()/2+200, 330); // titleImageS2D.setPosition((PixMindGame.w/2)-titleImageS2D.getWidth()/2, 350); background.setPosition((PixMindGame.w/2)-background.getWidth()/2, 0); //backgroundImage.setPosition(PixMindGame.w-backgroundImage.getWidth(), 0); playImageS2D.setScale(0.9f); optionsImageS2D.setScale(0.9f); exitImageS2D.setScale(0.9f); /* Interpolation interpolation = Interpolation.linear; playImageS2D.setOrigin(playImageS2D.getWidth()/2, playImageS2D.getHeight()/2); //playImageS2D.setRotation(-1); playImageS2D.setScale(0.9f); playImageS2D.addAction(Actions.forever(Actions.sequence( Actions.scaleBy(0.05f, -0.05f, 1f, interpolation), Actions.scaleBy(-0.05f, 0.05f, 1f, interpolation)))); optionsImageS2D.setOrigin(optionsImageS2D.getWidth()/2, optionsImageS2D.getHeight()/2); //optionsImageS2D.setRotation(-1); optionsImageS2D.setScale(0.9f); optionsImageS2D.addAction(Actions.forever(Actions.sequence( Actions.scaleBy(0.05f, -0.05f, 1f, interpolation), Actions.scaleBy(-0.05f, 0.05f, 1f, interpolation)))); exitImageS2D.setOrigin(exitImageS2D.getWidth()/2, exitImageS2D.getHeight()/2); //exitImageS2D.setRotation(-1); exitImageS2D.setScale(0.9f); exitImageS2D.addAction(Actions.forever(Actions.sequence( Actions.scaleBy(0.05f, -0.05f, 1f, interpolation), Actions.scaleBy(-0.05f, 0.05f, 1f, interpolation))));*/ // adding actors to the stage (to an stage group) mainMenuStage.addActor(background); // mainMenuStage.addActor(backgroundImage); mainMenuStage.addActor(playImageS2D); mainMenuStage.addActor(optionsImageS2D); mainMenuStage.addActor(exitImageS2D); //mainMenuStage.addActor(titleImageS2D); //mainMenuStage.addActor(sweet); //mainMenuStage.addActor(mind); // mainMenuStage.addActor(sweetes); //menuGroup.setPosition(-(854-PixMindGame.w)/2, 0); // loading and playing main menu music loop PixMindGame.getMusic().setLooping(true); PixMindGame.getMusic().setVolume(0.3f); if (PixMindGame.infoMusic) PixMindGame.getMusic().play(); /*if ( PixMindGame.getMusic().isPlaying() && game.getMusicState().equalsIgnoreCase("off") ) PixMindGame.getMusic().stop();*/ /*Preferences oP = Gdx.app.getPreferences("OptionsPrefs"); boolean musicOn = oP.getBoolean("mus"); if ( musicOn && !PixMindGame.getMusic().isPlaying() ) PixMindGame.getMusic().play(); if ( !musicOn && PixMindGame.getMusic().isPlaying() ) PixMindGame.getMusic().stop(); */ // mainMenuStage.addActor(menuGroup); //animacion candies = new ArrayList<Body>(); debugRenderer = new Box2DDebugRenderer(); world = new World(new Vector2(0, -6f), true); camera = new OrthographicCamera(PixMindGame.w * PixMindGame.WORLD_TO_BOX, PixMindGame.h * PixMindGame.WORLD_TO_BOX); camera.translate(PixMindGame.w / 2 * PixMindGame.WORLD_TO_BOX, PixMindGame.h / 2 * PixMindGame.WORLD_TO_BOX); /* generatePlatform(world, +PixMindGame.w* PixMindGame.WORLD_TO_BOX*0.22f, 3, PixMindGame.w / 4.4f* PixMindGame.WORLD_TO_BOX, 0.1f, - (float)Math.PI/5.4f); generatePlatform(world, PixMindGame.w* PixMindGame.WORLD_TO_BOX-PixMindGame.w* PixMindGame.WORLD_TO_BOX*0.22f, 3, PixMindGame.w / 4.4f* PixMindGame.WORLD_TO_BOX,0.1f, (float)Math.PI/5.4f); generatePlatform(world, PixMindGame.w* PixMindGame.WORLD_TO_BOX/2, 0.1f, 1.5f, 0.1f, 0); */ //generateCandy(world,2,4,10, PixMindGame.getSkin().getDrawable("redcandy")); generateSweet(world, (PixMindGame.w/2)-(sweet.getWidth())-20,110, sweet); generateMind(world, (PixMindGame.w/2)+50,110, mind); //generatePlatform(world, 3,0.3f,0.589f*4,0.138f*4,0); sweetes.setPosition((PixMindGame.w/2)-sweetes.getWidth()/2, 0); mainMenuStage.addActor(sweetes); // titleImageS2D.setZIndex(200); exitImageS2D.setZIndex(200); optionsImageS2D.setZIndex(200); playImageS2D.setZIndex(200); camera.update(); candiesDrawables[0] = PixMindGame.getSkin().getDrawable("redcandy"); candiesDrawables[1] = PixMindGame.getSkin().getDrawable("bluecandy"); candiesDrawables[2] = PixMindGame.getSkin().getDrawable("greencandy"); candiesDrawables[3] = PixMindGame.getSkin().getDrawable("orangecandy"); } private void generateSweet(World world, float x, float y, Image image) { // 0. Create a loader for the file saved from the editor. BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("gfx/sweet")); // 1. Create a BodyDef, as usual. BodyDef bd = new BodyDef(); bd.position.set(x*PixMindGame.WORLD_TO_BOX, y*PixMindGame.WORLD_TO_BOX); bd.type = BodyType.StaticBody; // 2. Create a FixtureDef, as usual. FixtureDef fd = new FixtureDef(); fd.density = 1; fd.friction = 0.9f; fd.restitution = 0.6f; // 3. Create a Body, as usual. Body bottleModel = world.createBody(bd); // 4. Create the body fixture automatically by using the loader. loader.attachFixture(bottleModel, "sweet", fd, 2.85f); image.setPosition(x, y); mainMenuStage.addActor(image); } private void generateMind(World world, float x, float y, Image image) { // 0. Create a loader for the file saved from the editor. BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("gfx/sweet")); // 1. Create a BodyDef, as usual. BodyDef bd = new BodyDef(); bd.position.set(x*PixMindGame.WORLD_TO_BOX, y*PixMindGame.WORLD_TO_BOX); bd.type = BodyType.StaticBody; // 2. Create a FixtureDef, as usual. FixtureDef fd = new FixtureDef(); fd.density = 1; fd.friction = 0.9f; fd.restitution = 0.6f; // 3. Create a Body, as usual. Body bottleModel = world.createBody(bd); // 4. Create the body fixture automatically by using the loader. loader.attachFixture(bottleModel, "mind", fd, 2.35f); image.setPosition(x, y); mainMenuStage.addActor(image); } private void generateCandy(World world, float x, float y, float rotation, Drawable image) { BodyDef bodyDef = new BodyDef(); //bodyDef.fixedRotation = true; // We set our body to dynamic, for something like ground which doesn't // move we would set it to StaticBody bodyDef.type = BodyType.DynamicBody; // Set our body's starting position in the world //setPosition(x, y); bodyDef.position.set(x,y); //bodyDef.angle = (float) (Math.PI/7); // Create our body in the world using our body definition Body body = world.createBody(bodyDef); // Create a polygon shape // Set the polygon shape as a box which is twice the size of our view // port and 20 high // (setAsBox takes half-width and half-height as arguments) // groundBox.setAsBox(camera.viewportWidth, 10.0f); Shape groundBox; if(image.equals( PixMindGame.getSkin().getDrawable("bluecandy"))){ groundBox = new PolygonShape(); PolygonShape s = (PolygonShape) groundBox; s.setAsBox(candySize,candySize/2.2f); }else if (image.equals( PixMindGame.getSkin().getDrawable("greencandy"))){ groundBox = new CircleShape(); groundBox.setRadius(candySize/1.7f); }else{ groundBox = new CircleShape(); groundBox.setRadius(candySize); } // Create a fixture definition to apply our shape to FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = groundBox; fixtureDef.density = 1f; fixtureDef.friction = 0.9f; fixtureDef.restitution = 0.6f; // Make it bounce a little bit // Create our fixture and attach it to the body Fixture fixture = body.createFixture(fixtureDef); Image candyImage = new Image(image); candyImage.setSize(candySize * PixMindGame.BOX_TO_WORLD * 2, candySize * PixMindGame.BOX_TO_WORLD * 2); candyImage.setOrigin(candySize* PixMindGame.BOX_TO_WORLD, candySize * PixMindGame.BOX_TO_WORLD); candyImage.setPosition((body.getPosition().x - candySize)*PixMindGame.BOX_TO_WORLD, (body.getPosition().y-candySize)*PixMindGame.BOX_TO_WORLD); candyImage.setRotation((float) (body.getAngle()*360/(2*Math.PI))); mainMenuStage.addActor(candyImage); fixture.setUserData(candyImage); candies.add(body); groundBox.dispose(); } public void generatePlatform(World world, float x, float y, float width, float height, float rotation){ BodyDef groundBodyDef =new BodyDef(); // Set its world position groundBodyDef.type = BodyType.StaticBody; groundBodyDef.position.set(new Vector2(x, y)); groundBodyDef.angle = rotation; // Create a body from the defintion and add it to the world Body groundBody = world.createBody(groundBodyDef); // Create a polygon shape PolygonShape groundBox = new PolygonShape(); // Set the polygon shape as a box which is twice the size of our view port and 20 high // (setAsBox takes half-width and half-height as arguments) // groundBox.setAsBox(camera.viewportWidth, 10.0f); groundBox.setAsBox(width, height); // Create a fixture definition to apply our shape to FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = groundBox; fixtureDef.density = 0.5f; //fixtureDef.isSensor = true; //dont collide phisically but register collide information fixtureDef.friction = 0.4f; //fixtureDef.restitution = 0.6f; // Make it bounce a little bit // Create our fixture and attach it to the body Fixture fixture = groundBody.createFixture(fixtureDef); Image platformImage = new Image(PixMindGame.getSkin().getDrawable("caramelos1")); platformImage.setSize(width * PixMindGame.BOX_TO_WORLD * 2, height * PixMindGame.BOX_TO_WORLD * 2); platformImage.setPosition(x * PixMindGame.BOX_TO_WORLD - width*PixMindGame.BOX_TO_WORLD, y * PixMindGame.BOX_TO_WORLD-height*PixMindGame.BOX_TO_WORLD); platformImage.setOrigin(width * PixMindGame.BOX_TO_WORLD, height * PixMindGame.BOX_TO_WORLD); platformImage.rotate((float) (360*rotation/(2*Math.PI))); mainMenuStage.addActor(platformImage); groundBox.dispose(); } @Override public void hide() { // TODO Auto-generated method stub } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { // TODO Auto-generated method stub mainMenuStage.dispose(); world.dispose(); candies.clear(); } }
tuxskar/pixmind
pixmind/src/com/pix/mind/screens/MainMenuScreen.java
Java
gpl-3.0
18,928
package ru.falseteam.vframe.socket; import javafx.util.Pair; import ru.falseteam.vframe.socket.ConnectionAbstract; import ru.falseteam.vframe.socket.Container; import java.lang.reflect.Array; import java.util.*; /** * Subscription manager. * * @author Sumin Vladislav * @version 3.0 */ public class SubscriptionManager<T extends Enum<T>> { static class SubscriptionProtocol extends ProtocolAbstract { @SuppressWarnings("unchecked") @Override public void exec(Map<String, Object> data, ConnectionAbstract connection) { if (data == null) return; String requestType = data.get("requestType").toString(); String eventName = data.get("eventName").toString(); if (requestType == null || eventName == null) return; Container container = new Container(getName(), true); container.data.put("eventName", eventName); switch (requestType) { case "subscribe": container.data.put("subscription", connection.getWorker().getSubscriptionManager().addSubscription(eventName, connection)); connection.send(container); return; case "unsubscribe": container.data.put("subscription", connection.getWorker().getSubscriptionManager().removeSubscription(eventName, connection)); connection.send(container); } } } SubscriptionManager() { } public interface SubscriptionInterface { Map<String, Object> getAllData(); } private class Data { final SubscriptionInterface subscriptionInterface; final List<ConnectionAbstract<T>> subscribers; final List<T> permissions; Data(SubscriptionInterface subscriptionInterface, T[] permissions) { this.subscriptionInterface = subscriptionInterface; this.permissions = Arrays.asList(permissions); subscribers = new LinkedList<>(); } } private final Map<String, Data> events = new HashMap<>(); public void addEvent(String name, SubscriptionInterface allInfoMethod, T... permissions) { synchronized (events) { events.put(name, new Data(allInfoMethod, permissions)); } } private Map<String, Object> getAllData(String eventName) { return events.get(eventName).subscriptionInterface.getAllData(); } public void onEventDataChange(String eventName, Map<String, Object> newData) { synchronized (events) { events.get(eventName).subscribers.forEach(connection -> connection.send(dataUpdate(eventName, newData))); //TODO отправлять только изменения а не все по новой } } boolean addSubscription(String eventName, ConnectionAbstract<T> connection) { synchronized (events) { if (events.containsKey(eventName)) { Data data = events.get(eventName); if (data.permissions.contains(connection.getPermission())) { data.subscribers.add(connection); connection.send(dataUpdate(eventName, getAllData(eventName))); return true; } } return false; } } boolean removeSubscription(String eventName, ConnectionAbstract<T> connection) { synchronized (events) { if (events.containsKey(eventName)) { events.get(eventName).subscribers.remove(connection); return true; } return false; } } public void removeSubscriber(ConnectionAbstract<T> connection) { synchronized (events) { events.forEach((s, pair) -> pair.subscribers.remove(connection)); } } private Container dataUpdate(String eventName, Map<String, Object> data) { Container container = new Container("SubscriptionSyncProtocol", true); container.data.put("eventName", eventName); container.data.put("data", data); return container; } //TODO возможно потом протокол синхронизации, где при повтороной подписке вычисляются изменения, но это потом. }
VladislavSumin/VFrame
server/src/main/java/ru/falseteam/vframe/socket/SubscriptionManager.java
Java
gpl-3.0
4,429
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.iface.instruction.formats; import org.jf.dexlib2.iface.instruction.PayloadInstruction; import java.util.List; public interface ArrayPayload extends PayloadInstruction { public int getElementWidth(); public List<Number> getArrayElements(); }
droidefense/engine
mods/memapktool/src/main/java/org/jf/dexlib2/iface/instruction/formats/ArrayPayload.java
Java
gpl-3.0
1,840
package org.dllearner.test.junit; import org.dllearner.algorithms.DisjointClassesLearner; import org.dllearner.kb.SparqlEndpointKS; import org.dllearner.reasoning.SPARQLReasoner; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClassExpression; import uk.ac.manchester.cs.owl.owlapi.OWLClassImpl; public class DisjointClassesLearningTest { //extends TestCase{ private SparqlEndpointKS ks; private SPARQLReasoner reasoner; private static final int maxExecutionTimeInSeconds = 10; // @Override // protected void setUp() throws Exception { // super.setUp(); // ks = new SparqlEndpointKS(SparqlEndpoint.getEndpointDBpediaLiveAKSW()); // // reasoner = new SPARQLReasoner(ks); // reasoner.prepareSubsumptionHierarchy(); // } public void testLearnSingleClass(){ DisjointClassesLearner l = new DisjointClassesLearner(ks); l.setReasoner(reasoner); l.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds); l.setEntityToDescribe(new OWLClassImpl(IRI.create("http://dbpedia.org/ontology/Book"))); l.start(); System.out.println(l.getCurrentlyBestAxioms(5)); } public void testLearnForMostGeneralClasses(){ DisjointClassesLearner l = new DisjointClassesLearner(ks); l.setReasoner(reasoner); l.setMaxExecutionTimeInSeconds(maxExecutionTimeInSeconds); for(OWLClassExpression cls : reasoner.getClassHierarchy().getMostGeneralClasses()){ l.setEntityToDescribe(cls.asOWLClass()); l.start(); System.out.println(l.getCurrentlyBestAxioms(5)); } } }
MaRoe/DL-Learner
components-core/src/test/java/org/dllearner/test/junit/DisjointClassesLearningTest.java
Java
gpl-3.0
1,518
/** * This file is part of SADL, a library for learning all sorts of (timed) automata and performing sequence-based anomaly detection. * Copyright (C) 2013-2018 the original author or authors. * * SADL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * SADL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with SADL. If not, see <http://www.gnu.org/licenses/>. */ package sadl.modellearner; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import gnu.trove.list.TDoubleList; import gnu.trove.list.array.TDoubleArrayList; import jsat.distributions.ContinuousDistribution; import jsat.distributions.MyDistributionSearch; import jsat.distributions.SingleValueDistribution; import jsat.distributions.empirical.MyKernelDensityEstimator; import jsat.distributions.empirical.kernelfunc.KernelFunction; import jsat.linear.DenseVector; import jsat.linear.Vec; import sadl.constants.MergeTest; import sadl.input.TimedInput; import sadl.input.TimedWord; import sadl.interfaces.ProbabilisticModelLearner; import sadl.models.PDTTAold; import sadl.structure.ZeroProbTransition; import sadl.utils.IoUtils; import sadl.utils.Settings; import treba.observations; import treba.treba; import treba.trebaConstants; import treba.wfsa; /** * * @author Timo Klerx * */ @SuppressWarnings("all") public class PdttaLeanerOld implements ProbabilisticModelLearner { double mergeAlpha; MergeTest mergeTest = MergeTest.ALERGIA; boolean recursiveMergeTest; private static Logger logger = LoggerFactory.getLogger(PdttaLeanerOld.class); int fsmStateCount = -1; KernelFunction kdeKernelFunction; double kdeBandwidth; double smoothingPrior = 0.00; int mergeT0 = 3; public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest) { this.mergeAlpha = mergeAlpha; this.recursiveMergeTest = recursiveMergeTest; } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, KernelFunction kdeKernelFunction, double kdeBandwidth) { this(mergeAlpha, recursiveMergeTest); this.kdeKernelFunction = kdeKernelFunction; this.kdeBandwidth = kdeBandwidth; } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, KernelFunction kdeKernelFunction, double kdeBandwidth, MergeTest mergeTest) { this(mergeAlpha, recursiveMergeTest, kdeKernelFunction, kdeBandwidth); this.mergeTest = mergeTest; } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, KernelFunction kdeKernelFunction, double kdeBandwidth, MergeTest mergeTest, double smoothingPrior) { this(mergeAlpha, recursiveMergeTest, kdeKernelFunction, kdeBandwidth, mergeTest); this.smoothingPrior = smoothingPrior; } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, KernelFunction kdeKernelFunction, double kdeBandwidth, MergeTest mergeTest, double smoothingPrior, int mergeT0) { this(mergeAlpha, recursiveMergeTest, kdeKernelFunction, kdeBandwidth, mergeTest, smoothingPrior); this.mergeT0 = mergeT0; } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, MergeTest mergeTest) { this(mergeAlpha, recursiveMergeTest, null, -1, mergeTest); } public PdttaLeanerOld(double mergeAlpha, boolean recursiveMergeTest, MergeTest mergeTest, double smoothingPrior) { this(mergeAlpha, recursiveMergeTest, null, -1, mergeTest, smoothingPrior); } @Override public PDTTAold train(TimedInput trainingSequences) { final PDTTAold pdtta; treba.log1plus_init_wrapper(); final Path tempDir = Paths.get(System.getProperty("java.io.tmpdir")); final long jobNumber = Double.doubleToLongBits(Math.random()); String jobName = Long.toString(jobNumber); jobName = jobName.substring(0, 5); // create treba input file final String tempFilePrefix = tempDir.toString() + File.separatorChar + jobName + getClass().getName(); final String trebaTrainSetFileString = tempFilePrefix + "train_set"; try { createTrebaFile(trainingSequences, trebaTrainSetFileString); final String trebaAutomatonFile = tempFilePrefix + "fsm.fsm"; final double loglikelihood = trainFsm(trebaTrainSetFileString, trebaAutomatonFile); logger.info("learned event automaton has loglikelihood of {}", loglikelihood); // compute paths through the automata for the training set and write to // 'trebaResultPathFile' final String trebaResultPathFile = tempFilePrefix + "train_likelihood"; computeAutomatonPaths(trebaAutomatonFile, trebaTrainSetFileString, trebaResultPathFile); // parse the 'trebaResultPathFile' // Fill time interval buckets and fit PDFs for every bucket final Map<ZeroProbTransition, TDoubleList> timeValueBuckets = parseAutomatonPaths(trebaResultPathFile, trainingSequences); // do the fitting final Map<ZeroProbTransition, ContinuousDistribution> transitionDistributions = fit(timeValueBuckets); // compute likelihood on test set for automaton and for time PDFs pdtta = new PDTTAold(Paths.get(trebaAutomatonFile), trainingSequences); pdtta.setTransitionDistributions(transitionDistributions); if (!Settings.isDebug()) { IoUtils.deleteFiles(new String[] { trebaTrainSetFileString, trebaAutomatonFile, trebaResultPathFile }); } else { logger.info("temp dir: {}", tempDir); } treba.log1plus_free_wrapper(); return pdtta; } catch (final IOException e) { logger.error("An unexpected error occured", e); e.printStackTrace(); } return null; } private Map<ZeroProbTransition, ContinuousDistribution> fit(Map<ZeroProbTransition, TDoubleList> timeValueBuckets) { final Map<ZeroProbTransition, ContinuousDistribution> result = new HashMap<>(); for (final ZeroProbTransition t : timeValueBuckets.keySet()) { result.put(t, fitDistribution(timeValueBuckets.get(t))); } return result; } double[] ds = new double[] { 627.0, 667.0, 691.0, 743.0, 756.0, 821.0, 823.0, 923.0, 1285.0, 2054.0, 2599.0, 2617.0, 2970.0, 3854.0, 4132.0, 5002.0, 5186.0, 5327.0, 6281.0, 6395.0, 8111.0, 8168.0, 8431.0, 8811.0, 8886.0, 9147.0, 9410.0, 9461.0, 9565.0, 9612.0, 9893.0, 10017.0, 10755.0, 10775.0, 12439.0, 13232.0, 13329.0, 13435.0, 18433.0, 22705.0, 24529.0, 37176.0 }; @SuppressWarnings("boxing") private ContinuousDistribution fitDistribution(TDoubleList transitionTimes) { if (Arrays.equals(ds, transitionTimes.toArray())) { logger.info("Peng"); } final Vec v = new DenseVector(transitionTimes.toArray()); final jsat.utils.Pair<Boolean, Double> sameValues = MyDistributionSearch.checkForDifferentValues(v); if (sameValues.getFirstItem()) { final ContinuousDistribution d = new SingleValueDistribution(sameValues.getSecondItem()); return d; } else { KernelFunction newKernelFunction = kdeKernelFunction; if (newKernelFunction == null) { newKernelFunction = MyKernelDensityEstimator.autoKernel(v); } double newKdeBandwidth = kdeBandwidth; if (newKdeBandwidth <= 0) { newKdeBandwidth = MyKernelDensityEstimator.BandwithGuassEstimate(v); } final MyKernelDensityEstimator kde = new MyKernelDensityEstimator(v, newKernelFunction, newKdeBandwidth); return kde; } } private Map<ZeroProbTransition, TDoubleList> parseAutomatonPaths(String trebaResultPathFile, TimedInput timedSequences) throws IOException { final Map<ZeroProbTransition, TDoubleList> result = new HashMap<>(); final BufferedReader br = Files.newBufferedReader(Paths.get(trebaResultPathFile), StandardCharsets.UTF_8); String line = null; int rowIndex = 0; int currentState = -1; int followingState = -1; while ((line = br.readLine()) != null) { final String[] split = line.split("\\s+"); if (split.length - 2 != timedSequences.get(rowIndex).getTimeValues().size()) { logger.error("There should be one more state than there are time values (time values fill the gaps between the states\n{}\n{}", Arrays.toString(split), timedSequences.get(rowIndex).getTimeValues()); logger.error("Error occured in line={}", rowIndex); break; } // first element is likelihood; not interested in that right now for (int i = 1; i < split.length - 1; i++) { currentState = Integer.parseInt(split[i]); followingState = Integer.parseInt(split[i + 1]); addTimeValue(result, currentState, followingState, timedSequences.get(rowIndex).getSymbol(i - 1), timedSequences.get(rowIndex).getTimeValue(i - 1)); } rowIndex++; } if (rowIndex != timedSequences.size()) { logger.error("rowCount and sequences length do not match ({} / {})", rowIndex, timedSequences.size()); } br.close(); return result; } private void addTimeValue(Map<ZeroProbTransition, TDoubleList> result, int currentState, int followingState, String event, double timeValue) { final ZeroProbTransition t = new ZeroProbTransition(currentState, followingState, event); final TDoubleList list = result.get(t); if (list == null) { final TDoubleList tempList = new TDoubleArrayList(); tempList.add(timeValue); result.put(t, tempList); } else { list.add(timeValue); } } @SuppressWarnings("null") private void computeAutomatonPaths(String trebaAutomatonFile, String trebaTrainFileString, String trebaResultPathFile) { // treba.log1plus_taylor_init_wrapper(); final observations o = treba.observations_read(trebaTrainFileString); final wfsa fsm = treba.wfsa_read_file(trebaAutomatonFile); final int obs_alphabet_size = treba.observations_alphabet_size(o); if (o == null) { logger.error("Error: the observations file could not be read:{}", trebaTrainFileString); System.exit(1); } if (fsm == null) { logger.error("Error: the fsm file could not be read:{}", trebaAutomatonFile); System.exit(1); } if (o != null && fsm != null && fsm.getAlphabet_size() < obs_alphabet_size) { logger.error("Error: the observations file has symbols outside the FSA alphabet.\n"); System.exit(1); } if (trebaConstants.FORMAT_LOG2 != 0) { treba.wfsa_to_log2(fsm); } fsmStateCount = fsm.getNum_states(); // write the visited states for each observation to the file (trebaResultPathFile) treba.forward_fsm_to_file(fsm, o, trebaConstants.DECODE_FORWARD_PROB, trebaResultPathFile); if (o != null) { treba.observations_destroy(o); } if (fsm != null) { treba.wfsa_destroy(fsm); // treba.log1plus_free_wrapper(); } } private void createTrebaFile(TimedInput timedSequences, String trebaTrainFileString) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(trebaTrainFileString), StandardCharsets.UTF_8)) { for (final TimedWord ts : timedSequences) { bw.write(getSymbolString(ts, timedSequences)); bw.append('\n'); } bw.close(); } } private String getSymbolString(TimedWord ts, TimedInput timedSequences) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < ts.length(); i++) { sb.append(timedSequences.getAlphIndex(ts.getSymbol(i))); if (i != ts.length() - 1) { sb.append(' '); } } return sb.toString(); } protected double trainFsm(String eventTrainFile, String fsmOutputFile) { int recursive_merge_test = 0; if (recursiveMergeTest) { recursive_merge_test = 1; } treba.setT0(mergeT0); treba.setPrior(smoothingPrior); double ll; observations o = treba.observations_read(eventTrainFile); if (o == null) { logger.error("Error reading observations file {}", eventTrainFile); System.exit(1); } o = treba.observations_sort(o); o = treba.observations_uniq(o); wfsa fsm; if (mergeTest == MergeTest.MDI) { fsm = treba.dffa_to_wfsa(treba.dffa_mdi(o, mergeAlpha)); } else { fsm = treba.dffa_to_wfsa(treba.dffa_state_merge(o, mergeAlpha, mergeTest.getAlgorithm(), recursive_merge_test)); } ll = treba.loglikelihood_all_observations_fsm(fsm, o); treba.wfsa_to_file(fsm, fsmOutputFile); if (fsm != null) { treba.wfsa_destroy(fsm); } if (o != null) { treba.observations_destroy(o); } return ll; } }
TKlerx/SADL
PDTTA-core/src/sadl/modellearner/PdttaLeanerOld.java
Java
gpl-3.0
12,608
package ro.godmark.tools.youtube.exceptions; /** * Custom Exception for missing youtube url. * User: Godmark * Date: 06/06/14 * Time: 21:29 */ public class MissingYoutubeUrlException extends Exception { /** * Default constructor. */ public MissingYoutubeUrlException() { super(); } /** * The constructor accepts a string as a message. * * @param message - the string message for this exception. */ public MissingYoutubeUrlException(final String message) { super(message); } }
GodMark/godmark_personal_tools
youtube_downloader/src/main/java/ro/godmark/tools/youtube/exceptions/MissingYoutubeUrlException.java
Java
gpl-3.0
554
// // Decompiled by Procyon v0.5.30 // package com.intenso.jira.plugins.synchronizer.entity; import net.java.ao.schema.Indexed; import net.java.ao.schema.Table; import net.java.ao.Preload; import net.java.ao.Entity; @Preload({ "contractId", "eventId" }) @Table("contr_events") public interface ContractEvents extends Entity { @Indexed Integer getContractId(); @Indexed Long getEventId(); Integer getEventType(); void setContractId(final Integer p0); void setEventId(final Long p0); void setEventType(final Integer p0); }
IrbisChaos/synchronizer
src/main/java/com/intenso/jira/plugins/synchronizer/entity/ContractEvents.java
Java
gpl-3.0
583
/******************************************************************************* * Copyright (c) 2014 BitRangers (Team C1). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BitRangers (Team C1) - initial API and implementation ******************************************************************************/ package com.bitranger.parknshop.admin.data; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.bitranger.parknshop.seller.model.PsOrderLog; /** * PsAdminAcc entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "ps_admin_acc", catalog = "c1_parknshop") public class PsAdminAcc implements java.io.Serializable { // Fields private Integer id; private PsAdministrator psAdministrator; private PsOrderLog psOrderLog; private Double amount; private Timestamp timeCreated; // Constructors /** default constructor */ public PsAdminAcc() { } /** minimal constructor */ public PsAdminAcc(PsAdministrator psAdministrator, PsOrderLog psOrderLog, Timestamp timeCreated) { this.psAdministrator = psAdministrator; this.psOrderLog = psOrderLog; this.timeCreated = timeCreated; } /** full constructor */ public PsAdminAcc(PsAdministrator psAdministrator, PsOrderLog psOrderLog, Double amount, Timestamp timeCreated) { this.psAdministrator = psAdministrator; this.psOrderLog = psOrderLog; this.amount = amount; this.timeCreated = timeCreated; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_admin", nullable = false) public PsAdministrator getPsAdministrator() { return this.psAdministrator; } public void setPsAdministrator(PsAdministrator psAdministrator) { this.psAdministrator = psAdministrator; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_order_log", nullable = false) public PsOrderLog getPsOrderLog() { return this.psOrderLog; } public void setPsOrderLog(PsOrderLog psOrderLog) { this.psOrderLog = psOrderLog; } @Column(name = "amount", precision = 9) public Double getAmount() { return this.amount; } public void setAmount(Double amount) { this.amount = amount; } @Column(name = "time_created", nullable = false, length = 19) public Timestamp getTimeCreated() { return this.timeCreated; } public void setTimeCreated(Timestamp timeCreated) { this.timeCreated = timeCreated; } }
BitRanger/C1_ParknShop
src/com/bitranger/parknshop/admin/data/PsAdminAcc.java
Java
gpl-3.0
3,083