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
|
---|---|---|---|---|---|
/*
* Copyright 2010, 2011, 2012 mapsforge.org
*
* This program 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 org.mapsforge.android.maps.mapgenerator.databaserenderer;
import android.graphics.Paint;
class ShapePaintContainer {
final Paint paint;
final ShapeContainer shapeContainer;
ShapePaintContainer(ShapeContainer shapeContainer, Paint paint) {
this.shapeContainer = shapeContainer;
this.paint = paint;
}
}
| tghoward/geopaparazzi | geopaparazzimapsforge/src/org/mapsforge/android/maps/mapgenerator/databaserenderer/ShapePaintContainer.java | Java | gpl-3.0 | 1,033 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. García ([email protected])
A. Fernández ([email protected])
J. Luengo ([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 keel.Algorithms.Fuzzy_Rule_Learning.Genetic.ClassifierSLAVE;
/**
* <p>
* @author Written by Alberto Fernández (University of Granada) 01/01/2007
* @author Modified by Francisco José Berlanga (University of Jaén) 09/12/2008
* @version 1.0
* @since JDK 1.6
* </p>
*/
package keel.Algorithms.Fuzzy_Rule_Learning.Genetic.ClassifierSLAVE2;
import java.util.StringTokenizer;
import java.util.ArrayList;
import org.core.Files;
public class parseParameters {
/**
* <p>
* It reads the configuration file (data-set files and parameters)
* </p>
*/
private String algorithmName;
private String trainingFile, validationFile, testFile;
private ArrayList <String> inputFiles;
private String outputTrFile, outputTstFile;
private ArrayList <String> outputFiles;
private ArrayList <String> parameters;
/**
* <p>
* Default constructor
* </p>
*/
public parseParameters() {
inputFiles = new ArrayList<String>();
outputFiles = new ArrayList<String>();
parameters = new ArrayList<String>();
}
/**
* <p>
* It obtains all the necesary information from the configuration file.<br/>
* First of all it reads the name of the input data-sets, training, validation and test.<br/>
* Then it reads the name of the output files, where the training (validation) and test outputs will be stored<br/>
* Finally it read the parameters of the algorithm, such as the random seed.<br/>
* </p>
* @param fileName Name of the configuration file
*/
public void parseConfigurationFile(String fileName) {
StringTokenizer line;
String file = Files.readFile(fileName); //file is an string containing the whole file
line = new StringTokenizer(file, "\n\r");
readName(line); //We read the algorithm name
readInputFiles(line); //We read all the input files
readOutputFiles(line); //We read all the output files
readAllParameters(line); //We read all the possible parameters
};
/**
* <p>
* It reads the name of the algorithm from the configuration file
* @param line StringTokenizer It is the line containing the algorithm name.
* </p>
*/
private void readName(StringTokenizer line){
StringTokenizer data = new StringTokenizer(line.nextToken(), " = \" ");
data.nextToken();
algorithmName = new String(data.nextToken());
while(data.hasMoreTokens()){
algorithmName += " "+data.nextToken(); //We read the algorithm name
}
}
/**
* <p>
* We read the input data-set files and all the possible input files
* @param line StringTokenizer It is the line containing the input files.
* </p>
*/
private void readInputFiles(StringTokenizer line){
String new_line = line.nextToken(); //We read the input data line
StringTokenizer data = new StringTokenizer(new_line, " = \" ");
data.nextToken(); //inputFile
trainingFile = data.nextToken();
validationFile = data.nextToken();
testFile = data.nextToken();
while(data.hasMoreTokens()){
inputFiles.add(data.nextToken());
}
}
/**
* <p>
* We read the output files for training and test and all the possible remaining output files
* @param line StringTokenizer It is the line containing the output files.
* </p>
*/
private void readOutputFiles(StringTokenizer line){
String new_line = line.nextToken(); //We read the input data line
StringTokenizer data = new StringTokenizer(new_line, " = \" ");
data.nextToken(); //inputFile
outputTrFile = data.nextToken();
outputTstFile = data.nextToken();
while(data.hasMoreTokens()){
outputFiles.add(data.nextToken());
}
}
/**
* <p>
* We read all the possible parameters of the algorithm
* @param line StringTokenizer It contains all the parameters.
* </p>
*/
private void readAllParameters(StringTokenizer line){
String new_line,cadena;
StringTokenizer data;
while (line.hasMoreTokens()) { //While there is more parameters...
new_line = line.nextToken();
data = new StringTokenizer(new_line, " = ");
cadena = new String("");
while (data.hasMoreTokens()){
cadena = data.nextToken(); //parameter name
}
parameters.add(cadena); //parameter value
}
//If the algorithm is non-deterministic the first parameter is the Random SEED
}
/**
* <p>
* It returns the name of the file containing the training data
* @return String the name of the file containing the training data
* </p>
*/
public String getTrainingInputFile(){
return this.trainingFile;
}
/**
* <p>
* It returns the name of the file containing the test data
* @return String the name of the file containing the test data
* </p>
*/
public String getTestInputFile(){
return this.testFile;
}
/**
* <p>
* It returns the name of the file containing the validation data
* @return String the name of the file containing the validation data
* </p>
*/
public String getValidationInputFile(){
return this.validationFile;
}
/**
* <p>
* It returns the name of the file containing the output for the training data
* @return String the name of the file containing the output for the training data
* </p>
*/
public String getTrainingOutputFile(){
return this.outputTrFile;
}
/**
* <p>
* It returns the name of the file containing the output for the test data
* @return String the name of the file containing the output for the test data
* </p>
*/
public String getTestOutputFile(){
return this.outputTstFile;
}
/**
* <p>
* It returns the name of the algorithm
* @return String the name of the algorithm
* </p>
*/
public String getAlgorithmName(){
return this.algorithmName;
}
/**
* <p>
* It returns all the parameters as an array of Strings
* @return String [] all the parameters of the algorithm
* </p>
*/
public String [] getParameters(){
String [] param = (String []) parameters.toArray();
return param;
}
/**
* <p>
* It returns the parameter in the position "pos"
* @param pos int Position of the parameter
* @return String [] the parameter of the algorithm in position "pos"
* </p>
*/
public String getParameter(int pos){
return (String)parameters.get(pos);
}
/**
* <p>
* It returns all the input files
* @return String [] all the input files
* </p>
*/
public String [] getInputFiles(){
return (String []) inputFiles.toArray();
}
/**
* <p>
* It returns the input file in the position "pos"
* @param pos int Position of the input file
* @return String [] the input file of the algorithm in position "pos"
* </p>
*/
public String getInputFile(int pos){
return (String)this.inputFiles.get(pos);
}
/**
* <p>
* It returns all the output files
* @return String [] all the output files
* </p>
*/
public String [] getOutputFiles(){
return (String [])this.outputFiles.toArray();
}
/**
* <p>
* It returns the output file in the position "pos"
* @param pos int Position of the output file
* @return String [] the output file of the algorithm in position "pos"
* </p>
*/
public String getOutputFile(int pos){
return (String)this.outputFiles.get(pos);
}
}
| triguero/Keel3.0 | src/keel/Algorithms/Fuzzy_Rule_Learning/Genetic/ClassifierSLAVE2/parseParameters.java | Java | gpl-3.0 | 9,596 |
package jadeutils.web.har;
public class HarEntry {
private HarRequest request;
private HarResponse response;
/**
* @return the request
*/
public HarRequest getRequest() {
return request;
}
/**
* @param request
* the request to set
*/
public void setRequest(HarRequest request) {
this.request = request;
}
/**
* @return the response
*/
public HarResponse getResponse() {
return response;
}
/**
* @param response
* the response to set
*/
public void setResponse(HarResponse response) {
this.response = response;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((request == null) ? 0 : request.hashCode());
result = prime * result + ((response == null) ? 0 : response.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HarEntry other = (HarEntry) obj;
if (request == null) {
if (other.request != null)
return false;
} else if (!request.equals(other.request))
return false;
if (response == null) {
if (other.response != null)
return false;
} else if (!response.equals(other.response))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "HarEntry [" + (request != null ? "request=" + request + ", " : "")
+ (response != null ? "response=" + response : "") + "]";
}
public HarEntry(HarRequest request, HarResponse response) {
super();
this.request = request;
this.response = response;
}
}
| Jade-Shan/Jade-Java-utils | javautils-web/src/main/java/jadeutils/web/har/HarEntry.java | Java | gpl-3.0 | 1,961 |
package game;
import java.awt.Frame;
import java.awt.Color;
final class C_100227_af
{
static int field_106166_d;
static String[] field_106164_f;
static String field_106173_h;
static Color field_106165_g;
static String field_106171_j;
static C_100182_cc field_106170_a;
static String[] field_106174_i;
static String field_106167_e;
static Frame field_106168_b;
static String field_106169_c;
private static final String[] field_106172_z;
static final void func_106159_a(C_100037_wb[] arg0, int arg1, int arg2, C_100037_wb[] arg3, int arg4, int arg5, int arg6, byte arg7, int arg8, int arg9, C_100112_r arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16, C_100112_r arg17, int arg18, C_100037_wb[] arg19)
{
// @000: iload #5
// @002: iload #16
// @004: iload_1
// @005: aload #10
// @007: iload_2
// @008: iload #11
// @00A: iload #6
// @00C: new game.C_100127_tl
// @00F: dup
// @010: aload_0
// @011: invokespecial game.C_100127_tl.<init>(game.C_100037_wb[])void
// @014: iload #12
// @016: iload #7
// @018: bipush 126 (0x7E)
// @01A: ixor
// @01B: iload #18
// @01D: new game.C_100127_tl
// @020: dup
// @021: aload #19
// @023: invokespecial game.C_100127_tl.<init>(game.C_100037_wb[])void
// @026: iload #4
// @028: iload #13
// @02A: new game.C_100127_tl
// @02D: dup
// @02E: aload_3
// @02F: invokespecial game.C_100127_tl.<init>(game.C_100037_wb[])void
// @032: iload #14
// @034: aload #17
// @036: iload #15
// @038: iload #8
// @03A: iload #9
// @03C: invokestatic game.C_100084_ug.func_104470_a(int, int, int, game.C_100112_r, int, int, int, game.C_100127_tl, int, int, int, game.C_100127_tl, int, int, game.C_100127_tl, int, game.C_100112_r, int, int, int)void
// @03F: iload #7
// @041: bipush -128 (0x80)
// @043: if_icmpeq @04B
// @046: bipush -27 (0xE5)
// @048: putstatic int game.C_100227_af.field_106166_d
// @04B: goto @181
// @04E: astore #20
// @050: aload #20
// @052: new java.lang.StringBuilder
// @055: dup
// @056: invokespecial java.lang.StringBuilder.<init>()void
// @059: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @05C: iconst_5
// @05D: aaload
// @05E: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @061: aload_0
// @062: ifnull @06E
// @065: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @068: iconst_0
// @069: aaload
// @06A: goto @073
// @06D: athrow
// @06E: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @071: iconst_1
// @072: aaload
// @073: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @076: bipush 44 (0x2C)
// @078: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @07B: iload_1
// @07C: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @07F: bipush 44 (0x2C)
// @081: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @084: iload_2
// @085: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @088: bipush 44 (0x2C)
// @08A: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @08D: aload_3
// @08E: ifnull @09A
// @091: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @094: iconst_0
// @095: aaload
// @096: goto @09F
// @099: athrow
// @09A: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @09D: iconst_1
// @09E: aaload
// @09F: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @0A2: bipush 44 (0x2C)
// @0A4: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0A7: iload #4
// @0A9: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0AC: bipush 44 (0x2C)
// @0AE: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0B1: iload #5
// @0B3: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0B6: bipush 44 (0x2C)
// @0B8: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0BB: iload #6
// @0BD: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0C0: bipush 44 (0x2C)
// @0C2: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0C5: iload #7
// @0C7: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0CA: bipush 44 (0x2C)
// @0CC: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0CF: iload #8
// @0D1: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0D4: bipush 44 (0x2C)
// @0D6: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0D9: iload #9
// @0DB: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0DE: bipush 44 (0x2C)
// @0E0: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0E3: aload #10
// @0E5: ifnull @0F1
// @0E8: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @0EB: iconst_0
// @0EC: aaload
// @0ED: goto @0F6
// @0F0: athrow
// @0F1: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @0F4: iconst_1
// @0F5: aaload
// @0F6: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @0F9: bipush 44 (0x2C)
// @0FB: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0FE: iload #11
// @100: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @103: bipush 44 (0x2C)
// @105: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @108: iload #12
// @10A: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @10D: bipush 44 (0x2C)
// @10F: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @112: iload #13
// @114: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @117: bipush 44 (0x2C)
// @119: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @11C: iload #14
// @11E: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @121: bipush 44 (0x2C)
// @123: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @126: iload #15
// @128: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @12B: bipush 44 (0x2C)
// @12D: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @130: iload #16
// @132: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @135: bipush 44 (0x2C)
// @137: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @13A: aload #17
// @13C: ifnull @148
// @13F: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @142: iconst_0
// @143: aaload
// @144: goto @14D
// @147: athrow
// @148: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @14B: iconst_1
// @14C: aaload
// @14D: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @150: bipush 44 (0x2C)
// @152: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @155: iload #18
// @157: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @15A: bipush 44 (0x2C)
// @15C: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @15F: aload #19
// @161: ifnull @16D
// @164: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @167: iconst_0
// @168: aaload
// @169: goto @172
// @16C: athrow
// @16D: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @170: iconst_1
// @171: aaload
// @172: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @175: bipush 41 (0x29)
// @177: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @17A: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @17D: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @180: athrow
// @181: return
}
static final boolean func_106156_a(byte arg0)
{
// @00: iload_0
// @01: bipush 43 (0x2B)
// @03: if_icmpge @16
// @06: bipush -17 (0xEF)
// @08: aconst_null
// @09: checkcast int[]
// @0C: bipush 92 (0x5C)
// @0E: invokestatic game.C_100227_af.func_106160_a(int, int[], int)int
// @11: pop
// @12: goto @16
// @15: athrow
// @16: getstatic game.C_100211_qd game.C_100068_vc.field_104342_d
// @19: getfield long game.C_100211_qd.field_102156_Gc
// @1C: getstatic long game.C_100321_hi.field_107215_f
// @1F: lcmp
// @20: ifne @28
// @23: iconst_1
// @24: goto @29
// @27: athrow
// @28: iconst_0
// @29: ireturn
// @2A: astore_1
// @2B: aload_1
// @2C: new java.lang.StringBuilder
// @2F: dup
// @30: invokespecial java.lang.StringBuilder.<init>()void
// @33: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @36: bipush 6 (0x06)
// @38: aaload
// @39: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @3C: iload_0
// @3D: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @40: bipush 41 (0x29)
// @42: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @45: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @48: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @4B: athrow
}
static final void func_106161_a(int arg0)
{
// @000: getstatic int game.SteelSentinels.field_105275_O
// @003: istore #4
// @005: iload_0
// @006: sipush -30146 (0x8A3E)
// @009: if_icmpeq @015
// @00C: bipush 48 (0x30)
// @00E: invokestatic game.C_100227_af.func_106161_a(int)void
// @011: goto @015
// @014: athrow
// @015: getstatic boolean game.C_100284_nj.field_106772_a
// @018: ifne @0BF
// @01B: getstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @01E: ifnull @029
// @021: goto @025
// @024: athrow
// @025: goto @032
// @028: athrow
// @029: iconst_4
// @02A: bipush 56 (0x38)
// @02C: invokestatic game.C_100121_ud.func_100708_b(int, byte)game.C_100219_an
// @02F: putstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @032: getstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @035: getfield boolean game.C_100219_an.field_100879_j
// @038: ifeq @0AC
// @03B: getstatic int[] game.C_100066_dl.field_101632_G
// @03E: astore_1
// @03F: getstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @042: getfield int[] game.C_100219_an.field_100881_k
// @045: astore_2
// @046: iconst_0
// @047: istore_3
// @048: iload_3
// @049: iconst_m1
// @04A: ixor
// @04B: bipush -9 (0xF7)
// @04D: if_icmple @06D
// @050: aload_1
// @051: iload_3
// @052: aload_1
// @053: iload_3
// @054: iaload
// @055: aload_2
// @056: iload_3
// @057: iaload
// @058: invokestatic game.C_100116_ei.func_104117_a(int, int)int
// @05B: iastore
// @05C: iinc #3 +1
// @05F: iload #4
// @061: ifne @078
// @064: iload #4
// @066: ifeq @048
// @069: goto @06D
// @06C: athrow
// @06D: getstatic int[] game.C_100139_tb.field_100529_w
// @070: astore_1
// @071: getstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @074: getfield int[] game.C_100219_an.field_100881_k
// @077: astore_2
// @078: iconst_0
// @079: istore_3
// @07A: iload_3
// @07B: bipush 8 (0x08)
// @07D: if_icmpge @09F
// @080: aload_1
// @081: iload_3
// @082: aload_1
// @083: iload_3
// @084: iaload
// @085: aload_2
// @086: iload_3
// @087: iaload
// @088: iconst_m1
// @089: ixor
// @08A: invokestatic game.C_100256_pk.func_100449_a(int, int)int
// @08D: iastore
// @08E: iinc #3 +1
// @091: iload #4
// @093: ifne @0A7
// @096: iload #4
// @098: ifeq @07A
// @09B: goto @09F
// @09E: athrow
// @09F: iconst_1
// @0A0: putstatic boolean game.C_100284_nj.field_106772_a
// @0A3: aconst_null
// @0A4: putstatic game.C_100219_an game.C_100264_mg.field_106518_f
// @0A7: bipush 84 (0x54)
// @0A9: invokestatic game.C_100086_uh.func_103026_g(int)void
// @0AC: getstatic boolean game.C_100284_nj.field_106772_a
// @0AF: ifne @0B6
// @0B2: goto @0BF
// @0B5: athrow
// @0B6: bipush 96 (0x60)
// @0B8: invokestatic game.C_100223_ab.func_106093_a(byte)void
// @0BB: iconst_0
// @0BC: invokestatic game.C_100140_bj.func_102960_a(boolean)void
// @0BF: getstatic boolean game.C_100156_sk.field_105384_w
// @0C2: ifne @123
// @0C5: aconst_null
// @0C6: getstatic game.C_100197_ra game.C_100093_fd.field_102782_V
// @0C9: if_acmpeq @0D4
// @0CC: goto @0D0
// @0CF: athrow
// @0D0: goto @0DE
// @0D3: athrow
// @0D4: bipush 6 (0x06)
// @0D6: bipush -102 (0x9A)
// @0D8: invokestatic game.C_100162_sc.func_102848_b(int, byte)game.C_100197_ra
// @0DB: putstatic game.C_100197_ra game.C_100093_fd.field_102782_V
// @0DE: getstatic game.C_100197_ra game.C_100093_fd.field_102782_V
// @0E1: getfield boolean game.C_100197_ra.field_100863_v
// @0E4: ifne @0EB
// @0E7: goto @123
// @0EA: athrow
// @0EB: getstatic game.C_100197_ra game.C_100093_fd.field_102782_V
// @0EE: getfield byte[] game.C_100197_ra.field_100868_q
// @0F1: sipush 9837 (0x266D)
// @0F4: invokestatic game.C_100030_gm.func_103329_a(byte[], int)void
// @0F7: iconst_1
// @0F8: putstatic boolean game.C_100156_sk.field_105384_w
// @0FB: aconst_null
// @0FC: putstatic game.C_100197_ra game.C_100093_fd.field_102782_V
// @0FF: getstatic game.C_100278_nd game.C_100115_ej.field_102043_Yb
// @102: bipush 65 (0x41)
// @104: iload_0
// @105: sipush 30252 (0x762C)
// @108: iadd
// @109: invokevirtual game.C_100278_nd.func_101189_h(int, int)void
// @10C: getstatic game.C_100278_nd game.C_100115_ej.field_102043_Yb
// @10F: bipush 68 (0x44)
// @111: bipush 125 (0x7D)
// @113: invokevirtual game.C_100278_nd.func_101189_h(int, int)void
// @116: getstatic game.C_100278_nd game.C_100115_ej.field_102043_Yb
// @119: bipush 70 (0x46)
// @11B: iload_0
// @11C: sipush 30265 (0x7639)
// @11F: iadd
// @120: invokevirtual game.C_100278_nd.func_101189_h(int, int)void
// @123: goto @147
// @126: astore_1
// @127: aload_1
// @128: new java.lang.StringBuilder
// @12B: dup
// @12C: invokespecial java.lang.StringBuilder.<init>()void
// @12F: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @132: iconst_3
// @133: aaload
// @134: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @137: iload_0
// @138: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @13B: bipush 41 (0x29)
// @13D: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @140: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @143: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @146: athrow
// @147: return
}
static final boolean func_106158_a(int arg0, boolean arg1)
{
// @00: iload_1
// @01: ifeq @0F
// @04: aconst_null
// @05: checkcast java.lang.String
// @08: putstatic java.lang.String game.C_100227_af.field_106167_e
// @0B: goto @0F
// @0E: athrow
// @0F: iconst_m1
// @10: iload_0
// @11: iconst_m1
// @12: ixor
// @13: if_icmplt @1A
// @16: goto @2A
// @19: athrow
// @1A: iconst_0
// @1B: iload_0
// @1C: iconst_m1
// @1D: isub
// @1E: iconst_4
// @1F: irem
// @20: if_icmpne @28
// @23: iconst_1
// @24: goto @29
// @27: athrow
// @28: iconst_0
// @29: ireturn
// @2A: sipush -1583 (0xF9D1)
// @2D: iload_0
// @2E: iconst_m1
// @2F: ixor
// @30: if_icmpge @44
// @33: iload_0
// @34: iconst_4
// @35: irem
// @36: ifne @42
// @39: goto @3D
// @3C: athrow
// @3D: iconst_1
// @3E: goto @43
// @41: athrow
// @42: iconst_0
// @43: ireturn
// @44: iload_0
// @45: iconst_4
// @46: irem
// @47: ifeq @4C
// @4A: iconst_0
// @4B: ireturn
// @4C: iload_0
// @4D: bipush 100 (0x64)
// @4F: irem
// @50: iconst_m1
// @51: ixor
// @52: iconst_m1
// @53: if_icmpeq @58
// @56: iconst_1
// @57: ireturn
// @58: iconst_0
// @59: iload_0
// @5A: sipush 400 (0x0190)
// @5D: irem
// @5E: if_icmpne @65
// @61: goto @67
// @64: athrow
// @65: iconst_0
// @66: ireturn
// @67: iconst_1
// @68: ireturn
// @69: astore_2
// @6A: aload_2
// @6B: new java.lang.StringBuilder
// @6E: dup
// @6F: invokespecial java.lang.StringBuilder.<init>()void
// @72: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @75: iconst_4
// @76: aaload
// @77: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @7A: iload_0
// @7B: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @7E: bipush 44 (0x2C)
// @80: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @83: iload_1
// @84: invokevirtual java.lang.StringBuilder.append(boolean)java.lang.StringBuilder
// @87: bipush 41 (0x29)
// @89: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @8C: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @8F: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @92: athrow
}
public static void func_106157_b(int arg0)
{
// @00: aconst_null
// @01: putstatic java.lang.String game.C_100227_af.field_106167_e
// @04: iload_0
// @05: ifeq @12
// @08: bipush -63 (0xC1)
// @0A: invokestatic game.C_100227_af.func_106156_a(byte)boolean
// @0D: pop
// @0E: goto @12
// @11: athrow
// @12: aconst_null
// @13: putstatic java.lang.String[] game.C_100227_af.field_106174_i
// @16: aconst_null
// @17: putstatic java.lang.String game.C_100227_af.field_106169_c
// @1A: aconst_null
// @1B: putstatic java.lang.String game.C_100227_af.field_106173_h
// @1E: aconst_null
// @1F: putstatic java.lang.String[] game.C_100227_af.field_106164_f
// @22: aconst_null
// @23: putstatic java.awt.Color game.C_100227_af.field_106165_g
// @26: aconst_null
// @27: putstatic java.awt.Frame game.C_100227_af.field_106168_b
// @2A: aconst_null
// @2B: putstatic game.C_100182_cc game.C_100227_af.field_106170_a
// @2E: aconst_null
// @2F: putstatic java.lang.String game.C_100227_af.field_106171_j
// @32: goto @57
// @35: astore_1
// @36: aload_1
// @37: new java.lang.StringBuilder
// @3A: dup
// @3B: invokespecial java.lang.StringBuilder.<init>()void
// @3E: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @41: bipush 7 (0x07)
// @43: aaload
// @44: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @47: iload_0
// @48: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @4B: bipush 41 (0x29)
// @4D: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @50: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @53: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @56: athrow
// @57: return
}
static final int func_106160_a(int arg0, int[] arg1, int arg2)
{
// @000: getstatic int game.SteelSentinels.field_105275_O
// @003: istore #7
// @005: iconst_0
// @006: aload_1
// @007: iconst_0
// @008: iaload
// @009: if_icmpeq @024
// @00C: bipush 55 (0x37)
// @00E: aload_1
// @00F: iconst_0
// @010: iaload
// @011: if_icmpeq @024
// @014: goto @018
// @017: athrow
// @018: bipush 57 (0x39)
// @01A: aload_1
// @01B: iconst_0
// @01C: iaload
// @01D: if_icmpne @029
// @020: goto @024
// @023: athrow
// @024: iconst_1
// @025: goto @02A
// @028: athrow
// @029: iconst_0
// @02A: istore_3
// @02B: iload_3
// @02C: ifne @033
// @02F: goto @08C
// @032: athrow
// @033: iload_0
// @034: bipush 53 (0x35)
// @036: iadd
// @037: aload_1
// @038: iconst_0
// @039: iaload
// @03A: invokestatic game.C_100042_we.func_104129_b(int, int)int[]
// @03D: astore #4
// @03F: aload #4
// @041: arraylength
// @042: iconst_m1
// @043: ixor
// @044: aload_1
// @045: arraylength
// @046: iconst_m1
// @047: ixor
// @048: if_icmpeq @052
// @04B: iconst_0
// @04C: istore_3
// @04D: iload #7
// @04F: ifeq @08C
// @052: iconst_0
// @053: istore #5
// @055: aload_1
// @056: arraylength
// @057: iconst_m1
// @058: ixor
// @059: iload #5
// @05B: iconst_m1
// @05C: ixor
// @05D: if_icmpge @08C
// @060: aload_1
// @061: iload #5
// @063: iaload
// @064: iconst_m1
// @065: ixor
// @066: iload #7
// @068: ifne @092
// @06B: aload #4
// @06D: iload #5
// @06F: iaload
// @070: iconst_m1
// @071: ixor
// @072: if_icmpeq @080
// @075: goto @079
// @078: athrow
// @079: iconst_0
// @07A: istore_3
// @07B: iload #7
// @07D: ifeq @08C
// @080: iinc #5 +1
// @083: iload #7
// @085: ifeq @055
// @088: goto @08C
// @08B: athrow
// @08C: aload_1
// @08D: bipush 109 (0x6D)
// @08F: invokestatic game.C_100013_fn.func_103732_a(int[], byte)int
// @092: istore #4
// @094: iload #4
// @096: iconst_m1
// @097: ixor
// @098: sipush -6101 (0xE82B)
// @09B: if_icmplt @0A3
// @09E: iconst_1
// @09F: goto @0A4
// @0A2: athrow
// @0A3: iconst_0
// @0A4: istore #5
// @0A6: iload_0
// @0A7: istore #6
// @0A9: iload_3
// @0AA: ifeq @0B3
// @0AD: iload #6
// @0AF: iconst_1
// @0B0: ior
// @0B1: istore #6
// @0B3: iload #5
// @0B5: ifeq @0BE
// @0B8: iload #6
// @0BA: iconst_2
// @0BB: ior
// @0BC: istore #6
// @0BE: iload #6
// @0C0: ireturn
// @0C1: astore_3
// @0C2: aload_3
// @0C3: new java.lang.StringBuilder
// @0C6: dup
// @0C7: invokespecial java.lang.StringBuilder.<init>()void
// @0CA: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @0CD: iconst_2
// @0CE: aaload
// @0CF: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @0D2: iload_0
// @0D3: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0D6: bipush 44 (0x2C)
// @0D8: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0DB: aload_1
// @0DC: ifnull @0E8
// @0DF: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @0E2: iconst_0
// @0E3: aaload
// @0E4: goto @0ED
// @0E7: athrow
// @0E8: getstatic java.lang.String[] game.C_100227_af.field_106172_z
// @0EB: iconst_1
// @0EC: aaload
// @0ED: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @0F0: bipush 44 (0x2C)
// @0F2: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0F5: iload_2
// @0F6: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @0F9: bipush 41 (0x29)
// @0FB: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @0FE: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @101: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @104: athrow
}
static
{
// @00: bipush 8 (0x08)
// @02: anewarray java.lang.String
// @05: dup
// @06: iconst_0
// @07: ldc "7\n\u00080q"
// @09: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @0C: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @0F: aastore
// @10: dup
// @11: iconst_1
// @12: ldc "\"QJr"
// @14: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @17: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @1A: aastore
// @1B: dup
// @1C: iconst_2
// @1D: ldc "-B\u0008[$"
// @1F: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @22: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @25: aastore
// @26: dup
// @27: iconst_3
// @28: ldc "-B\u0008_$"
// @2A: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @2D: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @30: aastore
// @31: dup
// @32: iconst_4
// @33: ldc "-B\u0008X$"
// @35: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @38: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @3B: aastore
// @3C: dup
// @3D: iconst_5
// @3E: ldc "-B\u0008\\$"
// @40: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @43: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @46: aastore
// @47: dup
// @48: bipush 6 (0x06)
// @4A: ldc "-B\u0008]$"
// @4C: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @4F: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @52: aastore
// @53: dup
// @54: bipush 7 (0x07)
// @56: ldc "-B\u0008Z$"
// @58: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @5B: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @5E: aastore
// @5F: putstatic java.lang.String[] game.C_100227_af.field_106172_z
// @62: ldc "p\u0001\u0017 ,;EU>x#K\u0006}`#WC>x#\u0004G>n#ID>e\"PClo)TR{hlF_>0i\u0014\u0018"
// @64: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @67: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @6A: putstatic java.lang.String game.C_100227_af.field_106173_h
// @6D: iconst_3
// @6E: anewarray java.lang.String
// @71: dup
// @72: iconst_0
// @73: ldc "\rHJ>c8LCl,!AK|i>\u0004Cf|-JUwc\"W"
// @75: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @78: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @7B: aastore
// @7C: dup
// @7D: iconst_1
// @7E: ldc "\u0000KGz\u007flIIlileEve)RCsi\"PU"
// @80: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @83: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @86: aastore
// @87: dup
// @88: iconst_2
// @89: ldc "\nQJr,/KKsy\"MRg,*AGjy>AU"
// @8B: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @8E: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @91: aastore
// @92: putstatic java.lang.String[] game.C_100227_af.field_106164_f
// @95: ldc "\u0005B\u0006gc9\u0004Bq,\"KRve\"C\u0006jd)\u0004A\u007fa)\u0004Qw` \u0004T{z)VR>x#\u0004Hq~!EJ>z%AQ>e\"\u0004\u001a;<r\u0004U{o#JBm\""
// @97: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @9A: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @9D: putstatic java.lang.String game.C_100227_af.field_106171_j
// @A0: bipush 16 (0x10)
// @A2: anewarray java.lang.String
// @A5: putstatic java.lang.String[] game.C_100227_af.field_106174_i
// @A8: iconst_0
// @A9: putstatic int game.C_100227_af.field_106166_d
// @AC: new java.awt.Color
// @AF: dup
// @B0: ldc 10040319 (0x9933ff)
// @B2: invokespecial java.awt.Color.<init>(int)void
// @B5: putstatic java.awt.Color game.C_100227_af.field_106165_g
// @B8: ldc "\u0007MEu,p\u0001\u0016 ,*VIs,8LOm,+EK{"
// @BA: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @BD: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @C0: putstatic java.lang.String game.C_100227_af.field_106167_e
// @C3: ldc "\u001fAHz,<VOhm8A\u0006Oy%GM>O$ER>x#\u0004\u001a;<r"
// @C5: invokestatic game.C_100227_af.func_106163_z(java.lang.String)char[]
// @C8: invokestatic game.C_100227_af.func_106162_z(char[])java.lang.String
// @CB: putstatic java.lang.String game.C_100227_af.field_106169_c
// @CE: return
}
private static char[] func_106163_z(String arg0)
{
// @00: aload_0
// @01: invokevirtual java.lang.String.toCharArray()char[]
// @04: dup
// @05: arraylength
// @06: iconst_2
// @07: if_icmpge @13
// @0A: dup
// @0B: iconst_0
// @0C: dup2
// @0D: caload
// @0E: bipush 12 (0x0C)
// @10: ixor
// @11: i2c
// @12: castore
// @13: areturn
}
private static String func_106162_z(char[] arg0)
{
// @00: aload_0
// @01: dup
// @02: arraylength
// @03: swap
// @04: iconst_0
// @05: istore_1
// @06: goto @4C
// @09: dup
// @0A: iload_1
// @0B: dup2
// @0C: caload
// @0D: iload_1
// @0E: iconst_5
// @0F: irem
// @10: tableswitch def: @44, for 0: @30, for 1: @35, for 2: @3A, for 3: @3F
// @30: bipush 76 (0x4C)
// @32: goto @46
// @35: bipush 36 (0x24)
// @37: goto @46
// @3A: bipush 38 (0x26)
// @3C: goto @46
// @3F: bipush 30 (0x1E)
// @41: goto @46
// @44: bipush 12 (0x0C)
// @46: ixor
// @47: i2c
// @48: castore
// @49: iinc #1 +1
// @4C: swap
// @4D: dup_x1
// @4E: iload_1
// @4F: if_icmpgt @09
// @52: new java.lang.String
// @55: dup_x1
// @56: swap
// @57: invokespecial java.lang.String.<init>(char[])void
// @5A: invokevirtual java.lang.String.intern()java.lang.String
// @5D: areturn
}
}
| mes59/ChromeConflict | SSSourceCode(Compiled)/C_100227_af.java | Java | gpl-3.0 | 29,690 |
/*
* Open Source Physics software is free software as described near the bottom of this code file.
*
* For additional information and documentation on Open Source Physics please see:
* <http://www.opensourcephysics.org/>
*/
package org.opensourcephysics.numerics;
/**
* VectorFunction defines a function of multiple variables that returns a resultant vector.
*
*/
public interface VectorFunction {
/**
* Evaluates the vector function and returns the the result.
*
* If the result array is null, a new array is allocated. Otherwise the result array is used.
* @param x
* @param result
* @return
*/
public double[] evaluate(double[] x, double[] result);
}
/*
* Open Source Physics software is free software; you can redistribute
* it and/or modify it under the terms of the GNU General Public License (GPL) as
* published by the Free Software Foundation; either version 2 of the License,
* or(at your option) any later version.
* Code that uses any portion of the code in the org.opensourcephysics package
* or any subpackage (subdirectory) of this package must must also be be released
* under the GNU GPL license.
*
* This software 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA
* or view the license online at http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2007 The Open Source Physics project
* http://www.opensourcephysics.org
*/
| dobrown/tracker-mvn | src/main/java/org/opensourcephysics/numerics/VectorFunction.java | Java | gpl-3.0 | 1,799 |
/**
* Copyright 2012-2015 Rafal Lewczuk <[email protected]>
*
* ZORKA 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.
*
* ZORKA 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
* ZORKA. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.common.util;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
/**
* Various utility methods used by other classes. THis is singleton class as some methods need to be
* instance methods.
*/
public class ZorkaUtil {
private final static ZorkaLog log = ZorkaLogger.getLog(ZorkaUtil.class);
/**
* Singleton instance
*/
protected final static AtomicReference<ZorkaUtil> instanceRef = new AtomicReference<ZorkaUtil>(null);
/**
* Returns singleton ZorkaUtil instance (and creates if needed)
*/
public static ZorkaUtil getInstance() {
ZorkaUtil instance = instanceRef.get();
if (instance == null) {
instanceRef.compareAndSet(null, new ZorkaUtil());
instance = instanceRef.get();
}
return instance;
}
/**
* Hidden to block direct instantiations of this class.
*/
protected ZorkaUtil() {
}
/**
* Tries to coerce a value to a specific (simple) data type.
*
* @param val value to be coerced (converted)
* @param c destination type class
* @return coerced value
*/
public static Object coerce(Object val, Class<?> c) {
if (val == null || c == null) {
return null;
} else if (val.getClass() == c) {
return val;
} else if (c == String.class) {
return castString(val);
} else if (c == Boolean.class || c == Boolean.TYPE) {
return coerceBool(val);
} else if (c == Long.class || c == Long.TYPE) {
return castLong(val);
} else if (c == Integer.class || c == Integer.TYPE) {
return castInteger(val);
} else if (c == Double.class || c == Double.TYPE) {
return castDouble(val);
} else if (c == Short.class || c == Short.TYPE) {
return castShort(val);
} else if (c == Float.class || c == Float.TYPE) {
return castFloat(val);
}
return null;
}
public static String castString(Object val) {
try {
return val != null ? val.toString() : "null";
} catch (Exception e) {
return "<ERR: " + e.getMessage() + ">";
}
}
private static float castFloat(Object val) {
return (val instanceof String)
? Float.parseFloat(val.toString().trim())
: ((Number) val).floatValue();
}
private static short castShort(Object val) {
return (val instanceof String)
? Short.parseShort(val.toString().trim())
: ((Number) val).shortValue();
}
private static double castDouble(Object val) {
return (val instanceof String)
? Double.parseDouble(val.toString().trim())
: ((Number) val).doubleValue();
}
private static int castInteger(Object val) {
return (val instanceof String)
? Integer.parseInt(val.toString().trim())
: ((Number) val).intValue();
}
private static long castLong(Object val) {
return (val instanceof String)
? Long.parseLong(val.toString().trim())
: ((Number) val).longValue();
}
/**
* Coerces any value to boolean.
*
* @param val value to be coerced
* @return false if value is null or boolean false, true otherwise
*/
public static boolean coerceBool(Object val) {
return !(val == null || val.equals(false));
}
/**
* Returns current time (in milliseconds since Epoch). This is used instead of System.currentTimeMillis(),
* so it can be swapped to mock implementation if needed.
*
* @return current time (milliseconds since Epoch)
*/
public long currentTimeMillis() {
return System.currentTimeMillis();
}
/**
* Equivalent of a.equals(b) handling edge cases (if a and/or b is null).
*
* @param a compared object
* @param b compared object
* @return true if both a and b are null or a equals b
*/
public static boolean objEquals(Object a, Object b) {
return a == null && b == null
|| a != null && a.equals(b);
}
/**
* Compares two arrays of objects
*
* @param a comapred array
* @param b compared array
* @return true if arrays are both null or have the same length and objects at each index are equal
*/
public static boolean arrayEquals(Object[] a, Object[] b) {
if (a == null || b == null) {
return a == null && b == null;
}
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++)
if (!objEquals(a[i], b[i]))
return false;
return true;
}
/**
* Returns string that contains of all elements of passed collection joined together
*
* @param sep separator (inserted between values)
* @param col collection of values to concatenate
* @return concatenated string
*/
public static String join(String sep, Collection<?> col) {
StringBuilder sb = new StringBuilder();
for (Object val : col) {
if (sb.length() > 0) sb.append(sep);
sb.append(castString(val));
}
return sb.toString();
}
/**
* Returns string that contains of all elements of passed (vararg) array joined together
*
* @param sep separator (inserted between values)
* @param vals array of values
* @return concatenated string
*/
public static String join(String sep, Object... vals) {
StringBuilder sb = new StringBuilder();
for (Object val : vals) {
if (sb.length() > 0) sb.append(sep);
sb.append(castString(val));
}
return sb.toString();
}
/**
* Parses string consisting of integer and (potential) suffix (kilo, mega, giga, ...).
*
* @param s string to be parsed
* @return result integer value
*/
public static long parseIntSize(String s) {
String sn = s.trim();
long n1 = 1;
if (sn.length() == 0) {
throw new NumberFormatException("Invalid (empty) size number passed.");
}
char ch = sn.charAt(sn.length() - 1);
if (Character.isLetter(ch)) {
sn = sn.substring(0, sn.length() - 1);
switch (ch) {
case 'k':
case 'K':
n1 = 1024;
break;
case 'm':
case 'M':
n1 = 1024 * 1024;
break;
case 'g':
case 'G':
n1 = 1024 * 1024 * 1024;
break;
case 't':
case 'T':
n1 = 1024 * 1024 * 1024 * 1024;
break;
default:
throw new NumberFormatException("Invalid size number passed: '" + s + "'");
}
}
return Long.parseLong(sn) * n1;
}
/**
* Placeholder for substitution macro
*/
private final static Pattern rePropVar = Pattern.compile("\\$\\{([^\\}]+)\\}");
/**
* Checks if given class instance of given type. Check is done only by name, so if two classes of the same
* name are loaded by two independent class loaders, they'll appear to be the same. This is enough if
* object implementing given class is then accessed using reflection. As this method uses only name comparison,
*
* @param c class to be checked
* @param name class or interface full name (with package prefix)
* @return true if class c is a or implements type named 'name'
*/
public static boolean instanceOf(Class<?> c, String name) {
for (Class<?> clazz = c; clazz != null && !"java.lang.Object".equals(clazz.getName()); clazz = clazz.getSuperclass()) {
if (name.equals(clazz.getName()) || interfaceOf(clazz, name)) {
return true;
}
}
return false;
}
public static boolean instanceOf(Class<?> c, Pattern clPattern) {
for (Class<?> clazz = c; clazz != null && !"java.lang.Object".equals(clazz.getName()); clazz = clazz.getSuperclass()) {
if (clPattern.matcher(clazz.getName()).matches() || interfaceOf(clazz, clPattern)) {
return true;
}
}
return false;
}
/**
* Checks if given class implements interface of name given by ifName. Analogous to above instanceOf() method.
*
* @param c class to be tested
* @param ifName interface full name (with package prefix)
* @return true if class c implements interface named 'ifName'
*/
public static boolean interfaceOf(Class<?> c, String ifName) {
for (Class<?> ifc : c.getInterfaces()) {
if (ifName.equals(ifc.getName()) || interfaceOf(ifc, ifName)) {
return true;
}
}
return false;
}
public static boolean interfaceOf(Class<?> c, Pattern ifcPattern) {
for (Class<?> ifc : c.getInterfaces()) {
if (ifcPattern.matcher(ifc.getName()).matches() || interfaceOf(ifc, ifcPattern)) {
return true;
}
}
return false;
}
/**
* Clones array of bytes. Implemented by hand as JDK 1.5 does not have such method.
*
* @param src source array
* @return copied array
*/
public static byte[] copyArray(byte[] src) {
if (src == null) {
return null;
}
byte[] dst = new byte[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
return dst;
}
/**
* Clones array of long integers. Implemented by hand as JDK 1.5 does not have such method.
*
* @param src source array
* @return copied array
*/
public static long[] copyArray(long[] src) {
if (src == null) {
return null;
}
long[] dst = new long[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
return dst;
}
/**
* Clones array of objects of type T
*
* @param src source array
* @param <T> type of array items
* @return copied array
*/
public static <T> T[] copyArray(T[] src) {
if (src == null) {
return null;
}
Class<?> arrayType = src.getClass().getComponentType();
T[] dst = (T[]) java.lang.reflect.Array.newInstance(arrayType, src.length);
System.arraycopy(src, 0, dst, 0, src.length);
return dst;
}
/**
* Clips or extends array of objects of type T. If passed length is less than length of original array,
* only so many elements of original array will be copied. If passed length is more than length of original
* array, new elements will be filled with null values. If passed length is the same as length of original
* array, it is equivalent to copyArray() method.
*
* @param src source array
* @param len target length
* @param <T> array type
* @return shortened/cloned/enlarged array
*/
public static <T> T[] clipArray(T[] src, int len) {
if (src == null) {
return null;
}
if (len < 0) {
len = src.length + len > 0 ? src.length + len : 0;
}
Class<?> arrayType = src.getClass().getComponentType();
T[] dst = (T[]) java.lang.reflect.Array.newInstance(arrayType, len);
if (len > 0) {
System.arraycopy(src, 0, dst, 0, len);
}
return dst;
}
/**
* Clips or extends array of objects of bytes. If passed length is less than length of original array,
* only so many elements of original array will be copied. If passed length is more than length of original
* array, new elements will be filled with zeros. If passed length is the same as length of original
* array, it is equivalent to copyArray() method.
*
* @param src source array
* @param offs source offset
* @param len target length
* @return shortened/cloned/enlarged array
*/
public static byte[] clipArray(byte[] src, int offs, int len) {
if (src == null) {
return null;
}
if (len < 0) {
len = src.length + len > offs ? src.length - len + offs : 0;
}
byte[] dst = new byte[len];
if (len > src.length) {
len = src.length;
}
if (len > 0) {
System.arraycopy(src, offs, dst, 0, len);
}
return dst;
}
/**
* Clips or extends array of objects of bytes. If passed length is less than length of original array,
* only so many elements of original array will be copied. If passed length is more than length of original
* array, new elements will be filled with zeros. If passed length is the same as length of original
* array, it is equivalent to copyArray() method.
*
* @param src source array
* @param len target length
* @return shortened/cloned/enlarged array
*/
public static byte[] clipArray(byte[] src, int len) {
if (src == null) {
return null;
}
if (len < 0) {
len = src.length + len > 0 ? src.length + len : 0;
}
byte[] dst = new byte[len];
if (len > src.length) {
len = src.length;
}
if (len > 0) {
System.arraycopy(src, 0, dst, 0, len);
}
return dst;
}
/**
* Clips or extends array of objects of bytes. If passed length is less than length of original array,
* only so many elements of original array will be copied. If passed length is more than length of original
* array, new elements will be filled with zeros. If passed length is the same as length of original
* array, it is equivalent to copyArray() method.
*
* @param src source array
* @param len target length
* @return shortened/cloned/enlarged array
*/
public static double[] clipArray(double[] src, int len) {
if (src == null) {
return null;
}
if (len < 0) {
len = src.length + len > 0 ? src.length + len : 0;
}
double[] dst = new double[len];
if (len > src.length) {
len = src.length;
}
if (len > 0) {
System.arraycopy(src, 0, dst, 0, len);
}
return dst;
}
/**
* Clips or extends array of objects of bytes. If passed length is less than length of original array,
* only so many elements of original array will be copied. If passed length is more than length of original
* array, new elements will be filled with zeros. If passed length is the same as length of original
* array, it is equivalent to copyArray() method.
*
* @param src source array
* @param len target length
* @return shortened/cloned/enlarged array
*/
public static long[] clipArray(long[] src, int len) {
if (src == null) {
return null;
}
if (len < 0) {
len = src.length + len > 0 ? src.length + len : 0;
}
long[] dst = new long[len];
if (len > src.length) {
len = src.length;
}
if (len > 0) {
System.arraycopy(src, 0, dst, 0, len);
}
return dst;
}
public static int[] intArray(List<Integer> l) {
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
}
public static long[] longArray(List<Long> l) {
long[] a = new long[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
}
public static double[] doubleArray(List<Double> l) {
double[] a = new double[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
}
/**
* Clips list if necessary. Contrasted to subList() method it creates copy of a list,
* so all objects not copied will be garbage collected if all references to original
* list are discarded.
*
* @param src original list
* @param maxSize maximum size
* @param <T> type of list elements
* @return (potentially) shortened list
*/
public static <T> List<T> clip(List<T> src, int maxSize) {
if (src.size() <= maxSize) {
return src;
}
List<T> lst = new ArrayList<T>(maxSize + 2);
for (int i = 0; i < maxSize; i++) {
lst.add(src.get(i));
}
return lst;
}
/**
* Conversions used by printableASCII7 method
*/
private static final String tab00c0 =
"AAAAAAACEEEEIIII" +
"DNOOOOO\u00d7\u00d8UUUUYI\u00df" +
"aaaaaaaceeeeiiii" +
"\u00f0nooooo\u00f7\u00f8uuuuy\u00fey" +
"AaAaAaCcCcCcCcDd" +
"DdEeEeEeEeEeGgGg" +
"GgGgHhHhIiIiIiIi" +
"IiJjJjKkkLlLlLlL" +
"lLlNnNnNnnNnOoOo" +
"OoOoRrRrRrSsSsSs" +
"SsTtTtTtUuUuUuUu" +
"UuUuWwYyYZzZzZzF";
/**
* Converts Unicode string to printable 7-bit ASCII characters.
*
* @param source unicode string
* @return 7-bit ASCII result
*/
public static String printableASCII7(String source) {
char[] vysl = new char[source.length()];
char one;
for (int i = 0; i < source.length(); i++) {
one = source.charAt(i);
if (one >= '\u00c0' && one <= '\u017f') {
one = tab00c0.charAt((int) one - '\u00c0');
}
if (one < (char) 32 || one > (char) 126) {
one = '.';
}
vysl[i] = one;
}
return new String(vysl);
}
/**
* This is useful to create a map of object in declarative way. Key-value pairs
* are passed as arguments to this method, so call will look like this:
* ZorkaUtil.map(k1, v1, k2, v2, ...)
*
* @param data keys and values (in pairs)
* @param <K> type of keys
* @param <V> type of values
* @return mutable map
*/
public static <K, V> Map<K, V> map(Object... data) {
Map<K, V> map = new HashMap<K, V>(data.length + 2);
for (int i = 1; i < data.length; i += 2) {
map.put((K) data[i - 1], (V) data[i]);
}
return map;
}
/**
* This is useful to create a map of object in declarative way. Key-value pairs
* are passed as arguments to this method, so call will look like this:
* ZorkaUtil.map(k1, v1, k2, v2, ...)
*
* @param data keys and values (in pairs)
* @param <K> type of keys
* @param <V> type of values
* @return mutable map
*/
public static <K, V> Map<K, V> lmap(Object... data) {
Map<K, V> map = new LinkedHashMap<K, V>(data.length + 2);
for (int i = 1; i < data.length; i += 2) {
map.put((K) data[i - 1], (V) data[i]);
}
return map;
}
/**
* Equivalent of map(k1, v1, ...) that returns constant (unmodifiable) map.
*
* @param data key value pairs (k1, v1, k2, v2, ...)
* @param <K> type of keys
* @param <V> type of values
* @return immutable map
*/
public static <K, V> Map<K, V> constMap(Object... data) {
Map<K, V> map = map(data);
return Collections.unmodifiableMap(map);
}
/**
* Creates a set from supplied strings.
*
* @param objs members of newly formed set
* @return set of strings
*/
public static <T> Set<T> set(T...objs) {
Set<T> set = new HashSet<T>(objs.length * 2 + 1);
for (T s : objs) {
set.add(s);
}
return set;
}
public static <T> Set<T> constSet(T...objs) {
Set<T> set = set(objs);
return Collections.unmodifiableSet(set);
}
public static String path(String... components) {
StringBuilder sb = new StringBuilder();
for (String s : components) {
if (s.endsWith("/") || s.endsWith("\\")) {
s = s.substring(0, s.length() - 1);
}
if (sb.length() == 0) {
sb.append(s);
} else {
if (s.startsWith("/") || s.startsWith("\\")) {
s = s.substring(1);
}
sb.append("/");
sb.append(s);
}
}
return sb.toString().replace('\\', '/');
}
public static String strClock(long clock) {
return new Date(clock).toString();
}
public static String strTime(long ns) {
double t = 1.0 * ns / 1000000.0;
String u = "ms";
if (t > 1000.0) {
t /= 1000.0;
u = "s";
}
return String.format(t > 10 ? "%.0f" : "%.2f", t) + u;
}
public static int iparam(Map<String, String> params, String name, int defval) {
try {
return params.containsKey(name) ? Integer.parseInt(params.get(name)) : defval;
} catch (NumberFormatException e) {
return defval;
}
}
public static void rmrf(String path) throws IOException {
rmrf(new File(path));
}
public static void rmrf(File f) throws IOException {
if (f.exists()) {
if (f.isDirectory()) {
for (File c : f.listFiles()) {
rmrf(c);
}
}
f.delete();
}
}
private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String hex(byte[] input) {
return hex(input, input.length);
}
public static String hex(byte[] input, int len) {
StringBuffer sb = new StringBuffer(input.length * 2);
for (int i = 0; i < len; i++) {
int c = input[i] & 0xff;
sb.append(HEX[(c >> 4) & 0x0f]);
sb.append(HEX[c & 0x0f]);
}
return sb.toString();
}
public static String crc32(String input) {
CRC32 crc32 = new CRC32();
crc32.update(input.getBytes());
return String.format("%08x", crc32.getValue());
}
public static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
return hex(md.digest());
} catch (NoSuchAlgorithmException e) {
log.error(ZorkaLogger.ZSP_ERRORS, "Not supported digest algorithm: 'MD5'");
}
return null;
}
public static String sha1(String input) {
try {
MessageDigest sha = MessageDigest.getInstance("SHA1");
sha.update(input.getBytes());
return hex(sha.digest());
} catch (NoSuchAlgorithmException e) {
log.error(ZorkaLogger.ZSP_ERRORS, "Not supported digest algorithm: 'SHA1'");
}
return null;
}
public static void sleep(long interval) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
}
| lionelliang/zorka | zorka-common/src/main/java/com/jitlogic/zorka/common/util/ZorkaUtil.java | Java | gpl-3.0 | 24,598 |
package com.jse.tutorials.design_patterns.structural.filter;
import java.util.ArrayList;
import java.util.List;
public class CriteriaSingle implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> singlePersons = new ArrayList<>();
for (Person person : persons) {
if ("SINGLE".equalsIgnoreCase(person.getMaritalStatus())) {
singlePersons.add(person);
}
}
return singlePersons;
}
}
| slavidlancer/JavaSEtraining | Exercising/src/com/jse/tutorials/design_patterns/structural/filter/CriteriaSingle.java | Java | gpl-3.0 | 530 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2016, SCISYS UK Limited
*
* 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.sldeditor.datasource.impl;
/**
* The Enum GeometryTypeEnum, represents the geometry type of the loaded symbol.
*
* @author Robert Ward (SCISYS)
*/
public enum GeometryTypeEnum {
/** Unknown geometry type. */
UNKNOWN,
/** A point. */
POINT,
/** A line. */
LINE,
/** A polygon. */
POLYGON,
/** A raster. */
RASTER
}
| robward-scisys/sldeditor | modules/application/src/main/java/com/sldeditor/datasource/impl/GeometryTypeEnum.java | Java | gpl-3.0 | 1,125 |
/*
* Kontalk Android client
* Copyright (C) 2018 Kontalk Devteam <[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 org.kontalk.ui;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.chatstates.ChatState;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.util.XmppStringUtils;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPPublicKeyRing;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import pub.devrel.easypermissions.EasyPermissions;
import org.kontalk.Kontalk;
import org.kontalk.Log;
import org.kontalk.R;
import org.kontalk.authenticator.Authenticator;
import org.kontalk.client.EndpointServer;
import org.kontalk.crypto.PGP;
import org.kontalk.data.Contact;
import org.kontalk.data.Conversation;
import org.kontalk.message.CompositeMessage;
import org.kontalk.provider.Keyring;
import org.kontalk.provider.KontalkGroupCommands;
import org.kontalk.provider.MessagesProviderClient;
import org.kontalk.provider.MyMessages;
import org.kontalk.provider.MyMessages.Threads;
import org.kontalk.provider.MyUsers;
import org.kontalk.provider.UsersProvider;
import org.kontalk.service.msgcenter.MessageCenterService;
import org.kontalk.service.msgcenter.PrivacyCommand;
import org.kontalk.service.msgcenter.event.ConnectedEvent;
import org.kontalk.service.msgcenter.event.LastActivityEvent;
import org.kontalk.service.msgcenter.event.LastActivityRequest;
import org.kontalk.service.msgcenter.event.NoPresenceEvent;
import org.kontalk.service.msgcenter.event.PreapproveSubscriptionRequest;
import org.kontalk.service.msgcenter.event.PresenceEvent;
import org.kontalk.service.msgcenter.event.PresenceRequest;
import org.kontalk.service.msgcenter.event.PublicKeyEvent;
import org.kontalk.service.msgcenter.event.PublicKeyRequest;
import org.kontalk.service.msgcenter.event.RosterLoadedEvent;
import org.kontalk.service.msgcenter.event.SendChatStateRequest;
import org.kontalk.service.msgcenter.event.SendMessageRequest;
import org.kontalk.service.msgcenter.event.SetUserPrivacyRequest;
import org.kontalk.service.msgcenter.event.SubscribeRequest;
import org.kontalk.service.msgcenter.event.UserBlockedEvent;
import org.kontalk.service.msgcenter.event.UserOfflineEvent;
import org.kontalk.service.msgcenter.event.UserOnlineEvent;
import org.kontalk.service.msgcenter.event.UserSubscribedEvent;
import org.kontalk.service.msgcenter.event.UserUnblockedEvent;
import org.kontalk.service.msgcenter.event.VersionEvent;
import org.kontalk.service.msgcenter.event.VersionRequest;
import org.kontalk.sync.Syncer;
import org.kontalk.util.MessageUtils;
import org.kontalk.util.Permissions;
import org.kontalk.util.Preferences;
import org.kontalk.util.SystemUtils;
import org.kontalk.util.XMPPUtils;
/**
* The composer fragment.
* @author Daniele Ricci
* @author Andrea Cappelli
*/
public class ComposeMessageFragment extends AbstractComposeFragment
implements EasyPermissions.PermissionCallbacks {
private static final String TAG = ComposeMessage.TAG;
ViewGroup mInvitationBar;
private MenuItem mViewContactMenu;
private MenuItem mCallMenu;
private MenuItem mBlockMenu;
private MenuItem mUnblockMenu;
/** The user we are talking to. */
String mUserJID;
private String mUserPhone;
String mLastActivityRequestId;
String mVersionRequestId;
String mKeyRequestId;
private boolean mIsTyping;
@Override
protected void onInflateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_message_menu, menu);
mViewContactMenu = menu.findItem(R.id.view_contact);
mCallMenu = menu.findItem(R.id.call_contact);
mBlockMenu = menu.findItem(R.id.block_user);
mUnblockMenu = menu.findItem(R.id.unblock_user);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (super.onOptionsItemSelected(item))
return true;
switch (item.getItemId()) {
case R.id.call_contact:
callContact();
return true;
case R.id.view_contact:
viewContact();
return true;
case R.id.block_user:
blockUser();
return true;
case R.id.unblock_user:
unblockUser();
return true;
}
return false;
}
private void callContact() {
final Context context = getContext();
if (Permissions.canCallPhone(context)) {
doCallContact();
}
else if (EasyPermissions.permissionPermanentlyDenied(this, Manifest.permission.CALL_PHONE)) {
doDialContact();
}
else {
Permissions.requestCallPhone(this);
}
}
private void doCallContact() {
SystemUtils.call(getContext(), mUserPhone);
}
private void doDialContact() {
SystemUtils.dial(getContext(), mUserPhone);
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
if (perms.contains(Manifest.permission.CALL_PHONE)) {
doCallContact();
}
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
if (perms.contains(Manifest.permission.CALL_PHONE)) {
doDialContact();
}
}
public void viewContactInfo() {
final Activity ctx = getActivity();
if (ctx == null)
return;
if (mConversation != null) {
Contact contact = mConversation.getContact();
if (contact != null) {
if (Kontalk.hasTwoPanesUI(ctx)) {
ContactInfoDialog.start(ctx, this, contact.getJID(), 0);
}
else {
ContactInfoActivity.start(ctx, this, contact.getJID(), 0);
}
}
}
}
public void viewContact() {
if (mConversation != null) {
Contact contact = mConversation.getContact();
if (contact != null) {
Uri uri = contact.getUri();
if (uri != null) {
Intent i = SystemUtils.externalIntent(Intent.ACTION_VIEW, uri);
if (i.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(i);
}
else {
// no contacts app found (crap device eh?)
Toast.makeText(getActivity(),
R.string.err_no_contacts_app,
Toast.LENGTH_LONG).show();
}
}
else {
// no contact found
Toast.makeText(getActivity(),
R.string.err_no_contact,
Toast.LENGTH_SHORT).show();
}
}
}
}
private void blockUser() {
new MaterialDialog.Builder(getActivity())
.title(R.string.title_block_user_warning)
.content(R.string.msg_block_user_warning)
.positiveText(R.string.menu_block_user)
.positiveColorRes(R.color.button_danger)
.negativeText(android.R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
setPrivacy(dialog.getContext(), PrivacyCommand.BLOCK);
}
})
.show();
}
private void unblockUser() {
new MaterialDialog.Builder(getActivity())
.title(R.string.title_unblock_user_warning)
.content(R.string.msg_unblock_user_warning)
.positiveText(R.string.menu_unblock_user)
.positiveColorRes(R.color.button_danger)
.negativeText(android.R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
setPrivacy(dialog.getContext(), PrivacyCommand.UNBLOCK);
}
})
.show();
}
/** Translates special contacts into special strings. */
private String getDisplayName(@NonNull Contact contact) {
Context context = getContext();
if (context == null)
return contact.getDisplayName();
EndpointServer server = Preferences.getEndpointServer(context);
if (contact.getJID().equalsIgnoreCase(server.getNetwork())) {
return context.getString(R.string.contact_name_server);
}
else {
return contact.getDisplayName();
}
}
@Override
protected void loadConversationMetadata(Uri uri) {
super.loadConversationMetadata(uri);
if (mConversation != null) {
mUserJID = mConversation.getRecipient();
Contact contact = mConversation.getContact();
if (contact != null) {
mUserName = getDisplayName(contact);
mUserPhone = contact.getNumber();
}
else {
mUserName = mUserJID;
}
}
}
@Override
protected void handleActionView(Uri uri) {
long threadId = 0;
ContentResolver cres = getContext().getContentResolver();
/*
* FIXME this will retrieve name directly from contacts,
* resulting in a possible discrepancy with users database
*/
Cursor c = cres.query(uri, new String[] {
Syncer.DATA_COLUMN_DISPLAY_NAME,
Syncer.DATA_COLUMN_PHONE }, null, null, null);
if (c.moveToFirst()) {
mUserName = c.getString(0);
mUserPhone = c.getString(1);
// FIXME should it be retrieved from RawContacts.SYNC3 ??
mUserJID = XMPPUtils.createLocalJID(getContext(),
XMPPUtils.createLocalpart(mUserPhone));
threadId = MessagesProviderClient.findThread(getContext(), mUserJID);
}
c.close();
if (threadId > 0) {
mConversation = Conversation.loadFromId(getActivity(),
threadId);
setThreadId(threadId);
}
else if (mUserJID == null) {
Toast.makeText(getActivity(), R.string.err_no_contact,
Toast.LENGTH_LONG).show();
closeConversation();
}
else {
mConversation = Conversation.createNew(getActivity());
mConversation.setRecipient(mUserJID);
}
}
@Override
protected boolean handleActionViewConversation(Uri uri, Bundle args) {
mUserJID = uri.getPathSegments().get(1);
mConversation = Conversation.loadFromUserId(getActivity(),
mUserJID);
if (mConversation == null) {
mConversation = Conversation.createNew(getActivity());
mConversation.setNumberHint(args.getString("number"));
mConversation.setRecipient(mUserJID);
}
// this way avoid doing the users database query twice
else {
if (mConversation.getContact() == null) {
mConversation.setNumberHint(args.getString("number"));
mConversation.setRecipient(mUserJID);
}
}
setThreadId(mConversation.getThreadId());
Contact contact = mConversation.getContact();
if (contact != null) {
mUserName = getDisplayName(contact);
mUserPhone = contact.getNumber();
}
else {
mUserName = mUserJID;
mUserPhone = null;
}
return true;
}
@Override
protected void onArgumentsProcessed() {
// non existant thread - check for not synced contact
if (getThreadId() <= 0 && mConversation != null && mUserJID != null) {
Contact contact = mConversation.getContact();
if ((contact == null || !contact.isRegistered()) && mUserPhone != null) {
// ask user to send invitation
new MaterialDialog.Builder(getActivity())
.title(R.string.title_user_not_found)
.content(R.string.message_user_not_found)
// nothing happens if user chooses to contact the user anyway
.positiveText(R.string.yes_user_not_found)
.negativeText(R.string.no_user_not_found)
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
sendInvitation();
}
})
.show();
}
}
}
@Override
public boolean sendTyping() {
if (mAvailableResources.size() > 0) {
mServiceBus.post(new SendChatStateRequest.Builder(null)
.setChatState(ChatState.composing)
.setTo(JidCreate.fromOrThrowUnchecked(mUserJID))
.build());
return true;
}
return false;
}
@Override
public boolean sendInactive() {
if (mAvailableResources.size() > 0) {
mServiceBus.post(new SendChatStateRequest.Builder(null)
.setChatState(ChatState.inactive)
.setTo(JidCreate.fromOrThrowUnchecked(mUserJID))
.build());
return true;
}
return false;
}
@Override
protected void deleteConversation() {
try {
// delete all
mConversation.delete(true);
}
catch (SQLiteDiskIOException e) {
Log.w(TAG, "error deleting thread");
Toast.makeText(getActivity(), R.string.error_delete_thread,
Toast.LENGTH_LONG).show();
}
}
@Override
protected boolean isUserId(String jid) {
return XMPPUtils.equalsBareJID(jid, mUserJID);
}
@Override
protected void resetConnectionStatus() {
super.resetConnectionStatus();
// reset any pending request
mLastActivityRequestId = null;
mVersionRequestId = null;
mKeyRequestId = null;
}
@Override
public void onRosterLoaded(RosterLoadedEvent event) {
super.onRosterLoaded(event);
// probe presence
requestPresence();
}
@Override
protected void onStartTyping(String jid, @Nullable String groupJid) {
mIsTyping = true;
setStatusText(getString(R.string.seen_typing_label));
}
@Override
protected void onStopTyping(String jid, @Nullable String groupJid) {
mIsTyping = false;
setStatusText(mCurrentStatus != null ? mCurrentStatus : "");
}
private void onUserStatusChanged(PresenceEvent event) {
final Context context = getContext();
if (context == null)
return;
// hide any present warning
hideWarning(WarningType.FATAL);
Contact contact = getContact();
if (contact != null) {
// if this is null, we are accepting the key for the first time
PGPPublicKeyRing trustedPublicKey = contact.getTrustedPublicKeyRing();
// request the key if we don't have a trusted one and of course if the user has a key
boolean unknownKey = (trustedPublicKey == null && contact.getFingerprint() != null);
boolean changedKey = false;
// check if fingerprint changed (only if we have roster presence)
if (event.type != null && trustedPublicKey != null && event.fingerprint != null) {
String oldFingerprint = PGP.getFingerprint(PGP.getMasterKey(trustedPublicKey));
if (!event.fingerprint.equalsIgnoreCase(oldFingerprint)) {
// fingerprint has changed since last time
changedKey = true;
}
}
// user has no key (or we have no roster presence) or it couldn't be found: request it
else if ((trustedPublicKey == null && event.fingerprint == null) || event.type == null) {
if (mKeyRequestId != null) {
// avoid request loop
mKeyRequestId = null;
}
else {
// autotrust the key we are about to request
// but set the trust level to ignored because we didn't really verify it
Keyring.setAutoTrustLevel(context, event.jid.toString(), MyUsers.Keys.TRUST_IGNORED);
requestPublicKey(event.jid);
}
}
// key checks are to be done in advanced mode only
if (Keyring.isAdvancedMode(context, event.jid.toString())) {
if (changedKey) {
// warn user that public key is changed
showKeyChangedWarning(event.fingerprint);
}
else if (unknownKey) {
// warn user that public key is unknown
showKeyUnknownWarning(event.fingerprint);
}
}
}
}
@Override
public void onUserOnline(UserOnlineEvent event) {
final Context context = getContext();
if (context == null)
return;
// check that origin matches the current chat
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
super.onUserOnline(event);
onUserStatusChanged(event);
CharSequence statusText;
mIsTyping = mIsTyping || Contact.isTyping(event.jid.toString());
if (mIsTyping) {
setStatusText(context.getString(R.string.seen_typing_label));
}
/*
* FIXME using mode this way has several flaws.
* 1. it doesn't take multiple resources into account
* 2. it doesn't account for away status duration (we don't have this information at all)
*/
boolean isAway = (event.mode == Presence.Mode.away);
if (isAway) {
statusText = context.getString(R.string.seen_away_label);
}
else {
statusText = context.getString(R.string.seen_online_label);
}
String version = Contact.getVersion(event.jid.toString());
// do not request version info if already requested before
if (!isAway && version == null && mVersionRequestId == null) {
requestVersion(event.jid);
}
// a new resource just connected, send typing information again
// (only if we already sent it in this session)
// FIXME this will always broadcast the message to all resources
if (mComposer.isComposeSent() && mComposer.isSendEnabled() &&
Preferences.getSendTyping(context)) {
sendTyping();
}
setCurrentStatusText(statusText);
}
@Override
public void onUserOffline(UserOfflineEvent event) {
final Context context = getContext();
if (context == null)
return;
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
int resourceCount = mAvailableResources.size();
super.onUserOffline(event);
boolean removed = resourceCount != mAvailableResources.size();
onUserStatusChanged(event);
CharSequence statusText = null;
/*
* All available resources have gone. Mark
* the user as offline immediately and use the
* timestamp provided with the stanza (if any).
*/
if (mAvailableResources.size() == 0) {
// an offline user can't be typing
mIsTyping = false;
if (removed) {
// resource was removed now, mark as just offline
statusText = context.getText(R.string.seen_moment_ago_label);
}
else {
// resource is offline, request last activity
Contact contact = getContact();
if (contact != null && contact.getLastSeen() > 0) {
setLastSeenTimestamp(context, contact.getLastSeen());
}
else if (mLastActivityRequestId == null) {
mLastActivityRequestId = StringUtils.randomString(6);
mServiceBus.post(new LastActivityRequest(mLastActivityRequestId, event.jid.asBareJid()));
}
}
}
if (statusText != null) {
setCurrentStatusText(statusText);
}
}
@Override
public void onNoUserPresence(NoPresenceEvent event) {
final Context context = getContext();
if (context == null)
return;
// check that origin matches the current chat
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
// no roster entry found, request subscription
// pre-approve our presence and request subscription
mServiceBus.post(new PreapproveSubscriptionRequest(event.jid));
mServiceBus.post(new SubscribeRequest(event.jid));
setStatusText(context.getString(R.string.invitation_sent_label));
}
/** Sends a subscription request for the current peer. */
void requestPresence() {
// do not request presence for domain JIDs
if (!XMPPUtils.isDomainJID(mUserJID)) {
Context context = getContext();
if (context != null) {
// all of this shall be done only if there isn't a request from the other contact
// FIXME when accepting an invitation, the if below could be
// false because of delay or no reloading of mConversation at all
// thus skipping the presence request.
// An automatic solution could be to emit a ROSTER_LOADED whenever the roster changes
// still this _if_ should go away in favour of the message center checking for subscription status
// and the UI reacting to a pending request status (i.e. "pending_in")
if (mConversation.getRequestStatus() != Threads.REQUEST_WAITING) {
// request last presence
mServiceBus.post(new PresenceRequest(JidCreate.bareFromOrThrowUnchecked(mUserJID)));
}
}
}
}
void sendInvitation() {
// FIXME is this specific to sms app?
Intent i = SystemUtils.externalIntent(Intent.ACTION_SENDTO,
Uri.parse("smsto:" + mUserPhone));
i.putExtra("sms_body",
getString(R.string.text_invite_message));
startActivity(i);
getActivity().finish();
}
/** Called when the {@link Conversation} object has been created. */
@Override
protected void onConversationCreated() {
super.onConversationCreated();
// setup invitation bar
boolean visible = (mConversation.getRequestStatus() == Threads.REQUEST_WAITING);
if (visible) {
if (mInvitationBar == null) {
mInvitationBar = getView().findViewById(R.id.invitation_bar);
// setup listeners and show button bar
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
mInvitationBar.setVisibility(View.GONE);
PrivacyCommand action;
if (v.getId() == R.id.button_accept)
action = PrivacyCommand.ACCEPT;
else
action = PrivacyCommand.REJECT;
setPrivacy(v.getContext(), action);
}
};
mInvitationBar.findViewById(R.id.button_accept)
.setOnClickListener(listener);
mInvitationBar.findViewById(R.id.button_block)
.setOnClickListener(listener);
// identity button has its own listener
mInvitationBar.findViewById(R.id.button_identity)
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showIdentityDialog(true, R.string.title_invitation);
}
}
);
}
}
if (mInvitationBar != null)
mInvitationBar.setVisibility(visible ? View.VISIBLE : View.GONE);
}
void setPrivacy(@NonNull Context ctx, PrivacyCommand action) {
int status;
switch (action) {
case ACCEPT:
status = Threads.REQUEST_REPLY_PENDING_ACCEPT;
break;
case BLOCK:
case REJECT:
status = Threads.REQUEST_REPLY_PENDING_BLOCK;
break;
case UNBLOCK:
status = Threads.REQUEST_REPLY_PENDING_UNBLOCK;
break;
default:
return;
}
// temporarly disable peer observer because the next call will write to the threads table
unregisterPeerObserver();
// mark request as pending accepted
UsersProvider.setRequestStatus(ctx, mUserJID, status);
// accept invitation
if (action == PrivacyCommand.ACCEPT) {
// trust the key
String fingerprint = getContact().getFingerprint();
// we might not have a fingerprint if it's an XMPP user
if (fingerprint != null) {
Kontalk.get().getMessagesController()
.setTrustLevelAndRetryMessages(mUserJID,
fingerprint, MyUsers.Keys.TRUST_VERIFIED);
}
}
// reload contact
invalidateContact();
// send command to message center
BareJid jid = JidCreate.bareFromOrThrowUnchecked(mUserJID);
MessageCenterService.bus()
.post(new SetUserPrivacyRequest(jid, action));
// reload manually
mConversation = Conversation.loadFromUserId(ctx, mUserJID);
if (mConversation == null) {
// threads was deleted (it was a request thread)
threadId = 0;
}
processStart();
if (threadId == 0) {
// no thread means no peer observer will be invoked
// we need to manually trigger this
ConnectedEvent connectedEvent = mServiceBus.getStickyEvent(ConnectedEvent.class);
if (connectedEvent != null) {
onConnected(connectedEvent);
}
RosterLoadedEvent rosterLoadedEvent = mServiceBus.getStickyEvent(RosterLoadedEvent.class);
if (rosterLoadedEvent != null) {
onRosterLoaded(rosterLoadedEvent);
}
}
}
void invalidateContact() {
Contact.invalidate(mUserJID);
reloadContact();
}
void reloadContact() {
if (mConversation != null) {
// this will trigger contact reload
mConversation.setRecipient(mUserJID);
}
}
@Override
protected void addUsers(String[] members) {
String selfJid = Authenticator.getSelfJID(getContext());
String groupId = StringUtils.randomString(20);
String groupJid = KontalkGroupCommands.createGroupJid(groupId, selfJid);
// ensure no duplicates
Set<String> usersList = new HashSet<>();
String userId = getUserId();
if (!userId.equalsIgnoreCase(selfJid))
usersList.add(userId);
for (String member : members) {
// exclude ourselves
if (!member.equalsIgnoreCase(selfJid))
usersList.add(member);
}
if (usersList.size() > 0) {
askGroupSubject(usersList, groupJid);
}
}
private void askGroupSubject(final Set<String> usersList, final String groupJid) {
new MaterialDialog.Builder(getContext())
.title(R.string.title_group_subject)
.positiveText(android.R.string.ok)
.negativeText(android.R.string.cancel)
.input(null, null, true, new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
String title = !TextUtils.isEmpty(input) ? input.toString() : null;
String[] users = usersList.toArray(new String[usersList.size()]);
long groupThreadId = Conversation.initGroupChat(getContext(),
groupJid, title, users,
mComposer.getText().toString());
// store create group command to outbox
// NOTE: group chats can currently only be created with chat encryption enabled
boolean encrypted = Preferences.getEncryptionEnabled(getContext());
String msgId = MessageCenterService.messageId();
Uri cmdMsg = KontalkGroupCommands.createGroup(getContext(),
groupThreadId, groupJid, users, msgId, encrypted);
// TODO check for null
// send create group command now
MessageCenterService.bus()
.post(new SendMessageRequest(ContentUris.parseId(cmdMsg)));
// open the new conversation
((ComposeMessageParent) getActivity()).loadConversation(groupThreadId, true);
}
})
.inputRange(0, MyMessages.Groups.GROUP_SUBJECT_MAX_LENGTH)
.show();
}
void showIdentityDialog(boolean informationOnly, int titleId) {
String fingerprint;
String uid;
PGPPublicKeyRing publicKey = Keyring.getPublicKey(getActivity(), mUserJID, MyUsers.Keys.TRUST_UNKNOWN);
if (publicKey != null) {
PGPPublicKey pk = PGP.getMasterKey(publicKey);
fingerprint = PGP.formatFingerprint(PGP.getFingerprint(pk));
uid = PGP.getUserId(pk, XmppStringUtils.parseDomain(mUserJID));
}
else {
// FIXME using another string
fingerprint = uid = getString(R.string.peer_unknown);
}
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(getString(R.string.text_invitation1))
.append('\n');
Contact c = mConversation.getContact();
if (c != null && c.getName() != null && c.getNumber() != null) {
text.append(c.getName())
.append(" <")
.append(c.getNumber())
.append('>');
}
else {
int start = text.length() - 1;
text.append(uid);
text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
text.append('\n')
.append(getString(R.string.text_invitation2))
.append('\n');
int start = text.length() - 1;
text.append(fingerprint);
text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
MaterialDialog.Builder builder = new MaterialDialog
.Builder(getActivity())
.content(text);
if (informationOnly) {
builder.title(titleId);
}
else {
builder.title(titleId)
.positiveText(R.string.button_accept)
.positiveColorRes(R.color.button_success)
.negativeText(R.string.button_block)
.negativeColorRes(R.color.button_danger)
.onAny(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
// hide warning bar
hideWarning();
switch (which) {
case POSITIVE:
// trust new key
trustKeyChange(dialog.getContext(), null);
break;
case NEGATIVE:
// block user immediately
setPrivacy(dialog.getContext(), PrivacyCommand.BLOCK);
break;
}
}
});
}
builder.show();
}
void trustKeyChange(@NonNull Context context, String fingerprint) {
// mark current key as trusted
if (fingerprint == null)
fingerprint = getContact().getFingerprint();
Kontalk.get().getMessagesController()
.setTrustLevelAndRetryMessages(mUserJID, fingerprint, MyUsers.Keys.TRUST_VERIFIED);
// reload contact
invalidateContact();
}
private void showKeyWarning(int textId, final int dialogTitleId, final int dialogMessageId, final Object... data) {
final Activity context = getActivity();
if (context != null) {
showWarning(context.getText(textId), new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialDialog.Builder(context)
.title(dialogTitleId)
.content(dialogMessageId)
.positiveText(R.string.button_accept)
.positiveColorRes(R.color.button_success)
.neutralText(R.string.button_identity)
.negativeText(R.string.button_block)
.negativeColorRes(R.color.button_danger)
.onAny(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
switch (which) {
case POSITIVE:
// hide warning bar
hideWarning();
// trust new key
trustKeyChange(dialog.getContext(), (String) data[0]);
break;
case NEUTRAL:
showIdentityDialog(false, dialogTitleId);
break;
case NEGATIVE:
// hide warning bar
hideWarning();
// block user immediately
setPrivacy(dialog.getContext(), PrivacyCommand.BLOCK);
break;
}
}
})
.show();
}
}, WarningType.FATAL);
}
}
private void showKeyUnknownWarning(String fingerprint) {
showKeyWarning(R.string.warning_public_key_unknown,
R.string.title_public_key_unknown_warning, R.string.msg_public_key_unknown_warning,
fingerprint);
}
private void showKeyChangedWarning(String newFingerprint) {
showKeyWarning(R.string.warning_public_key_changed,
R.string.title_public_key_changed_warning, R.string.msg_public_key_changed_warning,
newFingerprint);
}
void setVersionInfo(Context context, String version) {
if (SystemUtils.isOlderVersion(context, version)) {
showWarning(context.getText(R.string.warning_older_version), null, WarningType.WARNING);
}
}
private void setLastSeenTimestamp(Context context, long stamp) {
setCurrentStatusText(MessageUtils.formatRelativeTimeSpan(context, stamp));
}
void setLastSeenSeconds(Context context, long seconds) {
setCurrentStatusText(MessageUtils
.formatLastSeen(context, getContact(), seconds));
}
private void setCurrentStatusText(CharSequence statusText) {
mCurrentStatus = statusText;
if (!mIsTyping)
setStatusText(statusText);
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onPublicKey(PublicKeyEvent event) {
if (event.id != null && event.id.equals(mKeyRequestId)) {
// reload contact
invalidateContact();
// request presence again
requestPresence();
}
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onLastActivity(LastActivityEvent event) {
final Context context = getContext();
if (context == null)
return;
if (event.id != null && event.id.equals(mLastActivityRequestId)) {
mLastActivityRequestId = null;
// ignore last activity if we had an available presence in the meantime
if (mAvailableResources.size() == 0) {
if (event.error == null && event.idleTime >= 0) {
setLastSeenSeconds(context, event.idleTime);
}
else {
setCurrentStatusText(context.getString(R.string.seen_offline_label));
}
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onVersion(VersionEvent event) {
Context context = getContext();
if (context == null)
return;
// compare version and show warning if needed
if (event.id != null && event.id.equals(mVersionRequestId)) {
mVersionRequestId = null;
if (event.name != null && event.name.equalsIgnoreCase(context.getString(R.string.app_name))) {
if (event.version != null) {
// cache the version
Contact.setVersion(event.jid.toString(), event.version);
setVersionInfo(context, event.version);
}
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onUserSubscribed(UserSubscribedEvent event) {
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
// reload contact
invalidateContact();
// request presence
requestPresence();
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onUserBlocked(UserBlockedEvent event) {
final Context context = getContext();
if (context == null)
return;
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
// reload contact
reloadContact();
// this will update block/unblock menu items
updateUI();
Toast.makeText(context,
R.string.msg_user_blocked,
Toast.LENGTH_LONG).show();
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onUserUnblocked(UserUnblockedEvent event) {
final Context context = getContext();
if (context == null)
return;
if (!isUserId(event.jid.toString())) {
// not for us
return;
}
// reload contact
reloadContact();
// this will update block/unblock menu items
updateUI();
// hide any block warning
// a new warning will be issued for the key if needed
hideWarning();
// request presence subscription when unblocking
requestPresence();
Toast.makeText(context,
R.string.msg_user_unblocked,
Toast.LENGTH_LONG).show();
}
private void requestVersion(Jid jid) {
Context context = getActivity();
if (context != null) {
mVersionRequestId = StringUtils.randomString(6);
mServiceBus.post(new VersionRequest(mVersionRequestId, jid));
}
}
private void requestPublicKey(Jid jid) {
Context context = getActivity();
if (context != null) {
mKeyRequestId = StringUtils.randomString(6);
mServiceBus.post(new PublicKeyRequest(mKeyRequestId, jid));
}
}
public void onFocus() {
super.onFocus();
if (mUserJID != null) {
// clear chat invitation (if any)
MessagingNotification.clearChatInvitation(getActivity(), mUserJID);
}
}
protected void updateUI() {
super.updateUI();
Contact contact = (mConversation != null) ? mConversation
.getContact() : null;
boolean contactEnabled = contact != null && contact.getId() > 0;
if (mCallMenu != null) {
Context context = getContext();
// FIXME what about VoIP?
if (context != null && !context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TELEPHONY)) {
mCallMenu.setVisible(false).setEnabled(false);
}
else {
mCallMenu.setVisible(true).setEnabled(true);
mCallMenu.setEnabled(contactEnabled);
}
mViewContactMenu.setEnabled(contactEnabled);
}
if (mBlockMenu != null) {
Context context = getContext();
if (context != null) {
if (Authenticator.isSelfJID(context, mUserJID)) {
mBlockMenu.setVisible(false).setEnabled(false);
mUnblockMenu.setVisible(false).setEnabled(false);
}
else if (contact != null) {
// block/unblock
boolean blocked = contact.isBlocked();
if (blocked)
// show warning if blocked
showWarning(context.getText(R.string.warning_user_blocked),
null, WarningType.WARNING);
mBlockMenu.setVisible(!blocked).setEnabled(!blocked);
mUnblockMenu.setVisible(blocked).setEnabled(blocked);
}
else {
mBlockMenu.setVisible(true).setEnabled(true);
mUnblockMenu.setVisible(true).setEnabled(true);
}
}
}
}
@Override
public String getUserId() {
return mUserJID;
}
@Override
protected String getDecodedPeer(CompositeMessage msg) {
return mUserPhone != null ? mUserPhone : mUserJID;
}
@Override
protected String getDecodedName(CompositeMessage msg) {
Contact c = getContact();
return (c != null) ? c.getName() : null;
}
}
| 115ek/androidclient | app/src/main/java/org/kontalk/ui/ComposeMessageFragment.java | Java | gpl-3.0 | 44,925 |
package eu.transkribus.core.model.beans;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import eu.transkribus.core.exceptions.NullValueException;
import eu.transkribus.core.model.beans.adapters.EditStatusAdapter;
import eu.transkribus.core.model.beans.enums.EditStatus;
import eu.transkribus.core.model.beans.pagecontent.PcGtsType;
import eu.transkribus.core.util.CoreUtils;
import eu.transkribus.core.util.PageXmlUtils;
/**
* Includes the data of a single transcript version for a page.
* <br/><br/>
* TODO: DbUtils retrieves only fields declared, so extending TrpTranscriptStatistics
* and removing the respective inherited fields here does not work!
*
* @author philip
*
*/
@Entity
@Table(name = "transcripts")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TrpTranscriptMetadata extends ATranscriptStatistics implements ITrpFile, Serializable, Comparable<TrpTranscriptMetadata> {
private static final long serialVersionUID = 1L;
static DateFormat timeFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
@XmlTransient
TrpPage pageReferenceForLocalDocs;
@Id
@Column(name = "TSID")
private int tsId = -1;
@Column(name = "PARENT_TSID")
private int parentTsId = -1;
@Column(name = "xmlkey")
private String key = null; //the fimagestore key for getting the XML
@Column
private int pageId = -1;
@Transient
@Column
private int docId = -1;
@Transient
@Column
private int pageNr = -1;
@Transient
private File localFolder = null; // != null when local document
@Column
@Transient
private URL url;
@Column
@XmlJavaTypeAdapter(EditStatusAdapter.class)
private EditStatus status;
@Column(name="userId")
private String userName;
@Column(name="user_id")
private int userId;
// @XmlJavaTypeAdapter(DateAdapter.class)
// private Date time = new Date();
@Column
private long timestamp = System.currentTimeMillis();
@Column
private String toolName = null;
@Column
private Integer jobId;
@Column(name="NOTE")
private String note = "";
private String md5Sum = "";
@Column(name=N_REGIONS_COL_NAME)
private Integer nrOfRegions = 0;
@Column(name=N_TRANSCRIBED_REGIONS_COL_NAME)
private Integer nrOfTranscribedRegions = 0;
@Column(name=N_WORDS_IN_REGIONS_COL_NAME)
private Integer nrOfWordsInRegions = 0;
@Column(name=N_LINES_COL_NAME)
private Integer nrOfLines = 0;
@Column(name=N_TRANSCRIBED_LINES_COL_NAME)
private Integer nrOfTranscribedLines = 0;
@Column(name=N_WORDS_IN_LINES_COL_NAME)
private Integer nrOfWordsInLines = 0;
@Column(name=N_WORDS_COL_NAME)
private Integer nrOfWords = 0;
@Column(name=N_TRANSCRIBED_WORDS_COL_NAME)
private Integer nrOfTranscribedWords = 0;
@Column
@Transient
private Integer gtId = null;
//TODO tags
//TODO annotations
public TrpTranscriptMetadata() {
}
public TrpTranscriptMetadata(final int tsId, final String key, final int pageId,
final long timestamp, final int userId, final String userName, final EditStatus status, final int parentId, final String note) {
this.tsId = tsId;
this.key = key;
this.pageId = pageId;
this.timestamp = timestamp;
this.userId = userId;
this.userName = userName;
this.status = status;
this.parentTsId = parentId;
this.note = note;
}
public TrpTranscriptMetadata(TrpTranscriptMetadata m, TrpPage pageReferenceForLocalDocs) {
this();
this.pageReferenceForLocalDocs = pageReferenceForLocalDocs;
tsId = m.getTsId();
parentTsId = m.getParentTsId();
key = m.getKey();
pageId = m.getPageId();
docId = m.getDocId();
pageNr = m.getPageNr();
localFolder = m.getLocalFolder();
url = m.getUrl();
status = m.getStatus();
userName = m.getUserName();
userId = m.getUserId();
timestamp = m.getTimestamp();
toolName = m.getToolName();
jobId = m.getJobId();
note = m.getNote();
md5Sum = m.getMd5Sum();
this.setStats(m.getStats());
}
public int getTsId() {
return tsId;
}
public void setTsId(int tsId) {
this.tsId = tsId;
}
public int getParentTsId() {
return parentTsId;
}
public void setParentTsId(int parentTsId) {
this.parentTsId = parentTsId;
}
public File getLocalFolder() {
return localFolder;
}
public void setLocalFolder(File localFolder) {
this.localFolder = localFolder;
}
public String getKey() {
return key;
}
public void setKey(String xmlKey) {
this.key = xmlKey;
}
public int getPageId() {
return pageId;
}
public void setPageId(int pageId) {
this.pageId = pageId;
}
public int getDocId() {
return docId;
}
public void setDocId(int docId) {
this.docId = docId;
}
public int getPageNr() {
return pageNr;
}
public void setPageNr(int pageNr) {
this.pageNr = pageNr;
}
public URL getUrl() {
return url;
}
public void setUrl(URL xmlUrl) {
this.url = xmlUrl;
}
public String getXmlFileName() {
String name = null;
if(this.isLocalTranscript()) {
name = this.getFile().getName();
}
return name;
}
public EditStatus getStatus() {
return status;
}
public void setStatus(EditStatus status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public long getTimestamp() {
return timestamp;
}
public Date getTime() {
return new Date(this.timestamp);
}
public String getTimeFormatted() {
return timeFormatter.format(getTime());
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public void setTime(Date time) {
this.timestamp = time.getTime();
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public Integer getJobId() {
return jobId;
}
public void setJobId(Integer jobId) {
this.jobId= jobId;
}
public String getNote(){
return note;
}
public void setNote(String note){
this.note = note;
}
public String getMd5Sum() {
return this.md5Sum;
}
public void setMd5Sum(String md5Sum) {
this.md5Sum = md5Sum;
}
public TrpPage getPagePageReferenceForLocalDocs() {
return pageReferenceForLocalDocs;
}
public void setPageReferenceForLocalDocs(TrpPage pageReferenceForLocalDocs) {
this.pageReferenceForLocalDocs = pageReferenceForLocalDocs;
}
public Integer getNrOfRegions() {
return nrOfRegions;
}
public void setNrOfRegions(Integer nrOfRegions) {
this.nrOfRegions = nrOfRegions;
}
public Integer getNrOfTranscribedRegions() {
return nrOfTranscribedRegions;
}
public void setNrOfTranscribedRegions(Integer nrOfTranscribedRegions) {
this.nrOfTranscribedRegions = nrOfTranscribedRegions;
}
public Integer getNrOfWordsInRegions() {
return nrOfWordsInRegions;
}
public void setNrOfWordsInRegions(Integer nrOfWordsInRegions) {
this.nrOfWordsInRegions = nrOfWordsInRegions;
}
public Integer getNrOfLines() {
return nrOfLines;
}
public void setNrOfLines(Integer nrOfLines) {
this.nrOfLines = nrOfLines;
}
public Integer getNrOfTranscribedLines() {
return nrOfTranscribedLines;
}
public void setNrOfTranscribedLines(Integer nrOfTranscribedLines) {
this.nrOfTranscribedLines = nrOfTranscribedLines;
}
public Integer getNrOfWordsInLines() {
return nrOfWordsInLines;
}
public void setNrOfWordsInLines(Integer nrOfWordsInLines) {
this.nrOfWordsInLines = nrOfWordsInLines;
}
public Integer getNrOfWords() {
return nrOfWords;
}
public void setNrOfWords(Integer nrOfWords) {
this.nrOfWords = nrOfWords;
}
public Integer getNrOfTranscribedWords() {
return nrOfTranscribedWords;
}
public void setNrOfTranscribedWords(Integer nrOfTranscribedWords) {
this.nrOfTranscribedWords = nrOfTranscribedWords;
}
public Integer getGtId() {
return gtId;
}
public void setGtId(Integer gtId) {
this.gtId = gtId;
}
/**
* Check key and URL protocol.<br/>
* This method returns false, if there is a filekey set.<br/>
* It returns true, if there is no filekey and the URL points to an existing file.<br/>
*
* @return
* @throws IllegalStateException in case there are inconsistencies:
* <ul>
* <li>key of transcript is null, but the URL protocol is not "file://"</li>
* <li>key of transcript is null, but the file URL does not point to an existing file</li>
* </ul>
*/
public boolean isLocalTranscript() {
return isLocalFile();
}
@Override
public boolean equals(Object o) {
// FIXME ?? (not tested)
if (o==null || !(o instanceof TrpTranscriptMetadata))
return false;
TrpTranscriptMetadata m = (TrpTranscriptMetadata) o;
if (pageId != m.pageId)
return false;
if (!CoreUtils.equalsObjects(key, m.key))
return false;
if (!CoreUtils.equalsObjects(localFolder, m.localFolder))
return false;
int c = compareTo(m);
if (c != 0)
return false;
return true;
}
/**
* Uses the timestamp for comparison
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(TrpTranscriptMetadata md) {
int result = 0;
if (this.getTimestamp() > md.getTimestamp()) {
result = 1;
} else if (this.getTimestamp() < md.getTimestamp()) {
result = -1;
}
return result;
}
/**
* This method is just for testing equivalence of documents selected via different DocManager methods
* @param obj
* @return
*/
public boolean testEquals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TrpTranscriptMetadata other = (TrpTranscriptMetadata) obj;
if (docId != other.docId)
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (localFolder == null) {
if (other.localFolder != null)
return false;
} else if (!localFolder.equals(other.localFolder))
return false;
if (md5Sum == null) {
if (other.md5Sum != null)
return false;
} else if (!md5Sum.equals(other.md5Sum))
return false;
if (note == null) {
if (other.note != null)
return false;
} else if (!note.equals(other.note))
return false;
if (nrOfLines == null) {
if (other.nrOfLines != null)
return false;
} else if (!nrOfLines.equals(other.nrOfLines))
return false;
if (nrOfRegions == null) {
if (other.nrOfRegions != null)
return false;
} else if (!nrOfRegions.equals(other.nrOfRegions))
return false;
if (nrOfTranscribedLines == null) {
if (other.nrOfTranscribedLines != null)
return false;
} else if (!nrOfTranscribedLines.equals(other.nrOfTranscribedLines))
return false;
if (nrOfTranscribedRegions == null) {
if (other.nrOfTranscribedRegions != null)
return false;
} else if (!nrOfTranscribedRegions.equals(other.nrOfTranscribedRegions))
return false;
if (nrOfTranscribedWords == null) {
if (other.nrOfTranscribedWords != null)
return false;
} else if (!nrOfTranscribedWords.equals(other.nrOfTranscribedWords))
return false;
if (nrOfWords == null) {
if (other.nrOfWords != null)
return false;
} else if (!nrOfWords.equals(other.nrOfWords))
return false;
if (nrOfWordsInLines == null) {
if (other.nrOfWordsInLines != null)
return false;
} else if (!nrOfWordsInLines.equals(other.nrOfWordsInLines))
return false;
if (nrOfWordsInRegions == null) {
if (other.nrOfWordsInRegions != null)
return false;
} else if (!nrOfWordsInRegions.equals(other.nrOfWordsInRegions))
return false;
if (pageId != other.pageId)
return false;
if (pageNr != other.pageNr)
return false;
if (pageReferenceForLocalDocs == null) {
if (other.pageReferenceForLocalDocs != null)
return false;
} else if (!pageReferenceForLocalDocs.equals(other.pageReferenceForLocalDocs))
return false;
if (parentTsId != other.parentTsId)
return false;
if (status != other.status)
return false;
if (timestamp != other.timestamp)
return false;
if (toolName == null) {
if (other.toolName != null)
return false;
} else if (!toolName.equals(other.toolName))
return false;
if (jobId == null) {
if (other.jobId != null)
return false;
} else if (!jobId.equals(other.jobId))
return false;
if (tsId != other.tsId)
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
if (userId != other.userId)
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
public PcGtsType unmarshallTranscript() throws NullValueException, JAXBException {
if (getUrl()==null)
throw new NullValueException("URL of transcript is null!");
return PageXmlUtils.unmarshal(getUrl());
}
@Override
public String toString() {
return "TrpTranscriptMetadata [tsId=" + tsId
+ ", parentTsId=" + parentTsId + ", key=" + key + ", pageId=" + pageId + ", docId=" + docId
+ ", pageNr=" + pageNr + ", localFolder=" + localFolder + ", url=" + url + ", status=" + status
+ ", userName=" + userName + ", userId=" + userId + ", timestamp=" + timestamp + ", toolName="
+ toolName + ", jobId=" + jobId + ", note=" + note + ", md5Sum=" + md5Sum + ", nrOfRegions=" + nrOfRegions
+ ", nrOfTranscribedRegions=" + nrOfTranscribedRegions + ", nrOfWordsInRegions=" + nrOfWordsInRegions
+ ", nrOfLines=" + nrOfLines + ", nrOfTranscribedLines=" + nrOfTranscribedLines + ", nrOfWordsInLines="
+ nrOfWordsInLines + ", nrOfWords=" + nrOfWords + ", nrOfTranscribedWords=" + nrOfTranscribedWords
+ ", gtId=" + gtId + "]";
}
}
| Transkribus/TranskribusCore | src/main/java/eu/transkribus/core/model/beans/TrpTranscriptMetadata.java | Java | gpl-3.0 | 14,273 |
package info.infiniteloops.discuss.chat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import info.infiniteloops.discuss.R;
import info.infiniteloops.discuss.Utilities;
import info.infiniteloops.discuss.chat.data.FriendDB;
import info.infiniteloops.discuss.chat.data.GroupDB;
import info.infiniteloops.discuss.chat.data.StaticConfig;
import info.infiniteloops.discuss.chat.model.Group;
import info.infiniteloops.discuss.chat.model.ListFriend;
import info.infiniteloops.discuss.chat.ui.AddGroupActivity;
import info.infiniteloops.discuss.chat.ui.ChatActivity;
import info.infiniteloops.discuss.chat.util.ViewTarget;
public class TVFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerListGroups;
private ArrayList<Group> listGroup;
private ListMovieAdapter adapter;
private SwipeRefreshLayout mSwipeRefreshLayout;
public static final int REQUEST_EDIT_GROUP = 0;
public TVFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.chat_fragment_group, container, false);
listGroup = GroupDB.getInstance(getContext()).getListGroups();
recyclerListGroups = (RecyclerView) layout.findViewById(R.id.recycleListGroup);
mSwipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(this);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerListGroups.setLayoutManager(layoutManager);
adapter = new ListMovieAdapter(getContext(), listGroup);
recyclerListGroups.setAdapter(adapter);
if(listGroup.size() == 0){
//Ket noi server hien thi group
mSwipeRefreshLayout.setRefreshing(true);
getListGroup();
}
return layout;
}
private void getListGroup(){
Utilities.getFirebaseDBReference().child("user/"+ StaticConfig.UID+"/subscribed/movies").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
HashMap mapListGroup = (HashMap) dataSnapshot.getValue();
Iterator iterator = mapListGroup.keySet().iterator();
while (iterator.hasNext()){
String idGroup = mapListGroup.get(iterator.next().toString()).toString();
Group newGroup = new Group();
newGroup.id = idGroup;
listGroup.add(newGroup);
}
getGroupInfo(0);
}else{
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_EDIT_GROUP && resultCode == Activity.RESULT_OK) {
listGroup.clear();
ListMovieAdapter.listFriend = null;
GroupDB.getInstance(getContext()).dropDB();
getListGroup();
}
}
private void getGroupInfo(final int indexGroup){
if(indexGroup == listGroup.size()){
adapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}else {
Utilities.getFirebaseDBReference().child("movies/"+listGroup.get(indexGroup).id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.getValue() != null) {
HashMap mapGroup = (HashMap) dataSnapshot.getValue();
HashMap member = (HashMap) mapGroup.get("member");
Iterator iterator = member.keySet().iterator();
HashMap mapGroupInfo = (HashMap) mapGroup.get("groupInfo");
while (iterator.hasNext()) {
String idMember = member.get(iterator.next().toString()).toString();
listGroup.get(indexGroup).member.add(idMember);
}
listGroup.get(indexGroup).groupInfo.put("name", (String) mapGroupInfo.get("originalTitle"));
listGroup.get(indexGroup).groupInfo.put("admin", "Hellow World");
listGroup.get(indexGroup).groupInfo.put("poster",
Utilities.POSTER_IMAGE_BASE_URL
+ Utilities.POSTER_IMAGE_SIZE
+ (String) mapGroupInfo.get("posterPath"));
}
Log.d("TVFragment", listGroup.get(indexGroup).id + ": " + dataSnapshot.toString());
getGroupInfo(indexGroup + 1);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getContext(),"No Subscription",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
@Override
public void onRefresh() {
listGroup.clear();
ListMovieAdapter.listFriend = null;
GroupDB.getInstance(getContext()).dropDB();
adapter.notifyDataSetChanged();
getListGroup();
}
public class FragGroupClickFloatButton implements View.OnClickListener{
Context context;
public FragGroupClickFloatButton getInstance(Context context){
this.context = context;
return this;
}
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), AddGroupActivity.class));
}
}
}
class ListMovieAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Group> listGroup;
public static ListFriend listFriend = null;
private Context context;
public ListMovieAdapter(Context context,ArrayList<Group> listGroup){
this.context = context;
this.listGroup = listGroup;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.chat_rc_item_group, parent, false);
return new ItemMovieViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final String groupName = listGroup.get(position).groupInfo.get("name");
if(groupName != null && groupName.length() > 0) {
((ItemMovieViewHolder) holder).txtGroupName.setText(groupName);
((ItemMovieViewHolder) holder).iconGroup.setText((groupName.charAt(0) + "").toUpperCase());
}
ViewTarget viewTarget = new ViewTarget(((ItemMovieViewHolder) holder).groupBG);
Glide.with(context).load(listGroup.get(position).groupInfo.get("poster")).fitCenter().centerCrop().into(viewTarget);
((ItemMovieViewHolder) holder).btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setTag(new Object[]{groupName, position});
view.getParent().showContextMenuForChild(view);
}
});
((RelativeLayout)((ItemMovieViewHolder) holder).txtGroupName.getParent()).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(listFriend == null){
listFriend = FriendDB.getInstance(context).getListFriend();
}
ArrayList<CharSequence> idFriend = new ArrayList<>();
ChatActivity.bitmapAvataFriend = new HashMap<>();
for(String id : listGroup.get(position).member) {
idFriend.add(id);
String avata = listFriend.getAvataById(id);
if(!avata.equals(StaticConfig.STR_DEFAULT_BASE64)) {
byte[] decodedString = Base64.decode(avata, Base64.DEFAULT);
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
}else if(avata.equals(StaticConfig.STR_DEFAULT_BASE64)) {
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avata));
}else {
ChatActivity.bitmapAvataFriend.put(id, null);
}
}
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra(StaticConfig.INTENT_KEY_CHAT_FRIEND, groupName);
intent.putCharSequenceArrayListExtra(StaticConfig.INTENT_KEY_CHAT_ID, idFriend);
intent.putExtra(StaticConfig.INTENT_KEY_CHAT_ROOM_ID, listGroup.get(position).id);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return listGroup.size();
}
}
class ItemMovieViewHolder extends RecyclerView.ViewHolder {
public TextView iconGroup, txtGroupName;
public ImageButton btnMore;
public RelativeLayout groupBG;
public ItemMovieViewHolder(View itemView) {
super(itemView);
iconGroup = (TextView) itemView.findViewById(R.id.icon_group);
txtGroupName = (TextView) itemView.findViewById(R.id.txtName);
btnMore = (ImageButton) itemView.findViewById(R.id.btnMoreAction);
groupBG = (RelativeLayout) itemView.findViewById(R.id.groupBG);
}
} | ansarisufiyan777/Show_Chat | app/src/main/java/info/infiniteloops/discuss/chat/TVFragment.java | Java | gpl-3.0 | 11,392 |
/**
* <pre>
* The owner of the original code is Ciena Corporation.
*
* Portions created by the original owner are Copyright (C) 2004-2010
* the original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of DRAC (Dynamic Resource Allocation Controller).
*
* DRAC 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.
*
* DRAC 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/>.
* </pre>
*/
package com.nortel.appcore.app.drac.server.lpcp.rmi;
import static org.junit.Assert.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.rmi.Naming;
import java.rmi.Remote;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.opendrac.launcher.RmiLauncher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nortel.appcore.app.drac.common.info.RmiServerInfo;
import com.nortel.appcore.app.drac.common.types.AuditResult;
import com.nortel.appcore.app.drac.common.types.BandwidthRecord;
import com.nortel.appcore.app.drac.common.types.DracService;
import com.nortel.appcore.app.drac.common.types.GraphData;
import com.nortel.appcore.app.drac.common.types.LpcpStatus;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder;
import com.nortel.appcore.app.drac.common.types.SPF_KEYS;
import com.nortel.appcore.app.drac.common.types.ScheduleResult;
import com.nortel.appcore.app.drac.common.types.ServerInfoType;
import com.nortel.appcore.app.drac.common.types.State.SERVICE;
import com.nortel.appcore.app.drac.server.nrb.LpcpEventCallback;
public class LpcpRemoteTest {
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* This is a do nothing delegate for testing the NRB_PORT infrastructure.
*
* @author pitman
*/
static class Delegate implements LpcpServerInterface, Remote, Serializable {
private static final long serialVersionUID = 1L;
@Override
public void activateService(String serviceId) throws Exception {
return;
}
@Override
public List<AuditResult> auditModel() throws Exception {
return null;
}
@Override
public void cancelService(String[] serviceIds, SERVICE state)
throws Exception {
return;
}
@Override
public void confirmService(String serviceId) throws Exception {
return;
}
@Override
public void correctModel() throws Exception {
return;
}
@Override
public void deleteNetworkElement(NetworkElementHolder oldNe)
throws Exception {
return;
}
@Override
public void editFacility(String neid, String aid, String tna,
String faclabel, String mtu, String srlg, String grp, String cost,
String metric2, String sigType, String constraints, String domainId,
String siteId) throws Exception {
return;
}
@Override
public double getCurrentBandwidthUsage(String tna) throws Exception {
return 0;
}
@Override
public GraphData getGraphData() throws Exception {
return null;
}
@Override
public ServerInfoType getInfo() throws Exception {
return null;
}
@Override
public List<BandwidthRecord> getInternalBandwithUsage(long startTime,
long endTime) throws Exception {
return null;
}
@Override
public String getLpcpDiscoveryStatus() throws Exception {
return null;
}
@Override
public LpcpStatus getLpcpStatus() throws Exception {
return null;
}
@Override
public String getPeerIPAddress() throws Exception {
return null;
}
@Override
public String getSRLGListForServiceId(String serviceId) throws Exception {
return null;
}
@Override
public boolean isAlive() throws Exception {
return false;
}
@Override
public void registerForLpcpEventNotifications(LpcpEventCallback cb)
throws Exception {
return;
}
@Override
public ScheduleResult createSchedule(Map<SPF_KEYS, String> parms,
boolean queryOnly) throws Exception {
return null;
}
@Override
public ScheduleResult extendServiceTime(DracService service,
Integer minutesToExtendService) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
@Test
public void testLpcpRemote() throws Exception {
// Bind our rmi registry and LPCP_PORT to port zero so we'll work anywhere.
final int rmiRandomPort = 1099;
final RmiLauncher rmiLauncher = new RmiLauncher();
rmiLauncher.start();
log.debug("helper " + rmiLauncher);
LpcpRemote lpcp = new LpcpRemote(rmiRandomPort, new Delegate());
log.debug("Binding " + RmiServerInfo.LPCP_RMI_NAME);
Naming.rebind(RmiServerInfo.LPCP_RMI_NAME, lpcp);
LpcpInterface remoteLpcp = (LpcpInterface) Naming
.lookup(RmiServerInfo.LPCP_RMI_NAME);
assertNotNull(remoteLpcp);
// bogus but good enough
// Use reflection to call all of the methods in the interface remote class.
int ok = rmiRandomPort;
for (Method m : remoteLpcp.getClass().getDeclaredMethods()) {
if (!Modifier.isPublic(m.getModifiers())
|| Modifier.isStatic(m.getModifiers())) {
log.debug("Skipping method " + m.getName() + " " + ok);
continue;
}
// Type[] argTypes = m.getGenericParameterTypes();
Class<?>[] argTypes = m.getParameterTypes();
Object[] args = new Object[argTypes.length];
for (int i = 1; i < args.length; i++) {
if (argTypes[i].isPrimitive()) {
if (argTypes[i] == Integer.TYPE) {
args[i] = Integer.valueOf(rmiRandomPort);
}
else if (argTypes[i] == Long.TYPE) {
args[i] = Long.valueOf(rmiRandomPort);
}
else if (argTypes[i] == Boolean.TYPE) {
args[i] = Boolean.FALSE;
}
else if (argTypes[i] == Double.TYPE) {
args[i] = Double.valueOf(rmiRandomPort);
}
else {
fail("Unsupported type, enhance test case for primiative ");
}
}
}
}
rmiLauncher.stop();
}
}
| jmacauley/OpenDRAC | Server/Lpcp/src/test/java/com/nortel/appcore/app/drac/server/lpcp/rmi/LpcpRemoteTest.java | Java | gpl-3.0 | 6,819 |
/**
* DiJest is a program Program doing in silico digestion.
Copyright (C) 2014 Clément DELESTRE ([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 diJest;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
/**
* Interface that execute a R script for several files
* @author Clément DELESTRE
* @version 1.0
*/
public interface RloopInterface {
/**
* Set the files
* @param files
*/
public void setFiles(ArrayList<Path> files);
/**
* Launch the script
*/
public void lauchScript();
/**
* Set the script.
* @param R script
*/
public void setScript(Path script);
}
| AgResearch/dijest | src/diJest/RloopInterface.java | Java | gpl-3.0 | 1,261 |
package com.domain.nvm.morningfriend.features.puzzle.equation.data;
public class Equation {
private static final String UNKNOWN_NAME = "x";
private static Variable unknown;
private Expression left, right;
private Environment env;
public static Variable getUnknown() {
if (unknown == null) {
unknown = new Variable(UNKNOWN_NAME);
}
return unknown;
}
public Equation(Expression left, Expression right, int unknownValue) {
this.left = left;
this.right = right;
this.env = new Environment();
this.env.set(getUnknown(), unknownValue);
assert(holdsInvariant());
}
public Equation(Expression left, Expression right, Environment env) {
this.left = left;
this.right = right;
this.env = env;
assert(holdsInvariant());
}
private boolean holdsInvariant() {
try {
return left.eval(env) == right.eval(env);
}
catch (Environment.UndefinedVariableException ex) {
return false;
}
}
public boolean checkSolution(int val) {
try {
return env.get(getUnknown()) == val;
}
catch (Environment.UndefinedVariableException ex) {
throw new IllegalStateException("Unknown is not present in the equation environment");
}
}
@Override
public String toString() {
return left.toString() + " = " + right.toString();
}
}
| nevermourn/MorningFriend | app/src/main/java/com/domain/nvm/morningfriend/features/puzzle/equation/data/Equation.java | Java | gpl-3.0 | 1,491 |
package org.lantern.admin.rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
/**
* <p>
* Big thanks to this project for providing a template on using Jersey with
* AppEngine.
* </p>
*
* <p>
* https://github.com/GoogleCloudPlatform/appengine-angular-guestbook-java
* </p>
*/
public class LanternAdminApplication extends Application {
private Set<Class<?>> resources = new HashSet<Class<?>>();
public LanternAdminApplication() {
resources.add(InvitesResource.class);
resources.add(LatestLanternVersionResource.class);
resources.add(FriendingQuotaResource.class);
// register Jackson ObjectMapper resolver
resources.add(CustomObjectMapperProvider.class);
}
@Override
public Set<Class<?>> getClasses() {
return resources;
}
} | getlantern/lantern-controller | src/main/java/org/lantern/admin/rest/LanternAdminApplication.java | Java | gpl-3.0 | 849 |
package de.rehpoehler.project.controller;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import de.rehpoehler.mvc.AbstractController;
import de.rehpoehler.mvc.AlertMessage;
import de.rehpoehler.project.model.Project;
import de.rehpoehler.project.service.ProjectService;
import de.rehpoehler.user.model.UserAccount;
@Slf4j
@Component
@RequestMapping("/projects")
public class ProjectsController extends AbstractController {
private static final String CREATE_PROJECT_PAGE = "/project/new";
private static final String SHOW_PROJECT_PAGE = "/project/show";
private static final String SHOW_PROJECTS_REDIRECT = "redirect:/projects/";
private static final String USER_PROFILE_REDIRECT = "redirect:/userprofile";
@Autowired
ProjectService projectService;
/**
* Show a project
*
* @param uuid
* the uuid of the project to show
* @param model
* the spring model
*
* @return {@value #SHOW_PROJECT_PAGE}
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String showProject(@PathVariable("id") Long projectId, ModelMap model) {
log.debug("trying to show project with id: {}", projectId);
Project project = projectService.getProject(projectId);
UserAccount user = (UserAccount) model.get(CURRENT_USER);
if (project.isEditable() && !project.isEditable(user)) {
throw new AccessDeniedException("project.accessDenied", null);
}
else {
model.addAttribute("project", project);
}
return SHOW_PROJECT_PAGE;
}
/**
* create a new project.
*
* @param model
* @return {@value #CREATE_PROJECT_PAGE}
*/
@RequestMapping(method = RequestMethod.GET, value = "/create")
public String prepareCreateProject(Model model) {
model.addAttribute("project", new Project());
return CREATE_PROJECT_PAGE;
}
/**
* Valdiate and save the newly created project.
*
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String processCreateProject(@Valid Project project, BindingResult result,
@RequestParam(required = false) MultipartFile projectImage, ModelMap model) {
String fileExtension = validateImageUpload(result, projectImage);
UserAccount user = (UserAccount) model.get(CURRENT_USER);
if (result.hasErrors()) {
return CREATE_PROJECT_PAGE;
}
project.setOwner(user);
projectService.createProject(project, projectImage, fileExtension);
return SHOW_PROJECT_PAGE;
}
/**
* delete the project with the ID.
*
* @param projectId
* @param model
* @param redirectAttributes
* @return {@value #USER_PROFILE_REDIRECT} if successful, {@value #SHOW_PROJECTS_REDIRECT}/{projectId} otherwise
*/
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String deleteProject(@PathVariable("id") Long projectId, ModelMap model, RedirectAttributes redirectAttributes) {
Project project = projectService.getProject(projectId);
UserAccount user = (UserAccount) model.get(CURRENT_USER);
if (project.isDeletable(user)) {
projectService.delete(projectId);
redirectAttributes.addFlashAttribute(ALERT, AlertMessage.success("project.deleted"));
return USER_PROFILE_REDIRECT;
}
else {
throw new AccessDeniedException("project.accessDenied", null);
}
}
/**
* Publishes the project with the given ID and starts the funding phase.
*
* @param projectId
* @param model
* @param redirectAttributes
* @return {@value #SHOW_PROJECTS_REDIRECT}/{projectId}
*/
@RequestMapping(value = "/{id}/publish", method = RequestMethod.GET)
public String publishProject(@PathVariable("id") Long projectId, ModelMap model, RedirectAttributes redirectAttributes) {
Project project = projectService.getProject(projectId);
UserAccount user = (UserAccount) model.get(CURRENT_USER);
if (project.isEditable(user)) {
projectService.publish(projectId);
redirectAttributes.addFlashAttribute(ALERT, AlertMessage.success("project.published"));
}
else {
if (!project.isEditable()) {
redirectAttributes.addFlashAttribute(ALERT, AlertMessage.info("project.alreadyPublished"));
}
else {
throw new AccessDeniedException("project.accessDenied", null);
}
}
return SHOW_PROJECTS_REDIRECT + projectId;
}
}
| jereh16/bankroll | src/main/java/de/rehpoehler/project/controller/ProjectsController.java | Java | gpl-3.0 | 4,934 |
package com.tutorials._gui.address;
import com.tutorials._gui.address.model.Person;
import com.tutorials._gui.address.view.PersonEditDialogController;
import com.tutorials._gui.address.view.PersonOverviewController;
import javafx.application.Application;
/*import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;*/
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Person> personData = FXCollections.
observableArrayList();
public Main() {
personData.add(new Person(new SimpleStringProperty("first name 01"),
new SimpleStringProperty("last name 01")));
personData.add(new Person(new SimpleStringProperty("first name 02"),
new SimpleStringProperty("last name 02")));
personData.add(new Person(new SimpleStringProperty("first name 03"),
new SimpleStringProperty("last name 03")));
personData.add(new Person(new SimpleStringProperty("first name 04"),
new SimpleStringProperty("last name 04")));
personData.add(new Person(new SimpleStringProperty("first name 05"),
new SimpleStringProperty("last name 05")));
personData.add(new Person(new SimpleStringProperty("first name 06"),
new SimpleStringProperty("last name 06")));
personData.add(new Person(new SimpleStringProperty("first name 07"),
new SimpleStringProperty("last name 07")));
personData.add(new Person(new SimpleStringProperty("first name 08"),
new SimpleStringProperty("last name 08")));
}
public ObservableList<Person> getPersonData() {
return personData;
}
@Override
public void start(Stage primaryStage) throws Exception{
this.primaryStage = primaryStage;
//Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
this.primaryStage.setTitle("Address Application");
//primaryStage.setScene(new Scene(root, 300, 275));
//primaryStage.show();
initRootLayout();
showPersonOverview();
}
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void showPersonOverview() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource(
"view/PersonOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
rootLayout.setCenter(personOverview);
PersonOverviewController controller = loader.getController();
controller.setMain(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
/**
* Opens a dialog to edit details for the specified person. If the user
* clicks OK, the changes are saved into the provided person object and true
* is returned.
*
* @param person the person object to be edited
* @return true if the user clicked OK, false otherwise.
*/
public boolean showPersonEditDialog(Person person) {
try {
// Load the fxml file and create a new stage for the popup dialog.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/PersonEditDialog.fxml"));
AnchorPane page = (AnchorPane) loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Edit Person");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the person into the controller.
PersonEditDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
controller.setPerson(person);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
return controller.isOkClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
launch(args);
}
}
| slavidlancer/JavaSEtraining | TrainingFromTutorials/GUI/AddressApplication/src/com/tutorials/_gui/address/Main.java | Java | gpl-3.0 | 5,117 |
package org.nmdp.hmlfhirconverterapi.util;
/**
* Created by Andrew S. Brown, Ph.D., <[email protected]>, on 6/22/17.
* <p>
* service-hml-fhir-converter-api
* Copyright (c) 2012-2017 National Marrow Donor Program (NMDP)
* <p>
* 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 of the License, or (at
* your option) any later version.
* <p>
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
* <p>
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* <p>
* > http://www.fsf.org/licensing/licenses/lgpl.html
* > http://www.opensource.org/licenses/lgpl-license.php
*/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
import org.apache.log4j.Logger;
import org.bson.Document;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
public class Serializer {
private static final Logger LOG = Logger.getLogger(Serializer.class);
public static <T> String toJson(T object) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(object);
}
public static <T> String toJson(T object, String id) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement json = gson.toJsonTree(object);
JsonObject jsonObject = (JsonObject) json;
jsonObject.addProperty("fhirId", id);
return gson.toJson(jsonObject);
}
public static String toXml(Document document) {
try {
StringWriter stringWriter = new StringWriter();
InputStream stream = new ByteArrayInputStream(document.toJson().getBytes());
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).prettyPrint(true).build();
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(stream);
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(stringWriter);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
return stringWriter.getBuffer().toString();
} catch (Exception ex) {
LOG.error(ex);
return null;
}
}
}
| nmdp-bioinformatics/service-hml-fhir-converter-api | src/main/java/org/nmdp/hmlfhirconverterapi/util/Serializer.java | Java | gpl-3.0 | 3,072 |
package dev.aura.bungeechat.api.placeholder;
public interface ReplacementSupplier {
public String get(BungeeChatContext context);
}
| AuraDevelopmentTeam/BungeeChat2 | BungeeChatApi/src/main/java/dev/aura/bungeechat/api/placeholder/ReplacementSupplier.java | Java | gpl-3.0 | 135 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 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.items.potions;
import com.watabou.noosa.Game;
import com.watabou.noosa.audio.Sample;
import com.watabou.pixeldungeon.Assets;
import com.watabou.pixeldungeon.Dungeon;
import com.watabou.pixeldungeon.R;
import com.watabou.pixeldungeon.actors.blobs.Blob;
import com.watabou.pixeldungeon.actors.blobs.ParalyticGas;
import com.watabou.pixeldungeon.actors.blobs.ToxicGas;
import com.watabou.pixeldungeon.actors.buffs.Buff;
import com.watabou.pixeldungeon.actors.buffs.GasesImmunity;
import com.watabou.pixeldungeon.actors.hero.Hero;
import com.watabou.pixeldungeon.effects.CellEmitter;
import com.watabou.pixeldungeon.effects.Speck;
import com.watabou.pixeldungeon.levels.Level;
import com.watabou.pixeldungeon.utils.BArray;
import com.watabou.pixeldungeon.utils.GLog;
import com.watabou.utils.PathFinder;
public class PotionOfPurity extends Potion {
private static final String TXT_FRESHNESS = Game.getVar(R.string.PotionOfPurity_Freshness);
private static final String TXT_NO_SMELL = Game.getVar(R.string.PotionOfPurity_NoSmell);
private static final int DISTANCE = 2;
{
name = Game.getVar(R.string.PotionOfPurity_Name);
}
@Override
public void shatter( int cell ) {
PathFinder.buildDistanceMap( cell, BArray.not( Level.losBlocking, null ), DISTANCE );
boolean procd = false;
Blob[] blobs = {
Dungeon.level.blobs.get( ToxicGas.class ),
Dungeon.level.blobs.get( ParalyticGas.class )
};
for (int j=0; j < blobs.length; j++) {
Blob blob = blobs[j];
if (blob == null) {
continue;
}
for (int i=0; i < Level.LENGTH; i++) {
if (PathFinder.distance[i] < Integer.MAX_VALUE) {
int value = blob.cur[i];
if (value > 0) {
blob.cur[i] = 0;
blob.volume -= value;
procd = true;
if (Dungeon.visible[i]) {
CellEmitter.get( i ).burst( Speck.factory( Speck.DISCOVER ), 1 );
}
}
}
}
}
boolean heroAffected = PathFinder.distance[Dungeon.hero.pos] < Integer.MAX_VALUE;
if (procd) {
if (Dungeon.visible[cell]) {
splash( cell );
Sample.INSTANCE.play( Assets.SND_SHATTER );
}
setKnown();
if (heroAffected) {
GLog.p( TXT_FRESHNESS );
}
} else {
super.shatter( cell );
if (heroAffected) {
GLog.i( TXT_FRESHNESS );
setKnown();
}
}
}
@Override
protected void apply( Hero hero ) {
GLog.w( TXT_NO_SMELL );
Buff.prolong( hero, GasesImmunity.class, GasesImmunity.DURATION );
setKnown();
}
@Override
public String desc() {
return Game.getVar(R.string.PotionOfPurity_Info);
}
@Override
public int price() {
return isKnown() ? 50 * quantity : super.price();
}
}
| rodriformiga/pixel-dungeon | src/com/watabou/pixeldungeon/items/potions/PotionOfPurity.java | Java | gpl-3.0 | 3,435 |
/*
* This file is part of MystudiesMyteaching application.
*
* MystudiesMyteaching application 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.
*
* MystudiesMyteaching application 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 MystudiesMyteaching application. If not, see <http://www.gnu.org/licenses/>.
*/
package fi.helsinki.opintoni.integration.esb;
import java.util.List;
import java.util.Optional;
public interface ESBClient {
List<ESBEmployeeInfo> getEmployeeInfo(String employeeNumber);
Optional<OptimeStaffInformation> getStaffInformation(String staffId);
}
| UH-StudentServices/mystudies-myteaching-backend | src/main/java/fi/helsinki/opintoni/integration/esb/ESBClient.java | Java | gpl-3.0 | 1,041 |
//ShowTree Tree Visualization System
//Copyright (C) 2009 Yuvi Masory
//
//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, version 3 only.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
package display.actions;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import componentImage.SaveComponentImage;
import display.components.TreeFrame;
/*
* Allows user to choose location to save a screenshot of the program.
* At this point does NOT capture title bar, and the color of JLabeledTextFields seems lighter.
*/
public class CaptureScreenshotAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private static Preferences prefs;
public CaptureScreenshotAction(String str, String toolTip, Icon icon) {
super(str, icon);
prefs = Preferences.userNodeForPackage(CaptureScreenshotAction.class);
putValue(SHORT_DESCRIPTION, toolTip);
}
public void actionPerformed(ActionEvent arg0) {
String currentPath = null;
try {
currentPath = new File(".").getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
}
String maybeLastPath = prefs.get("LAST_CS_DIR", currentPath);
if(new File(maybeLastPath).exists() == false) {
maybeLastPath = currentPath;
}
String chosenPath = new SaveComponentImage().exportComponentImage(TreeFrame.getInstance(),
new Rectangle(0, 0, (int) TreeFrame.getInstance().getBounds().getWidth(), (int) TreeFrame.getInstance().getBounds().getHeight()),
"Save Screenshot",
"screenshot-1",
maybeLastPath,
TreeFrame.getInstance());
if(chosenPath != null) {
prefs.put("LAST_CS_DIR", new File(chosenPath).getParentFile().getPath());
}
}
}
| ymasory/ShowTree | src/display/actions/CaptureScreenshotAction.java | Java | gpl-3.0 | 2,352 |
package cs307.butterfly;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}
| Hamza141/Butterfly | Client/app/src/main/java/cs307/butterfly/HomeActivity.java | Java | gpl-3.0 | 841 |
package com.perblo.payment.constants;
public class TransactionStatus {
public static final int SUCCESSFUL = 0;
public static final int INITIALIZED = 1;
public static final int FAILED = 2;
}
| csokafor/hostelapplication | src/main/java/com/perblo/payment/constants/TransactionStatus.java | Java | gpl-3.0 | 215 |
package is.idega.idegaweb.golf.entity;
public class AddressHomeImpl extends com.idega.data.IDOFactory implements AddressHome
{
protected Class getEntityInterfaceClass(){
return Address.class;
}
public Address create() throws javax.ejb.CreateException{
return (Address) super.idoCreate();
}
public Address createLegacy(){
try{
return create();
}
catch(javax.ejb.CreateException ce){
throw new RuntimeException("CreateException:"+ce.getMessage());
}
}
public Address findByPrimaryKey(int id) throws javax.ejb.FinderException{
return (Address) super.idoFindByPrimaryKey(id);
}
public Address findByPrimaryKey(Object pk) throws javax.ejb.FinderException{
return (Address) super.idoFindByPrimaryKey(pk);
}
public Address findByPrimaryKeyLegacy(int id) throws java.sql.SQLException{
try{
return findByPrimaryKey(id);
}
catch(javax.ejb.FinderException fe){
throw new java.sql.SQLException(fe.getMessage());
}
}
} | idega/platform2 | src/is/idega/idegaweb/golf/entity/AddressHomeImpl.java | Java | gpl-3.0 | 952 |
package com.relicum.scb.listeners;
import com.relicum.scb.SCB;
import com.relicum.scb.types.SkyApi;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
/**
* SuperSkyBros
*
* @author Relicum
* @version 0.1
*/
public class PlayerLoginNoPerm implements Listener {
public SCB plugin;
public PlayerLoginNoPerm(JavaPlugin p) {
this.plugin = (SCB) p;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void preLogin(PlayerLoginEvent e) {
if (plugin.getConfig().getBoolean("autoJoinLobby")) {
if (!e.getPlayer().hasPermission("ssb.player.join")) {
e.disallow(PlayerLoginEvent.Result.KICK_OTHER, SkyApi.getMessageManager().getRawMessage("system.kickJoinNoPerm"));
}
}
}
}
| Relicum/SuperSkyBros | src/main/java/com/relicum/scb/listeners/PlayerLoginNoPerm.java | Java | gpl-3.0 | 920 |
package io.kodokojo.commons.service.repository.search;
import io.kodokojo.commons.model.ProjectConfiguration;
import io.kodokojo.commons.service.elasticsearch.DataIdProvider;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
public class SoftwareFactorySearchDto implements DataIdProvider {
private static final String SOFTWAREFACTORY = "softwarefactory";
private String identifier;
private String name;
public SoftwareFactorySearchDto() {
super();
}
public static SoftwareFactorySearchDto convert(ProjectConfiguration projectConfiguration) {
requireNonNull(projectConfiguration, "projectConfiguration must be defined.");
return converter().apply(projectConfiguration);
}
public static Function<ProjectConfiguration, SoftwareFactorySearchDto> converter() {
return projectConfiguration -> {
SoftwareFactorySearchDto res = new SoftwareFactorySearchDto();
res.setIdentifier(projectConfiguration.getIdentifier());
res.setName(projectConfiguration.getName());
return res;
};
}
@Override
public String getId() {
return identifier;
}
@Override
public String getType() {
return SOFTWAREFACTORY;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| jpthiery/kodokojo | src/main/java/io/kodokojo/commons/service/repository/search/SoftwareFactorySearchDto.java | Java | gpl-3.0 | 1,599 |
package com.example.geniuschimp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class TitleActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SoundPool soundPool;
private int startSndId;
private float soundVolume=0.f;
private SharedPreferences shrP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title);
shrP=getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
shrP.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(shrP,"");
soundPool=new SoundPool(3, android.media.AudioManager.STREAM_MUSIC, 0);
startSndId=soundPool.load(this,R.raw.start,1);
TextView versionLabel=(TextView) findViewById(R.id.version_label);
String versionName;
try {
versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "0";
}
versionLabel.setText(versionName);
}
@Override
public void onDestroy() {
soundPool.release();
soundPool=null;
super.onDestroy();
}
private void playSFX(int SFXid) {
soundPool.play(SFXid, soundVolume, soundVolume, 1, 0, 1.f);
}
public boolean StartButtonClicked(View v) {
playSFX(startSndId);
Intent intent=new Intent(this,ChimpActivity.class);
startActivity(intent);
return true;
}
public boolean HighscoreButtonClicked(View v) {
playSFX(startSndId);
Intent intent=new Intent(this,HighscoreActivity.class);
startActivity(intent);
return true;
}
public boolean ConfigButtonClicked(View v) {
playSFX(startSndId);
Intent intent=new Intent(this,ConfigActivity.class);
startActivity(intent);
return true;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences shrP, String arg) {
boolean soundEnabled=shrP.getBoolean(ConfigActivity.PrefsKeySound, ConfigActivity.defSound);
soundVolume=soundEnabled?1.f:0.f;
}
}
| tomari/GeniusChimp | app/src/main/java/com/example/geniuschimp/TitleActivity.java | Java | gpl-3.0 | 2,240 |
/**
*
*/
package com.xinxilanr.venus.common;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* @author norris
*
*/
public class FileUtil {
public static void writeToFile(String filePath, byte[] fileContent) throws IOException {
Files.write(Paths.get(filePath), fileContent, StandardOpenOption.CREATE);
}
public static String getExtensionFromFileName(String filename) {
int position = filename.lastIndexOf(".");
if (position < 0) {
return null;
}
return filename.substring(position + 1);
}
}
| norris-zhang/venus | parent/common/src/main/java/com/xinxilanr/venus/common/FileUtil.java | Java | gpl-3.0 | 598 |
package com.asalfo.wiulgi.data.model;
import android.support.annotation.NonNull;
/**
* Created by asalfo on 23/06/16.
*/
public class ApiError {
private int statusCode;
private String detail;
private String message = "";
private String type;
private String title;
public ApiError() {
}
public int status() {
return statusCode;
}
public String message() {
return message;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@NonNull
@Override
public String toString() {
return "ApiError{" +
"statusCode=" + statusCode +
", detail='" + detail + '\'' +
", message='" + message + '\'' +
", type='" + type + '\'' +
", title='" + title + '\'' +
'}';
}
}
| asalfo/Capstone-Project | app/src/main/java/com/asalfo/wiulgi/data/model/ApiError.java | Java | gpl-3.0 | 1,507 |
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Layout.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.database.constraint;
import com.sun.electric.database.CellBackup;
import com.sun.electric.database.IdMapper;
import com.sun.electric.database.ImmutableArcInst;
import com.sun.electric.database.ImmutableCell;
import com.sun.electric.database.ImmutableExport;
import com.sun.electric.database.ImmutableLibrary;
import com.sun.electric.database.ImmutableNodeInst;
import com.sun.electric.database.Snapshot;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.EDatabase;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.id.CellId;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitivePort;
import com.sun.electric.technology.Technology;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Class to implement the layout-constraint system.
* Handles the fixed-angle and rigid constraints.
* Also propagates these constraints up the hierarchy.
*/
public class Layout extends Constraints {
// private static final Layout layoutConstraint = new Layout();
static final boolean DEBUG = false;
private static boolean doChangesQuietly;
private static Snapshot oldSnapshot;
private static long revisionDate;
private static String userName;
private static Set<Cell> goodSpacingDRCCells, goodAreaDRCCells;
private static Variable goodSpacingDRCDate, goodSpacingDRCBit, goodAreaDRCDate;
/** Shadow Cell info */
private static final ArrayList<LayoutCell> cellInfos = new ArrayList<LayoutCell>();
/** Map which contains temporary rigidity of ArcInsts. */
private static final HashMap<ArcInst, Boolean> tempRigid = new HashMap<ArcInst, Boolean>();
/** key of Variable for last valid DRC date on a Cell. Only spacing rules */
public static final Variable.Key DRC_LAST_GOOD_DATE_SPACING = Variable.newKey("DRC_last_good_drc_date");
/** key of Variable for last valid DRC bit on a Cell. Only spacing rules */
public static final Variable.Key DRC_LAST_GOOD_BIT_SPACING = Variable.newKey("DRC_last_good_drc_bit");
/** Default valud when no bit is found **/
public static final int DRC_LAST_GOOD_BIT_DEFAULT = -1;
/** No need of bit for area since it is only 1 mode */
public static final Variable.Key DRC_LAST_GOOD_DATE_AREA = Variable.newKey("DRC_last_good_drc_area_date");
Layout() {
}
// /**
// * Method to return the current constraint solver.
// * @return the current constraint solver.
// */
// public static Layout getConstraint() { return layoutConstraint; }
/**
* Method to set the subsequent changes to be "quiet".
* Quiet changes are not passed to constraint satisfaction, not recorded for Undo and are not broadcast.
* This method is used to suppress endBatch.
*/
public static void changesQuiet(boolean quiet) {
doChangesQuietly = true;
}
/**
* Method to start a batch of changes.
* @param initialSnapshot snapshot before job changes.
*/
@Override
public void startBatch(Snapshot initialSnapshot) {
// force every cell to remember its current bounds
doChangesQuietly = false;
oldSnapshot = initialSnapshot;
tempRigid.clear();
goodSpacingDRCCells = null;
goodAreaDRCCells = null;
makeLayoutCells();
}
/**
* Method to do hierarchical update on any cells that changed
*/
@Override
public void endBatch(String userName) {
if (DEBUG) {
System.out.println("Temporary rigid:");
for (Map.Entry<ArcInst, Boolean> e : tempRigid.entrySet()) {
System.out.println("\t" + e.getKey() + " --> " + e.getValue());
}
}
Layout.userName = userName;
revisionDate = System.currentTimeMillis();
if (goodSpacingDRCCells != null) {
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodSpacingDRCDate = Variable.newInstance(DRC_LAST_GOOD_DATE_SPACING, new Long(revisionDate + 1), td); // If cell is changed during this 1 millisecond ???
}
if (goodAreaDRCCells != null) {
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodAreaDRCDate = Variable.newInstance(DRC_LAST_GOOD_DATE_AREA, new Long(revisionDate + 1), td); // If cell is changed during this 1 millisecond ???
}
if (!doChangesQuietly) {
// Propagate changes and mark changed cells.
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
assert cell.isLinked();
LayoutCell cellInfo = getCellInfo(cell);
cellInfo.compute();
}
}
}
cellInfos.clear();
tempRigid.clear();
// Set revision dates to modified Cells, update DRC date, update bounds
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
cell.lowLevelMadeRevision(revisionDate, userName, oldSnapshot.getCellRevision(cell.getId()));
if (goodSpacingDRCCells != null && goodSpacingDRCCells.contains(cell)) {
cell.addVar(goodSpacingDRCDate);
cell.addVar(goodSpacingDRCBit);
}
if (goodAreaDRCCells != null && goodAreaDRCCells.contains(cell)) {
cell.addVar(goodAreaDRCDate);
}
}
}
EDatabase.serverDatabase().backup();
goodSpacingDRCCells = null;
goodAreaDRCCells = null;
oldSnapshot = null;
}
/**
* Method to handle a change to a NodeInst.
* @param ni the NodeInst that was changed.
* @param oD the old contents of the NodeInst.
*/
@Override
public void modifyNodeInst(NodeInst ni, ImmutableNodeInst oD) {
if (doChangesQuietly) {
return;
}
getCellInfo(ni.getParent()).modifyNodeInst(ni, oD);
}
/**
* Method to handle a change to an ArcInst.
* @param ai the ArcInst that changed.
* @param oD the old contents of the ArcInst.
*/
@Override
public void modifyArcInst(ArcInst ai, ImmutableArcInst oD) {
if (doChangesQuietly) {
return;
}
getCellInfo(ai.getParent()).modifyArcInst(ai, oD);
}
/**
* Method to handle a change to an Export.
* @param pp the Export that moved.
* @param oldD the old contents of the Export.
*/
@Override
public void modifyExport(Export pp, ImmutableExport oldD) {
if (doChangesQuietly) {
return;
}
PortInst oldPi = pp.getParent().getPortInst(oldD.originalNodeId, oldD.originalPortId);
if (oldPi == pp.getOriginalPort()) {
return;
}
getCellInfo(pp.getParent()).modifyExport(pp, oldPi);
}
/**
* Method to handle a change to a Cell.
* @param cell the Cell that was changed.
* @param oD the old contents of the Cell.
*/
@Override
public void modifyCell(Cell cell, ImmutableCell oD) {
}
/**
* Method to handle a change to a Library.
* @param lib the Library that was changed.
* @param oldD the old contents of the Library.
*/
@Override
public void modifyLibrary(Library lib, ImmutableLibrary oldD) {
}
/**
* Method to handle the creation of a new ElectricObject.
* @param obj the ElectricObject that was just created.
*/
@Override
public void newObject(ElectricObject obj) {
if (doChangesQuietly) {
return;
}
Cell cell = obj.whichCell();
if (obj == cell) {
newCellInfo(cell, null);
} else if (cell != null) {
getCellInfo(cell).newObject(obj);
}
}
/**
* Method to announce than Ids were renamed.
* @param idMapper mapper from old Ids to new Ids.
*/
@Override
public void renameIds(IdMapper idMapper) {
EDatabase database = EDatabase.serverDatabase();
for (CellId cellId : idMapper.getNewCellIds()) {
newObject(cellId.inDatabase(database));
}
// for (ExportId exportId: idMapper.getNewExportIds())
// newObject(exportId.inDatabase(database));
}
/**
* Method to set temporary rigidity on an ArcInst.
* @param ai the ArcInst to make temporarily rigid/not-rigid.
* @param tempRigid true to make the ArcInst temporarily rigid;
* false to make it temporarily not-rigid.
*/
public static void setTempRigid(ArcInst ai, boolean tempRigid) {
if (DEBUG) {
System.out.println("setTempRigid " + ai + " " + tempRigid);
}
ai.checkChanging();
Layout.tempRigid.put(ai, Boolean.valueOf(tempRigid));
// if (tempRigid)
// {
// if (ai.getChangeClock() == changeClock + 2) return;
// ai.setChangeClock(changeClock + 2);
// } else
// {
// if (ai.getChangeClock() == changeClock + 3) return;
// ai.setChangeClock(changeClock + 3);
// }
}
/**
* Method to remove temporary rigidity on an ArcInst.
* @param ai the ArcInst to remove temporarily rigidity.
*/
public static void removeTempRigid(ArcInst ai) {
ai.checkChanging();
tempRigid.remove(ai);
// if (ai.getChangeClock() != changeClock + 3 && ai.getChangeClock() != changeClock + 2) return;
// ai.setChangeClock(changeClock - 3);
}
/*
* Method to request to set
*/
public static void setGoodDRCCells(Set<Cell> goodDRCCells, Variable.Key key, int activeBits, boolean inMemory) {
assert (!inMemory); // call only if you are storing in disk
if (key == DRC_LAST_GOOD_DATE_SPACING) {
Layout.goodSpacingDRCCells = goodDRCCells;
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withDisplay(false);
goodSpacingDRCBit = Variable.newInstance(DRC_LAST_GOOD_BIT_SPACING, new Integer(activeBits), td);
} else // min area
{
Layout.goodAreaDRCCells = goodDRCCells;
}
}
/**
** Returns rigidity of an ArcInst considering temporary rigidity.
* @param ai ArcInst to test rigidity.
* @return true if the ArcInst is considered rigid in this batch.
*/
static boolean isRigid(ArcInst ai) {
Boolean override = tempRigid.get(ai);
return override != null ? override.booleanValue() : ai.isRigid();
}
private static void makeLayoutCells() {
cellInfos.clear();
for (Iterator<Library> it = Library.getLibraries(); it.hasNext();) {
Library lib = it.next();
for (Iterator<Cell> cIt = lib.getCells(); cIt.hasNext();) {
Cell cell = cIt.next();
newCellInfo(cell, oldSnapshot.getCell(cell.getId()));
}
}
}
/******************** NODE MODIFICATION CODE *************************/
/**
* Method to compute the position of portinst "pi" and
* place the center of the area in the parameters "x" and "y". The position
* is the "old" position, as determined by any changes that may have occured
* to the nodeinst (and any sub-nodes).
*/
static Poly oldPortPosition(PortInst pi) {
NodeInst ni = pi.getNodeInst();
PortProto pp = pi.getPortProto();
// descend to the primitive node
AffineTransform subrot = makeOldRot(ni);
if (subrot == null) {
return null;
}
NodeInst bottomNi = ni;
PortProto bottomPP = pp;
while (bottomNi.isCellInstance()) {
AffineTransform localtran = makeOldTrans(bottomNi);
subrot.concatenate(localtran);
PortInst bottomPi = getOldOriginalPort((Export) bottomPP);
bottomNi = bottomPi.getNodeInst();
bottomPP = bottomPi.getPortProto();
localtran = makeOldRot(bottomNi);
subrot.concatenate(localtran);
}
// if the node hasn't changed, use its current values
ImmutableNodeInst d = Layout.getOldD(bottomNi);
assert d != null;
if (d != bottomNi.getD()) {
// create a fake node with these values
bottomNi = NodeInst.makeDummyInstance(bottomNi.getProto());
bottomNi.lowLevelModify(d);
}
PrimitiveNode np = (PrimitiveNode) bottomNi.getProto();
Technology tech = np.getTechnology();
Poly poly = tech.getShapeOfPort(bottomNi, (PrimitivePort) bottomPP);
poly.transform(subrot);
return (poly);
}
private static AffineTransform makeOldRot(NodeInst ni) {
// if the node has not been modified, just use the current transformation
ImmutableNodeInst d = getOldD(ni);
if (d == null) {
return null;
}
// get the old values
double cX = d.anchor.getX();
double cY = d.anchor.getY();
return d.orient.rotateAbout(cX, cY);
}
private static AffineTransform makeOldTrans(NodeInst ni) {
ImmutableNodeInst d = getOldD(ni);
if (d == null) {
return null;
}
// create the former translation matrix
AffineTransform transform = new AffineTransform();
double cX = d.anchor.getX();
double cY = d.anchor.getY();
transform.translate(cX, cY);
return transform;
}
static PortInst getOldOriginalPort(Export e) {
return getCellInfo(e.getParent()).getOldOriginalPort(e);
}
static ImmutableNodeInst getOldD(NodeInst ni) {
return getCellInfo(ni.getParent()).getOldD(ni);
}
private static void newCellInfo(Cell cell, CellBackup oldBackup) {
int cellIndex = cell.getCellIndex();
while (cellInfos.size() <= cellIndex) {
cellInfos.add(null);
}
// assert cellInfos.get(cellIndex) == null;
cellInfos.set(cellIndex, new LayoutCell(cell, oldBackup));
}
static LayoutCell getCellInfo(Cell cell) {
return cellInfos.get(cell.getCellIndex());
}
}
| imr/Electric8 | com/sun/electric/database/constraint/Layout.java | Java | gpl-3.0 | 15,956 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.29 at 05:11:02 PM WET
//
package com.trackit.presentation.view.map.provider.here.routes.routingcalculatematrix;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Shape represented using Well-known text (WKT) as markup language.
*
* <p>Java class for WKTShapeType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="WKTShapeType">
* <complexContent>
* <extension base="{http://www.navteq.com/lbsp/Common/4}GeoShapeType">
* <sequence>
* <element name="Value" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "WKTShapeType", namespace = "http://www.navteq.com/lbsp/Common/4", propOrder = {
"value"
})
public class WKTShapeType
extends GeoShapeType
{
@XmlElement(name = "Value", required = true)
protected String value;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
| Spaner/TrackIt | src/main/java/com/trackit/presentation/view/map/provider/here/routes/routingcalculatematrix/WKTShapeType.java | Java | gpl-3.0 | 1,949 |
/*
* Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0.
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 HOLDER 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.icgc.dcc.etl.core.util;
import static com.google.common.base.Preconditions.checkState;
import static lombok.AccessLevel.PRIVATE;
import static org.icgc.dcc.etl.core.model.Component.CONCATENATOR;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.icgc.dcc.common.core.model.FileTypes.FileType;
import org.icgc.dcc.common.core.util.Joiners;
import org.icgc.dcc.etl.core.model.Component;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
@NoArgsConstructor(access = PRIVATE)
public final class EtlConventions {
public static final Joiner JOB_ID_JOINER = Joiners.DASH;
public static final Iterable<Entry<FileType, Component>> GENERATED_FILE_TYPE_TO_COMPONENT = ImmutableList.of(
getEntry(FileType.SSM_P_TYPE, Component.NORMALIZER),
getEntry(FileType.SGV_P_TYPE, Component.NORMALIZER),
getEntry(FileType.SSM_S_TYPE, Component.ANNOTATOR),
getEntry(FileType.SGV_S_TYPE, Component.ANNOTATOR));
public static String getConcatenatorProjectInputDir(
@NonNull final String workingDir,
@NonNull final String projectKey) {
return CONCATENATOR.getProjectDir(workingDir, projectKey);
}
public static String getInputGeneratingComponentProjectInputDir(
@NonNull final Component inputGeneratingComponent,
@NonNull final String workingDir,
@NonNull final String projectKey) {
checkState(inputGeneratingComponent.isEtlInputGenerating());
return inputGeneratingComponent.getProjectDir(workingDir, projectKey);
}
public static String getLoaderOutputDir(@NonNull final String workingDir) {
return Component.LOADER.getComponentDir(workingDir);
}
public static String getIndexerOutputDir(@NonNull final String workingDir) {
return Component.INDEXER.getComponentDir(workingDir);
}
private static Entry<FileType, Component> getEntry(FileType fileType, Component component) {
return new SimpleEntry<FileType, Component>(fileType, component);
}
}
| icgc-dcc/dcc-etl | dcc-etl-core/src/main/java/org/icgc/dcc/etl/core/util/EtlConventions.java | Java | gpl-3.0 | 3,737 |
/*
* Copyright (c) 2016-2017 Projekt Substratum
* This file is part of Substratum.
*
* Substratum 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.
*
* Substratum 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 Substratum. If not, see <http://www.gnu.org/licenses/>.
*/
package projekt.substratum.common.systems;
public class ProfileItem {
private String packageName;
private String targetPackage;
private String parentTheme;
private String type1a;
private String type1b;
private String type1c;
private String type2;
private String type3;
ProfileItem(String packageName) {
this.packageName = packageName;
}
public String getPackageName() {
return packageName;
}
public String getTargetPackage() {
return targetPackage;
}
public void setTargetPackage(String targetPackage) {
this.targetPackage = targetPackage;
}
public String getParentTheme() {
return parentTheme;
}
void setParentTheme(String parentTheme) {
this.parentTheme = parentTheme;
}
public String getType1a() {
return type1a;
}
public void setType1a(String type1a) {
this.type1a = type1a;
}
public String getType1b() {
return type1b;
}
public void setType1b(String type1b) {
this.type1b = type1b;
}
public String getType1c() {
return type1c;
}
public void setType1c(String type1c) {
this.type1c = type1c;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public String getType3() {
return type3;
}
public void setType3(String type3) {
this.type3 = type3;
}
} | divergeTeam/diverge | app/src/main/java/projekt/substratum/common/systems/ProfileItem.java | Java | gpl-3.0 | 2,240 |
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyRenameCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 2) {
if (UserManager.getPlayer((Player) sender) == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
Party playerParty = mcMMOPlayer.getParty();
String oldPartyName = playerParty.getName();
String newPartyName = args[1];
// This is to prevent party leaders from spamming other players with the rename message
if (oldPartyName.equalsIgnoreCase(newPartyName)) {
sender.sendMessage(LocaleLoader.getString("Party.Rename.Same"));
return true;
}
Player player = mcMMOPlayer.getPlayer();
// Check to see if the party exists, and if it does cancel renaming the party
if (PartyManager.checkPartyExistence(player, newPartyName)) {
return true;
}
String leaderName = playerParty.getLeader().getPlayerName();
for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, oldPartyName, newPartyName, EventReason.CHANGED_PARTIES)) {
return true;
}
if (!member.getName().equalsIgnoreCase(leaderName)) {
member.sendMessage(LocaleLoader.getString("Party.InformedOnNameChange", leaderName, newPartyName));
}
}
playerParty.setName(newPartyName);
sender.sendMessage(LocaleLoader.getString("Commands.Party.Rename", newPartyName));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "rename", "<" + LocaleLoader.getString("Commands.Usage.PartyName") + ">"));
return true;
}
}
| mcMMO-Dev/mcMMO | src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java | Java | gpl-3.0 | 2,670 |
package org.modules.utils;
import org.sdk.EBISystem;
import org.sdk.interfaces.IEBIGUIRenderer;
import org.sdk.utils.EBIAbstractTableModel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class HeaderSelector extends MouseAdapter {
private final JXTable table;
public HeaderEditor editor;
private IEBIGUIRenderer guiRenderer = null;
public HeaderSelector(final JXTable t) {
table = t;
editor = new HeaderEditor(this);
guiRenderer = EBISystem.gui();
}
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
final JXTableHeader th = (JXTableHeader) e.getSource();
final Point p = e.getPoint();
final int col = getColumn(th, p);
final TableColumn column = th.getColumnModel().getColumn(col);
final String oldValue = (String) column.getHeaderValue();
final Object value = editor.showEditor(th, col, oldValue);
((EBIAbstractTableModel) table.getModel()).columnNames[col] = value.toString();
guiRenderer.combo("keyText", "csvSetImportDialog").removeAllItems();
guiRenderer.combo("keyText", "csvSetImportDialog").addItem(EBISystem.i18n("EBI_LANG_PLEASE_SELECT"));
for (int i = 0; i < ((EBIAbstractTableModel) table.getModel()).columnNames.length; i++) {
if (i <= ((EBIAbstractTableModel) table.getModel()).columnNames.length) {
guiRenderer.combo("keyText", "csvSetImportDialog").addItem(((EBIAbstractTableModel) table.getModel()).columnNames[i]);
}
}
if (!"".equals(value)) {
column.setHeaderValue(value);
}
th.resizeAndRepaint();
}
}
private int getColumn(final JXTableHeader th, final Point p) {
final TableColumnModel model = th.getColumnModel();
int ret = -1;
for (int col = 0; col < model.getColumnCount(); col++) {
if (th.getHeaderRect(col).contains(p)) {
ret = col;
break;
}
}
return ret;
}
}
| EBINEUTRINO/EBINeutrino | src/org/modules/utils/HeaderSelector.java | Java | gpl-3.0 | 2,367 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ar.com.zir.osiris.web.app.personas.security;
import ar.com.zir.osiris.api.security.*;
import ar.com.zir.osiris.ejb.services.SeguridadService;
import ar.com.zir.osiris.web.app.AbmBean;
import java.util.Collection;
import javax.inject.Inject;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
/**
*
* @author jmrunge
*/
public abstract class SecurityObjectBean extends AbmBean {
private TreeNode rootOptions = new DefaultTreeNode("root", null);
@Inject
private SeguridadService seguridadService;
@Override
public String newObject() throws DuplicatedSessionException {
String url = super.newObject();
_initObject();
fillRootOptions();
return url;
}
@Override
public void selectObject(NodeSelectEvent evt) throws DuplicatedSessionException {
super.selectObject(evt);
_initObject();
fillRootOptions();
}
protected void fillRootOptions() throws DuplicatedSessionException {
rootOptions = new DefaultTreeNode("root", null);
for (SystemOption so : seguridadService.getParentSystemOptions(getSystemUser())) {
addSubOption(rootOptions, so);
}
}
private void addSubOption(TreeNode parent, SystemOption option) {
SystemOptionDAO dao = new SystemOptionDAO();
dao.setInherited(null);
dao.setName(option.getTitulo());
DefaultTreeNode node = new DefaultTreeNode(dao, parent);
if (option.getChildren() == null || option.getChildren().isEmpty()) {
addSystemOptionSecurityValues(node, option);
} else {
for (SystemOption so : option.getChildren()) {
addSubOption(node, so);
}
}
}
private void addSystemOptionSecurityValues(TreeNode parent, SystemOption option) {
if (option.getSystemOptionSecurityOptionCollection() != null && !option.getSystemOptionSecurityOptionCollection().isEmpty()) {
for (SystemOptionSecurityOption soso : option.getSystemOptionSecurityOptionCollection()) {
SecurityObject so = (SecurityObject) getObject();
boolean existe = false;
for (SystemOptionSecurityValue sosv : so.getSystemOptionSecurityValues(option.getCodigo())) {
if (sosv.getSystemOptionSecurityOption().equals(soso)) {
existe = true;
addSystemOptionSecurityValueNode(sosv, parent);
break;
}
}
if (!existe) {
SystemOptionSecurityValue sosv = new SystemOptionSecurityValue();
sosv.setCanDoIt(false);
sosv.setInheritedFrom(null);
sosv.setSecurityObject(so);
sosv.setSystemOptionSecurityOption(soso);
so.addSystemOptionSecurityValue(sosv);
addSystemOptionSecurityValueNode(sosv, parent);
}
}
}
}
private void addSystemOptionSecurityValueNode(SystemOptionSecurityValue sosv, TreeNode parent) {
SystemOptionDAO dao = new SystemOptionDAO();
dao.setInherited(sosv.getInheritedFromString());
dao.setName(sosv.getSystemOptionSecurityOption().getSystemOptionSecurity().getOptionTitle());
dao.setOption(sosv);
new DefaultTreeNode(dao, parent);
}
protected abstract void _initObject() throws DuplicatedSessionException;
@Override
protected Object createObject(Object object) throws Exception {
return _createObject((SecurityObject)object);
}
protected abstract SecurityObject _createObject(SecurityObject object) throws Exception;
@Override
protected Object updateObject(Object object) throws Exception {
return _updateObject((SecurityObject)object);
}
protected abstract SecurityObject _updateObject(SecurityObject object) throws Exception;
public TreeNode getSystemOptionNode() {
return rootOptions;
}
}
| jmrunge/osiris-platform | osiris-web-lib/src/ar/com/zir/osiris/web/app/personas/security/SecurityObjectBean.java | Java | gpl-3.0 | 4,258 |
package tv.mineinthebox.simpleserver.events;
import java.io.File;
import java.net.InetAddress;
import java.util.Map;
import tv.mineinthebox.simpleserver.Content;
import tv.mineinthebox.simpleserver.HttpClient;
import tv.mineinthebox.simpleserver.MimeType;
import tv.mineinthebox.simpleserver.Server;
import tv.mineinthebox.simpleserver.Tag;
public interface SimpleEvent {
public boolean isGetRequest();
public boolean isPostRequest();
public Server getServer();
public String getUri();
public void addContent(byte[] bytes);
public void addContent(Content content);
public void setContent(File f);
public void setContent(byte[] bytes);
public void setContent(Content content);
public boolean hasContents();
public byte[] getContents();
public boolean isCancelled();
public void setCancelled(boolean bol);
public MimeType getMimeType();
public void setMimeType(MimeType type);
public boolean hasFormData();
public Map<String, String> getFormData();
public HttpClient getClientHeaderData();
public boolean hasTags();
public Tag[] getAvailableTags();
public boolean isMimeText();
public InetAddress getInetAddress();
}
| xEssentials/xEssentials | src/tv/mineinthebox/simpleserver/events/SimpleEvent.java | Java | gpl-3.0 | 1,185 |
package nl.juraji.biliomi.components.integrations.spotify.api.v1.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by Juraji on 1-10-2017.
* Biliomi
*/
@XmlRootElement(name = "SpotifySnapshot")
@XmlAccessorType(XmlAccessType.FIELD)
public class SpotifySnapshot {
@XmlElement(name = "snapshot_id")
private String snapshotId;
public String getSnapshotId() {
return snapshotId;
}
public void setSnapshotId(String snapshotId) {
this.snapshotId = snapshotId;
}
}
| Juraji/Biliomi | packages/integrations/spotify/src/main/java/nl/juraji/biliomi/components/integrations/spotify/api/v1/model/SpotifySnapshot.java | Java | gpl-3.0 | 668 |
package ihl.processing.chemistry;
import java.util.ArrayList;
import java.util.List;
import ic2.api.network.INetworkDataProvider;
import ic2.api.tile.IWrenchable;
import ic2.core.IC2;
import ihl.utils.IHLUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
public class RefluxCondenserTileEntity extends TileEntity implements IWrenchable, INetworkDataProvider, IFluidHandler{
private short facing=2;
private short lastFacing=2;
public FractionatorBottomTileEntity columnBottom;
public RefluxCondenserTileEntity()
{
super();
}
public boolean enableUpdateEntity()
{
return IC2.platform.isSimulating();
}
@Override
public List<String> getNetworkedFields()
{
List<String> fields = new ArrayList<String>();
fields.add("facing");
return fields;
}
@Override
public void updateEntity()
{
super.updateEntity();
if(lastFacing!=facing)
{
IC2.network.get().updateTileEntityField(this, "facing");
lastFacing=facing;
}
}
@Override
public boolean wrenchCanSetFacing(EntityPlayer entityPlayer, int side) {
return this.getFacing()!=side;
}
@Override
public short getFacing() {
return this.facing;
}
@Override
public void setFacing(short facing1)
{
facing=(short) Math.max(2,facing1);
if(IC2.platform.isSimulating())
{
IC2.network.get().updateTileEntityField(this, "facing");
}
}
@Override
public boolean wrenchCanRemove(EntityPlayer entityPlayer) {
return true;
}
@Override
public float getWrenchDropRate() {
return 1F;
}
@Override
public ItemStack getWrenchDrop(EntityPlayer entityPlayer) {
return IHLUtils.getThisModItemStack("refluxCondenser");
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
super.readFromNBT(nbttagcompound);
facing=nbttagcompound.getShort("facing");
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
super.writeToNBT(nbttagcompound);
nbttagcompound.setShort("facing", facing);
}
@Override
public boolean canDrain(ForgeDirection arg0, Fluid arg1) {
return false;
}
@Override
public boolean canFill(ForgeDirection direction, Fluid arg1) {
return direction.equals(ForgeDirection.UP);
}
@Override
public FluidStack drain(ForgeDirection arg0, FluidStack arg1, boolean arg2) {
return null;
}
@Override
public FluidStack drain(ForgeDirection arg0, int arg1, boolean arg2) {
return null;
}
@Override
public int fill(ForgeDirection direction, FluidStack fluidStack, boolean doFill) {
if(fluidStack!=null && fluidStack.getFluid()!=null && this.canFill(direction, fluidStack.getFluid()) && columnBottom!=null)
{
return columnBottom.fill(direction, fluidStack, doFill);
}
return 0;
}
@Override
public FluidTankInfo[] getTankInfo(ForgeDirection arg0)
{
if(columnBottom!=null)
return columnBottom.getTankInfo(arg0);
else
return new FluidTankInfo[] {new FluidTankInfo(null, 8000)};
}
}
| Foghrye4/ihl | src/main/java/ihl/processing/chemistry/RefluxCondenserTileEntity.java | Java | gpl-3.0 | 3,502 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2016, SCISYS UK Limited
*
* 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.sldeditor.test.unit.datasource.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.sldeditor.common.DataSourcePropertiesInterface;
import com.sldeditor.datasource.DataSourceInterface;
import com.sldeditor.datasource.DataSourceUpdatedInterface;
import com.sldeditor.datasource.SLDEditorFileInterface;
import com.sldeditor.datasource.attribute.DataSourceAttributeData;
import com.sldeditor.datasource.attribute.DataSourceAttributeListInterface;
import com.sldeditor.datasource.checks.CheckAttributeInterface;
import com.sldeditor.datasource.example.ExampleLineInterface;
import com.sldeditor.datasource.example.ExamplePointInterface;
import com.sldeditor.datasource.example.ExamplePolygonInterface;
import com.sldeditor.datasource.example.impl.ExampleLineImpl;
import com.sldeditor.datasource.example.impl.ExamplePointImpl;
import com.sldeditor.datasource.example.impl.ExamplePolygonImplIOM;
import com.sldeditor.datasource.impl.CreateDataSourceInterface;
import com.sldeditor.datasource.impl.DataSourceFactory;
import com.sldeditor.datasource.impl.GeometryTypeEnum;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.data.FeatureSource;
import org.geotools.styling.UserLayer;
import org.junit.jupiter.api.Test;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.PropertyDescriptor;
/**
* Unit test for DataSourceFactory.
*
* <p>{@link com.sldeditor.datasource.impl.DataSourceFactory}
*
* @author Robert Ward (SCISYS)
*/
public class DataSourceFactoryTest {
class DummyDataSource implements DataSourceInterface {
public GeometryTypeEnum geometryType = GeometryTypeEnum.UNKNOWN;
@Override
public void addListener(DataSourceUpdatedInterface listener) {}
@Override
public void connect(
String typeName,
SLDEditorFileInterface editorFile,
List<CheckAttributeInterface> checkList) {}
@Override
public void reset() {}
@Override
public FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource() {
return null;
}
@Override
public List<String> getAttributes(Class<?> expectedDataType) {
return null;
}
@Override
public GeometryTypeEnum getGeometryType() {
return geometryType;
}
@Override
public void readAttributes(DataSourceAttributeListInterface attributeData) {}
@Override
public DataSourcePropertiesInterface getDataConnectorProperties() {
return null;
}
@Override
public List<String> getAvailableDataStoreList() {
return null;
}
@Override
public void updateFields(DataSourceAttributeListInterface attributeData) {}
@Override
public void addField(DataSourceAttributeData dataSourceField) {}
@Override
public void setDataSourceCreation(
CreateDataSourceInterface internalDataSource,
CreateDataSourceInterface externalDataSource,
CreateDataSourceInterface inlineDataSource) {}
@Override
public Collection<PropertyDescriptor> getPropertyDescriptorList() {
return null;
}
@Override
public void removeListener(DataSourceUpdatedInterface listener) {}
@Override
public AbstractGridCoverage2DReader getGridCoverageReader() {
return null;
}
@Override
public FeatureSource<SimpleFeatureType, SimpleFeature> getExampleFeatureSource() {
return null;
}
@Override
// CHECKSTYLE:OFF
public Map<UserLayer, FeatureSource<SimpleFeatureType, SimpleFeature>>
getUserLayerFeatureSource() {
return null;
}
// CHECKSTYLE:ON
@Override
public void updateUserLayers() {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.datasource.DataSourceInterface#updateFieldType(java.lang.String,
* java.lang.Class)
*/
@Override
public void updateFieldType(String fieldName, Class<?> dataType) {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.datasource.DataSourceInterface#getGeometryFieldName()
*/
@Override
public String getGeometryFieldName() {
return null;
}
/* (non-Javadoc)
* @see com.sldeditor.datasource.DataSourceInterface#getAllAttributes(boolean)
*/
@Override
public List<String> getAllAttributes(boolean includeGeometry) {
return null;
}
}
/**
* Test method for {@link
* com.sldeditor.datasource.impl.DataSourceFactory#createDataSource(java.lang.String)}. Test
* method for {@link com.sldeditor.datasource.impl.DataSourceFactory#getDataSource()}.
*/
@Test
public void testCreateDataSource() {
DataSourceInterface dataSource = DataSourceFactory.createDataSource(null);
assertTrue(dataSource != null);
assertTrue(DataSourceFactory.getDataSource() != null);
}
/**
* Test method for {@link
* com.sldeditor.datasource.impl.DataSourceFactory#createExamplePolygon(java.lang.String)}.
*/
@Test
public void testCreateExamplePolygon() {
ExamplePolygonInterface examplePolygon = DataSourceFactory.createExamplePolygon(null);
assertEquals(ExamplePolygonImplIOM.class, examplePolygon.getClass());
}
/**
* Test method for {@link
* com.sldeditor.datasource.impl.DataSourceFactory#createExampleLine(java.lang.Object)}.
*/
@Test
public void testCreateExampleLine() {
ExampleLineInterface exampleLine = DataSourceFactory.createExampleLine(null);
assertEquals(ExampleLineImpl.class, exampleLine.getClass());
}
/**
* Test method for {@link
* com.sldeditor.datasource.impl.DataSourceFactory#createExamplePoint(java.lang.Object)}.
*/
@Test
public void testCreateExamplePoint() {
ExamplePointInterface examplePoint = DataSourceFactory.createExamplePoint(null);
assertEquals(ExamplePointImpl.class, examplePoint.getClass());
}
}
| robward-scisys/sldeditor | modules/application/src/test/java/com/sldeditor/test/unit/datasource/impl/DataSourceFactoryTest.java | Java | gpl-3.0 | 7,273 |
////////////////////////////////////////////////////////////////////////////////
// This file is part of MABED. //
// //
// MABED 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. //
// //
// MABED 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 MABED. If not, see <http://www.gnu.org/licenses/>. //
////////////////////////////////////////////////////////////////////////////////
package fr.ericlab.mabed.structure;
/**
*
* @author Adrien GUILLE, ERIC Lab, University of Lyon 2
* @email [email protected]
*/
public class WeightedTerm implements Comparable<WeightedTerm>{
public String term;
public double weight;
public WeightedTerm(String t){
term = t;
weight = 0;
}
public WeightedTerm(String t, double w){
term = t;
weight = w;
}
@Override
public int compareTo(WeightedTerm o) {
if(o.weight-this.weight<0){
return -1;
}else{
if(o.weight-this.weight>0){
return 1;
}else{
return 0;
}
}
}
}
| AdrienGuille/MABED | src/fr/ericlab/mabed/structure/WeightedTerm.java | Java | gpl-3.0 | 2,014 |
package de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.matchingRules.kaggle_jokecamp;
import java.io.File;
import de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.ErrorAnalysisClubs;
import de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.model.Club;
import de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.model.ClubXMLReader;
import de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.comparators.ClubNameComparatorLevenshtein;
import de.uni_mannheim.informatik.dws.wdi.SoccerIdentityResolution.comparators.ClubNameComparatorMongeElkan;
//import de.uni_mannheim.informatik.dws.wdi.ExerciseIdentityResolution.Blocking.MovieBlockingKeyByDecadeGenerator;
//import de.uni_mannheim.informatik.dws.wdi.ExerciseIdentityResolution.Comparators.MovieDateComparator10Years;
//import de.uni_mannheim.informatik.dws.wdi.ExerciseIdentityResolution.Comparators.MovieTitleComparatorLevenshtein;
//import de.uni_mannheim.informatik.dws.wdi.ExerciseIdentityResolution.model.Movie;
//import de.uni_mannheim.informatik.dws.wdi.ExerciseIdentityResolution.model.MovieXMLReader;
import de.uni_mannheim.informatik.dws.winter.matching.MatchingEngine;
import de.uni_mannheim.informatik.dws.winter.matching.MatchingEvaluator;
import de.uni_mannheim.informatik.dws.winter.matching.blockers.NoBlocker;
import de.uni_mannheim.informatik.dws.winter.matching.rules.LinearCombinationMatchingRule;
import de.uni_mannheim.informatik.dws.winter.model.Correspondence;
import de.uni_mannheim.informatik.dws.winter.model.HashedDataSet;
import de.uni_mannheim.informatik.dws.winter.model.MatchingGoldStandard;
import de.uni_mannheim.informatik.dws.winter.model.Performance;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.model.io.CSVCorrespondenceFormatter;
import de.uni_mannheim.informatik.dws.winter.processing.Processable;
/**
* Data Set Kaggle ↔ Jokecamp
* Learning Combination Rules for Clubs
*/
public class IR_linear_combination_simple_clubs
{
public static void main( String[] args ) throws Exception
{
// loading data
HashedDataSet<Club, Attribute> kaggle = new HashedDataSet<>();
new ClubXMLReader().loadFromXML(new File("data/input/kaggle.xml"), "/clubs/club", kaggle);
HashedDataSet<Club, Attribute> dataJokecamp = new HashedDataSet<>();
new ClubXMLReader().loadFromXML(new File("data/input/jokecamp.xml"), "/clubs/club", dataJokecamp);
System.out.println("Sample from transfermarket: " + kaggle.getRandomRecord());
System.out.println("Sample from jokecamp others: " + dataJokecamp.getRandomRecord());
// create a matching rule
LinearCombinationMatchingRule<Club, Attribute> matchingRule = new LinearCombinationMatchingRule<>(
0.85);
// F1:0.8440 [P:0.9583, R:0.7541]
// add comparators
// matchingRule.addComparator(new MovieDateComparator10Years(), 0.5);
matchingRule.addComparator(new ClubNameComparatorMongeElkan(true, "levenshtein", true), 1.0);
// create a blocker (blocking strategy)
// StandardRecordBlocker<Club, Attribute> blocker = new StandardRecordBlocker<Club, Attribute>(new MovieBlockingKeyByDecadeGenerator());
NoBlocker<Club, Attribute> blocker = new NoBlocker<>();
// SortedNeighbourhoodBlocker<Movie, Attribute, Attribute> blocker = new SortedNeighbourhoodBlocker<>(new MovieBlockingKeyByDecadeGenerator(), 1);
// Initialize Matching Engine
MatchingEngine<Club, Attribute> engine = new MatchingEngine<>();
// Execute the matching
Processable<Correspondence<Club, Attribute>> correspondences = engine.runIdentityResolution(
kaggle, dataJokecamp, null, matchingRule,
blocker);
// write the correspondences to the output file
new CSVCorrespondenceFormatter().writeCSV(new File("data/output/kaggle_jokecamp_correspondences.csv"), correspondences);
// load the gold standard (test set)
MatchingGoldStandard gsTest = new MatchingGoldStandard();
gsTest.loadFromCSVFile(new File(
"data/goldstandard/completeGoldstandard/gs_jokecamp_kaggle_clubs.csv"));
// evaluate your result
MatchingEvaluator<Club, Attribute> evaluator = new MatchingEvaluator<Club, Attribute>(true);
Performance perfTest = evaluator.evaluateMatching(correspondences.get(),
gsTest);
new ErrorAnalysisClubs().printFalsePositives(correspondences, gsTest);
new ErrorAnalysisClubs().printFalseNegatives(kaggle, dataJokecamp, correspondences, gsTest);
// print the evaluation result
System.out.println("Kaggle ↔ Jokecamp");
System.out
.println(String.format(
"Precision: %.4f\nRecall: %.4f\nF1: %.4f",
perfTest.getPrecision(), perfTest.getRecall(),
perfTest.getF1()));
}
}
| WebDataIntegrationProject/SoccerIdentityResolution | src/main/java/de/uni_mannheim/informatik/dws/wdi/SoccerIdentityResolution/matchingRules/kaggle_jokecamp/IR_linear_combination_simple_clubs.java | Java | gpl-3.0 | 5,039 |
package tud.tangram.svgplot.plotting.texture;
import org.w3c.dom.Element;
import tud.tangram.svgplot.xml.SvgDocument;
public class TertiaryTextureMaker extends TextureMaker {
@Override
protected String addTigerEmbosserTexture(SvgDocument doc) {
String id = "diagonal_line1_SP_T";
Element g = doc.getOrCreateChildGroupById(doc.defs, "patterns");
Element pattern = createPattern(doc, id, 10.16, 10.16);
Element rect = createRect(doc, 0., 0., "100%", "100%", "white", "none");
Element line1 = createLine(doc, 5.85, -1.27, 18.55, 11.43, "black", 0.8);
Element line2 = createLine(doc, -1.77, 1.27, 8.39, 11.43, "black", 0.8);
pattern.appendChild(rect);
pattern.appendChild(line1);
pattern.appendChild(line2);
g.appendChild(pattern);
return id;
}
@Override
protected String addMicroCapsulePaperTexture(SvgDocument doc) {
return addTigerEmbosserTexture(doc);
}
@Override
protected String addPinDeviceTexture(SvgDocument doc) {
String id = "diagonal_line1_PD";
Element g = doc.getOrCreateChildGroupById(doc.defs, "patterns");
Element pattern = createPattern(doc, id, 10., 10.);
Element rect = createRect(doc, 0., 0., "100%", "100%", "white", "none");
Element line1 = createLine(doc, 2.5, -2.5, 17.5, 12.5, "black", 1.3);
Element line2 = createLine(doc, -2.5, 2.5, 7.5, 12.5, "black", 1.3);
pattern.appendChild(rect);
pattern.appendChild(line1);
pattern.appendChild(line2);
g.appendChild(pattern);
return id;
}
}
| TUD-INF-IAI-MCI/SVG-Plott | ext_svgplot/svgplot/src/tud/tangram/svgplot/plotting/texture/TertiaryTextureMaker.java | Java | gpl-3.0 | 1,490 |
package ru.vlsu.gibdd.webservice.register.service.api;
import ru.vlsu.gibdd.webservice.register.io.FindRegistrationCertificateRequestIo;
import ru.vlsu.gibdd.webservice.register.io.FindRegistrationCertificateResponseIo;
import ru.vlsu.gibdd.webservice.register.io.RegisterVehicleRequestIo;
import ru.vlsu.gibdd.webservice.register.io.RegisterVehicleResponseIo;
/**
* @author Victor Zhivotikov
* @since 25.04.2016
*/
public interface RegistrationCertificateService {
FindRegistrationCertificateResponseIo findRegistrationCertificate(FindRegistrationCertificateRequestIo request);
RegisterVehicleResponseIo createRegistrationCertificate(RegisterVehicleRequestIo request);
}
| deathman92/gibdd-web-services | register-vehicle-web-service/src/main/java/ru/vlsu/gibdd/webservice/register/service/api/RegistrationCertificateService.java | Java | gpl-3.0 | 686 |
package sporemodder.userinterface.dialogs;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import sporemodder.MainApp;
import sporemodder.files.formats.ConvertAction;
import sporemodder.files.formats.FileStructureError;
import sporemodder.userinterface.ErrorManager;
import sporemodder.userinterface.dialogs.AdvancedFileChooser.ChooserType;
import sporemodder.utilities.InputOutputPaths;
import sporemodder.utilities.InputOutputPaths.InputOutputPair;
public class UIConvertDialog extends JPanel {
/**
*
*/
private static final long serialVersionUID = -4192713466752761123L;
private String defaultInputExtension;
private String defaultOutputExtension;
private boolean removeExtension;
private ConvertAction convertAction;
private JDialog parent;
private JPanel infoPanel;
private JLabel lblInputFile;
private JLabel lblOutputFile;
private JTextField tfInputFile;
private JTextField tfOutputFile;
//private JButton btnFindInFile;
//private JButton btnFindOutFile;
private JPanel buttonsPanel;
private JButton btnCancel;
private JButton btnConvert;
// private AdvancedFileChooser inputFileChooser;
// private AdvancedFileChooser outputFileChooser;
private int inputSelectionMode;
private int outputSelectionMode;
private boolean inputMultiSelectEnabled;
private boolean outputMultiSelectEnabled;
public UIConvertDialog(
JDialog parent, FileNameExtensionFilter inputFilter, FileNameExtensionFilter outputFilter, String defaultInputExtension, String defaultOutputExtension, boolean removeExtension,
ConvertAction convertAction) {
this(parent, inputFilter, outputFilter, defaultInputExtension, defaultOutputExtension, removeExtension, convertAction, null, JFileChooser.FILES_AND_DIRECTORIES, true);
}
public UIConvertDialog(
JDialog parent, FileNameExtensionFilter inputFilter, FileNameExtensionFilter outputFilter, String defaultInputExtension,
String defaultOutputExtension, boolean removeExtension, ConvertAction convertAction, JPanel advancedOptionsPanel) {
this(parent, inputFilter, outputFilter, defaultInputExtension, defaultOutputExtension, removeExtension, convertAction, advancedOptionsPanel, JFileChooser.FILES_AND_DIRECTORIES, true);
}
public UIConvertDialog(
JDialog parent, FileNameExtensionFilter inputFilter, FileNameExtensionFilter outputFilter, String defaultInputExtension,
String defaultOutputExtension, boolean removeExtension, ConvertAction convertAction, JPanel advancedOptionsPanel, int selectionMode, boolean multiSelectEnabled) {
this(parent, inputFilter, outputFilter, defaultInputExtension, defaultOutputExtension, removeExtension, convertAction, advancedOptionsPanel,
selectionMode, multiSelectEnabled, selectionMode, multiSelectEnabled);
}
public UIConvertDialog(
JDialog parent, FileNameExtensionFilter inputFilter, FileNameExtensionFilter outputFilter, String defaultInputExtension,
String defaultOutputExtension, boolean removeExtension, ConvertAction convertAction, JPanel advancedOptionsPanel,
int inputSelectionMode, boolean inputMultiSelectEnabled, int outputSelectionMode, boolean outputMultiSelectEnabled) {
this.parent = parent;
this.defaultInputExtension = defaultInputExtension;
this.defaultOutputExtension = defaultOutputExtension;
this.removeExtension = removeExtension;
this.convertAction = convertAction;
this.inputSelectionMode = inputSelectionMode;
this.outputSelectionMode = outputSelectionMode;
this.inputMultiSelectEnabled = inputMultiSelectEnabled;
this.outputMultiSelectEnabled = outputMultiSelectEnabled;
if (advancedOptionsPanel == null) {
advancedOptionsPanel = convertAction.createOptionsPanel();
if (advancedOptionsPanel != null) {
advancedOptionsPanel.setBorder(BorderFactory.createTitledBorder("Advanced options"));
}
}
setLayout(new BorderLayout());
infoPanel = new JPanel();
infoPanel.setLayout(new GridBagLayout());
infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
GridBagConstraints c = new GridBagConstraints();
///////// LABELS /////////
lblInputFile = new JLabel("Input file: ");
lblOutputFile = new JLabel("Output file: ");
c.gridx = 0;
c.gridy = 0;
infoPanel.add(lblInputFile, c);
c.gridy = 1;
infoPanel.add(lblOutputFile, c);
///////// TEXT FIELDS /////////
tfInputFile = new JTextField();
tfInputFile.setDropTarget(new DropTargetTextField(tfInputFile, true));
tfInputFile.setColumns(50);
tfOutputFile = new JTextField();
tfOutputFile.setDropTarget(new DropTargetTextField(tfOutputFile, false));
tfOutputFile.setColumns(50);
c.gridx = 1;
c.gridy = 0;
infoPanel.add(tfInputFile, c);
c.gridy = 1;
infoPanel.add(tfOutputFile, c);
///////// FIND FILE BUTTONS /////////
c.gridx = 1;
c.gridy = 0;
if (inputSelectionMode == JFileChooser.FILES_AND_DIRECTORIES || inputSelectionMode == JFileChooser.FILES_ONLY) {
JButton btnFindInFile = new JButton("Find file");
btnFindInFile.addActionListener(new AdvancedFileChooser(tfInputFile, parent,
inputSelectionMode, inputMultiSelectEnabled, "untitled." + (removeExtension ? (defaultOutputExtension + "." + defaultInputExtension) : defaultInputExtension),
ChooserType.OPEN, inputFilter));
c.gridx += 1;
infoPanel.add(btnFindInFile, c);
}
if (inputSelectionMode == JFileChooser.FILES_AND_DIRECTORIES || inputSelectionMode == JFileChooser.DIRECTORIES_ONLY) {
JButton btnFindInFolder = new JButton("Find folder");
// force it to find folders
btnFindInFolder.addActionListener(new AdvancedFileChooser(tfInputFile, parent,
JFileChooser.DIRECTORIES_ONLY, inputMultiSelectEnabled, "untitled." + (removeExtension ? (defaultOutputExtension + "." + defaultInputExtension) : defaultInputExtension),
ChooserType.OPEN, inputFilter));
c.gridx += 1;
infoPanel.add(btnFindInFolder, c);
}
c.gridx = 1;
c.gridy = 1;
if (outputSelectionMode == JFileChooser.FILES_AND_DIRECTORIES || outputSelectionMode == JFileChooser.FILES_ONLY) {
JButton btnFindOutFile = new JButton("Find file");
btnFindOutFile.addActionListener(new AdvancedFileChooser(tfOutputFile, parent,
outputSelectionMode, outputMultiSelectEnabled, "untitled." + (removeExtension ? defaultOutputExtension : (defaultInputExtension + "." + defaultOutputExtension)),
ChooserType.SAVE, outputFilter));
c.gridx += 1;
infoPanel.add(btnFindOutFile, c);
}
if (outputSelectionMode == JFileChooser.FILES_AND_DIRECTORIES || outputSelectionMode == JFileChooser.DIRECTORIES_ONLY) {
JButton btnFindOutFolder = new JButton("Find folder");
// force it to find folders
btnFindOutFolder.addActionListener(new AdvancedFileChooser(tfOutputFile, parent,
JFileChooser.DIRECTORIES_ONLY, outputMultiSelectEnabled, "untitled." + (removeExtension ? defaultOutputExtension : (defaultInputExtension + "." + defaultOutputExtension)),
ChooserType.SAVE, outputFilter));
c.gridx += 1;
infoPanel.add(btnFindOutFolder, c);
}
///////// BUTTONS PANEL /////////
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
buttonsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5));
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ALCancel());
btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ALConvert());
buttonsPanel.add(btnConvert);
buttonsPanel.add(btnCancel);
parent.getRootPane().setDefaultButton(btnConvert);
add(infoPanel, BorderLayout.NORTH);
if (advancedOptionsPanel != null) {
add(advancedOptionsPanel, BorderLayout.CENTER);
}
add(buttonsPanel, BorderLayout.SOUTH);
}
private class ALConvert implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
String inputFile = tfInputFile.getText();
String outputFile = tfOutputFile.getText();
List<InputOutputPair> pairs = null;
if (inputFile.length() == 0 || outputFile.length() == 0) {
JOptionPane.showMessageDialog(UIConvertDialog.this, "No input/output file specified", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// These special cases (like effects) require a directory as input
if (!inputMultiSelectEnabled || !outputMultiSelectEnabled ||
inputSelectionMode == JFileChooser.DIRECTORIES_ONLY || outputSelectionMode == JFileChooser.DIRECTORIES_ONLY) {
pairs = new ArrayList<InputOutputPair>();
pairs.add(new InputOutputPair(inputFile, outputFile));
}
else {
try {
pairs = InputOutputPaths.parsePairs(inputFile, outputFile, defaultInputExtension, defaultOutputExtension, removeExtension);
} catch (Exception e) {
JOptionPane.showMessageDialog(UIConvertDialog.this, "Error parsing input/outputs strings: \n" + e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
if (pairs.size() > 1) {
new ProgressDialog(pairs);
}
else if (pairs.size() > 0) {
InputOutputPair pair = pairs.get(0);
try {
List<FileStructureError> errors = convertAction.convert(pair.input, pair.output).getAllErrors();
if (errors != null && errors.size() > 0) {
JOptionPane.showMessageDialog(UIConvertDialog.this, "Errors converting file " + pair.input + ":\n" + FileStructureError.getErrorsString(errors),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(UIConvertDialog.this, "Error converting file " + pair.input + ":\n" + ErrorManager.getStackTraceString(e),
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
JOptionPane.showMessageDialog(UIConvertDialog.this, "No files were converted", "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
parent.dispose();
}
}
private class ALCancel implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
parent.dispose();
}
}
private class ProgressDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 669845576013891050L;
private List<InputOutputPair> pairs;
private JProgressBar progressBar;
private Task task;
private ProgressDialog(List<InputOutputPair> pairs) {
super(MainApp.getUserInterface());
setModalityType(ModalityType.TOOLKIT_MODAL);
this.pairs = pairs;
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
//progressBar.setStringPainted(true);
add(progressBar);
task = new Task();
task.addPropertyChangeListener(new TaskProgressListener());
task.execute();
pack();
setVisible(true);
}
private class TaskProgressListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent arg0) {
progressBar.setValue(task.getProgress());
}
}
private class Task extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
float inc = 100.0f / pairs.size();
float progress = 0;
List<List<FileStructureError>> errors = new ArrayList<List<FileStructureError>>();
List<Exception> exceptions = new ArrayList<Exception>();
List<InputOutputPair> failedPairs = new ArrayList<InputOutputPair>();
for (InputOutputPair pair : pairs) {
try {
List<FileStructureError> error = convertAction.convert(pair.input, pair.output).getAllErrors();
if (error != null && error.size() > 0) {
errors.add(error);
failedPairs.add(pair);
}
} catch (Exception e) {
failedPairs.add(pair);
exceptions.add(e);
}
progress += inc;
setProgress((int) progress);
}
if (failedPairs.size() > 0) {
StringBuilder sb = new StringBuilder("Couldn't convert the following files:\n");
for (int i = 0; i < failedPairs.size(); i++)
{
sb.append(failedPairs.get(i).input + "\n");
}
JOptionPane.showMessageDialog(ProgressDialog.this, sb.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
return null;
}
@Override
public void done() {
dispose();
}
}
}
public static void addConvertTab(JDialog parent, JTabbedPane tabbedPane, ConvertAction action, String title,
FileNameExtensionFilter inFilter, FileNameExtensionFilter outFilter, String inExtension, String outExtension, boolean removeExtension) {
JPanel panel = action.createOptionsPanel();
if (panel != null) {
panel.setBorder(BorderFactory.createTitledBorder("Advanced options"));
}
tabbedPane.addTab(title, new UIConvertDialog(parent, inFilter, outFilter, inExtension, outExtension, removeExtension, action, panel));
}
}
| Emd4600/SporeModder | src/sporemodder/userinterface/dialogs/UIConvertDialog.java | Java | gpl-3.0 | 13,394 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PreferencesDialog.java
*
* Created on Apr 26, 2012, 3:18:17 PM
*/
package org.pepsoft.worldpainter;
import java.util.SortedMap;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import org.pepsoft.worldpainter.themes.TerrainListCellRenderer;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.swing.*;
import static org.pepsoft.worldpainter.Terrain.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.worldpainter.Constants.*;
import org.pepsoft.worldpainter.TileRenderer.LightOrigin;
import org.pepsoft.worldpainter.themes.SimpleTheme;
/**
*
* @author pepijn
*/
public class PreferencesDialog extends javax.swing.JDialog {
/** Creates new form PreferencesDialog */
public PreferencesDialog(java.awt.Frame parent, ColourScheme colourScheme) {
super(parent, true);
this.colourScheme = colourScheme;
initComponents();
comboBoxSurfaceMaterial.setModel(new DefaultComboBoxModel(Terrain.PICK_LIST));
comboBoxSurfaceMaterial.setRenderer(new TerrainListCellRenderer(colourScheme));
if (! JAVA_7) {
comboBoxLookAndFeel.setModel(new DefaultComboBoxModel(new Object[] {"System", "Metal", "Nimbus", "Dark Metal"}));
}
List<AccelerationType> accelTypes = AccelerationType.getForThisOS();
radioButtonAccelDefault.setEnabled(accelTypes.contains(AccelerationType.DEFAULT));
radioButtonAccelDirect3D.setEnabled(accelTypes.contains(AccelerationType.DIRECT3D));
radioButtonAccelOpenGL.setEnabled(accelTypes.contains(AccelerationType.OPENGL));
radioButtonAccelQuartz.setEnabled(accelTypes.contains(AccelerationType.QUARTZ));
radioButtonAccelUnaccelerated.setEnabled(accelTypes.contains(AccelerationType.UNACCELERATED));
radioButtonAccelXRender.setEnabled(accelTypes.contains(AccelerationType.XRENDER));
loadSettings();
ActionMap actionMap = rootPane.getActionMap();
actionMap.put("cancel", new AbstractAction("cancel") {
@Override
public void actionPerformed(ActionEvent e) {
cancel();
}
private static final long serialVersionUID = 1L;
});
InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel");
rootPane.setDefaultButton(buttonOK);
pack();
setLocationRelativeTo(parent);
}
public void ok() {
saveSettings();
cancelled = false;
dispose();
}
public void cancel() {
dispose();
}
public boolean isCancelled() {
return cancelled;
}
private void loadSettings() {
Configuration config = Configuration.getInstance();
if (Main.privateContext == null) {
checkBoxPing.setSelected(false);
checkBoxPing.setEnabled(false);
pingNotSet = true;
} else if (config.getPingAllowed() != null) {
checkBoxPing.setSelected(config.getPingAllowed());
} else {
checkBoxPing.setSelected(false);
pingNotSet = true;
}
if ((Main.privateContext == null)
|| "true".equals(System.getProperty("org.pepsoft.worldpainter.devMode"))
|| "true".equals(System.getProperty("org.pepsoft.worldpainter.disableUpdateCheck"))) {
checkBoxCheckForUpdates.setSelected(false);
checkBoxCheckForUpdates.setEnabled(false);
} else {
checkBoxCheckForUpdates.setSelected(config.isCheckForUpdates());
}
if ("true".equals(System.getProperty("org.pepsoft.worldpainter.disableUndo"))) {
checkBoxUndo.setSelected(false);
checkBoxUndo.setEnabled(false);
spinnerUndoLevels.setEnabled(false);
} else {
checkBoxUndo.setSelected(config.isUndoEnabled());
spinnerUndoLevels.setValue(config.getUndoLevels());
}
checkBoxGrid.setSelected(config.isDefaultGridEnabled());
spinnerGrid.setValue(config.getDefaultGridSize());
checkBoxContours.setSelected(config.isDefaultContoursEnabled());
spinnerContours.setValue(config.getDefaultContourSeparation());
checkBoxViewDistance.setSelected(config.isDefaultViewDistanceEnabled());
checkBoxWalkingDistance.setSelected(config.isDefaultWalkingDistanceEnabled());
comboBoxLightDirection.setSelectedItem(config.getDefaultLightOrigin());
checkBoxCircular.setSelected(config.isDefaultCircularWorld());
spinnerBrushSize.setValue(config.getMaximumBrushSize());
spinnerWidth.setValue(config.getDefaultWidth() * 128);
spinnerHeight.setValue(config.getDefaultHeight() * 128);
comboBoxHeight.setSelectedItem(Integer.toString(config.getDefaultMaxHeight()));
if (config.isHilly()) {
radioButtonHilly.setSelected(true);
} else {
radioButtonFlat.setSelected(true);
spinnerRange.setEnabled(false);
spinnerScale.setEnabled(false);
}
spinnerRange.setValue((int) (config.getDefaultRange() + 0.5f));
spinnerScale.setValue((int) (config.getDefaultScale() * 100 + 0.5f));
spinnerGroundLevel.setValue(config.getLevel());
spinnerWaterLevel.setValue(config.getWaterLevel());
checkBoxLava.setSelected(config.isLava());
checkBoxBeaches.setSelected(config.isBeaches());
comboBoxSurfaceMaterial.setSelectedItem(config.getSurface());
spinnerWorldBackups.setValue(config.getWorldFileBackups());
checkBoxExtendedBlockIds.setSelected(config.isDefaultExtendedBlockIds());
// Export settings
checkBoxChestOfGoodies.setSelected(config.isDefaultCreateGoodiesChest());
comboBoxWorldType.setSelectedIndex(config.getDefaultGenerator().ordinal());
generatorOptions = config.getDefaultGeneratorOptions();
checkBoxStructures.setSelected(config.isDefaultMapFeatures());
comboBoxMode.setSelectedIndex(config.getDefaultGameType());
checkBoxCheats.setSelected(config.isDefaultAllowCheats());
previousExp = (int) Math.round(Math.log(config.getDefaultMaxHeight()) / Math.log(2.0));
comboBoxLookAndFeel.setSelectedIndex(config.getLookAndFeel() != null ? config.getLookAndFeel().ordinal() : 0);
switch (config.getAccelerationType()) {
case DEFAULT:
radioButtonAccelDefault.setSelected(true);
break;
case DIRECT3D:
radioButtonAccelDirect3D.setSelected(true);
break;
case OPENGL:
radioButtonAccelOpenGL.setSelected(true);
break;
case QUARTZ:
radioButtonAccelQuartz.setSelected(true);
break;
case UNACCELERATED:
radioButtonAccelUnaccelerated.setSelected(true);
break;
case XRENDER:
radioButtonAccelXRender.setSelected(true);
break;
}
switch (config.getOverlayType()) {
case OPTIMISE_ON_LOAD:
radioButtonOverlayOptimiseOnLoad.setSelected(true);
break;
case SCALE_ON_LOAD:
radioButtonOverlayScaleOnLoad.setSelected(true);
break;
case SCALE_ON_PAINT:
radioButtonOverlayScaleOnPaint.setSelected(true);
break;
}
setControlStates();
}
private void saveSettings() {
Configuration config = Configuration.getInstance();
if (! pingNotSet) {
config.setPingAllowed(checkBoxPing.isSelected());
}
if ((! "true".equals(System.getProperty("org.pepsoft.worldpainter.devMode")))
&& (! "true".equals(System.getProperty("org.pepsoft.worldpainter.disableUpdateCheck")))) {
config.setCheckForUpdates(checkBoxCheckForUpdates.isSelected());
}
if (! "true".equals(System.getProperty("org.pepsoft.worldpainter.disableUndo"))) {
config.setUndoEnabled(checkBoxUndo.isSelected());
config.setUndoLevels(((Number) spinnerUndoLevels.getValue()).intValue());
}
config.setDefaultGridEnabled(checkBoxGrid.isSelected());
config.setDefaultGridSize((Integer) spinnerGrid.getValue());
config.setDefaultContoursEnabled(checkBoxContours.isSelected());
config.setDefaultContourSeparation((Integer) spinnerContours.getValue());
config.setDefaultViewDistanceEnabled(checkBoxViewDistance.isSelected());
config.setDefaultWalkingDistanceEnabled(checkBoxWalkingDistance.isSelected());
config.setDefaultLightOrigin((LightOrigin) comboBoxLightDirection.getSelectedItem());
config.setDefaultWidth(((Integer) spinnerWidth.getValue()) / 128);
// Set defaultCircularWorld *before* defaultHeight, otherwise defaultHeight might not take
config.setDefaultCircularWorld(checkBoxCircular.isSelected());
config.setDefaultHeight(((Integer) spinnerHeight.getValue()) / 128);
config.setDefaultMaxHeight(Integer.parseInt((String) comboBoxHeight.getSelectedItem()));
config.setHilly(radioButtonHilly.isSelected());
config.setDefaultRange(((Number) spinnerRange.getValue()).floatValue());
config.setDefaultScale((Integer) spinnerScale.getValue() / 100.0);
config.setLevel((Integer) spinnerGroundLevel.getValue());
config.setWaterLevel((Integer) spinnerWaterLevel.getValue());
config.setLava(checkBoxLava.isSelected());
config.setBeaches(checkBoxBeaches.isSelected());
config.setSurface((Terrain) comboBoxSurfaceMaterial.getSelectedItem());
config.setWorldFileBackups((Integer) spinnerWorldBackups.getValue());
config.setMaximumBrushSize((Integer) spinnerBrushSize.getValue());
config.setDefaultExtendedBlockIds(checkBoxExtendedBlockIds.isSelected());
// Export settings
config.setDefaultCreateGoodiesChest(checkBoxChestOfGoodies.isSelected());
config.setDefaultGenerator(Generator.values()[comboBoxWorldType.getSelectedIndex()]);
config.setDefaultGeneratorOptions(generatorOptions);
config.setDefaultMapFeatures(checkBoxStructures.isSelected());
config.setDefaultGameType(comboBoxMode.getSelectedIndex());
config.setDefaultAllowCheats(checkBoxCheats.isSelected());
config.setLookAndFeel(Configuration.LookAndFeel.values()[comboBoxLookAndFeel.getSelectedIndex()]);
if (radioButtonAccelDefault.isSelected()) {
config.setAccelerationType(AccelerationType.DEFAULT);
} else if (radioButtonAccelDirect3D.isSelected()) {
config.setAccelerationType(AccelerationType.DIRECT3D);
} else if (radioButtonAccelOpenGL.isSelected()) {
config.setAccelerationType(AccelerationType.OPENGL);
} else if (radioButtonAccelQuartz.isSelected()) {
config.setAccelerationType(AccelerationType.QUARTZ);
} else if (radioButtonAccelUnaccelerated.isSelected()) {
config.setAccelerationType(AccelerationType.UNACCELERATED);
} else if (radioButtonAccelXRender.isSelected()) {
config.setAccelerationType(AccelerationType.XRENDER);
}
if (radioButtonOverlayOptimiseOnLoad.isSelected()) {
config.setOverlayType(Configuration.OverlayType.OPTIMISE_ON_LOAD);
} else if (radioButtonOverlayScaleOnLoad.isSelected()) {
config.setOverlayType(Configuration.OverlayType.SCALE_ON_LOAD);
} else if (radioButtonOverlayScaleOnPaint.isSelected()) {
config.setOverlayType(Configuration.OverlayType.SCALE_ON_PAINT);
}
try {
config.save();
} catch (IOException e) {
ErrorDialog errorDialog = new ErrorDialog(this);
errorDialog.setException(e);
errorDialog.setVisible(true);
}
}
private void setControlStates() {
spinnerUndoLevels.setEnabled(checkBoxUndo.isSelected());
boolean hilly = radioButtonHilly.isSelected();
spinnerRange.setEnabled(hilly);
spinnerScale.setEnabled(hilly);
spinnerHeight.setEnabled(! checkBoxCircular.isSelected());
buttonModePreset.setEnabled(comboBoxWorldType.getSelectedIndex() == 1);
}
private void editTerrainAndLayerSettings() {
Configuration config = Configuration.getInstance();
Dimension defaultSettings = config.getDefaultTerrainAndLayerSettings();
DimensionPropertiesDialog dialog = new DimensionPropertiesDialog(this, defaultSettings, colourScheme, true);
dialog.setVisible(true);
TileFactory tileFactory = defaultSettings.getTileFactory();
if ((tileFactory instanceof HeightMapTileFactory)
&& (((HeightMapTileFactory) tileFactory).getTheme() instanceof SimpleTheme)) {
HeightMapTileFactory heightMapTileFactory = (HeightMapTileFactory) tileFactory;
SimpleTheme theme = (SimpleTheme) ((HeightMapTileFactory) tileFactory).getTheme();
checkBoxBeaches.setSelected(theme.isBeaches());
int waterLevel = heightMapTileFactory.getWaterHeight();
spinnerWaterLevel.setValue(waterLevel);
defaultSettings.setBorderLevel(heightMapTileFactory.getWaterHeight());
SortedMap<Integer, Terrain> terrainRanges = theme.getTerrainRanges();
comboBoxSurfaceMaterial.setSelectedItem(terrainRanges.get(terrainRanges.headMap(waterLevel + 3).lastKey()));
}
}
/** 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jRadioButton3 = new javax.swing.JRadioButton();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
checkBoxPing = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
checkBoxCheckForUpdates = new javax.swing.JCheckBox();
jLabel6 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
checkBoxGrid = new javax.swing.JCheckBox();
jLabel7 = new javax.swing.JLabel();
spinnerGrid = new javax.swing.JSpinner();
jLabel8 = new javax.swing.JLabel();
checkBoxContours = new javax.swing.JCheckBox();
spinnerContours = new javax.swing.JSpinner();
checkBoxViewDistance = new javax.swing.JCheckBox();
checkBoxWalkingDistance = new javax.swing.JCheckBox();
jLabel9 = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
jLabel10 = new javax.swing.JLabel();
spinnerWidth = new javax.swing.JSpinner();
jLabel11 = new javax.swing.JLabel();
spinnerHeight = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
comboBoxHeight = new javax.swing.JComboBox();
jLabel13 = new javax.swing.JLabel();
radioButtonHilly = new javax.swing.JRadioButton();
radioButtonFlat = new javax.swing.JRadioButton();
jLabel14 = new javax.swing.JLabel();
spinnerGroundLevel = new javax.swing.JSpinner();
jLabel15 = new javax.swing.JLabel();
spinnerWaterLevel = new javax.swing.JSpinner();
checkBoxLava = new javax.swing.JCheckBox();
checkBoxBeaches = new javax.swing.JCheckBox();
jLabel16 = new javax.swing.JLabel();
comboBoxSurfaceMaterial = new javax.swing.JComboBox();
labelTerrainAndLayerSettings = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
buttonReset = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
jLabel20 = new javax.swing.JLabel();
spinnerWorldBackups = new javax.swing.JSpinner();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
comboBoxLightDirection = new javax.swing.JComboBox();
jLabel23 = new javax.swing.JLabel();
spinnerRange = new javax.swing.JSpinner();
jLabel24 = new javax.swing.JLabel();
spinnerScale = new javax.swing.JSpinner();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
spinnerBrushSize = new javax.swing.JSpinner();
jLabel27 = new javax.swing.JLabel();
checkBoxCircular = new javax.swing.JCheckBox();
checkBoxExtendedBlockIds = new javax.swing.JCheckBox();
jLabel17 = new javax.swing.JLabel();
jSeparator5 = new javax.swing.JSeparator();
checkBoxChestOfGoodies = new javax.swing.JCheckBox();
jLabel28 = new javax.swing.JLabel();
comboBoxWorldType = new javax.swing.JComboBox();
buttonModePreset = new javax.swing.JButton();
checkBoxStructures = new javax.swing.JCheckBox();
jLabel29 = new javax.swing.JLabel();
comboBoxMode = new javax.swing.JComboBox();
checkBoxCheats = new javax.swing.JCheckBox();
jLabel30 = new javax.swing.JLabel();
comboBoxLookAndFeel = new javax.swing.JComboBox();
jLabel32 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
checkBoxUndo = new javax.swing.JCheckBox();
jLabel5 = new javax.swing.JLabel();
spinnerUndoLevels = new javax.swing.JSpinner();
jPanel3 = new javax.swing.JPanel();
jLabel31 = new javax.swing.JLabel();
radioButtonAccelDefault = new javax.swing.JRadioButton();
radioButtonAccelDirect3D = new javax.swing.JRadioButton();
radioButtonAccelOpenGL = new javax.swing.JRadioButton();
radioButtonAccelQuartz = new javax.swing.JRadioButton();
radioButtonAccelXRender = new javax.swing.JRadioButton();
radioButtonAccelUnaccelerated = new javax.swing.JRadioButton();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
jLabel36 = new javax.swing.JLabel();
jLabel37 = new javax.swing.JLabel();
jLabel38 = new javax.swing.JLabel();
jLabel39 = new javax.swing.JLabel();
jLabel35 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel40 = new javax.swing.JLabel();
jLabel41 = new javax.swing.JLabel();
radioButtonOverlayScaleOnLoad = new javax.swing.JRadioButton();
radioButtonOverlayOptimiseOnLoad = new javax.swing.JRadioButton();
radioButtonOverlayScaleOnPaint = new javax.swing.JRadioButton();
jLabel42 = new javax.swing.JLabel();
jLabel43 = new javax.swing.JLabel();
jLabel44 = new javax.swing.JLabel();
buttonCancel = new javax.swing.JButton();
buttonOK = new javax.swing.JButton();
jRadioButton3.setText("jRadioButton3");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Preferences");
jLabel1.setText("Configure your preferences and default settings on this screen:");
jLabel2.setFont(jLabel2.getFont().deriveFont((jLabel2.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel2.setText("General ");
checkBoxPing.setSelected(true);
checkBoxPing.setText("Send usage information to the developer");
checkBoxPing.addActionListener(this::checkBoxPingActionPerformed);
jLabel3.setFont(jLabel3.getFont().deriveFont((jLabel3.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel3.setText("Note that the information does not include personally identifiable ");
jLabel4.setFont(jLabel4.getFont().deriveFont((jLabel4.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel4.setText("information, and will never be sold or given to third parties. ");
checkBoxCheckForUpdates.setSelected(true);
checkBoxCheckForUpdates.setText("Check for updates on startup");
jLabel6.setFont(jLabel6.getFont().deriveFont((jLabel6.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel6.setText("Default view settings ");
checkBoxGrid.setText("Grid enabled");
jLabel7.setLabelFor(spinnerGrid);
jLabel7.setText("Grid size:");
spinnerGrid.setModel(new javax.swing.SpinnerNumberModel(128, 2, 999, 1));
jLabel8.setText("Separation:");
checkBoxContours.setSelected(true);
checkBoxContours.setText("Contour lines enabled");
spinnerContours.setModel(new javax.swing.SpinnerNumberModel(10, 2, 999, 1));
checkBoxViewDistance.setText("View distance enabled");
checkBoxWalkingDistance.setText("Walking distance enabled");
jLabel9.setFont(jLabel9.getFont().deriveFont((jLabel9.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel9.setText("Default world settings ");
jLabel10.setLabelFor(spinnerWidth);
jLabel10.setText("Dimensions:");
spinnerWidth.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(640), Integer.valueOf(128), null, Integer.valueOf(128)));
spinnerWidth.addChangeListener(this::spinnerWidthStateChanged);
jLabel11.setText("x");
spinnerHeight.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(640), Integer.valueOf(128), null, Integer.valueOf(128)));
spinnerHeight.addChangeListener(this::spinnerHeightStateChanged);
jLabel12.setLabelFor(comboBoxHeight);
jLabel12.setText("Height:");
comboBoxHeight.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "32", "64", "128", "256", "512", "1024", "2048" }));
comboBoxHeight.setSelectedIndex(3);
comboBoxHeight.addActionListener(this::comboBoxHeightActionPerformed);
jLabel13.setText("Topography:");
buttonGroup1.add(radioButtonHilly);
radioButtonHilly.setSelected(true);
radioButtonHilly.setText("Hilly");
radioButtonHilly.addActionListener(this::radioButtonHillyActionPerformed);
buttonGroup1.add(radioButtonFlat);
radioButtonFlat.setText("Flat");
radioButtonFlat.addActionListener(this::radioButtonFlatActionPerformed);
jLabel14.setLabelFor(spinnerGroundLevel);
jLabel14.setText("Level:");
spinnerGroundLevel.setModel(new javax.swing.SpinnerNumberModel(58, 1, 255, 1));
jLabel15.setText("Water level:");
spinnerWaterLevel.setModel(new javax.swing.SpinnerNumberModel(62, 0, 255, 1));
spinnerWaterLevel.addChangeListener(this::spinnerWaterLevelStateChanged);
checkBoxLava.setText("Lava instead of water");
checkBoxBeaches.setSelected(true);
checkBoxBeaches.setText("Beaches");
checkBoxBeaches.addActionListener(this::checkBoxBeachesActionPerformed);
jLabel16.setText("Surface material:");
comboBoxSurfaceMaterial.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboBoxSurfaceMaterial.addActionListener(this::comboBoxSurfaceMaterialActionPerformed);
labelTerrainAndLayerSettings.setForeground(java.awt.Color.blue);
labelTerrainAndLayerSettings.setText("<html><u>Configure default border, terrain and layer settings</u></html>");
labelTerrainAndLayerSettings.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelTerrainAndLayerSettings.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelTerrainAndLayerSettingsMouseClicked(evt);
}
});
jLabel19.setText("blocks");
jLabel18.setFont(jLabel18.getFont().deriveFont((jLabel18.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel18.setText("(Note that changes to these settings will only take effect for the next world you load or create.) ");
buttonReset.setText("Reset...");
buttonReset.addActionListener(this::buttonResetActionPerformed);
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel20.setText("No. of backups of .world files to keep:");
spinnerWorldBackups.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(3), Integer.valueOf(0), null, Integer.valueOf(1)));
jLabel21.setText(" ");
jLabel22.setText("Light direction:");
comboBoxLightDirection.setModel(new DefaultComboBoxModel(LightOrigin.values()));
jLabel23.setText("(height:");
spinnerRange.setModel(new javax.swing.SpinnerNumberModel(20, 1, 255, 1));
jLabel24.setText("scale:");
spinnerScale.setModel(new javax.swing.SpinnerNumberModel(100, 1, 999, 1));
jLabel25.setText("%)");
jLabel26.setText("Maximum brush size:");
spinnerBrushSize.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(300), Integer.valueOf(100), null, Integer.valueOf(10)));
jLabel27.setFont(jLabel27.getFont().deriveFont((jLabel27.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel27.setText("Warning: large brush sizes could slow your computer to a crawl! ");
checkBoxCircular.setText("Circular world");
checkBoxCircular.addActionListener(this::checkBoxCircularActionPerformed);
checkBoxExtendedBlockIds.setText("Extended block ID's");
jLabel17.setFont(jLabel17.getFont().deriveFont((jLabel17.getFont().getStyle() | java.awt.Font.ITALIC)));
jLabel17.setText("Default export settings");
checkBoxChestOfGoodies.setText("Include chest of goodies");
jLabel28.setText("World type:");
comboBoxWorldType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Default", "Superflat", "Large Biomes" }));
comboBoxWorldType.addActionListener(this::comboBoxWorldTypeActionPerformed);
buttonModePreset.setText("...");
buttonModePreset.addActionListener(this::buttonModePresetActionPerformed);
checkBoxStructures.setText("Structures");
jLabel29.setText("Mode:");
comboBoxMode.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Survival", "Creative", "Adventure" }));
comboBoxMode.addActionListener(this::comboBoxModeActionPerformed);
checkBoxCheats.setText("Allow Cheats");
jLabel30.setText("Visual theme:");
comboBoxLookAndFeel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "System", "Metal", "Nimbus", "Dark Metal", "Dark Nimbus" }));
jLabel32.setText("<html><em>Effective after restart </em></html>");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel18))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addComponent(jSeparator2)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelTerrainAndLayerSettings, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonReset))
.addComponent(jSeparator1)
.addComponent(jSeparator5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(checkBoxChestOfGoodies)
.addGap(18, 18, 18)
.addComponent(jLabel28)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxWorldType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonModePreset)
.addGap(18, 18, 18)
.addComponent(checkBoxStructures)
.addGap(18, 18, 18)
.addComponent(jLabel29)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBoxCheats))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jLabel19)
.addGap(18, 18, 18)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(radioButtonHilly)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerRange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel24)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(radioButtonFlat))
.addComponent(jLabel6)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerGrid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(checkBoxGrid))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxContours)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerContours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxWalkingDistance)
.addComponent(checkBoxViewDistance))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel26)
.addGap(6, 6, 6)
.addComponent(spinnerBrushSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxLightDirection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel27)))
.addComponent(jLabel9)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(checkBoxCircular)
.addGap(18, 18, 18)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerGroundLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerWaterLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(checkBoxLava)
.addGap(18, 18, 18)
.addComponent(checkBoxBeaches))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxSurfaceMaterial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(checkBoxExtendedBlockIds))
.addComponent(jLabel2)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxPing)
.addComponent(checkBoxCheckForUpdates)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel20)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerWorldBackups, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel30)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboBoxLookAndFeel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(jLabel17))
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18)
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(checkBoxGrid)
.addComponent(checkBoxContours)
.addComponent(checkBoxViewDistance)
.addComponent(jLabel22)
.addComponent(comboBoxLightDirection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(spinnerGrid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(spinnerContours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxWalkingDistance)
.addComponent(jLabel21)
.addComponent(jLabel26)
.addComponent(spinnerBrushSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel27)
.addGap(18, 18, 18)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(spinnerWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(spinnerHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12)
.addComponent(comboBoxHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addComponent(radioButtonHilly)
.addComponent(radioButtonFlat)
.addComponent(jLabel19)
.addComponent(jLabel23)
.addComponent(spinnerRange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24)
.addComponent(spinnerScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel25))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(spinnerGroundLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15)
.addComponent(spinnerWaterLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxLava)
.addComponent(checkBoxBeaches)
.addComponent(checkBoxCircular))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(comboBoxSurfaceMaterial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxExtendedBlockIds))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelTerrainAndLayerSettings, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonReset))
.addGap(18, 18, 18)
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(checkBoxChestOfGoodies)
.addComponent(jLabel28)
.addComponent(comboBoxWorldType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonModePreset)
.addComponent(checkBoxStructures)
.addComponent(jLabel29)
.addComponent(comboBoxMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxCheats))
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(checkBoxPing)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(checkBoxCheckForUpdates))
.addComponent(jSeparator4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(spinnerWorldBackups, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel30)
.addComponent(comboBoxLookAndFeel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("General", jPanel1);
checkBoxUndo.setSelected(true);
checkBoxUndo.setText("Enable undo");
checkBoxUndo.addActionListener(this::checkBoxUndoActionPerformed);
jLabel5.setLabelFor(spinnerUndoLevels);
jLabel5.setText("Undo levels:");
spinnerUndoLevels.setModel(new javax.swing.SpinnerNumberModel(25, 1, 999, 1));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Hardware Acceleration"));
jLabel31.setText("Select a method of hardware accelerated painting. Experiment with this to improve the general editor performance:");
buttonGroup2.add(radioButtonAccelDefault);
radioButtonAccelDefault.setText("Default");
buttonGroup2.add(radioButtonAccelDirect3D);
radioButtonAccelDirect3D.setText("Direct3D");
buttonGroup2.add(radioButtonAccelOpenGL);
radioButtonAccelOpenGL.setText("OpenGL");
buttonGroup2.add(radioButtonAccelQuartz);
radioButtonAccelQuartz.setText("Quartz");
buttonGroup2.add(radioButtonAccelXRender);
radioButtonAccelXRender.setText("XRender");
buttonGroup2.add(radioButtonAccelUnaccelerated);
radioButtonAccelUnaccelerated.setText("Unaccelerated");
jLabel33.setText("Disable all hardware acceleration");
jLabel34.setText("Uses the XRender X11 extension on Linux");
jLabel36.setText("<html><em>Effective after restart </em></html>");
jLabel37.setText("Uses the OpenGL rendering system ");
jLabel38.setText("Uses the Direct3D rendering system on Windows");
jLabel39.setText("Uses Java's default rendering settings");
jLabel35.setText("Uses Apple's Quartz rendering system on Mac OS X");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31)
.addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(radioButtonAccelUnaccelerated)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel34)
.addComponent(jLabel33)
.addComponent(jLabel35)
.addComponent(jLabel37)
.addComponent(jLabel38)
.addComponent(jLabel39)))
.addComponent(radioButtonAccelDirect3D)
.addComponent(radioButtonAccelDefault)
.addComponent(radioButtonAccelXRender)
.addComponent(radioButtonAccelQuartz)
.addComponent(radioButtonAccelOpenGL))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel31)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelDefault)
.addComponent(jLabel39))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelDirect3D)
.addComponent(jLabel38))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelOpenGL)
.addComponent(jLabel37))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelQuartz)
.addComponent(jLabel35))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelXRender)
.addComponent(jLabel34))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonAccelUnaccelerated)
.addComponent(jLabel33))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Overlay Scaling and Painting"));
jLabel40.setText("Select a method of overlay image scaling and painting. Experiment with this to improve overlay image performance:");
jLabel41.setText("<html><em>Effective after reload </em></html>");
buttonGroup3.add(radioButtonOverlayScaleOnLoad);
radioButtonOverlayScaleOnLoad.setText("Scale on load");
buttonGroup3.add(radioButtonOverlayOptimiseOnLoad);
radioButtonOverlayOptimiseOnLoad.setText("Optimise on load, scale on paint");
buttonGroup3.add(radioButtonOverlayScaleOnPaint);
radioButtonOverlayScaleOnPaint.setText("Scale on paint");
jLabel42.setText("Optimises the image when it is first loaded, but scales it when painting. Uses less memory.");
jLabel43.setText("Scales and optimises the image in memory when it is first loaded. Uses a lot of memory.");
jLabel44.setText("Does not optimise the image at all and scales it when painting. Uses least memory.");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel40)
.addComponent(jLabel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(radioButtonOverlayOptimiseOnLoad)
.addComponent(radioButtonOverlayScaleOnLoad)
.addComponent(radioButtonOverlayScaleOnPaint))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel44)
.addComponent(jLabel43)
.addComponent(jLabel42))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel40)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel41, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonOverlayScaleOnLoad)
.addComponent(jLabel43))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonOverlayOptimiseOnLoad)
.addComponent(jLabel42))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioButtonOverlayScaleOnPaint)
.addComponent(jLabel44))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxUndo)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerUndoLevels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(checkBoxUndo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(spinnerUndoLevels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Performance", jPanel2);
buttonCancel.setText("Cancel");
buttonCancel.addActionListener(this::buttonCancelActionPerformed);
buttonOK.setText("OK");
buttonOK.addActionListener(this::buttonOKActionPerformed);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(buttonOK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonCancel)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonCancel)
.addComponent(buttonOK))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
cancel();
}//GEN-LAST:event_buttonCancelActionPerformed
private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
ok();
}//GEN-LAST:event_buttonOKActionPerformed
private void checkBoxUndoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxUndoActionPerformed
setControlStates();
}//GEN-LAST:event_checkBoxUndoActionPerformed
private void labelTerrainAndLayerSettingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelTerrainAndLayerSettingsMouseClicked
editTerrainAndLayerSettings();
}//GEN-LAST:event_labelTerrainAndLayerSettingsMouseClicked
private void checkBoxPingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxPingActionPerformed
pingNotSet = false;
}//GEN-LAST:event_checkBoxPingActionPerformed
private void comboBoxHeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxHeightActionPerformed
int maxHeight = Integer.parseInt((String) comboBoxHeight.getSelectedItem());
int exp = (int) (Math.log(maxHeight) / Math.log(2));
if (exp != previousExp) {
previousExp = exp;
int terrainLevel = (Integer) spinnerGroundLevel.getValue();
int waterLevel = (Integer) spinnerWaterLevel.getValue();
if (terrainLevel >= maxHeight) {
spinnerGroundLevel.setValue(maxHeight - 1);
}
if (waterLevel >= maxHeight) {
spinnerWaterLevel.setValue(maxHeight - 1);
}
((SpinnerNumberModel) spinnerGroundLevel.getModel()).setMaximum(maxHeight - 1);
((SpinnerNumberModel) spinnerWaterLevel.getModel()).setMaximum(maxHeight - 1);
int range = (Integer) spinnerRange.getValue();
if (range >= maxHeight) {
spinnerRange.setValue(maxHeight - 1);
}
((SpinnerNumberModel) spinnerRange.getModel()).setMaximum(maxHeight - 1);
setControlStates();
}
}//GEN-LAST:event_comboBoxHeightActionPerformed
private void spinnerWaterLevelStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerWaterLevelStateChanged
int waterLevel = ((Number) spinnerWaterLevel.getValue()).intValue();
Dimension defaults = Configuration.getInstance().getDefaultTerrainAndLayerSettings();
defaults.setBorderLevel(waterLevel);
TileFactory tileFactory = defaults.getTileFactory();
if (tileFactory instanceof HeightMapTileFactory) {
((HeightMapTileFactory) tileFactory).setWaterHeight(waterLevel);
}
}//GEN-LAST:event_spinnerWaterLevelStateChanged
private void checkBoxBeachesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxBeachesActionPerformed
TileFactory tileFactory = Configuration.getInstance().getDefaultTerrainAndLayerSettings().getTileFactory();
if (tileFactory instanceof HeightMapTileFactory) {
((HeightMapTileFactory) tileFactory).setBeaches(checkBoxBeaches.isSelected());
}
}//GEN-LAST:event_checkBoxBeachesActionPerformed
private void comboBoxSurfaceMaterialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxSurfaceMaterialActionPerformed
// Update the terrain ranges map to conform to the surface material
// setting
Configuration config = Configuration.getInstance();
Dimension defaultSettings = config.getDefaultTerrainAndLayerSettings();
TileFactory tileFactory = defaultSettings.getTileFactory();
if ((tileFactory instanceof HeightMapTileFactory)
&& (((HeightMapTileFactory) tileFactory).getTheme() instanceof SimpleTheme)) {
SortedMap<Integer, Terrain> defaultTerrainRanges = ((SimpleTheme) ((HeightMapTileFactory) tileFactory).getTheme()).getTerrainRanges();
// Find what is probably meant to be the surface material. With the
// default settings this should be -1, but if someone configured a
// default underwater material, try not to change that
int waterLevel = (Integer) spinnerWaterLevel.getValue();
int surfaceLevel = defaultTerrainRanges.headMap(waterLevel + 3).lastKey();
defaultTerrainRanges.put(surfaceLevel, (Terrain) comboBoxSurfaceMaterial.getSelectedItem());
}
}//GEN-LAST:event_comboBoxSurfaceMaterialActionPerformed
private void buttonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetActionPerformed
if (JOptionPane.showConfirmDialog(this, "Are you sure you want to reset all default world settings,\nincluding the border, terrain and layer settings, to the defaults?", "Confirm Reset", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
spinnerWidth.setValue(640);
spinnerHeight.setValue(640);
comboBoxHeight.setSelectedIndex(3);
radioButtonHilly.setSelected(true);
spinnerGroundLevel.setValue(58);
spinnerWaterLevel.setValue(62);
checkBoxLava.setSelected(false);
checkBoxBeaches.setSelected(true);
comboBoxSurfaceMaterial.setSelectedItem(GRASS);
Configuration.getInstance().setDefaultTerrainAndLayerSettings(new Dimension(World2.DEFAULT_OCEAN_SEED, TileFactoryFactory.createNoiseTileFactory(new Random().nextLong(), GRASS, DEFAULT_MAX_HEIGHT_2, 58, 62, false, true, 20, 1.0), DIM_NORMAL, DEFAULT_MAX_HEIGHT_2));
}
}//GEN-LAST:event_buttonResetActionPerformed
private void spinnerWidthStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerWidthStateChanged
int value = (Integer) spinnerWidth.getValue();
value = Math.round(value / 128f) * 128;
if (value < 128) {
value = 128;
}
spinnerWidth.setValue(value);
}//GEN-LAST:event_spinnerWidthStateChanged
private void spinnerHeightStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerHeightStateChanged
int value = (Integer) spinnerHeight.getValue();
value = Math.round(value / 128f) * 128;
if (value < 128) {
value = 128;
}
spinnerHeight.setValue(value);
}//GEN-LAST:event_spinnerHeightStateChanged
private void radioButtonHillyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioButtonHillyActionPerformed
setControlStates();
}//GEN-LAST:event_radioButtonHillyActionPerformed
private void radioButtonFlatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioButtonFlatActionPerformed
setControlStates();
}//GEN-LAST:event_radioButtonFlatActionPerformed
private void checkBoxCircularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxCircularActionPerformed
setControlStates();
}//GEN-LAST:event_checkBoxCircularActionPerformed
private void buttonModePresetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonModePresetActionPerformed
String editedGeneratorOptions = JOptionPane.showInputDialog(this, "Edit the Superflat mode preset:", generatorOptions);
if (editedGeneratorOptions != null) {
generatorOptions = editedGeneratorOptions;
}
}//GEN-LAST:event_buttonModePresetActionPerformed
private void comboBoxWorldTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxWorldTypeActionPerformed
setControlStates();
}//GEN-LAST:event_comboBoxWorldTypeActionPerformed
private void comboBoxModeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxModeActionPerformed
if (comboBoxMode.getSelectedIndex() > 0) {
checkBoxCheats.setSelected(true);
}
}//GEN-LAST:event_comboBoxModeActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonCancel;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JButton buttonModePreset;
private javax.swing.JButton buttonOK;
private javax.swing.JButton buttonReset;
private javax.swing.JCheckBox checkBoxBeaches;
private javax.swing.JCheckBox checkBoxCheats;
private javax.swing.JCheckBox checkBoxCheckForUpdates;
private javax.swing.JCheckBox checkBoxChestOfGoodies;
private javax.swing.JCheckBox checkBoxCircular;
private javax.swing.JCheckBox checkBoxContours;
private javax.swing.JCheckBox checkBoxExtendedBlockIds;
private javax.swing.JCheckBox checkBoxGrid;
private javax.swing.JCheckBox checkBoxLava;
private javax.swing.JCheckBox checkBoxPing;
private javax.swing.JCheckBox checkBoxStructures;
private javax.swing.JCheckBox checkBoxUndo;
private javax.swing.JCheckBox checkBoxViewDistance;
private javax.swing.JCheckBox checkBoxWalkingDistance;
private javax.swing.JComboBox comboBoxHeight;
private javax.swing.JComboBox comboBoxLightDirection;
private javax.swing.JComboBox comboBoxLookAndFeel;
private javax.swing.JComboBox comboBoxMode;
private javax.swing.JComboBox comboBoxSurfaceMaterial;
private javax.swing.JComboBox comboBoxWorldType;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel38;
private javax.swing.JLabel jLabel39;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel40;
private javax.swing.JLabel jLabel41;
private javax.swing.JLabel jLabel42;
private javax.swing.JLabel jLabel43;
private javax.swing.JLabel jLabel44;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel labelTerrainAndLayerSettings;
private javax.swing.JRadioButton radioButtonAccelDefault;
private javax.swing.JRadioButton radioButtonAccelDirect3D;
private javax.swing.JRadioButton radioButtonAccelOpenGL;
private javax.swing.JRadioButton radioButtonAccelQuartz;
private javax.swing.JRadioButton radioButtonAccelUnaccelerated;
private javax.swing.JRadioButton radioButtonAccelXRender;
private javax.swing.JRadioButton radioButtonFlat;
private javax.swing.JRadioButton radioButtonHilly;
private javax.swing.JRadioButton radioButtonOverlayOptimiseOnLoad;
private javax.swing.JRadioButton radioButtonOverlayScaleOnLoad;
private javax.swing.JRadioButton radioButtonOverlayScaleOnPaint;
private javax.swing.JSpinner spinnerBrushSize;
private javax.swing.JSpinner spinnerContours;
private javax.swing.JSpinner spinnerGrid;
private javax.swing.JSpinner spinnerGroundLevel;
private javax.swing.JSpinner spinnerHeight;
private javax.swing.JSpinner spinnerRange;
private javax.swing.JSpinner spinnerScale;
private javax.swing.JSpinner spinnerUndoLevels;
private javax.swing.JSpinner spinnerWaterLevel;
private javax.swing.JSpinner spinnerWidth;
private javax.swing.JSpinner spinnerWorldBackups;
// End of variables declaration//GEN-END:variables
private final ColourScheme colourScheme;
private boolean pingNotSet, cancelled = true;
private int previousExp;
private String generatorOptions;
private static final long serialVersionUID = 1L;
} | forairan/WorldPainter | WorldPainter/WPGUI/src/main/java/org/pepsoft/worldpainter/PreferencesDialog.java | Java | gpl-3.0 | 78,028 |
package elcon.mods.elconqore;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
public class EQConfig {
public static final String CATEGORY_GENERAL = "general";
public static final String CATEGORY_VERSION = "version";
public static final String CATEGORY_BLOCK = "block";
public static final String CATEGORY_ITEM = "item";
public Configuration config;
public boolean displayVersionResult = true;
public String lastDiscoveredVersion = "";
public String lastDiscoveredVersionType = "";
public static int BLOCK_OVERLAY_RENDER_ID;
public static int BLOCK_FLUID_RENDER_ID;
public EQConfig(Configuration config) {
this.config = config;
}
public EQConfig(File config) {
this(new Configuration(config));
}
public void load() {
config.load();
}
public void save() {
config.save();
}
public Property get(String category, String key) {
if(config.getCategoryNames().contains(category)) {
if(config.getCategory(category).containsKey(category)) {
return config.getCategory(category).get(key);
}
}
return null;
}
public void set(String category, String key, String value) {
if(config.getCategoryNames().contains(category)) {
if(config.getCategory(category).containsKey(category)) {
config.getCategory(category).get(key).set(value);
}
} else {
config.get(category, key, value);
}
config.save();
}
public void set(String category, String key, boolean value) {
if(config.getCategoryNames().contains(category)) {
if(config.getCategory(category).containsKey(category)) {
config.getCategory(category).get(key).set(value);
}
} else {
config.get(category, key, value);
}
config.save();
}
public void set(String category, String key, int value) {
if(config.getCategoryNames().contains(category)) {
if(config.getCategory(category).containsKey(category)) {
config.getCategory(category).get(key).set(value);
}
} else {
config.get(category, key, value);
}
config.save();
}
public void set(String category, String key, double value) {
if(config.getCategoryNames().contains(category)) {
if(config.getCategory(category).containsKey(category)) {
config.getCategory(category).get(key).set(value);
}
} else {
config.get(category, key, value);
}
config.save();
}
}
| ElConquistador/ElConQore | src/main/java/elcon/mods/elconqore/EQConfig.java | Java | gpl-3.0 | 2,369 |
/**********************************************************************
* FILE : BaseEntity.java
* CREATE DATE : Jan 5, 2009
* DESCRIPTION :
* 所有数据库记录对象的基类
* CHANGE HISTORY LOG
*---------------------------------------------------------------------
* NO.| DATE | NAME | REASON | DESCRIPTION
*---------------------------------------------------------------------
* 1 2009-1-5 LiuYanLu Draft Create
**********************************************************************
*/
package itaf.framework.core.domain;
import java.io.Serializable;
/**
* An entity is a java object represents a row data of data store.
* <p>
* This class defines a property "id" with {@link java.lang.Long} type for
* holding a primary key of data row.
*
* @author Danne
*
*/
public abstract class BaseEntity extends BaseObjectEntity implements Serializable {
private static final long serialVersionUID = 4327325007976895036L;
public abstract Long getId();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
return true;
}
}
| zpxocivuby/freetong_mobile_server | itaf-aggregator/itaf-core/src/main/java/itaf/framework/core/domain/BaseEntity.java | Java | gpl-3.0 | 1,553 |
package engine.event;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright by michidk
* Created: 25.12.2014.
*/
public class EventManager {
private static List<Listener> listeners = new ArrayList<>();
public static void callEvent(Event event) {
for (Listener listener : listeners) {
listener.onEvent(event);
}
}
public static void registerListener(Listener listener) {
listeners.add(listener);
}
public static void unregisterListener(Listener listener) {
listeners.remove(listener);
}
}
| johnkingjk/LowPolyEngine | src/main/java/engine/event/EventManager.java | Java | gpl-3.0 | 583 |
package com.invoicebinderhome.shared.model;
import com.google.gwt.user.client.rpc.IsSerializable;
public class ValidationResult implements IsSerializable {
private String message;
private String tagname;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTagname() {
return tagname;
}
public void setTagname(String tagname) {
this.tagname = tagname;
}
}
| mon2au/invoicebinder | invoicebinderhome/src/main/java/com/invoicebinderhome/shared/model/ValidationResult.java | Java | gpl-3.0 | 516 |
/*
* Copyright (C) 2009-2017 by the geOrchestra PSC
*
* This file is part of geOrchestra.
*
* geOrchestra 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.
*
* geOrchestra 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
* geOrchestra. If not, see <http://www.gnu.org/licenses/>.
*/
package org.georchestra.extractorapp.ws.extractor.csw;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* This class is responsible to maintain the metadata values in a file.
*
* @author Mauricio Pazos
*
*/
final class MetadataEntity {
protected static final Log LOG = LogFactory.getLog(MetadataEntity.class.getPackage().getName());
private CSWRequest request;
/**
* a new instance of {@link MetadataEntity}.
*
* @param cswRequest where the metadata is available
*/
private MetadataEntity(CSWRequest cswRequest) {
this.request = cswRequest;
}
/**
* Crates a new instance of {@link MetadataEntity}. Its values will be retrieved
* from the Catalog service specified in the request parameter.
*
* @param cswRequest where the metadata is available
*/
public static MetadataEntity create(final CSWRequest cswRequest) {
return new MetadataEntity(cswRequest);
}
/**
* Stores the metadata retrieved from CSW using the request value.
*
* @param fileName file name where the metadata must be saved.
*
* @throws IOException
*/
public void save(final String fileName) throws IOException {
InputStream content = null;
BufferedReader reader = null;
PrintWriter writer = null;
try {
writer = new PrintWriter( fileName, "UTF-8" );
HttpGet get = new HttpGet(this.request.buildURI() );
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext localContext = HttpClientContext.create();
// if credentials are actually provided, use them to configure
// the HttpClient object.
try {
if (this.request.getUser() != null && request.getPassword() != null) {
Credentials credentials = new UsernamePasswordCredentials(request.getUser(), request.getPassword());
AuthScope authScope = new AuthScope(get.getURI().getHost(), get.getURI().getPort());
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(authScope, credentials);
localContext.setCredentialsProvider(credentialsProvider);
}
} catch (Exception e) {
LOG.error("Unable to set basic-auth on http client to get the Metadata remotely, trying without ...", e);
}
content = httpclient.execute(get, localContext).getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(content));
String line = reader.readLine();
while(line!=null){
writer.println(line);
line=reader.readLine();
}
} catch (Exception e ){
final String msg = "The metadata could not be extracted";
LOG.error(msg, e);
throw new IOException(e);
} finally {
if(writer != null) writer.close();
if(reader != null) reader.close();
if( content != null ) content.close();
}
}
}
| MSHE-Ledoux/georchestra-geosync | extractorapp/src/main/java/org/georchestra/extractorapp/ws/extractor/csw/MetadataEntity.java | Java | gpl-3.0 | 4,593 |
package pt.utl.ist.marc.iso2709;
import org.apache.log4j.Logger;
import pt.utl.ist.characters.CharacterConverterI;
import pt.utl.ist.marc.Field;
import pt.utl.ist.marc.Record;
import pt.utl.ist.marc.Subfield;
import pt.utl.ist.marc.util.Leader;
import java.util.ArrayList;
import java.util.List;
class ISOHandler implements MARCHandler {
private static final Logger log = Logger.getLogger(ISOHandler.class);
CharacterConverterI charConverter = null;
protected Record rec;
private Field dataField;
public List<Record> records;
public ISOHandler() {
}
public ISOHandler(CharacterConverterI charConverter) {
this.charConverter = charConverter;
}
public void startTape() {
records = new ArrayList<Record>();
}
public void endTape() {
}
public void startRecord(Leader leader) {
rec = new Record();
rec.setLeader(getString(leader.getSerializedForm()));
}
public void endRecord() {
records.add(rec);
}
public void controlField(String tag, String chars) {
Field fld = rec.addField(Integer.parseInt(tag));
fld.setValue(getString(chars));
if (tag.equals("001")) {
try {
rec.setNc(fld.getValue());
} catch (NumberFormatException e) {//just ignore...
}
}
}
public void startDataField(String tag, char ind1, char ind2) {
try {
short tagInt = Short.parseShort(tag);
dataField = rec.addField(tagInt);
dataField.setInd1(ind1);
dataField.setInd2(ind2);
} catch (NumberFormatException e) {
dataField = rec.addField(999);
dataField.setInd1(ind1);
dataField.setInd2(ind2);
}
}
public void endDataField(String tag) {
// rec.getFields().add(dataField);
}
public void subfield(char code, String chars) {
Subfield sfld = new Subfield(code, getString(chars));
dataField.getSubfields().add(sfld);
}
protected String getString(String string) {
if (charConverter != null)
return charConverter.convert(string);
return string;
}
} | repoxIST/repoxLight | repox-core/src/main/java/pt/utl/ist/marc/iso2709/ISOHandler.java | Java | gpl-3.0 | 2,208 |
/*
* Copyright (C) 2011 SeqWare
*
* 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 net.sourceforge.seqware.webservice.resources.filters;
import net.sourceforge.seqware.webservice.resources.AbstractResourceTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author mtaschuk
*/
public class WorkflowTestsFilterTest extends AbstractResourceTest {
private final Logger logger = LoggerFactory.getLogger(WorkflowTestsFilterTest.class);
String workflowId;
public WorkflowTestsFilterTest() {
super("/workflows/1/tests");
workflowId = "1";
}
@Override
public void testGet() {
System.out.println(getRelativeURI() + " GET");
// try {
// Assert.assertTrue(resource.get().getText().contains("GET all tests from " + workflowId));
// } catch (Exception e) {
// Assert.fail(e.getMessage());
// logger.error("WorkflowTestsFilterTest.testGet exception:",e);
// }
}
@Override
public void testPut() {
System.out.println(getRelativeURI() + " PUT");
// try {
// resource.put(null).write(System.out);
// Assert.fail("No PUT on " + getRelativeURI());
// } catch (Exception e) {
// Assert.assertEquals("Method Not Allowed", e.getMessage());
// }
}
@Override
public void testPost() {
System.out.println(getRelativeURI() + " POST");
// try {
// StringRepresentation myString = new StringRepresentation("Test test test");
// Assert.assertTrue(resource.post(myString).getText().contains("POST test Test test test"));
// } catch (Exception e) {
// Assert.fail(e.getMessage());
// logger.error("WorkflowTestsFilterTest.testPost exception:",e);
// }
}
// @Override
@Override
public void testDelete() {
System.out.println(getRelativeURI() + " DELETE");
// try {
// resource.delete().write(System.out);
// Assert.fail("No DELETE on " + getRelativeURI());
// } catch (Exception e) {
// Assert.assertEquals("Method Not Allowed", e.getMessage());
// }
}
}
| oicr-gsi/niassa | seqware-webservice/src/test/java/net/sourceforge/seqware/webservice/resources/filters/WorkflowTestsFilterTest.java | Java | gpl-3.0 | 2,778 |
package com.google.analytics.tracking.android;
public abstract interface f
{
public abstract void a();
public abstract void b();
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.google.analytics.tracking.android.f
* JD-Core Version: 0.6.2
*/ | isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/google/analytics/tracking/android/f.java | Java | gpl-3.0 | 276 |
package gui.main.mouse;
/**
* MIDIPlayer
*
* @author Jhon Jairo Eslava
* @code 1310012946
*
*/
import gui.main.Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Load the "Load" frame
*
*/
public class LoadList implements ActionListener {
private Controller controller;
public LoadList(Controller controller) {
super();
this.controller = controller;
}
public void actionPerformed(ActionEvent e) {
new gui.load.Controller(this.controller);
}
}
| JhonPolitecnico/Proyectos-2014 | MIDIPlayer/src/gui/main/mouse/LoadList.java | Java | gpl-3.0 | 512 |
/*
* 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/>.
*/
/*
* ClearCallableDisplayTest.java
* Copyright (C) 2011-2014 University of Waikato, Hamilton, New Zealand
*/
package adams.flow.control;
import junit.framework.Test;
import junit.framework.TestSuite;
import adams.core.option.AbstractArgumentOption;
import adams.data.DecimalFormatString;
import adams.env.Environment;
import adams.flow.AbstractFlowTest;
import adams.flow.core.AbstractActor;
/**
* Test for ClearCallableDisplay actor.
*
* @author fracpete
* @author adams.core.option.FlowJUnitTestProducer (code generator)
* @version $Revision: 8896 $
*/
public class ClearCallableDisplayTest
extends AbstractFlowTest {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public ClearCallableDisplayTest(String name) {
super(name);
}
/**
*
* Returns a test suite.
*
* @return the test suite
*/
public static Test suite() {
return new TestSuite(ClearCallableDisplayTest.class);
}
/**
* Used to create an instance of a specific actor.
*
* @return a suitably configured <code>AbstractActor</code> value
*/
@Override
public AbstractActor getActor() {
AbstractArgumentOption argOption;
Flow flow = new Flow();
try {
argOption = (AbstractArgumentOption) flow.getOptionManager().findByProperty("actors");
adams.flow.core.AbstractActor[] tmp1 = new adams.flow.core.AbstractActor[4];
adams.flow.standalone.CallableActors tmp2 = new adams.flow.standalone.CallableActors();
argOption = (AbstractArgumentOption) tmp2.getOptionManager().findByProperty("actors");
adams.flow.core.AbstractActor[] tmp3 = new adams.flow.core.AbstractActor[1];
adams.flow.sink.SequencePlotter tmp4 = new adams.flow.sink.SequencePlotter();
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("writer");
adams.gui.print.NullWriter tmp6 = new adams.gui.print.NullWriter();
tmp4.setWriter(tmp6);
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("paintlet");
adams.gui.visualization.sequence.StickPaintlet tmp8 = new adams.gui.visualization.sequence.StickPaintlet();
tmp4.setPaintlet(tmp8);
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("markerPaintlet");
adams.flow.sink.sequenceplotter.NoMarkers tmp10 = new adams.flow.sink.sequenceplotter.NoMarkers();
tmp4.setMarkerPaintlet(tmp10);
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("colorProvider");
adams.gui.visualization.core.DefaultColorProvider tmp12 = new adams.gui.visualization.core.DefaultColorProvider();
tmp4.setColorProvider(tmp12);
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("axisX");
adams.gui.visualization.core.AxisPanelOptions tmp14 = new adams.gui.visualization.core.AxisPanelOptions();
argOption = (AbstractArgumentOption) tmp14.getOptionManager().findByProperty("label");
tmp14.setLabel((java.lang.String) argOption.valueOf("x"));
argOption = (AbstractArgumentOption) tmp14.getOptionManager().findByProperty("width");
tmp14.setWidth((Integer) argOption.valueOf("40"));
argOption = (AbstractArgumentOption) tmp14.getOptionManager().findByProperty("customFormat");
tmp14.setCustomFormat(new DecimalFormatString("0.000"));
tmp4.setAxisX(tmp14);
argOption = (AbstractArgumentOption) tmp4.getOptionManager().findByProperty("axisY");
adams.gui.visualization.core.AxisPanelOptions tmp19 = new adams.gui.visualization.core.AxisPanelOptions();
argOption = (AbstractArgumentOption) tmp19.getOptionManager().findByProperty("label");
tmp19.setLabel((java.lang.String) argOption.valueOf("y"));
argOption = (AbstractArgumentOption) tmp19.getOptionManager().findByProperty("width");
tmp19.setWidth((Integer) argOption.valueOf("40"));
argOption = (AbstractArgumentOption) tmp19.getOptionManager().findByProperty("customFormat");
tmp19.setCustomFormat(new DecimalFormatString("0.0"));
tmp4.setAxisY(tmp19);
tmp3[0] = tmp4;
tmp2.setActors(tmp3);
tmp1[0] = tmp2;
adams.flow.source.Start tmp24 = new adams.flow.source.Start();
tmp1[1] = tmp24;
adams.flow.control.Trigger tmp25 = new adams.flow.control.Trigger();
argOption = (AbstractArgumentOption) tmp25.getOptionManager().findByProperty("actors");
adams.flow.core.AbstractActor[] tmp26 = new adams.flow.core.AbstractActor[3];
adams.flow.source.ForLoop tmp27 = new adams.flow.source.ForLoop();
tmp26[0] = tmp27;
adams.flow.transformer.MakePlotContainer tmp28 = new adams.flow.transformer.MakePlotContainer();
tmp26[1] = tmp28;
adams.flow.sink.CallableSink tmp29 = new adams.flow.sink.CallableSink();
argOption = (AbstractArgumentOption) tmp29.getOptionManager().findByProperty("callableName");
tmp29.setCallableName((adams.flow.core.CallableActorReference) argOption.valueOf("SequencePlotter"));
tmp26[2] = tmp29;
tmp25.setActors(tmp26);
tmp1[2] = tmp25;
adams.flow.control.ClearCallableDisplay tmp31 = new adams.flow.control.ClearCallableDisplay();
argOption = (AbstractArgumentOption) tmp31.getOptionManager().findByProperty("callableName");
tmp31.setCallableName((adams.flow.core.CallableActorReference) argOption.valueOf("SequencePlotter"));
tmp1[3] = tmp31;
flow.setActors(tmp1);
}
catch (Exception e) {
fail("Failed to set up actor: " + e);
}
return flow;
}
/**
* Runs the test from commandline.
*
* @param args ignored
*/
public static void main(String[] args) {
Environment.setEnvironmentClass(adams.env.Environment.class);
runTest(suite());
}
}
| automenta/adams-core | src/test/java/adams/flow/control/ClearCallableDisplayTest.java | Java | gpl-3.0 | 6,475 |
package org.letsgo.cucumber;
import org.junit.runner.RunWith;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(plugin = "pretty", features = "src/test/features")
public class CucumberIT {
}
| Konstantin-Surzhin/letsgo | jhipster-blog/src/test/java/org/letsgo/cucumber/CucumberIT.java | Java | gpl-3.0 | 266 |
package ch.cyberduck.core.s3;
/*
* Copyright (c) 2002-2013 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to [email protected]
*/
import ch.cyberduck.core.Path;
import ch.cyberduck.core.exception.NotfoundException;
import ch.cyberduck.core.logging.LoggingConfiguration;
import ch.cyberduck.test.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.EnumSet;
import java.util.UUID;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class S3LoggingFeatureTest extends AbstractS3Test {
@Test
public void testGetConfiguration() throws Exception {
final S3LoggingFeature feature = new S3LoggingFeature(session);
final Path bucket = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
feature.setConfiguration(bucket, new LoggingConfiguration(true, "test-logging-us-east-1-cyberduck"));
final LoggingConfiguration configuration = feature.getConfiguration(bucket);
assertNotNull(configuration);
assertEquals("test-logging-us-east-1-cyberduck", configuration.getLoggingTarget());
assertTrue(configuration.isEnabled());
}
@Test(expected = NotfoundException.class)
public void testReadNotFound() throws Exception {
new S3LoggingFeature(session).getConfiguration(
new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory))
);
}
@Test(expected = NotfoundException.class)
public void testWriteNotFound() throws Exception {
new S3LoggingFeature(session).setConfiguration(
new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)), new LoggingConfiguration(false)
);
}
}
| iterate-ch/cyberduck | s3/src/test/java/ch/cyberduck/core/s3/S3LoggingFeatureTest.java | Java | gpl-3.0 | 2,334 |
/*
* Copyright (C) 2010-2021 JPEXS
*
* 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.sun.jna.platform.win32;
/**
*
* @author JPEXS
*/
/* Copyright (c) 2010 Daniel Doubrovkine, 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.
*/
import com.sun.jna.platform.win32.WinNT.HRESULT;
/**
* Win32 exception.
*
* @author dblock[at]dblock[dot]org
*/
public class Win32Exception extends RuntimeException {
private static final long serialVersionUID = 1L;
private HRESULT _hr;
/**
* Returns the error code of the error.
*
* @return Error code.
*/
public HRESULT getHR() {
return _hr;
}
/**
* New Win32 exception from HRESULT.
*
* @param hr HRESULT
*/
public Win32Exception(HRESULT hr) {
//super(Kernel32Util.formatMessageFromHR(hr));
_hr = hr;
}
/**
* New Win32 exception from an error code, usually obtained from
* GetLastError.
*
* @param code Error code.
*/
public Win32Exception(int code) {
this(W32Errors.HRESULT_FROM_WIN32(code));
}
}
| jindrapetrik/jpexs-decompiler | src/com/sun/jna/platform/win32/Win32Exception.java | Java | gpl-3.0 | 2,206 |
package com.nouveauxterritoires.web.slimy.acl.entities.pk;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
import com.nouveauxterritoires.web.slimy.acl.entities.Profiles;
import com.nouveauxterritoires.web.slimy.core.entities.Languages;
import com.nouveauxterritoires.web.slimy.core.entities.pk.PK;
@Embeddable
public class ProfilesLanguagesPk implements Serializable, PK {
private static final long serialVersionUID = -5565206615187133530L;
@ManyToOne
private Profiles profile;
@ManyToOne
private Languages language;
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProfilesLanguagesPk that = (ProfilesLanguagesPk) o;
if (profile != null ? !profile.equals(that.profile) : that.profile != null) return false;
if (language != null ? !language.equals(that.language) : that.language != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (profile != null ? profile.hashCode() : 0);
result = 31 * result + (language != null ? language.hashCode() : 0);
return result;
}
public Languages getLanguage() {
return language;
}
public void setLanguage(Languages language) {
this.language = language;
}
public Profiles getProfile() {
return profile;
}
public void setProfile(Profiles profile) {
this.profile = profile;
}
}
| teger/slimy | slimy-acl/src/main/java/com/nouveauxterritoires/web/slimy/acl/entities/pk/ProfilesLanguagesPk.java | Java | gpl-3.0 | 1,569 |
/*
* Copyright (C) Mojang AB
* All rights reserved.
*/
package kk.freecraft.util;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import kk.freecraft.inventory.IInventory;
import kk.freecraft.item.Item;
import kk.freecraft.item.ItemStack;
import kk.freecraft.tileentity.TileEntityDispenser;
public class WeightedRandomChestContent extends WeightedRandom.Item {
/**
* The Item/Block ID to generate in the Chest.
*/
private ItemStack theItemId;
/**
* The minimum chance of item generating.
*/
private int theMinimumChanceToGenerateItem;
/**
* The maximum chance of item generating.
*/
private int theMaximumChanceToGenerateItem;
public WeightedRandomChestContent(Item p_i45311_1_, int p_i45311_2_, int p_i45311_3_, int p_i45311_4_, int p_i45311_5_) {
super(p_i45311_5_);
this.theItemId = new ItemStack(p_i45311_1_, 1, p_i45311_2_);
this.theMinimumChanceToGenerateItem = p_i45311_3_;
this.theMaximumChanceToGenerateItem = p_i45311_4_;
}
public WeightedRandomChestContent(ItemStack p_i1558_1_, int p_i1558_2_, int p_i1558_3_, int p_i1558_4_) {
super(p_i1558_4_);
this.theItemId = p_i1558_1_;
this.theMinimumChanceToGenerateItem = p_i1558_2_;
this.theMaximumChanceToGenerateItem = p_i1558_3_;
}
public static void generateChestContents(Random p_177630_0_, List p_177630_1_, IInventory p_177630_2_, int p_177630_3_) {
for (int var4 = 0; var4 < p_177630_3_; ++var4) {
WeightedRandomChestContent var5 = (WeightedRandomChestContent) WeightedRandom.getRandomItem(p_177630_0_, p_177630_1_);
int var6 = var5.theMinimumChanceToGenerateItem + p_177630_0_.nextInt(var5.theMaximumChanceToGenerateItem - var5.theMinimumChanceToGenerateItem + 1);
if (var5.theItemId.getMaxStackSize() >= var6) {
ItemStack var7 = var5.theItemId.copy();
var7.stackSize = var6;
p_177630_2_.setInventorySlotContents(p_177630_0_.nextInt(p_177630_2_.getSizeInventory()), var7);
} else {
for (int var9 = 0; var9 < var6; ++var9) {
ItemStack var8 = var5.theItemId.copy();
var8.stackSize = 1;
p_177630_2_.setInventorySlotContents(p_177630_0_.nextInt(p_177630_2_.getSizeInventory()), var8);
}
}
}
}
public static void func_177631_a(Random p_177631_0_, List p_177631_1_, TileEntityDispenser p_177631_2_, int p_177631_3_) {
for (int var4 = 0; var4 < p_177631_3_; ++var4) {
WeightedRandomChestContent var5 = (WeightedRandomChestContent) WeightedRandom.getRandomItem(p_177631_0_, p_177631_1_);
int var6 = var5.theMinimumChanceToGenerateItem + p_177631_0_.nextInt(var5.theMaximumChanceToGenerateItem - var5.theMinimumChanceToGenerateItem + 1);
if (var5.theItemId.getMaxStackSize() >= var6) {
ItemStack var7 = var5.theItemId.copy();
var7.stackSize = var6;
p_177631_2_.setInventorySlotContents(p_177631_0_.nextInt(p_177631_2_.getSizeInventory()), var7);
} else {
for (int var9 = 0; var9 < var6; ++var9) {
ItemStack var8 = var5.theItemId.copy();
var8.stackSize = 1;
p_177631_2_.setInventorySlotContents(p_177631_0_.nextInt(p_177631_2_.getSizeInventory()), var8);
}
}
}
}
public static List func_177629_a(List p_177629_0_, WeightedRandomChestContent... p_177629_1_) {
ArrayList var2 = Lists.newArrayList(p_177629_0_);
Collections.addAll(var2, p_177629_1_);
return var2;
}
}
| KubaKaszycki/FreeCraft | src/main/java/kk/freecraft/util/WeightedRandomChestContent.java | Java | gpl-3.0 | 3,390 |
package com.yc.meituan.mapper;
import java.util.List;
import java.util.Map;
import com.yc.meituan.entity.GoodsInfo;
import com.yc.meituan.entity.SellerInfo;
import com.yc.meituan.entity.bean.EvaluateBean;
import com.yc.meituan.entity.bean.UorderBean;
import com.yc.meituan.web.bean.SellerGoodsBean;
public interface SellerInfoMapper {
SellerInfo login(SellerGoodsBean sellerGoodsBean);
// 商家后台显示商品信息
List<GoodsInfo> selectSBackShowGoods(int sid);
List<UorderBean> sListOrder(Map<String, Object> params);
void updateGoodsType(int gid);
// 商家后台显示商品详情信息
SellerGoodsBean getSGoodsInfosById(int gid);
// 更新商品信息(包括详情)
void modyfySGoodsinfos(SellerGoodsBean sellerGoodsBean);
void modyfySGoodsintros(SellerGoodsBean sellerGoodsBean);
//按密码显示订单详情
List<SellerGoodsBean> showOrderInfo(String opwd);
int useOrder(String opwd);
//显示历史销量
List<GoodsInfo> selectSumgsoldcount(int sid);
//显示评价
List<EvaluateBean> selectEvaluates(int sid);
List<SellerGoodsBean> getTotalSoldBySid(int sid);
Integer highUseCount(Map<String, Object> params);
} | JTR8655/Meituan | meituan/src/main/java/com/yc/meituan/mapper/SellerInfoMapper.java | Java | gpl-3.0 | 1,211 |
/*
* Copyright (C) 2014 Nick Schatz
*
* This file is part of Apocalyptic.
*
* Apocalyptic 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.
*
* Apocalyptic 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 Apocalyptic. If not, see <http://www.gnu.org/licenses/>.
*/
package net.cyberninjapiggy.apocalyptic.commands;
import net.cyberninjapiggy.apocalyptic.Apocalyptic;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.text.DecimalFormat;
/**
*
* @author Nick
*/
public class RadiationCommandExecutor implements CommandExecutor {
private final Apocalyptic a;
private final DecimalFormat fmt;
public RadiationCommandExecutor(Apocalyptic a) {
this.a = a;
fmt = new DecimalFormat("0.#");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if (cmd.getName().equalsIgnoreCase("radiation")) {
if (sender == a.getServer().getConsoleSender()) {
if (args.length == 0) {
sender.sendMessage("Cannot use this command and no arguments from console.");
}
if (args.length == 1) {
if (a.getServer().getPlayer(args[0]).isOnline()) {
sendRadiationMessage(sender, a.getRadiationManager().getPlayerRadiation(a.getServer().getPlayer(args[0])));
}
else {
sender.sendMessage("Cannot find player \"" + args[0] + "\"");
}
}
if (args.length == 2) {
if (a.getServer().getPlayer(args[0]).isOnline()) {
if (isNumeric(args[1])) {
sender.sendMessage("Set radiation");
a.getRadiationManager().setPlayerRadiation(a.getServer().getPlayer(args[0]), Double.parseDouble(args[1]));
}
else {
sender.sendMessage(args[1] + " is not a valid number.");
}
}
else {
sender.sendMessage("Cannot find player \"" + args[0] + "\"");
}
}
}
else {
if (args.length == 0 && a.canDoCommand(sender, "radiation.self")) {
sendRadiationMessage(sender, a.getRadiationManager().getPlayerRadiation((Player) sender));
}
if (args.length == 1 && a.canDoCommand(sender, "radiation.other")) {
if (a.getServer().getPlayer(args[0]).isOnline()) {
sendRadiationMessage(sender, a.getRadiationManager().getPlayerRadiation(a.getServer().getPlayer(args[0])));
}
else {
sender.sendMessage("Cannot find player \"" + args[0] + "\"");
}
}
if (args.length == 2 && a.canDoCommand(sender, "radiation.change")) {
if (a.getServer().getPlayer(args[0]).isOnline()) {
if (isNumeric(args[1])) {
sender.sendMessage("Set radiation");
a.getRadiationManager().setPlayerRadiation(a.getServer().getPlayer(args[0]), Double.parseDouble(args[1]));
}
else {
sender.sendMessage("" + args[1] + " is not a valid number.");
}
}
else {
sender.sendMessage("Cannot find player \"" + args[0] + "\"");
}
}
}
return true;
}
return false;
}
private static boolean isNumeric(String str) {return str.matches("-?\\d+(\\.\\d+)?");}
private void sendRadiationMessage(CommandSender s, double radiation) {
ChatColor color = ChatColor.GREEN;
if (radiation >= 0.8 && radiation < 1.0) {
color = ChatColor.YELLOW;
}
else if (radiation >= 1.0 && radiation < 5.0) {
color = ChatColor.RED;
}
else if (radiation >= 5.0 && radiation < 6.0) {
color = ChatColor.DARK_RED;
}
else if (radiation >= 6.0 && radiation < 9.0) {
color = ChatColor.LIGHT_PURPLE;
}
else if (radiation >= 9.0 && radiation < 10.0) {
color = ChatColor.DARK_PURPLE;
}
else if (radiation >= 10.0) {
color = ChatColor.BLACK;
}
s.sendMessage(color +""+ fmt.format(radiation) + " " + a.getMessages().getCaption("grays"));
}
}
| epicfacecreeper/Apocalyptic | src/main/java/net/cyberninjapiggy/apocalyptic/commands/RadiationCommandExecutor.java | Java | gpl-3.0 | 5,340 |
/*
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.redphone.directory;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import org.thoughtcrime.redphone.Constants;
import org.thoughtcrime.redphone.signaling.DirectoryResponse;
import org.thoughtcrime.redphone.signaling.SignalingException;
import org.thoughtcrime.redphone.signaling.SignalingSocket;
import org.thoughtcrime.redphone.util.PeriodicActionUtils;
/**
* A broadcast receiver that is responsible for scheduling and handling notifications
* for periodic directory update events.
*
* @author Moxie Marlinspike
*
*/
public class DirectoryUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
Log.w("DirectoryUpdateReceiver", "Initiating scheduled directory update...");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences.getBoolean(Constants.REGISTERED_PREFERENCE, false)) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
SignalingSocket signalingSocket = new SignalingSocket(context);
DirectoryResponse response = signalingSocket.getNumberFilter();
if (response != null) {
NumberFilter filter = new NumberFilter(response.getFilter(), response.getHashCount());
filter.serializeToFile(context);
}
} catch (SignalingException se) {
Log.w("DirectoryUpdateReceiver", se);
} catch (Exception e) {
Log.w("DirectoryUpdateReceiver", e);
}
return null;
}
}.execute();
PeriodicActionUtils.scheduleUpdate(context, DirectoryUpdateReceiver.class);
}
}
}
| rkolli1008/TalkSecure | src/org/thoughtcrime/redphone/directory/DirectoryUpdateReceiver.java | Java | gpl-3.0 | 2,665 |
/*
* Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre ([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 <https://www.gnu.org/licenses/>.
*/
package com.b3dgs.lionengine.graphic.engine;
import com.b3dgs.lionengine.Check;
import com.b3dgs.lionengine.Config;
import com.b3dgs.lionengine.Constant;
import com.b3dgs.lionengine.Resolution;
import com.b3dgs.lionengine.UtilMath;
import com.b3dgs.lionengine.graphic.Screen;
/**
* Frame skipping loop, prioritizing update over render in order to respect the expected frame rate.
* <p>
* Speed is always the same, but frames may be skipped during rendering in order to not be late on update.
* </p>
* <p>
* If update takes more time than expected frame rate, rendering is performed at a minimum rate.
* </p>
*/
public final class LoopFrameSkipping implements Loop
{
/** Nano to milli. */
static final long NANO_TO_MILLI = 1_000_000L;
/** Maximum frame time in nano. */
static final long MAX_FRAME_TIME_NANO = 250 * NANO_TO_MILLI;
/** Maximum expected frame rate. */
private static final int MAX_FRAME_RATE = 1000;
private static double computeFrameTime(int rate)
{
final double expectedRate;
if (rate == 0)
{
expectedRate = MAX_FRAME_RATE;
}
else
{
expectedRate = rate;
}
return Constant.ONE_SECOND_IN_MILLI / expectedRate * Constant.NANO_TO_MILLI;
}
/**
* Check if screen has sync locked.
*
* @param screen The screen reference.
* @return <code>true</code> if sync enabled, <code>false</code> else.
*/
private static boolean hasSync(Screen screen)
{
final Config config = screen.getConfig();
final Resolution output = config.getOutput();
return config.isWindowed() && output.getRate() > 0;
}
/** Extrapolation base. */
private final double extrp;
/** Running flag. */
private boolean isRunning;
/** Max frame time in nano. */
private double maxFrameTimeNano = -1.0;
/**
* Create loop.
*/
public LoopFrameSkipping()
{
super();
extrp = Constant.EXTRP;
}
/**
* Create loop.
*
* @param rateOriginal The original rate.
* @param rateDesired The desired rate.
*/
public LoopFrameSkipping(int rateOriginal, int rateDesired)
{
super();
if (rateOriginal == rateDesired)
{
extrp = Constant.EXTRP;
}
else
{
extrp = rateOriginal / (double) rateDesired;
}
maxFrameTimeNano = computeFrameTime(rateDesired);
}
/*
* Loop
*/
@Override
public void start(Screen screen, Frame frame)
{
Check.notNull(screen);
Check.notNull(frame);
final boolean sync = hasSync(screen);
if (maxFrameTimeNano < 0)
{
notifyRateChanged(screen.getConfig().getOutput().getRate());
}
long currentTimeNano = System.nanoTime();
double acc = 0.0;
isRunning = true;
while (isRunning)
{
if (screen.isReady())
{
final long firstTimeNano = System.nanoTime();
final long frameTimeNano = UtilMath.clamp(firstTimeNano - currentTimeNano, 0L, MAX_FRAME_TIME_NANO);
currentTimeNano = firstTimeNano;
acc += frameTimeNano;
do
{
frame.update(extrp);
acc -= maxFrameTimeNano;
}
while (acc > maxFrameTimeNano);
screen.preUpdate();
frame.render();
screen.update();
while (sync && System.nanoTime() - firstTimeNano < maxFrameTimeNano)
{
Thread.yield();
}
frame.computeFrameRate(firstTimeNano, Math.max(firstTimeNano + 1L, System.nanoTime()));
}
else
{
frame.check();
UtilSequence.pause(Constant.DECADE);
}
}
}
@Override
public void stop()
{
isRunning = false;
}
@Override
public void notifyRateChanged(int rate)
{
maxFrameTimeNano = computeFrameTime(rate);
}
}
| b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/engine/LoopFrameSkipping.java | Java | gpl-3.0 | 5,134 |
/*
* Copyright (C) 2017 phantombot.tv
*
* 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 me.mast3rplan.phantombot.event.gamewisp;
import me.mast3rplan.phantombot.event.Event;
import me.mast3rplan.phantombot.twitchwsirc.Channel;
public class GameWispEvent extends Event {
private final Channel channel;
protected GameWispEvent() {
this.channel = null;
}
protected GameWispEvent(Channel channel) {
this.channel = channel;
}
public Channel getChannel() {
return this.channel;
}
}
| MrAdder/PhantomBot | source/me/mast3rplan/phantombot/event/gamewisp/GameWispEvent.java | Java | gpl-3.0 | 1,146 |
/*
* AudioUtils.java
* Copyright (c) 2017
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import hcm.ssj.core.Log;
import hcm.ssj.file.FileCons;
/**
* Class that is responsible for decoding of audio files into a sequence of raw bytes.
* Bytes are represented in little-endian ordering.
* Supports and was tested with mp3, mp4, and wav files.
*/
public final class AudioDecoder
{
private static final int EOF = -1;
private int sampleRate;
private int channelCount;
private int audioLength;
private short[] samples;
public AudioDecoder(String filepath)
{
try
{
File rawAudio = decode(filepath);
samples = getAudioSample(rawAudio);
int sampleCount = samples.length;
audioLength = calculateAudioLength(sampleCount, sampleRate, channelCount);
}
catch (IOException e)
{
Log.e("Audio file with the given path couldn't be decoded: " + e.getMessage());
}
}
/**
* Calculates the length of the audio file in milliseconds.
* @param sampleCount Number of samples.
* @param sampleRate Sample rate (i.e. 16000, 44100, ..)
* @param channelCount Number of audio channels.
* @return length of audio file in seconds.
*/
private int calculateAudioLength(int sampleCount, int sampleRate, int channelCount)
{
return ((sampleCount / channelCount) * 1000) / sampleRate;
}
/**
* Converts given raw audio file to a byte array.
* @return Byte array in little-endian byte order.
* @throws IOException If given file couldn't be read.
*/
private short[] getAudioSample(File file) throws IOException
{
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int bytesRead = fileInputStream.read(data);
short[] samples = null;
if (bytesRead != EOF)
{
ShortBuffer sb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
samples = new short[sb.limit()];
sb.get(samples);
}
return samples;
}
public int getSampleRate()
{
return sampleRate;
}
public short[] getSamples()
{
return samples;
}
public int getAudioLength()
{
return audioLength;
}
/**
* Decodes audio file into a raw file. This method accepts audio file formats with valid
* headers (like .mp3, .mp4, and .wav).
* @param filepath Path of the file to decode.
* @return Decoded raw audio file.
* @throws IOException when file cannot be read.
*/
private File decode(String filepath) throws IOException
{
// Set selected audio file as a source.
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(filepath);
// Get audio format.
MediaFormat format = extractor.getTrackFormat(0);
String mime = format.getString(MediaFormat.KEY_MIME);
// Cache necessary audio attributes.
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
// Create and configure decoder based on audio format.
MediaCodec decoder = MediaCodec.createDecoderByType(mime);
decoder.configure(format, null, null, 0);
decoder.start();
// Create input/output buffers.
ByteBuffer[] inputBuffers = decoder.getInputBuffers();
ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
extractor.selectTrack(0);
File dst = new File(FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "output.raw");
FileOutputStream f = new FileOutputStream(dst);
boolean endOfStreamReached = false;
while (true)
{
if (!endOfStreamReached)
{
int inputBufferIndex = decoder.dequeueInputBuffer(10 * 1000);
if (inputBufferIndex >= 0)
{
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
int sampleSize = extractor.readSampleData(inputBuffer, 0);
if (sampleSize < 0)
{
// Pass empty buffer and the end of stream flag to the codec.
decoder.queueInputBuffer(inputBufferIndex, 0, 0,
0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
endOfStreamReached = true;
}
else
{
// Pass data-filled buffer to the decoder.
decoder.queueInputBuffer(inputBufferIndex, 0, sampleSize,
extractor.getSampleTime(), 0);
extractor.advance();
}
}
}
int outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 10 * 1000);
if (outputBufferIndex >= 0)
{
ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
byte[] data = new byte[bufferInfo.size];
outputBuffer.get(data);
outputBuffer.clear();
if (data.length > 0)
{
f.write(data, 0, data.length);
}
decoder.releaseOutputBuffer(outputBufferIndex, false);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
{
endOfStreamReached = true;
}
}
else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED)
{
outputBuffers = decoder.getOutputBuffers();
}
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
{
return dst;
}
}
}
}
| vitaly-krumins/ssj | libssj/src/main/java/hcm/ssj/audio/AudioDecoder.java | Java | gpl-3.0 | 6,573 |
package com.cloudera.server.web.cmf;
import com.cloudera.cmf.model.DbConfig;
import com.cloudera.cmf.model.DbService;
import com.cloudera.cmf.service.Validation;
import com.cloudera.cmf.service.ValidationCollection;
import com.cloudera.cmf.service.ValidationContext;
import com.cloudera.cmf.service.config.ParamSpec;
import com.cloudera.cmf.version.Release;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public abstract class AlertData
implements Comparable<AlertData>
{
protected HashMultimap<AlertItemType, AlertItemData> enabledAlertDescriptions;
protected HashMultimap<AlertItemType, AlertItemData> disabledAlertDescriptions;
private final String id;
public AlertData()
{
this.enabledAlertDescriptions = HashMultimap.create();
this.disabledAlertDescriptions = HashMultimap.create();
this.id = UUID.randomUUID().toString();
}
public abstract String getContextName();
public abstract String getConfigUrl();
public List<AlertItemData> getSortedDisabledAlertDescriptionsForType(AlertItemType type)
{
return sortDescriptions(this.disabledAlertDescriptions.get(type));
}
public List<AlertItemData> getSortedEnabledAlertDescriptionsForType(AlertItemType type)
{
return sortDescriptions(this.enabledAlertDescriptions.get(type));
}
public String getID()
{
return this.id;
}
public boolean isAlertableForType(AlertItemType type)
{
return (!this.enabledAlertDescriptions.get(type).isEmpty()) || (!this.disabledAlertDescriptions.get(type).isEmpty());
}
protected List<AlertItemData> sortDescriptions(Collection<AlertItemData> col)
{
List descList = Lists.newArrayList(col.iterator());
Collections.sort(descList);
return descList;
}
protected void writeBooleanConfigDescription(ParamSpec<Boolean> ps, ValidationContext context, AlertItemData aid, ValidationCollection allResourceValidations, AlertItemType type)
{
if (isParamSpecEnabled(ps, context, allResourceValidations))
this.enabledAlertDescriptions.put(type, aid);
else
this.disabledAlertDescriptions.put(type, aid);
}
private boolean isParamSpecEnabled(ParamSpec<Boolean> bps, ValidationContext context, ValidationCollection vc)
{
Validation v = vc.getSingleParamValidation(bps, context);
if ((v != null) && (v.getContext().getConfig() != null)) {
return Boolean.parseBoolean(v.getContext().getConfig().getValueCoercingNull());
}
DbService service = v.getContext().getService();
Release versionToCheck = service == null ? Release.NULL : service.getServiceVersion();
return Boolean.parseBoolean(v.getContext().getParamSpec().getDefaultValue(versionToCheck).toString());
}
public int compareTo(AlertData other)
{
if (other == null) {
return 1;
}
return getContextName().compareTo(other.getContextName());
}
public static enum AlertItemType
{
HEALTH,
LOG,
ACTIVITY;
}
} | Mapleroid/cm-server | server-5.11.0.src/com/cloudera/server/web/cmf/AlertData.java | Java | gpl-3.0 | 3,191 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2016, SCISYS UK Limited
*
* 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.sldeditor.test.unit.datasource.extension.filesystem.dataflavour;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import com.sldeditor.datasource.extension.filesystem.dataflavour.SLDDataFlavour;
import java.awt.datatransfer.DataFlavor;
import org.junit.jupiter.api.Test;
/**
* Unit test for SLDDataFlavour class.
*
* <p>{@link com.sldeditor.datasource.extension.filesystem.dataflavour.SLDDataFlavour}
*
* @author Robert Ward (SCISYS)
*/
public class SLDDataFlavourTest {
/**
* Test method for {@link
* com.sldeditor.datasource.extension.filesystem.dataflavour.SLDDataFlavour#SLDDataFlavour()}.
*/
@Test
public void testSLDDataFlavour() {
SLDDataFlavour actual1 = new SLDDataFlavour();
String mimeType = "application/json";
String humanPresentableName = "humanPresentableName";
ClassLoader classLoader = SLDDataFlavourTest.class.getClassLoader();
SLDDataFlavour actual2 = null;
try {
actual2 = new SLDDataFlavour(mimeType, humanPresentableName, classLoader);
} catch (ClassNotFoundException e) {
e.printStackTrace();
fail(e.getMessage());
}
SLDDataFlavour actual4 = null;
SLDDataFlavour actual4a = null;
try {
actual4 = new SLDDataFlavour(mimeType);
actual4a = new SLDDataFlavour(mimeType);
} catch (ClassNotFoundException e) {
e.printStackTrace();
fail(e.getMessage());
}
SLDDataFlavour actual5 = new SLDDataFlavour(getClass(), humanPresentableName);
SLDDataFlavour actual6 = new SLDDataFlavour(getClass(), humanPresentableName);
DataFlavor tmp = null;
assertFalse(actual1.equals(tmp));
assertFalse(actual1.equals(actual2));
assertTrue(actual5.equals(actual6));
assertTrue(actual4a.equals(actual4));
SLDDataFlavour actual3 = new SLDDataFlavour(mimeType, humanPresentableName);
SLDDataFlavour actual3a = new SLDDataFlavour(mimeType, humanPresentableName);
SLDDataFlavour actual3b = new SLDDataFlavour(mimeType, "different");
assertTrue(actual3a.equals(actual3));
assertFalse(actual3b.equals(actual3));
Object actual7 = new SLDDataFlavour(mimeType, humanPresentableName);
assertTrue(actual3.equals(actual7));
}
}
| robward-scisys/sldeditor | modules/application/src/test/java/com/sldeditor/test/unit/datasource/extension/filesystem/dataflavour/SLDDataFlavourTest.java | Java | gpl-3.0 | 3,245 |
/*******************************************************************************************************
*
* msi.gama.util.file.GamaFile.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and
* simulation platform (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gama.util.file;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.common.util.FileUtils;
import msi.gama.ext.webb.Webb;
import msi.gama.ext.webb.WebbException;
import msi.gama.metamodel.shape.ILocation;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.GamaListFactory;
import msi.gama.util.IAddressableContainer;
import msi.gama.util.IContainer;
import msi.gama.util.IList;
import msi.gama.util.IMap;
import msi.gama.util.IModifiableContainer;
import msi.gama.util.matrix.IMatrix;
import msi.gaml.expressions.IExpression;
import msi.gaml.operators.Cast;
import msi.gaml.statements.Facets;
import msi.gaml.types.IType;
import one.util.streamex.StreamEx;
/**
* Written by drogoul Modified on 7 août 2010
*
* @todo Description
*
*/
@SuppressWarnings ({ "rawtypes", "unchecked" })
public abstract class GamaFile<Container extends IAddressableContainer & IModifiableContainer, Contents>
implements IGamaFile<Container, Contents> {
private File file;
protected final String localPath;
protected final String originalPath;
protected final URL url;
protected boolean writable = false;
private Container buffer;
public GamaFile(final IScope scope, final String pn) throws GamaRuntimeException {
this(scope, pn, true);
}
protected GamaFile(final IScope scope, final String pn, final boolean forReading) throws GamaRuntimeException {
originalPath = pn;
String tempPath = originalPath;
if (originalPath == null) {
throw GamaRuntimeException.error("Attempt to " + (forReading ? "read" : "write") + " a null file", scope);
}
if (originalPath.startsWith("http")) {
url = buildURL(scope, originalPath);
} else {
url = null;
}
if (url != null) {
if (forReading) {
tempPath = FileUtils.constructAbsoluteFilePath(scope, fetchFromURL(scope), forReading);
if (tempPath == null) {
// We do not attempt to create the file. It will probably be taken in charge later directly from the
// URL or there has been an error trying to download it.
tempPath = "";
}
} else {
tempPath = FileUtils.constructAbsoluteTempFilePath(scope, url);
}
} else {
tempPath = FileUtils.constructAbsoluteFilePath(scope, originalPath, forReading);
}
localPath = tempPath;
checkValidity(scope);
}
public boolean isRemote() {
return url != null;
}
public GamaFile(final IScope scope, final String pathName, final Container container) {
this(scope, pathName, false);
setWritable(scope, true);
setContents(container);
}
@Override
public String getOriginalPath() {
return originalPath;
}
/**
* Whether or not passing an URL will automatically make GAMA cache its contents in a temp file. Should be redefined
* by GamaFiles that can retrieve from URL directly (like, e.g., GeoTools'datastore-backed files). If false, the url
* will be initialized, but the path will be set to the empty string and no attempt will be made to download data
* later. In that case, it is the responsibility of subclasses to use the url -- and NOT the path -- to download the
* contents of the file later (for example in fillBuffer()). The default is true.
*
* @return true or false depending on whether the contents should be cached in a temp file
*/
protected boolean automaticallyFetchFromURL() {
return true;
}
protected String fetchFromURL(final IScope scope) {
if (!automaticallyFetchFromURL()) { return null; }
return FileUtils.fetchToTempFile(scope, url);
}
protected void sendToURL(final IScope scope) throws GamaRuntimeException {
final String urlPath = url.toExternalForm();
final String status = "Uploading file to " + urlPath;
scope.getGui().getStatus(scope).beginSubStatus(status);
final Webb web = Webb.create();
try {
web.post(urlPath).ensureSuccess().connectTimeout(20000).retry(1, false)
.header(Webb.HDR_CONTENT_TYPE, getHttpContentType()).body(getFile(scope)).asVoid();
} catch (final WebbException e) {
throw GamaRuntimeException.create(e, scope);
} finally {
scope.getGui().getStatus(scope).endSubStatus(status);
}
}
/**
* The content type to use for uploading the contents of the file. see
* http://www.iana.org/assignments/media-types/media-types.xhtml
*
* @return
*/
protected String getHttpContentType() {
return "text/plain";
}
protected URL buildURL(final IScope scope, final String urlPath) throws GamaRuntimeException {
try {
return new URL(urlPath);
} catch (final MalformedURLException e1) {
throw GamaRuntimeException.error("Malformed URL " + urlPath, scope);
}
}
protected void checkValidity(final IScope scope) throws GamaRuntimeException {
if (getFile(scope).exists() && getFile(scope).isDirectory()) {
throw GamaRuntimeException
.error(getFile(scope).getAbsolutePath() + " is a folder. Files can not overwrite folders", scope);
}
}
@Override
public void setWritable(final IScope scope, final boolean w) {
writable = w;
}
protected void fillBuffer(final IScope scope) throws GamaRuntimeException {
throw GamaRuntimeException.error("Loading is not yet impletemented for files of type "
+ this.getExtension(scope) + ". Please post a request for enhancement to implement "
+ getClass().getSimpleName() + ".fillBuffer(IScope, Facets)", scope);
}
protected void flushBuffer(final IScope scope, final Facets facets) throws GamaRuntimeException {
throw GamaRuntimeException.error("Saving is not yet impletemented for files of type " + this.getExtension(scope)
+ ". Please post a request for enhancement to implement " + getClass().getSimpleName()
+ ".flushBuffer(IScope, Facets)", scope);
}
@Override
public final void setContents(final Container cont) throws GamaRuntimeException {
if (writable) {
setBuffer(cont);
}
}
protected String _stringValue(final IScope scope) throws GamaRuntimeException {
return getPath(scope);
}
// 09/01/14:Trying to keep the interface simple.
// Three methods for add and put operations:
// The simple method, that simply contains the object to add
@Override
public void addValue(final IScope scope, final Object value) {
fillBuffer(scope);
getBuffer().addValue(scope, value);
}
// The same but with an index (this index represents the old notion of
// parameter where it is needed.
@Override
public void addValueAtIndex(final IScope scope, final Object index, final Object value) {
fillBuffer(scope);
getBuffer().addValueAtIndex(scope, index, value);
}
// Put, that takes a mandatory index (also replaces the parameter)
@Override
public void setValueAtIndex(final IScope scope, final Object index, final Object value) {
fillBuffer(scope);
getBuffer().setValueAtIndex(scope, index, value);
}
// Then, methods for "all" operations
// Adds the values if possible, without replacing existing ones
@Override
public void addValues(final IScope scope, final Object index, final IContainer values) {
// Addition of the index (see #2985)
fillBuffer(scope);
getBuffer().addValues(scope, index, values);
}
// Adds this value to all slots (if this operation is available), otherwise
// replaces the values with this one
@Override
public void setAllValues(final IScope scope, final Object value) {
fillBuffer(scope);
getBuffer().setAllValues(scope, value);
}
@Override
public void removeValue(final IScope scope, final Object value) {
fillBuffer(scope);
getBuffer().removeValue(scope, value);
}
@Override
public void removeIndex(final IScope scope, final Object index) {
fillBuffer(scope);
getBuffer().removeIndex(scope, index);
}
@Override
public void removeValues(final IScope scope, final IContainer values) {
fillBuffer(scope);
getBuffer().removeValues(scope, values);
}
@Override
public void removeAllOccurrencesOfValue(final IScope scope, final Object value) {
fillBuffer(scope);
getBuffer().removeAllOccurrencesOfValue(scope, value);
}
@Override
public void removeIndexes(final IScope scope, final IContainer indexes) {
fillBuffer(scope);
getBuffer().removeIndexes(scope, indexes);
}
/*
* (non-Javadoc)
*
* @see msi.gama.interfaces.IGamaContainer#checkBounds(java.lang.Object, boolean)
*/
@Override
public boolean checkBounds(final IScope scope, final Object index, final boolean forAdding) {
getContents(scope);
return getBuffer().checkBounds(scope, index, forAdding);
}
/*
* (non-Javadoc)
*
* @see msi.gama.interfaces.IGamaContainer#contains(java.lang.Object)
*/
@Override
public boolean contains(final IScope scope, final Object o) throws GamaRuntimeException {
getContents(scope);
return getBuffer().contains(scope, o);
}
@Override
public IGamaFile copy(final IScope scope) {
// files are supposed to be immutable
return this;
}
@Override
public Boolean exists(final IScope scope) {
return getFile(scope).exists();
}
/*
* @see msi.gama.interfaces.IGamaContainer#first()
*/
@Override
public Contents firstValue(final IScope scope) throws GamaRuntimeException {
getContents(scope);
return (Contents) getBuffer().firstValue(scope);
}
/*
* @see msi.gama.interfaces.IGamaContainer#get(java.lang.Object)
*/
@Override
public Contents get(final IScope scope, final Object index) throws GamaRuntimeException {
getContents(scope);
return (Contents) getBuffer().get(scope, index);
}
@Override
public Contents getFromIndicesList(final IScope scope, final IList indices) throws GamaRuntimeException {
getContents(scope);
return (Contents) getBuffer().getFromIndicesList(scope, indices);
}
@Override
// @getter( IKeyword.EXTENSION)
public String getExtension(final IScope scope) {
// In order to avoid too many calls to the file system, we can safely consider that the extension of files
// remain the same between the urls, local paths and links to external paths
final String path = getOriginalPath().toLowerCase();
// final String path = getPath(scope).toLowerCase();
final int mid = path.lastIndexOf('.');
if (mid == -1) { return ""; }
return path.substring(mid + 1, path.length());
}
@Override
public String getName(final IScope scope) {
return getFile(scope).getName();
}
@Override
public String getPath(final IScope scope) {
return localPath;
}
@Override
public Container getContents(final IScope scope) throws GamaRuntimeException {
if (buffer == null && !exists(scope)) {
throw GamaRuntimeException.error("File " + getFile(scope).getAbsolutePath() + " does not exist", scope);
}
fillBuffer(scope);
return getBuffer();
}
@Override
public boolean isEmpty(final IScope scope) {
getContents(scope);
return getBuffer().isEmpty(scope);
}
@Override
public Boolean isFolder(final IScope scope) {
return getFile(scope).isDirectory();
}
@Override
public Boolean isReadable(final IScope scope) {
return getFile(scope).canRead();
}
@Override
public Boolean isWritable(final IScope scope) {
return getFile(scope).canWrite();
}
@Override
public java.lang.Iterable<? extends Contents> iterable(final IScope scope) {
return getContents(scope).iterable(scope);
}
@Override
public Contents lastValue(final IScope scope) throws GamaRuntimeException {
getContents(scope);
return (Contents) getBuffer().lastValue(scope);
}
@Override
public int length(final IScope scope) {
getContents(scope);
return getBuffer().length(scope);
}
@Override
public IList<Contents> listValue(final IScope scope, final IType contentsType, final boolean copy)
throws GamaRuntimeException {
getContents(scope);
return getBuffer().listValue(scope, contentsType, copy);
}
@Override
public StreamEx<Contents> stream(final IScope scope) {
getContents(scope);
return getBuffer().stream(scope);
}
@Override
public IMap<?, ?> mapValue(final IScope scope, final IType keyType, final IType contentsType, final boolean copy)
throws GamaRuntimeException {
getContents(scope);
return getBuffer().mapValue(scope, keyType, contentsType, copy);
}
@Override
public IMatrix<?> matrixValue(final IScope scope, final IType contentsType, final boolean copy)
throws GamaRuntimeException {
return matrixValue(scope, contentsType, null, copy);
}
@Override
public IMatrix<?> matrixValue(final IScope scope, final IType contentsType, final ILocation preferredSize,
final boolean copy) throws GamaRuntimeException {
return _matrixValue(scope, contentsType, preferredSize, copy);
}
protected IMatrix _matrixValue(final IScope scope, final IType contentsType, final ILocation preferredSize,
final boolean copy) throws GamaRuntimeException {
getContents(scope);
return getBuffer().matrixValue(scope, contentsType, preferredSize, copy);
}
@Override
public IContainer<?, ?> reverse(final IScope scope) throws GamaRuntimeException {
getContents(scope);
return getBuffer().reverse(scope);
// No side effect
}
@Override
public String stringValue(final IScope scope) throws GamaRuntimeException {
return _stringValue(scope);
}
@Override
public String serialize(final boolean includingBuiltIn) {
return "file('" + getPath(GAMA.getRuntimeScope()) + "')";
}
@Override
public Contents anyValue(final IScope scope) {
getContents(scope);
return (Contents) getBuffer().anyValue(scope);
}
public File getFile(final IScope scope) {
if (file == null) {
file = new File(getPath(scope));
}
return file;
}
@Override
public Container getBuffer() {
return buffer;
}
protected void setBuffer(final Container buffer) {
this.buffer = buffer;
}
public void invalidateContents() {
buffer = null;
}
@Override
public IList<String> getAttributes(final IScope scope) {
// TODO what to return ?
return GamaListFactory.EMPTY_LIST;
}
/**
* This method is being called from the save statement (see SaveStatement.java). The scope and all the facets
* declared in the save statement are passed as parameters, which allows the programmer to retrieve them (for
* instance, to get the crs for shape files, or the attributes to save from a list of agents, etc.). This method
* cannot be redefined. Instead, programmers should redefine flushBuffer(), which takes the same arguments
*/
@Override
public final void save(final IScope scope, final Facets saveFacets) {
// TODO AD
// Keep in mind that facets might contain a method for uploading (like method: #post) ?
// Keep in mind that facets might contain a content-type
// Keep in mind possible additional resources (shp additions)
final IExpression exp = saveFacets.getExpr(IKeyword.REWRITE);
final boolean overwrite = exp == null || Cast.asBool(scope, exp.value(scope));
if (overwrite && getFile(scope).exists()) {
getFile(scope).delete();
}
if (!writable) { throw GamaRuntimeException.error("File " + getName(scope) + " is not writable", scope); }
// This will save to the local file
flushBuffer(scope, saveFacets);
if (isRemote()) {
sendToURL(scope);
}
}
// protected void setPath(final String path) {
// this.localPath = path;
// }
}
| gama-platform/gama | msi.gama.core/src/msi/gama/util/file/GamaFile.java | Java | gpl-3.0 | 15,684 |
package com.amazonaws.ec2.doc._2008_12_01;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CreateKeyPairResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CreateKeyPairResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="requestId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="keyName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="keyFingerprint" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="keyMaterial" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreateKeyPairResponseType", propOrder = {
"requestId",
"keyName",
"keyFingerprint",
"keyMaterial"
})
public class CreateKeyPairResponseType {
@XmlElement(required = true)
protected String requestId;
@XmlElement(required = true)
protected String keyName;
@XmlElement(required = true)
protected String keyFingerprint;
@XmlElement(required = true)
protected String keyMaterial;
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
/**
* Gets the value of the keyName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeyName() {
return keyName;
}
/**
* Sets the value of the keyName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeyName(String value) {
this.keyName = value;
}
/**
* Gets the value of the keyFingerprint property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeyFingerprint() {
return keyFingerprint;
}
/**
* Sets the value of the keyFingerprint property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeyFingerprint(String value) {
this.keyFingerprint = value;
}
/**
* Gets the value of the keyMaterial property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeyMaterial() {
return keyMaterial;
}
/**
* Sets the value of the keyMaterial property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeyMaterial(String value) {
this.keyMaterial = value;
}
}
| rforge/biocep | src_aws_client/com/amazonaws/ec2/doc/_2008_12_01/CreateKeyPairResponseType.java | Java | gpl-3.0 | 3,605 |
package ch.cyberduck.core;
/*
* Copyright (c) 2002-2014 David Kocher. All rights reserved.
* http://cyberduck.io/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* [email protected]
*/
import ch.cyberduck.core.proxy.Proxy;
import ch.cyberduck.core.proxy.ProxyFinder;
import ch.cyberduck.core.proxy.ProxySocketFactory;
import ch.cyberduck.core.socket.DefaultSocketConfigurator;
import ch.cyberduck.core.socket.SocketConfigurator;
import ch.cyberduck.test.IntegrationTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class ProxySocketFactoryTest {
@Test
public void testCreateSocketNoProxy() throws Exception {
assertNotNull(new ProxySocketFactory(new Host(new TestProtocol(), "localhost")).createSocket("localhost", 22));
}
@Test(expected = SocketException.class)
public void testCreateSocketWithProxy() throws Exception {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost"), new DefaultSocketConfigurator(),
new ProxyFinder() {
@Override
public Proxy find(final String target) {
return new Proxy(Proxy.Type.SOCKS, "localhost", 7000);
}
}).createSocket();
assertNotNull(socket);
socket.connect(new InetSocketAddress("test.cyberduck.ch", 21));
}
@Test
public void testCreateSocketIPv6Localhost() throws Exception {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost")).createSocket("::1", 22);
assertNotNull(socket);
assertTrue(socket.getInetAddress() instanceof Inet6Address);
}
// IPv6 in the test environment
@Test
@Ignore
public void testConnectIPv6LocalAddress() throws Exception {
for(String address : Collections.singletonList("fe80::c62c:3ff:fe0b:8670")) {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost")).createSocket(address, 22);
assertNotNull(socket);
assertTrue(socket.getInetAddress() instanceof Inet6Address);
}
}
@Test(expected = SocketException.class)
public void testCreateSocketIPv6LocalAddressConnectionRefused() throws Exception {
for(String address : Collections.singletonList("fe80::9272:40ff:fe02:c363")) {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost")).createSocket(address, 22);
}
}
@Test
public void testCreateSocketDualStackGoogle() throws Exception {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost")).createSocket("ipv6test.google.com", 80);
assertNotNull(socket);
// We have set `java.net.preferIPv6Addresses` to `false` by default
assertTrue(socket.getInetAddress() instanceof Inet4Address);
}
// IPv6 in the test environment
@Test
@Ignore
public void testCreateSocketIPv6OnlyWithInetAddress() throws Exception {
for(String address : Collections.singletonList("ftp6.netbsd.org")) {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost"), new SocketConfigurator() {
@Override
public void configure(final Socket socket) throws IOException {
assertTrue(socket.getInetAddress() instanceof Inet6Address);
assertEquals(((Inet6Address) socket.getInetAddress()).getScopeId(),
((Inet6Address) InetAddress.getByName("::1%en0")).getScopedInterface().getIndex());
}
}).createSocket(address, 21);
assertNotNull(socket);
assertTrue(socket.getInetAddress() instanceof Inet6Address);
}
}
// IPv6 in the test environment
@Test
@Ignore
public void testCreateSocketIPv6OnlyUnknownDestination() throws Exception {
for(String address : Collections.singletonList("ftp6.netbsd.org")) {
final Socket socket = new ProxySocketFactory(new Host(new TestProtocol(), "localhost"), new SocketConfigurator() {
@Override
public void configure(final Socket socket) {
// Not yet connected
assertNull(socket.getInetAddress());
}
}).createSocket();
assertNotNull(socket);
assertNull(socket.getInetAddress());
socket.connect(new InetSocketAddress(address, 21), 0);
assertTrue(socket.getInetAddress() instanceof Inet6Address);
assertEquals(((Inet6Address) socket.getInetAddress()).getScopeId(),
((Inet6Address) InetAddress.getByName("::1%en0")).getScopedInterface().getIndex());
assertTrue(socket.getInetAddress() instanceof Inet6Address);
}
}
@Test
@Ignore
public void testSpecificNetworkInterfaceForIP6Address() throws Exception {
final InetAddress loopback = InetAddress.getByName("::1%en0");
assertNotNull(loopback);
assertTrue(loopback.isLoopbackAddress());
assertTrue(loopback instanceof Inet6Address);
assertEquals(NetworkInterface.getByName("en0").getIndex(),
((Inet6Address) loopback).getScopedInterface().getIndex());
}
// IPv6 in the test environment
@Test
@Ignore
public void testDefaultNetworkInterfaceForIP6Address() throws Exception {
assertEquals(InetAddress.getByName("::1"), InetAddress.getByName("::1%en0"));
// Bug. Defaults to awdl0 on OS X
assertEquals(((Inet6Address) InetAddress.getByName("::1")).getScopeId(),
((Inet6Address) InetAddress.getByName("::1%en0")).getScopeId());
}
@Test(expected = ConnectException.class)
@Ignore
public void testFixDefaultNetworkInterface() throws Exception {
final ProxySocketFactory factory = new ProxySocketFactory(new Host(new TestProtocol(), "localhost"));
assertEquals(
((Inet6Address) factory.createSocket("::1%en0", 80).getInetAddress()).getScopeId(),
((Inet6Address) factory.createSocket("::1", 80).getInetAddress()).getScopeId()
);
}
}
| iterate-ch/cyberduck | core/dylib/src/test/java/ch/cyberduck/core/ProxySocketFactoryTest.java | Java | gpl-3.0 | 7,192 |
/*
* Decompiled with CFR 0_115.
*/
package android.support.annotation;
import java.lang.annotation.Annotation;
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;
@Documented
@Retention(value=RetentionPolicy.CLASS)
@Target(value={ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.LOCAL_VARIABLE})
public @interface DrawableRes {
}
| SPACEDAC7/TrabajoFinalGrado | uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/android/support/annotation/DrawableRes.java | Java | gpl-3.0 | 509 |
package com.tmser.train.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;
import com.tmser.train.Constants;
import com.tmser.train.NetConnectException;
import com.tmser.train.ResManager;
import com.tmser.train.bean.TrainQueryInfo;
/**
* 查询车次信息
* @author tmser
*
*/
class SearchTrainInfoAction extends AbstractAction{
private static final long serialVersionUID = -798538352042404436L;
private RobTicket rob;
JRadioButton rbEnableProxy,rbDisableProxy;
JButton btnApply;
JDialog dialog;
JTable table;
JLabel imgLabel;
DefaultTableModel model;
protected SearchTrainInfoAction(RobTicket robTicket) {
this.rob = robTicket;
}
public void actionPerformed(ActionEvent e) {
if ("".equals(rob.getFromCity()) ||
"".equals(rob.getToCity())){
JOptionPane.showMessageDialog(rob.getFrame(),
ResManager.getString("RobTicket.SOptionPane"));
return;
}
createDiolag();
TrainQueryInfo trainInfo = new TrainQueryInfo();
trainInfo.setFromStationName(rob.getFromCity());
trainInfo.setToStationName(rob.getToCity());
trainInfo.setStartTime(rob.getStartDate());
trainInfo.setRangeDate(rob.getRangDate());
/* trainInfo.setTrainNo("T145");
trainInfo.setStartTime("11:00");
List<TrainQueryInfo> lst = new ArrayList<TrainQueryInfo>();
lst.add(trainInfo);
addTrainInfoColumn(lst);*/
queryTrainInfo(trainInfo);
dialog.setVisible(true);
}
void addTrainInfoColumn(List<TrainQueryInfo> lst ){
model.setRowCount(0);
for(TrainQueryInfo train : lst){
model.addRow(new Object[]{train.getStationTrainCode(),"<html>"+train.getFromStationName()+"<br/>"+train.getStartTime()+"</html>",
"<html>"+train.getToStationName()+"<br/>"+ train.getArriveTime()+"</html>",train.getLishi(),Boolean.FALSE});
}
}
void createDiolag(){
dialog = new JDialog(rob.getFrame(),ResManager.getString("RobTicket.btnSearch"),true);
Object[][] p={};
Object[] n={ResManager.getString("RobTicket.label_10"),ResManager.getString("RobTicket.txtFromStation"),
ResManager.getString("RobTicket.txtToStation"),ResManager.getString("RobTicket.txtTakeTime"),ResManager.getString("RobTicket.tbTitle.opt")};
model = new DefaultTableModel(p,n){
private static final long serialVersionUID = -6680116928362316922L;
@Override
public boolean isCellEditable(int row, int col){
if(col < 4){
return false;
}else {
return true;
}
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c) != null ?getValueAt(0, c).getClass() : Object.class;
}
};
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(380,160));
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setRowHeight(36);
DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
tcr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
DefaultTableCellRenderer hr = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
table.setDefaultRenderer(Object.class, tcr);
model.addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent e) {
TableModel model = (TableModel)e.getSource();
StringBuilder output = new StringBuilder();
for (int c =0; c < model.getRowCount(); c++) {
Boolean data = (Boolean) model.getValueAt(c, 4);
if(data){
output.append(model.getValueAt(c, 0));
output.append("|");
}
}
if(output.length() > 0){
rob.setTrainNo(output.substring(0,output.length() - 1));
}else{
rob.setTrainNo("");
}
}
});
//RobTicket.labSearchInfo
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(new EmptyBorder(10, 10, 10, 10));
JPanel panel = new JPanel();
panel.add(scrollPane);
/* imgLabel = new JLabel();
imgLabel.setHorizontalAlignment(JLabel.CENTER);
imgLabel.setIcon(ResManager.createImageIcon("loading.gif"));
imgLabel.setVisible(false);
panel.add(imgLabel);*/
scrollPane.setBackground(Color.WHITE);
panel.setBackground(Color.WHITE);
dialog.setContentPane(panel);
dialog.setResizable(false);
dialog.setSize(new Dimension(400,250));
dialog.setLocationRelativeTo(rob.getFrame());
}
void queryTrainInfo(TrainQueryInfo trainInfo){
SwingUtilities.invokeLater(new SearchThread(trainInfo));
}
class SearchThread extends Thread {
private final Logger log = Logger.getLogger(SearchThread.class);
private TrainQueryInfo trainInfo;
SearchThread(TrainQueryInfo trainInfo){
this.trainInfo = trainInfo;
}
/**
* override 方法<p>
* 登陆线程,登陆成功后才进行购票。
*/
@Override
public void run() {
try {
if(Constants.isLoginSuc){
// imgLabel.setVisible(true);
if(Constants.QUERY_LOG_URL != ""){
try {
rob.getClient().queryTrainLog(
rob.getFromCity(), rob.getToCity(), rob.getStartDate(),
rob.getRangDate(),rob.getLandDate(),rob.getTicketType());
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
List<TrainQueryInfo> allTrain = rob.getClient().queryTrain(
trainInfo.getFromStationName(), trainInfo.getToStationName(), trainInfo.getStartTime(),
trainInfo.getRangeDate(),rob.getLandDate(), rob.getTicketType());
addTrainInfoColumn(allTrain);
// imgLabel.setVisible(false);
}else{
JOptionPane.showMessageDialog(dialog,
ResManager.getString("RobTicket.msg.notLogin"));
dialog.setVisible(false);
return;
}
}catch(NetConnectException e) {
//rob.console(ResManager.getString("RobTicket.err.net"));
JOptionPane.showMessageDialog(dialog,
ResManager.getString("RobTicket.err.net"));
} catch(Exception e){
log.error(e);
e.printStackTrace();
JOptionPane.showMessageDialog(dialog,
ResManager.getString("RobTicket.err.unkwnow"));
}
}
}
}
| tjx222/tr | src/com/tmser/train/gui/SearchTrainInfoAction.java | Java | gpl-3.0 | 7,161 |
package net.foxopen.fox;
import org.json.simple.JSONAware;
/**
* Class to use with the simple JSON library FOX uses when you need to pass in a string but don't want the JSON library
* to escape it when calling toJSONString()
*/
public class JSONNonEscapedValue implements JSONAware {
private final String mValue;
public JSONNonEscapedValue (String pValue) {
mValue = pValue;
}
@Override
public String toJSONString() {
return mValue;
}
}
| Fivium/FOXopen | src/main/java/net/foxopen/fox/JSONNonEscapedValue.java | Java | gpl-3.0 | 464 |
package com.github.bordertech.wcomponents.subordinate;
import com.github.bordertech.wcomponents.ComponentWithContext;
import com.github.bordertech.wcomponents.Request;
import com.github.bordertech.wcomponents.UIContext;
import com.github.bordertech.wcomponents.UIContextHolder;
import com.github.bordertech.wcomponents.WebUtilities;
import com.github.bordertech.wcomponents.container.SubordinateControlInterceptor;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* SubordinateControlHelper provides convenience methods to register Subordinate Controls for use with the
* {@link SubordinateControlInterceptor}.
*
* @author Jonathan Austin
* @since 1.0.0
*/
public final class SubordinateControlHelper {
/**
* The logger instance for this class.
*/
private static final Log LOG = LogFactory.getLog(SubordinateControlHelper.class);
/**
* The key we use to store the subordinate controls that are currently active on the client.
*/
public static final String SUBORDINATE_CONTROL_SESSION_KEY = "subordinate.control.active";
/**
* Prevent instantiation of this class.
*/
private SubordinateControlHelper() {
// Do Nothing
}
/**
* Register the Subordinate Control so that it can be applied by the {@link SubordinateControlInterceptor}.
*
* @param controlId the subordinate id
* @param request the request to store the operation under.
*/
public static void registerSubordinateControl(final String controlId, final Request request) {
HashSet<String> controls = (HashSet<String>) request.getSessionAttribute(
SUBORDINATE_CONTROL_SESSION_KEY);
if (controls == null) {
controls = new HashSet<>();
request.setSessionAttribute(SUBORDINATE_CONTROL_SESSION_KEY, controls);
}
controls.add(controlId);
}
/**
* Apply the registered Subordinate Controls.
*
* @param request the request being processed.
* @param useRequestValues the flag to indicate the controls should use values from the request.
*/
public static void applyRegisteredControls(final Request request, final boolean useRequestValues) {
HashSet<String> controls = (HashSet<String>) request.getSessionAttribute(
SUBORDINATE_CONTROL_SESSION_KEY);
if (controls != null) {
for (String controlId : controls) {
// Find the Component for this ID
ComponentWithContext controlWithContext = WebUtilities.getComponentById(controlId,
true);
if (controlWithContext == null) {
LOG.warn(
"Subordinate control for id " + controlId + " is no longer in the tree.");
continue;
}
if (!(controlWithContext.getComponent() instanceof WSubordinateControl)) {
LOG.warn("Component for id " + controlId + " is not a subordinate control.");
continue;
}
WSubordinateControl control = (WSubordinateControl) controlWithContext.
getComponent();
UIContext uic = controlWithContext.getContext();
UIContextHolder.pushContext(uic);
try {
if (useRequestValues) {
control.applyTheControls(request);
} else {
control.applyTheControls();
}
} finally {
UIContextHolder.popContext();
}
}
}
}
/**
* Clear all registered Subordinate Controls on the session.
*
* @param request the request being processed.
*/
public static void clearAllRegisteredControls(final Request request) {
request.setSessionAttribute(SUBORDINATE_CONTROL_SESSION_KEY, null);
}
}
| Joshua-Barclay/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/subordinate/SubordinateControlHelper.java | Java | gpl-3.0 | 3,561 |
package com.tns.gen.android.webkit;
public class WebViewClient_frnal_ts_helpers_l58_c38__WebViewClientImpl extends android.webkit.WebViewClient implements com.tns.NativeScriptHashCodeProvider {
public WebViewClient_frnal_ts_helpers_l58_c38__WebViewClientImpl(){
super();
com.tns.Runtime.initInstance(this);
}
public boolean shouldOverrideUrlLoading(android.webkit.WebView param_0, java.lang.String param_1) {
java.lang.Object[] args = new java.lang.Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Runtime.callJSMethod(this, "shouldOverrideUrlLoading", boolean.class, args);
}
public boolean shouldOverrideUrlLoading(android.webkit.WebView param_0, android.webkit.WebResourceRequest param_1) {
java.lang.Object[] args = new java.lang.Object[2];
args[0] = param_0;
args[1] = param_1;
return (boolean)com.tns.Runtime.callJSMethod(this, "shouldOverrideUrlLoading", boolean.class, args);
}
public void onPageStarted(android.webkit.WebView param_0, java.lang.String param_1, android.graphics.Bitmap param_2) {
java.lang.Object[] args = new java.lang.Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Runtime.callJSMethod(this, "onPageStarted", void.class, args);
}
public void onPageFinished(android.webkit.WebView param_0, java.lang.String param_1) {
java.lang.Object[] args = new java.lang.Object[2];
args[0] = param_0;
args[1] = param_1;
com.tns.Runtime.callJSMethod(this, "onPageFinished", void.class, args);
}
public void onReceivedError(android.webkit.WebView param_0, int param_1, java.lang.String param_2, java.lang.String param_3) {
java.lang.Object[] args = new java.lang.Object[4];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
args[3] = param_3;
com.tns.Runtime.callJSMethod(this, "onReceivedError", void.class, args);
}
public void onReceivedError(android.webkit.WebView param_0, android.webkit.WebResourceRequest param_1, android.webkit.WebResourceError param_2) {
java.lang.Object[] args = new java.lang.Object[3];
args[0] = param_0;
args[1] = param_1;
args[2] = param_2;
com.tns.Runtime.callJSMethod(this, "onReceivedError", void.class, args);
}
public boolean equals__super(java.lang.Object other) {
return super.equals(other);
}
public int hashCode__super() {
return super.hashCode();
}
}
| ner01/MobileAppTest | Groceries/platforms/android/src/main/java/com/tns/gen/android/webkit/WebViewClient_frnal_ts_helpers_l58_c38__WebViewClientImpl.java | Java | gpl-3.0 | 2,361 |
package pt.uminho.sysbio.biosynth.integration.io.dao.neo4j;
import org.neo4j.graphdb.Label;
@Deprecated
public enum LiteratureMajorLabel implements Label {
Patent, CiteXplore, PubMed,
}
| Fxe/biosynth-framework | biosynth-integration/src/main/java/pt/uminho/sysbio/biosynth/integration/io/dao/neo4j/LiteratureMajorLabel.java | Java | gpl-3.0 | 189 |
/*
city-scape: a 3d scene of a city soft rendered in java
Copyright (C) 2017 Wil Gaboury
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 Model;
import Model.Mesh.Mesh;
import Model.Mesh.MeshImplementationHelper;
/**
* Created by 18wgaboury on 5/7/2017.
* stores both a mesh and an initial model to world transformation matrix
*/
public class Object3D
{
private Mesh model;
private TransformationMatrix modelToWorld;
/**
* makes a new object 3D using a Mesh and a transformation matrix
* @param model a model
* @param modelToWorld a transformation matrix
*/
public Object3D(Mesh model, TransformationMatrix modelToWorld)
{
this.model = model;
this.modelToWorld = modelToWorld;
}
/**
* creates an empty object3D
*/
public Object3D()
{
model = new MeshImplementationHelper(){};
modelToWorld = new TransformationMatrix.IdentityMatrix();
}
/**
* gets the mesh
* @return the mesh
*/
public Mesh getModel()
{ return model; }
/**
* sets the mesh object
* @param model a mesh object
*/
public void setModel(Mesh model)
{ this.model = model; }
/**
* gets the current model to world transformation matrix
* @return the current model to world transformation matrix
*/
public TransformationMatrix getModelToWorld()
{ return modelToWorld; }
/**
* sets the current model to world transformation matrix
* @param modelToWorld the current model to world transformation matrix
*/
public void setModelToWorld(TransformationMatrix modelToWorld)
{ this.modelToWorld = modelToWorld; }
}
| thecreamedcorn/city-scape | src/Model/Object3D.java | Java | gpl-3.0 | 2,110 |
package gnu.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;
/** Classpath utility. */
public class Classpath {
public static final String CLASSPATH
= System.getProperty ("java.class.path");
public static final File [] CLASSPATH_DIRS;
static {
StringTokenizer st = new StringTokenizer (CLASSPATH,
File.pathSeparator);
int count = st.countTokens ();
CLASSPATH_DIRS = new File [count];
for (int i = 0; i<count; i++)
CLASSPATH_DIRS [i] = new File (st.nextToken());
}
/**
* Find a class file in default classpath.
*
* @see #find_file(File[], String)
*/
public static File find_class (String name) {
return find_file (to_class_filename (name));
}
/**
* Find a class file given search path directories.
*
* @see #find_file(File[], String)
*/
public static File find_class (File [] dirs, String name) {
return find_file (dirs, to_class_filename (name));
}
/**
* Find a plain file or a directory in default classpath.
*
* @see #find_file(File[], String)
*/
public static File find_file (String name) {
return find_file (CLASSPATH_DIRS, name);
}
/**
* Find a plain file or a directory.
*
* @param dirs search paths
* @param name filename (basename with extension) or dirname
* @return <code>null</code> if not found
*/
public static File find_file (File [] dirs, String name) {
for (int i=0; i<dirs.length; i++) {
File file = new File (dirs [i], name);
if (file.canRead ()) return file;
}
return null;
}
/**
* Find all class files of a package in default classpath.
*
* @see #find_package(File[], String)
*/
public static File [] find_package (String name) {
return find_package (CLASSPATH_DIRS, name);
}
/**
* Find all class files of a package in given search path directories.
*
* @see #find_file(File[], String)
*/
public static File [] find_package (File [] dirs, String name) {
File package_file = find_file (dirs, to_filename (name));
return package_file.listFiles (new java.io.FilenameFilter () {
public boolean accept (File dir, String filename) {
return filename.endsWith (".class");
}
});
}
/**
* Convert a JVM class name to a class filename.
*/
public static String to_class_filename (String name) {
return to_filename (name) + ".class";
}
/**
* Convert a JVM name to a filename.
*/
public static String to_filename (String name) {
return name.replace ('.', File.separatorChar);
}
/**
* Get the JVM class name of a file.
*/
public static String to_jvm_name (String package_name, File file) {
String filename = file.getName ();
String basename = filename.substring (0,
filename.length () - ".class".length ());
return package_name + "." + basename;
}
/**
* Get a list of JVM class names from a list of class files.
*/
public static String [] to_jvm_name (String package_name,
File [] files) {
String [] names = new String [files.length];
for (int i=0; i<files.length; i++)
names [i] = to_jvm_name (package_name, files [i]);
return names;
}
}
| chriskmanx/qmole | QMOLEDEV/escher-0.3/src/gnu/util/Classpath.java | Java | gpl-3.0 | 3,288 |
package template.egork.generated.collections.list;
import template.egork.generated.collections.DoubleReversableCollection;
import template.egork.generated.collections.comparator.DoubleComparator;
import template.egork.generated.collections.iterator.DoubleIterator;
import template.egork.generated.collections.function.DoubleCharPredicate;
import template.egork.generated.collections.function.DoubleDoublePredicate;
import template.egork.generated.collections.function.DoubleFilter;
import template.egork.generated.collections.function.DoubleIntPredicate;
import template.egork.generated.collections.function.DoubleLongPredicate;
import template.egork.generated.collections.function.IntToDoubleFunction;
/**
* @author Egor Kulikov
*/
public interface DoubleList extends DoubleReversableCollection {
public static final DoubleList EMPTY = new DoubleArray(new double[0]);
//abstract
public abstract double get(int index);
public abstract void set(int index, double value);
public abstract void addAt(int index, double value);
public abstract void removeAt(int index);
//base
default public double first() {
return get(0);
}
default public double last() {
return get(size() - 1);
}
default public void swap(int first, int second) {
if (first == second) {
return;
}
double temp = get(first);
set(first, get(second));
set(second, temp);
}
default public DoubleIterator doubleIterator() {
return new DoubleIterator() {
private int at;
private boolean removed;
public double value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public DoubleIterator reverseIterator() {
return new DoubleIterator() {
private int at = size() - 1;
private boolean removed;
public double value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at--;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at >= 0;
}
public void remove() {
removeAt(at);
removed = true;
}
};
}
@Override
default public void add(double value) {
addAt(size(), value);
}
default public void popLast() {
removeAt(size() - 1);
}
default public void popFirst() {
removeAt(0);
}
//algorithms
default public int minIndex() {
double result = Double.POSITIVE_INFINITY;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
double current = get(i);
if (current < result) {
result = current;
at = i;
}
}
return at;
}
default public int minIndex(DoubleComparator comparator) {
double result = Double.MIN_NORMAL;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
double current = get(i);
if (result == Double.MIN_NORMAL || comparator.compare(result, current) > 0) {
result = current;
at = i;
}
}
return at;
}
default public int maxIndex() {
double result = Double.NEGATIVE_INFINITY;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
double current = get(i);
if (current > result) {
result = current;
at = i;
}
}
return at;
}
default public int maxIndex(DoubleComparator comparator) {
double result = Double.MIN_NORMAL;
int size = size();
int at = -1;
for (int i = 0; i < size; i++) {
double current = get(i);
if (result == Double.MIN_NORMAL || comparator.compare(result, current) < 0) {
result = current;
at = i;
}
}
return at;
}
default public DoubleList sort() {
sort(DoubleComparator.DEFAULT);
return this;
}
default public DoubleList sort(DoubleComparator comparator) {
Sorter.sort(this, comparator);
return this;
}
default public int find(double value) {
int size = size();
for (int i = 0; i < size; i++) {
if (get(i) == value) {
return i;
}
}
return -1;
}
default public int find(DoubleFilter filter) {
int size = size();
for (int i = 0; i < size; i++) {
if (filter.accept(get(i))) {
return i;
}
}
return -1;
}
default public int findLast(double value) {
for (int i = size() - 1; i >= 0; i--) {
if (get(i) == value) {
return i;
}
}
return -1;
}
default public int findLast(DoubleFilter filter) {
for (int i = size() - 1; i >= 0; i--) {
if (filter.accept(get(i))) {
return i;
}
}
return -1;
}
default public boolean nextPermutation() {
return nextPermutation(DoubleComparator.DEFAULT);
}
default public boolean nextPermutation(DoubleComparator comparator) {
int size = size();
double last = get(size - 1);
for (int i = size - 2; i >= 0; i--) {
double current = get(i);
if (comparator.compare(last, current) > 0) {
for (int j = size - 1; j > i; j--) {
if (comparator.compare(get(j), current) > 0) {
swap(i, j);
subList(i + 1, size).inPlaceReverse();
return true;
}
}
}
last = current;
}
return false;
}
default public void inPlaceReverse() {
for (int i = 0, j = size() - 1; i < j; i++, j--) {
swap(i, j);
}
}
default DoubleList unique() {
double last = Double.MIN_NORMAL;
DoubleList result = new DoubleArrayList();
int size = size();
for (int i = 0; i < size; i++) {
double current = get(i);
if (current != last) {
result.add(current);
last = current;
}
}
return result;
}
default int mismatch(DoubleList l) {
int size = Math.min(size(), l.size());
for (int i = 0; i < size; i++) {
if (get(i) != l.get(i)) {
return i;
}
}
if (size() != l.size()) {
return size;
}
return -1;
}
default int mismatch(DoubleList l, DoubleDoublePredicate p) {
int size = Math.min(size(), l.size());
for (int i = 0; i < size; i++) {
if (!p.value(get(i), l.get(i))) {
return i;
}
}
if (size() != l.size()) {
return size;
}
return -1;
}
default int mismatch(IntList l, DoubleIntPredicate p) {
int size = Math.min(size(), l.size());
for (int i = 0; i < size; i++) {
if (!p.value(get(i), l.get(i))) {
return i;
}
}
if (size() != l.size()) {
return size;
}
return -1;
}
default int mismatch(LongList l, DoubleLongPredicate p) {
int size = Math.min(size(), l.size());
for (int i = 0; i < size; i++) {
if (!p.value(get(i), l.get(i))) {
return i;
}
}
if (size() != l.size()) {
return size;
}
return -1;
}
default int mismatch(CharList l, DoubleCharPredicate p) {
int size = Math.min(size(), l.size());
for (int i = 0; i < size; i++) {
if (!p.value(get(i), l.get(i))) {
return i;
}
}
if (size() != l.size()) {
return size;
}
return -1;
}
default DoubleList fill(double value) {
int size = size();
for (int i = 0; i < size; i++) {
set(i, value);
}
return this;
}
default DoubleList fill(IntToDoubleFunction f) {
int size = size();
for (int i = 0; i < size; i++) {
set(i, f.value(i));
}
return this;
}
default DoubleList replace(double sample, double value) {
int size = size();
for (int i = 0; i < size; i++) {
if (get(i) == sample) {
set(i, value);
}
}
return this;
}
default DoubleList replace(DoubleFilter f, double value) {
int size = size();
for (int i = 0; i < size; i++) {
if (f.accept(get(i))) {
set(i, value);
}
}
return this;
}
default int binarySearch(DoubleFilter f) {
int left = 0;
int right = size();
while (left < right) {
int middle = (left + right) >> 1;
if (f.accept(get(middle))) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
default int moreOrEqual(double value) {
int left = 0;
int right = size();
while (left < right) {
int middle = (left + right) >> 1;
if (value <= get(middle)) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
default int moreOrEqual(double value, DoubleComparator c) {
int left = 0;
int right = size();
while (left < right) {
int middle = (left + right) >> 1;
if (c.compare(value, get(middle)) <= 0) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
default int more(double value) {
int left = 0;
int right = size();
while (left < right) {
int middle = (left + right) >> 1;
if (value < get(middle)) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
default int more(double value, DoubleComparator c) {
int left = 0;
int right = size();
while (left < right) {
int middle = (left + right) >> 1;
if (c.compare(value, get(middle)) < 0) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
//views
default public DoubleList subList(final int from, final int to) {
return new DoubleList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > DoubleList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", capacity = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public double get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", capacity = " + size());
}
return DoubleList.this.get(at + shift);
}
public void addAt(int index, double value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, double value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", capacity = " + size());
}
DoubleList.this.set(at + shift, value);
}
public DoubleList compute() {
return new DoubleArrayList(this);
}
};
}
}
| hack1nt0/AC | src/main/java/template/egork/generated/collections/list/DoubleList.java | Java | gpl-3.0 | 13,038 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.graql.internal.pattern.property;
import ai.grakn.graql.VarName;
import ai.grakn.graql.admin.Atomic;
import ai.grakn.graql.admin.ReasonerQuery;
import ai.grakn.graql.admin.VarAdmin;
import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet;
import ai.grakn.graql.internal.gremlin.sets.EquivalentFragmentSets;
import ai.grakn.graql.internal.reasoner.atom.NotEquals;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Stream;
/**
* Represents the {@code !=} property on a {@link ai.grakn.concept.Concept}.
*
* This property can be queried. It asserts identity inequality between two concepts. Concepts may have shared
* properties but still be distinct. For example, two instances of a type without any resources are still considered
* unequal. Similarly, two resources with the same value but of different types are considered unequal.
*
* @author Felix Chapman
*/
public class NeqProperty extends AbstractVarProperty implements NamedProperty {
private final VarAdmin var;
public NeqProperty(VarAdmin var) {
this.var = var;
}
public VarAdmin getVar() {
return var;
}
@Override
public String getName() {
return "!=";
}
@Override
public String getProperty() {
return var.getPrintableName();
}
@Override
public Collection<EquivalentFragmentSet> match(VarName start) {
return Sets.newHashSet(
EquivalentFragmentSets.notCasting(start),
EquivalentFragmentSets.notCasting(var.getVarName()),
EquivalentFragmentSets.neq(start, var.getVarName())
);
}
@Override
public Stream<VarAdmin> getInnerVars() {
return Stream.of(var);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NeqProperty that = (NeqProperty) o;
return var.equals(that.var);
}
@Override
public int hashCode() {
return var.hashCode();
}
@Override
public Atomic mapToAtom(VarAdmin var, Set<VarAdmin> vars, ReasonerQuery parent) {
return new NotEquals(var.getVarName(), this, parent);
}
}
| sklarman/grakn | grakn-graql/src/main/java/ai/grakn/graql/internal/pattern/property/NeqProperty.java | Java | gpl-3.0 | 3,011 |
package com.mec.app.plugin.filemanager;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import org.junit.Ignore;
import org.junit.Test;
import com.mec.app.plugin.filemanager.XMLParamComparatorController.OperationInProgress;
import com.mec.app.plugin.filemanager.XMLParamComparatorController.ParamDirectoryExtractor;
import com.mec.app.plugin.filemanager.resources.MsgLogger;
import com.mec.app.plugin.filemanager.resources.MsgLogger.StringLogger;
import com.mec.app.plugin.filemanager.resources.MsgLogger.StringPrefixLogger;
import javafx.application.Application;
import javafx.stage.Stage;
public class XMLParamComparatorControllerTest {
@Ignore
@Test
public void testMatchNumDir() {
// fail("Not yet implemented");
Path p = Paths.get("1");
Matcher m = ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.matcher(p.getFileName().toString());
logger.log("%s matches pattern %s? %s", p.toString(),
ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.toString(),
m.matches());
p = Paths.get("12");
m = ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.matcher(p.getFileName().toString());
logger.log("%s matches pattern %s? %s", p.toString(),
ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.toString(),
m.matches());
p = Paths.get("a12");
m = ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.matcher(p.getFileName().toString());
logger.log("%s matches pattern %s? %s", p.toString(),
ParamDirectoryExtractor.NUM_SUB_DIR_PATTERN.toString(),
m.matches());
}
/*
* 2016-05-19, result:
* EE Accounting Rules\Module
EE Accounting Rules\System
EE Amount&Rate Format\Module
EE Amount&Rate Format\System
EE Attribute\Module
EE Attribute\System
EE Batch Manage
EE Business Unit Config
EE Calculation
EE Catalog\Module\Multi
EE Catalog\Module\Single
EE Catalog\System\Multi
EE Catalog\System\Single
EE Clause\Module
EE Clause\System
EE Component Manage
EE DataSource Manage
EE DB Dictionary
EE Event Driven
EE Field Conversion\Module
EE Field Conversion\System
EE Form\Module
EE Form\System
EE Function Group
EE GAPI Setting\Authorize
EE GAPI Setting\Inquire
EE GAPI Setting\Release
EE GAPI Setting\Transaction
EE Get CUBK\Module
EE Get CUBK\System
EE Get DO DATA\Module
EE Get DO DATA\System
EE HandWriting
EE Message Broker Setting
EE Message Mapping
EE Module&Event
EE Protocol Manager
EE Screen
EE Screen\Module
EE Screen\System
EE Security Parameters
EE Server Side JS
EE STD Setting
EE SWIFT
EE System Maintain
EE System Parameter
EE Transaction Function
EE Transfer To\Module
EE Transfer To\System
*
*/
@Ignore
@Test
public void testGetCharacteristicPath(){
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure");
// ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger, rootDir);
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
List<Path> cps = pe.getCharacteristicPath(rootDir);
// logger.log(cps.toString());
// cps.forEach(cp -> logger.log(cp.toString()));
cps.forEach(cp -> logger.log((rootDir.relativize(cp)).toString()));
}
@Ignore
@Test
public void testListXmlParamFiles(){
Path numDir1 = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure/EE Accounting Rules/Module/1");
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
List<Path> xmlFiles = pe.listXmlParamFiles(numDir1);
xmlFiles.forEach(rp -> logger.log(rp.toString()));
}
@Ignore
@Test
public void testListAllChildNumDirs(){
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure/EE Accounting Rules/Module");
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
List<Path> numDirs = pe.listChildNumDirs(rootDir);
numDirs.forEach(p -> logger.log(p.toString()));
}
@Ignore
@Test
public void testGroupNumDirContents(){
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure/EE Accounting Rules/Module");
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
// List<Path> numDirs = pe.listChildNumDirs(rootDir);
Map<Path, List<Set<Path>>> groupedNumDirsByXMLStruct = pe.groupNumDirContents(rootDir);
// logger.log(groupedNumDirsByXMLStruct.toString());
for(Path paramFile : groupedNumDirsByXMLStruct.keySet()){
logger.log("==========================================");
logger.log(paramFile.toString());
List<Set<Path>> groupedNumDirs = groupedNumDirsByXMLStruct.get(paramFile);
// String groupedNumDirsStr = groupedNumDirs.stream()
// .map(sp -> sp.stream()
//// .sorted(Comparator.comparingInt(p -> Integer.parseInt(p.getFileName().toString()))
// .map(p -> p.getFileName().toString()).collect(Collectors.joining(",", "{", "}")))
// .collect(Collectors.joining(",", "[", "]"));
// String groupedNumDirsStr = groupedNumDirs.stream()
// .map(sp -> sp.stream()
// .sorted(Comparator.comparingInt(p -> Integer.parseInt(p.getFileName().toString())))
// .map(p -> p.getFileName().toString())
// .collect(Collectors.joining(",", "{", "}"))
// ).collect(Collectors.joining(",", "[", "]"));
String groupedNumDirsStr = pe.listOfSetsToStr(groupedNumDirs);
logger.log(groupedNumDirsStr);
}
}
@Ignore
@Test
public void testGroupingXmlParamFilesInAllCharacteristicPaths() throws IOException{
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure");
// ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger, rootDir);
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
Path outputLogFile = Paths.get("data/difference_report.log");
BufferedWriter outputWriter = Files.newBufferedWriter(outputLogFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
List<Path> cps = pe.getCharacteristicPath(rootDir);
for(Path cp : cps){
// logger.log("\n\n==========================\n==%s\n==========================", rootDir.relativize(cp).toString());
logAndWrite(outputWriter, "\n\n==========================\n==%s\n==========================\n", rootDir.relativize(cp).toString());
Map<Path, List<Set<Path>>> groupedNumDirsByXMLStruct = pe.groupNumDirContents(cp);
for(Path paramFile : groupedNumDirsByXMLStruct.keySet()){
List<Set<Path>> groupedNumDirs = groupedNumDirsByXMLStruct.get(paramFile);
if(1 < groupedNumDirs.size()){
String groupedNumDirsStr = pe.listOfSetsToStr(groupedNumDirs);
// logger.log("%s: %s", paramFile.toString(), groupedNumDirsStr);
logAndWrite(outputWriter, "%s: %s", paramFile.toString(), groupedNumDirsStr);
}
}
}
outputWriter.close();
}
@Ignore
@Test
public void testGroupingXmlParamFilesInAllCharacteristicPaths2() throws IOException{
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure");
// ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger, rootDir);
ParamDirectoryExtractor pe = ParamDirectoryExtractor.newInst(logger);
Path outputLogFile = Paths.get("data/difference_report.log");
BufferedWriter outputWriter = Files.newBufferedWriter(outputLogFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
List<Path> cps = pe.getCharacteristicPath(rootDir);
for(Path cp : cps){
// logger.log("\n\n==========================\n==%s\n==========================", rootDir.relativize(cp).toString());
logAndWrite(outputWriter, "\n\n==========================\n==%s\n==========================\n", rootDir.relativize(cp).toString());
Map<Path, List<Set<Path>>> groupedNumDirsByXMLStruct = pe.groupNumDirContents(cp);
for(Path paramFile : groupedNumDirsByXMLStruct.keySet()){
List<Set<Path>> groupedNumDirs = groupedNumDirsByXMLStruct.get(paramFile);
if(1 < groupedNumDirs.size()){
String groupedNumDirsStr = pe.listOfSetsToStr(groupedNumDirs);
// logger.log("%s: %s", paramFile.toString(), groupedNumDirsStr);
logAndWrite(outputWriter, "%s: %s", paramFile.toString(), groupedNumDirsStr);
}
}
}
outputWriter.close();
}
@Ignore
@Test
public void testStringLogger(){
StringLogger sl = new StringLogger();
sl.log("Hello, World");
logger.log(sl.toString());
sl.log("\nHello, again");
logger.log(sl.toString());
}
@Ignore
@Test
public void testStringPrefixLogger(){
StringPrefixLogger sl = new StringPrefixLogger("------");
sl.ln("Hello, World");
logger.log(sl.toString());
sl.ln("Hello, again");
logger.log(sl.toString());
}
@Ignore
@Test
public void testOutputDifferenceLog(){
XMLParamComparatorController xpc = new XMLParamComparatorController();
Path rootDir = Paths.get("//10.39.100.2/dev2/Utility Doc/Web Utility Test Information/Original Utility 测试点分析/XML Structure");
Path outputLogFile = Paths.get("data/difference_report_v2.log");
xpc.parseParamXmlStruct(rootDir);
xpc.outputDifferenceLog(outputLogFile);
}
@Ignore
@Test
public void testSystemProperty(){
// logger.log(System.getProperty("user.dir"));
logger.log(System.getProperty("user.home"));
Properties props = System.getProperties();
props.keySet().stream().forEach(key -> logger.log(String.format("%s: %s", key, props.get(key))));
}
//
// @Test
// public void testOperationInProgress(){
//// OperationInProgress oip = new OperationInProgress();
//// oip.show();
//// OperationInProgressApplication app = new OperationInProgressApplication();
//// app.st
////
// Application.launch(OperationInProgressApplication.class);
// }
//
//
// static class OperationInProgressApplication extends Application{
//
// @Override
// public void start(Stage primaryStage) throws Exception {
// OperationInProgress oip = new OperationInProgress();
// oip.show();
// }
//
// }
void logAndWrite(Writer writer, String format, Object ... args) throws IOException{
String content = String.format(format, args);
logger.log(content);
writer.append(content);
}
MsgLogger logger = MsgLogger.defaultLogger();
}
| mectest1/HelloGUI | HelloUtilityPlugin-FileManager/test/com/mec/app/plugin/filemanager/XMLParamComparatorControllerTest.java | Java | gpl-3.0 | 11,036 |
package com.nightscout.core.upload;
import com.nightscout.core.dexcom.records.CalRecord;
import com.nightscout.core.dexcom.records.GlucoseDataSet;
import com.nightscout.core.dexcom.records.InsertionRecord;
import com.nightscout.core.dexcom.records.MeterRecord;
import com.nightscout.core.drivers.AbstractUploaderDevice;
import com.nightscout.core.preferences.NightscoutPreferences;
import com.nightscout.core.utils.RestUriUtils;
import org.apache.http.message.AbstractHttpMessage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URI;
import static net.tribe7.common.base.Preconditions.checkArgument;
public class RestV1Uploader extends AbstractRestUploader {
private final String secret;
public RestV1Uploader(NightscoutPreferences preferences, URI uri) {
super(preferences, RestUriUtils.removeToken(uri));
checkArgument(RestUriUtils.hasToken(uri), "Rest API v1 requires a token.");
secret = RestUriUtils.generateSecret(uri.getUserInfo());
}
protected String getSecret() {
return secret;
}
@Override
protected void setExtraHeaders(AbstractHttpMessage post) {
post.setHeader("api-secret", secret);
}
private JSONObject toJSONObjectEgv(GlucoseDataSet record) throws JSONException {
JSONObject json = new JSONObject();
json.put("device", deviceStr);
json.put("date", record.getWallTime().getMillis());
json.put("sysTime", record.getRawSysemTimeEgv());
json.put("dateString", record.getWallTime().toString());
json.put("sgv", record.getBgMgdl());
json.put("direction", record.getTrend().friendlyTrendName());
json.put("type", "sgv");
return json;
}
private JSONObject toJSONObjectSensor(GlucoseDataSet record, JSONObject json) throws JSONException {
json.put("filtered", record.getFiltered());
json.put("unfiltered", record.getUnfiltered());
json.put("rssi", record.getRssi());
json.put("noise", record.getNoise());
return json;
}
private JSONObject toJSONObject(GlucoseDataSet record) throws JSONException {
JSONObject json = new JSONObject();
json.put("device", deviceStr);
json.put("date", record.getWallTime().getMillis());
json.put("dateString", record.getWallTime().toString());
json.put("sgv", record.getBgMgdl());
json.put("direction", record.getTrend().friendlyTrendName());
json.put("type", "sgv");
if (getPreferences().isRawEnabled()) {
json.put("filtered", record.getFiltered());
json.put("unfiltered", record.getUnfiltered());
json.put("rssi", record.getRssi());
json.put("noise", record.getNoise());
}
log.error("Json: {}", json);
return json;
}
private JSONObject toJSONObject(MeterRecord record) throws JSONException {
JSONObject json = new JSONObject();
json.put("device", deviceStr);
json.put("type", "mbg");
json.put("date", record.getWallTime().getMillis());
json.put("sysTime", record.getRawSystemTimeSeconds());
json.put("dateString", record.getWallTime().toString());
json.put("mbg", record.getBgMgdl());
log.error("Json: {}", json);
return json;
}
private JSONObject toJSONObject(CalRecord record) throws JSONException {
JSONObject json = new JSONObject();
json.put("device", deviceStr);
json.put("type", "cal");
json.put("date", record.getWallTime().getMillis());
json.put("sysTime", record.getRawSystemTimeSeconds());
json.put("dateString", record.getWallTime().toString());
json.put("slope", record.getSlope());
json.put("intercept", record.getIntercept());
json.put("scale", record.getScale());
log.error("Json: {}", json);
return json;
}
private JSONObject toJSONObject(InsertionRecord insertionRecord) throws JSONException {
JSONObject output = new JSONObject();
output.put("sysTime", insertionRecord.getRawSystemTimeSeconds());
output.put("date", insertionRecord.getWallTime().getMillis());
output.put("dateString", insertionRecord.getWallTime().toString());
output.put("state", insertionRecord.getState().name());
output.put("type", insertionRecord.getRecordType());
return output;
}
private JSONObject toJSONObject(AbstractUploaderDevice deviceStatus, int rcvrBat) throws JSONException {
JSONObject json = new JSONObject();
json.put("uploaderBattery", deviceStatus.getBatteryLevel());
json.put("receiverBattery", rcvrBat);
log.error("Json: {}", json);
return json;
}
@Override
protected boolean doUpload(GlucoseDataSet glucoseDataSet) throws IOException {
try {
JSONObject json = toJSONObjectEgv(glucoseDataSet);
log.error("Json: {}", json);
if (!preferences.isRawEnabled()) {
log.debug("Raw not enabled. JSON: {}", json);
return doPost("entries", json);
} else {
if (glucoseDataSet.areRecordsMatched()) {
json = toJSONObjectSensor(glucoseDataSet, json);
log.debug("Records matched Json: {}", json);
return doPost("entries", json);
} else {
log.error("Records not matched Json: {}", json);
boolean result = doPost("entries", json);
return result;
}
}
} catch (JSONException e) {
log.error("Could not create JSON object for rest v1 glucose data set.", e);
return false;
}
}
@Override
protected boolean doUpload(MeterRecord meterRecord) throws IOException {
try {
// TODO(trhodeos): in Uploader.java, this method still used 'entries' as the endpoint,
// but this seems like a bug to me.
return doPost("entries", toJSONObject(meterRecord));
} catch (JSONException e) {
log.error("Could not create JSON object for rest v1 meter record.", e);
return false;
}
}
@Override
protected boolean doUpload(CalRecord calRecord) throws IOException {
try {
// TODO(trhodeos): in Uploader.java, this method still used 'entries' as the endpoint,
// but this seems like a bug to me.
return doPost("entries", toJSONObject(calRecord));
} catch (JSONException e) {
log.error("Could not create JSON object for rest v1 cal record.", e);
return false;
}
}
@Override
protected boolean doUpload(InsertionRecord insertionRecord) throws IOException {
try {
// TODO(trhodeos): in Uploader.java, this method still used 'entries' as the endpoint,
// but this seems like a bug to me.
JSONObject json = toJSONObject(insertionRecord);
log.info("Insertion JSON object to upload: {}", json.toString());
return doPost("entries", toJSONObject(insertionRecord));
} catch (JSONException e) {
log.error("Could not create JSON object for rest v1 cal record.", e);
return false;
}
}
@Override
protected boolean doUpload(AbstractUploaderDevice deviceStatus, int rcvrBat) throws IOException {
try {
return doPost("devicestatus", toJSONObject(deviceStatus, rcvrBat));
} catch (JSONException e) {
log.error("Could not create JSON object for rest v1 device status.", e);
return false;
}
}
}
| nightscout/lasso | core/src/main/java/com/nightscout/core/upload/RestV1Uploader.java | Java | gpl-3.0 | 7,783 |
package com.rmsi.android.mast.Fragment;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.rmsi.android.mast.activity.R;
import com.rmsi.android.mast.adapter.SurveyListingAdapter;
import com.rmsi.android.mast.db.DbController;
import com.rmsi.android.mast.domain.Feature;
import com.rmsi.android.mast.util.CommonFunctions;
public class CompletedSurveyFragment extends Fragment {
Context context;
SurveyListingAdapter adapter;
List<Feature> features = new ArrayList<Feature>();
public static int count;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
View view = inflater.inflate(R.layout.fragment_survey_review_data_list, container, false);
ListView listView = (ListView) view.findViewById(android.R.id.list);
TextView emptyText = (TextView) view.findViewById(android.R.id.empty);
listView.setEmptyView(emptyText);
adapter = new SurveyListingAdapter(context, this, features, "final");
listView.setAdapter(adapter);
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && DraftSurveyFragment.listChanged) {
refreshList();
Toast.makeText(context, R.string.refreshing_msg, Toast.LENGTH_SHORT).show();
DraftSurveyFragment.listChanged = false;
}
}
private void refreshList() {
DbController db = DbController.getInstance(context);
features.clear();
features.addAll(db.fetchCompletedFeatures());
adapter.notifyDataSetChanged();
}
@Override
public void onResume() {
refreshList();
super.onResume();
}
}
| MASTUSAID/MAST-MOBILE | MAST-MOBILE/src/main/java/com/rmsi/android/mast/Fragment/CompletedSurveyFragment.java | Java | gpl-3.0 | 2,149 |
/**
*
* Copyright (c) 2014, Openflexo
*
* This file is part of Pamela-core, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software 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 http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo ([email protected])
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.pamela;
import java.lang.reflect.Method;
import org.openflexo.pamela.exceptions.ModelDefinitionException;
/**
* Finalizer used for a method that should be called after the whole graph of objects has been deserialized<br>
* Order of calls of these methods just respect the order where objects were created
*
* @author sylvain
*
*/
public class DeserializationFinalizer {
private final org.openflexo.pamela.annotations.DeserializationFinalizer finalizer;
private final Method deserializationFinalizerMethod;
/**
* Constructor
*
* @param finalizer
* @param deserializationFinalizerMethod
* @throws ModelDefinitionException
*/
public DeserializationFinalizer(org.openflexo.pamela.annotations.DeserializationFinalizer finalizer,
Method deserializationFinalizerMethod) throws ModelDefinitionException {
this.finalizer = finalizer;
this.deserializationFinalizerMethod = deserializationFinalizerMethod;
}
/**
* Return deserialization method
*
* @return
*/
public Method getDeserializationFinalizerMethod() {
return deserializationFinalizerMethod;
}
}
| openflexo-team/pamela | pamela-core/src/main/java/org/openflexo/pamela/DeserializationFinalizer.java | Java | gpl-3.0 | 2,665 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.02 at 08:08:55 PM CEST
//
package net.ramso.dita.task;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for syntaxdiagram.class complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="syntaxdiagram.class">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{}syntaxdiagram.content"/>
* </sequence>
* <attGroup ref="{}syntaxdiagram.attributes"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "syntaxdiagram.class", propOrder = {
"title",
"groupseqOrGroupchoiceOrGroupcomp"
})
@XmlSeeAlso({
Syntaxdiagram.class
})
public class SyntaxdiagramClass {
protected Title title;
@XmlElements({
@XmlElement(name = "groupseq", type = Groupseq.class),
@XmlElement(name = "groupchoice", type = Groupchoice.class),
@XmlElement(name = "groupcomp", type = Groupcomp.class),
@XmlElement(name = "fragref", type = Fragref.class),
@XmlElement(name = "synnote", type = Synnote.class),
@XmlElement(name = "synnoteref", type = Synnoteref.class),
@XmlElement(name = "fragment", type = Fragment.class),
@XmlElement(name = "synblk", type = Synblk.class)
})
protected List<java.lang.Object> groupseqOrGroupchoiceOrGroupcomp;
@XmlAttribute(name = "outputclass")
protected String outputclass;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "conref")
protected String conref;
@XmlAttribute(name = "conrefend")
protected String conrefend;
@XmlAttribute(name = "conaction")
protected ConactionAttClass conaction;
@XmlAttribute(name = "conkeyref")
protected String conkeyref;
@XmlAttribute(name = "translate")
protected YesnoAttClass translate;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "dir")
protected DirAttsClass dir;
@XmlAttribute(name = "base")
protected String base;
@XmlAttribute(name = "rev")
protected String rev;
@XmlAttribute(name = "importance")
protected ImportanceAttsClass importance;
@XmlAttribute(name = "status")
protected StatusAttsClass status;
@XmlAttribute(name = "props")
protected String props;
@XmlAttribute(name = "platform")
protected String platform;
@XmlAttribute(name = "product")
protected String product;
@XmlAttribute(name = "audience")
protected String audienceMod;
@XmlAttribute(name = "otherprops")
protected String otherprops;
@XmlAttribute(name = "scale")
protected String scale;
@XmlAttribute(name = "frame")
protected FrameAttClass frame;
@XmlAttribute(name = "expanse")
protected ExpanseAttClass expanse;
@XmlAttribute(name = "xtrc")
protected String xtrc;
@XmlAttribute(name = "xtrf")
protected String xtrf;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link Title }
*
*/
public Title getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link Title }
*
*/
public void setTitle(Title value) {
this.title = value;
}
/**
* Gets the value of the groupseqOrGroupchoiceOrGroupcomp property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the groupseqOrGroupchoiceOrGroupcomp property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGroupseqOrGroupchoiceOrGroupcomp().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Groupseq }
* {@link Groupchoice }
* {@link Groupcomp }
* {@link Fragref }
* {@link Synnote }
* {@link Synnoteref }
* {@link Fragment }
* {@link Synblk }
*
*
*/
public List<java.lang.Object> getGroupseqOrGroupchoiceOrGroupcomp() {
if (groupseqOrGroupchoiceOrGroupcomp == null) {
groupseqOrGroupchoiceOrGroupcomp = new ArrayList<java.lang.Object>();
}
return this.groupseqOrGroupchoiceOrGroupcomp;
}
/**
* Gets the value of the outputclass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutputclass() {
return outputclass;
}
/**
* Sets the value of the outputclass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutputclass(String value) {
this.outputclass = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the conref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConref() {
return conref;
}
/**
* Sets the value of the conref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConref(String value) {
this.conref = value;
}
/**
* Gets the value of the conrefend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConrefend() {
return conrefend;
}
/**
* Sets the value of the conrefend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConrefend(String value) {
this.conrefend = value;
}
/**
* Gets the value of the conaction property.
*
* @return
* possible object is
* {@link ConactionAttClass }
*
*/
public ConactionAttClass getConaction() {
return conaction;
}
/**
* Sets the value of the conaction property.
*
* @param value
* allowed object is
* {@link ConactionAttClass }
*
*/
public void setConaction(ConactionAttClass value) {
this.conaction = value;
}
/**
* Gets the value of the conkeyref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConkeyref() {
return conkeyref;
}
/**
* Sets the value of the conkeyref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConkeyref(String value) {
this.conkeyref = value;
}
/**
* Gets the value of the translate property.
*
* @return
* possible object is
* {@link YesnoAttClass }
*
*/
public YesnoAttClass getTranslate() {
return translate;
}
/**
* Sets the value of the translate property.
*
* @param value
* allowed object is
* {@link YesnoAttClass }
*
*/
public void setTranslate(YesnoAttClass value) {
this.translate = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link DirAttsClass }
*
*/
public DirAttsClass getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link DirAttsClass }
*
*/
public void setDir(DirAttsClass value) {
this.dir = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Gets the value of the rev property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRev() {
return rev;
}
/**
* Sets the value of the rev property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRev(String value) {
this.rev = value;
}
/**
* Gets the value of the importance property.
*
* @return
* possible object is
* {@link ImportanceAttsClass }
*
*/
public ImportanceAttsClass getImportance() {
return importance;
}
/**
* Sets the value of the importance property.
*
* @param value
* allowed object is
* {@link ImportanceAttsClass }
*
*/
public void setImportance(ImportanceAttsClass value) {
this.importance = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusAttsClass }
*
*/
public StatusAttsClass getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusAttsClass }
*
*/
public void setStatus(StatusAttsClass value) {
this.status = value;
}
/**
* Gets the value of the props property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProps() {
return props;
}
/**
* Sets the value of the props property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProps(String value) {
this.props = value;
}
/**
* Gets the value of the platform property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlatform() {
return platform;
}
/**
* Sets the value of the platform property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlatform(String value) {
this.platform = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the audienceMod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudienceMod() {
return audienceMod;
}
/**
* Sets the value of the audienceMod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudienceMod(String value) {
this.audienceMod = value;
}
/**
* Gets the value of the otherprops property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOtherprops() {
return otherprops;
}
/**
* Sets the value of the otherprops property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOtherprops(String value) {
this.otherprops = value;
}
/**
* Gets the value of the scale property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getScale() {
return scale;
}
/**
* Sets the value of the scale property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setScale(String value) {
this.scale = value;
}
/**
* Gets the value of the frame property.
*
* @return
* possible object is
* {@link FrameAttClass }
*
*/
public FrameAttClass getFrame() {
return frame;
}
/**
* Sets the value of the frame property.
*
* @param value
* allowed object is
* {@link FrameAttClass }
*
*/
public void setFrame(FrameAttClass value) {
this.frame = value;
}
/**
* Gets the value of the expanse property.
*
* @return
* possible object is
* {@link ExpanseAttClass }
*
*/
public ExpanseAttClass getExpanse() {
return expanse;
}
/**
* Sets the value of the expanse property.
*
* @param value
* allowed object is
* {@link ExpanseAttClass }
*
*/
public void setExpanse(ExpanseAttClass value) {
this.expanse = value;
}
/**
* Gets the value of the xtrc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrc() {
return xtrc;
}
/**
* Sets the value of the xtrc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrc(String value) {
this.xtrc = value;
}
/**
* Gets the value of the xtrf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrf() {
return xtrf;
}
/**
* Sets the value of the xtrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrf(String value) {
this.xtrf = value;
}
}
| ramsodev/DitaManagement | dita/dita.task/src/net/ramso/dita/task/SyntaxdiagramClass.java | Java | gpl-3.0 | 16,371 |
/*
* Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma
* de Madrid, http://ir.ii.uam.es
*
* 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 es.uam.eps.ir.ranksys.core.preference;
/**
* A user or item preference.
*
* @author Saúl Vargas ([email protected])
*
* @param <I> type of the user or item
* @param <O> type of other information
*/
public class IdPref<I, O> {
/**
* The ID of a user or an item.
*/
public final I id;
/**
* The weight (rating, play count, etc.) of the preference.
*/
public final double v;
/**
* Other information (such as an access log, context) of the preference.
*/
public final O o;
/**
* Constructs a preference.
*
* @param id ID of user or item for which the preference is expressed
* @param value weight of the preference
* @param other other information of the preference
*/
public IdPref(I id, double value, O other) {
this.id = id;
this.v = value;
this.o = other;
}
}
| OlafLee/RankSys | RankSys-core/src/main/java/es/uam/eps/ir/ranksys/core/preference/IdPref.java | Java | gpl-3.0 | 1,669 |
package gui;
import chen.c;
public class Rmscd extends command {
Rms dis;
String name;
Contrlable g;
Rmscd(Rms g) {
this.g = g;
dis = g;
show = new String[]{"´ò¿ª", "ɾ³ý", "н¨", "ÐÅÏ¢", "Ë¢ÐÂ", "½ØÆÁ", "µ¼Èë", "µ¼³ö", "·µ»Ø"};
kd = Canvas.font.stringWidth("8. ²ì¿´") + 2;
zhs = show.length;
}
public void select() {
switch (hs) {
case 0:
dis.select();
break;
case 1:
if (dis.dodelete(dis.hs-1)) {
dis.dodelete(dis.hs - 1);
}
break;
case 2:
dis.create();
break;
case 3:
dis.info();
break;
case 4:
dis.openDir();
break;
case 5:
dis.jiepin();
break;
case 6:
case 7:
c.browser.ll.state = 1;
c.browser.showll = true;
c.browser.ll.init();
Showhelper.show=c.browser;
default:
break;
}
}
}
| ghostgzt/STX | src/gui/Rmscd.java | Java | gpl-3.0 | 1,197 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.util.Random;
// Referenced classes of package net.minecraft.src:
// BlockContainer, Material, World, Block,
// TileEntityEnchantmentTable, EntityPlayer, TileEntity
public class BlockEnchantmentTable extends BlockContainer
{
protected BlockEnchantmentTable(int p_i698_1_)
{
super(p_i698_1_, 166, Material.field_1334_d);
func_213_a(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F);
func_256_d(0);
}
public boolean func_242_c()
{
return false;
}
public void func_247_b(World p_247_1_, int p_247_2_, int p_247_3_, int p_247_4_, Random p_247_5_)
{
super.func_247_b(p_247_1_, p_247_2_, p_247_3_, p_247_4_, p_247_5_);
for(int i = p_247_2_ - 2; i <= p_247_2_ + 2; i++)
{
for(int j = p_247_4_ - 2; j <= p_247_4_ + 2; j++)
{
if(i > p_247_2_ - 2 && i < p_247_2_ + 2 && j == p_247_4_ - 1)
{
j = p_247_4_ + 2;
}
if(p_247_5_.nextInt(16) != 0)
{
continue;
}
for(int k = p_247_3_; k <= p_247_3_ + 1; k++)
{
if(p_247_1_.func_600_a(i, k, j) != Block.field_407_ao.field_376_bc)
{
continue;
}
if(!p_247_1_.func_20084_d((i - p_247_2_) / 2 + p_247_2_, k, (j - p_247_4_) / 2 + p_247_4_))
{
break;
}
p_247_1_.func_694_a("enchantmenttable", (double)p_247_2_ + 0.5D, (double)p_247_3_ + 2D, (double)p_247_4_ + 0.5D, (double)((float)(i - p_247_2_) + p_247_5_.nextFloat()) - 0.5D, (float)(k - p_247_3_) - p_247_5_.nextFloat() - 1.0F, (double)((float)(j - p_247_4_) + p_247_5_.nextFloat()) - 0.5D);
}
}
}
}
public boolean func_217_b()
{
return false;
}
public int func_232_a(int p_232_1_, int p_232_2_)
{
return func_218_a(p_232_1_);
}
public int func_218_a(int p_218_1_)
{
if(p_218_1_ == 0)
{
return field_378_bb + 17;
}
if(p_218_1_ == 1)
{
return field_378_bb;
} else
{
return field_378_bb + 16;
}
}
public TileEntity func_283_a_()
{
return new TileEntityEnchantmentTable();
}
public boolean func_250_a(World p_250_1_, int p_250_2_, int p_250_3_, int p_250_4_, EntityPlayer p_250_5_)
{
if(p_250_1_.field_1026_y)
{
return true;
} else
{
p_250_5_.func_40181_c(p_250_2_, p_250_3_, p_250_4_);
return true;
}
}
}
| sethten/MoDesserts | mcp50/temp/src/minecraft/net/minecraft/src/BlockEnchantmentTable.java | Java | gpl-3.0 | 2,991 |
/*******************************************************************************
* | o |
* | o o | HELYX-OS: The Open Source GUI for OpenFOAM |
* | o O o | Copyright (C) 2012-2016 ENGYS |
* | o o | http://www.engys.com |
* | o | |
* |---------------------------------------------------------------------------|
* | License |
* | This file is part of HELYX-OS. |
* | |
* | HELYX-OS 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. |
* | |
* | HELYX-OS 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 HELYX-OS; if not, write to the Free Software Foundation, |
* | Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
*******************************************************************************/
package eu.engys.gui.casesetup.fields;
import java.util.ArrayList;
import java.util.List;
import eu.engys.core.project.Model;
import eu.engys.core.project.geometry.Surface;
import eu.engys.core.project.zero.fields.CellSetInitialisation.ScalarSurface;
import eu.engys.core.project.zero.fields.Fields;
import eu.engys.core.project.zero.fields.ScalarCellSetInitialisation;
import eu.engys.util.progress.ProgressMonitor;
public class InitialisationScalarCellSetDialog extends CellSetDialog {
private final String fieldName;
private ScalarCellSetInitialisation initialisation;
public InitialisationScalarCellSetDialog(Model model, String fieldName, ProgressMonitor monitor) {
super(model, getTitle(fieldName), monitor);
this.fieldName = fieldName;
}
private static String getTitle(String fieldName) {
return fieldName.equals(Fields.ALPHA_1) ? fieldName + " [phase 1]" : fieldName;
}
@Override
protected CellSetRow newRow(Surface surface) {
if (fieldName.startsWith(Fields.ALPHA)) {
return new InitialisationAlphaCellSetRow(model, fieldName, surface, 0.0, monitor);
} else {
return new InitialisationScalarCellSetRow(model, fieldName, surface, 0.0, monitor);
}
}
private CellSetRow createRow(Surface surface, double value, Integer i) {
if (fieldName.startsWith(Fields.ALPHA)) {
return new InitialisationAlphaCellSetRow(model, fieldName, surface, value, monitor);
} else {
return new InitialisationScalarCellSetRow(model, fieldName, surface, value, monitor);
}
}
@Override
public void load() {
List<ScalarSurface> sources = initialisation.getSurfaces();
for (int i = 0; i < sources.size(); i++) {
ScalarSurface scalarSurface = sources.get(i);
addRow(createRow(scalarSurface.getSurface(), scalarSurface.getValue(), i));
}
}
@Override
public void save() {
List<Surface> surfaces = getSurfaces();
List<Double> values = getValues();
List<ScalarSurface> ss = new ArrayList<>();
for (int i = 0; i < surfaces.size(); i++) {
Surface surface = surfaces.get(i);
Double value = values.get(i);
ss.add(new ScalarSurface(surface, value));
}
initialisation.setSurfaces(ss);
}
private List<Double> getValues() {
List<Double> values = new ArrayList<>();
for (CellSetRow row : rowsMap.values()) {
if (row instanceof InitialisationScalarCellSetRow) {
values.add(((InitialisationScalarCellSetRow)row).getValue());
} else if (row instanceof InitialisationAlphaCellSetRow) {
values.add(((InitialisationAlphaCellSetRow)row).getValue());
}
}
return values;
}
public void setInitialisation(ScalarCellSetInitialisation initialisation) {
this.initialisation = initialisation;
}
public ScalarCellSetInitialisation getInitialisation() {
return initialisation;
}
}
| ENGYS/HELYX-OS | src/eu/engys/gui/casesetup/fields/InitialisationScalarCellSetDialog.java | Java | gpl-3.0 | 5,102 |
package dfh.anagrammar;
import java.util.Arrays;
public class CharCount {
int n = 0;
final int[] counts;
CharCount(int countSize) {
counts = new int[countSize];
}
CharCount dup() {
return new CharCount(n, counts);
}
/**
* @param i
* @return whether there are any characters with index i
*/
boolean has(int i) {
return n > 0 && i < counts.length && counts[i] > 0;
}
/**
* @param i
* translated character to decrement
* @return appropriately decremented duplicate character count, or null if
* this particular count cannot be decremented
*/
CharCount decrement(int i) {
if (i < counts.length && counts[i] > 0) {
CharCount d = dup();
d.counts[i]--;
d.n--;
return d;
} else {
return null;
}
}
boolean empty() {
return n == 0;
}
private CharCount(int n, int[] counts) {
this.n = n;
this.counts = Arrays.copyOf(counts, counts.length);
}
@Override
public String toString() {
StringBuffer b = new StringBuffer();
b.append('[');
for (int i = 0; i < counts.length - 1; i++)
b.append(counts[i]).append(',');
b.append(counts[counts.length - 1]).append("](").append(n).append(')');
return b.toString();
}
}
| dfhoughton/anagrammar | src/dfh/anagrammar/CharCount.java | Java | gpl-3.0 | 1,204 |
package com.cjmcguire.bukkit.dynamic.commands.scale;
import org.bukkit.Server;
import com.cjmcguire.bukkit.dynamic.playerdata.MobInfo;
/**
* Tests the ScaleDefenseCommand class.
* @author CJ McGuire
*/
public class TestScaleDefenseCommand extends TestAbstractScaleCommand
{
@Override
protected AbstractScaleCommand getScaleCommand(Server mockServer)
{
return new ScaleDefenseCommand(mockServer);
}
@Override
protected String getCommandName()
{
return ScaleDefenseCommand.NAME;
}
@Override
protected boolean shouldScaleAttribute(MobInfo mobInfo)
{
return mobInfo.shouldScaleDefense();
}
}
| siege1313/DynamicDifficulty | tests/com/cjmcguire/bukkit/dynamic/commands/scale/TestScaleDefenseCommand.java | Java | gpl-3.0 | 646 |
package com.palbaladejo.tripbooker.integration.flight;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.palbaladejo.tripbooker.dto.domain.flight.IFlightDO;
import com.palbaladejo.tripbooker.dto.domain.factory.DOFactory;
import com.palbaladejo.tripbooker.integration.factory.DAO;
import com.palbaladejo.tripbooker.persistence.database.exception.TransactionException;
/**
*
* @author Pablo Albaladejo Mestre <[email protected]>
*/
public class FlightDAOImp extends DAO implements IFlightDAO{
private void copyResultFlightData(ResultSet result, IFlightDO flight) throws SQLException {
flight.setFlightID(result.getInt(1));
flight.setCode(result.getString(2));
flight.setAirlineID(result.getInt(3));
flight.setAircraftID(result.getInt(4));
flight.setRouteID(result.getInt(5));
flight.setDate(toJavaDate(result.getDate(6), result.getTime(6)));
flight.setEconomyFare(result.getFloat(7));
flight.setBusinessFare(result.getFloat(8));
flight.setOfferFare(result.getFloat(9));
flight.setBusinessSeats(result.getInt(10));
}
@Override
public List<IFlightDO> getAllFlights() throws TransactionException {
List<IFlightDO> list = new ArrayList<IFlightDO>();
String query = "SELECT * FROM flight";
try {
this.resultSet = this.statement.executeQuery(query);
while (this.resultSet.next()) {
IFlightDO flight = DOFactory.getInstance().getFlightDO();
copyResultFlightData(resultSet, flight);
list.add(flight);
}
} catch (SQLException e) {
throw new TransactionException(e);
}
return list;
}
@Override
public IFlightDO getFlightByID(int id) throws TransactionException {
IFlightDO flight = null;
String query = "SELECT * FROM flight"
+ " WHERE flightID = '" + id + "'";
try {
this.resultSet = this.statement.executeQuery(query);
if (resultSet.next()) {
flight = DOFactory.getInstance().getFlightDO();
copyResultFlightData(resultSet, flight);
} else {
flight = null;
}
} catch (SQLException e) {
throw new TransactionException(e);
}
return flight;
}
@Override
public IFlightDO getFlightByCodeDate(String code, Date date)throws TransactionException {
IFlightDO flight = null;
String query = "SELECT * FROM flight"
+ " WHERE code = '" + code + "' AND date ='"+this.toSqlDate(date)+"'";
try {
this.resultSet = this.statement.executeQuery(query);
if (resultSet.next()) {
flight = DOFactory.getInstance().getFlightDO();
copyResultFlightData(resultSet, flight);
} else {
flight = null;
}
} catch (SQLException e) {
throw new TransactionException(e);
}
return flight;
}
@Override
public List<IFlightDO> getFlightsByAirline(int airlineID) throws TransactionException {
List<IFlightDO> list = new ArrayList<IFlightDO>();
String query = "SELECT * FROM flight WHERE airlineID ='"+airlineID+"'";
try {
this.resultSet = this.statement.executeQuery(query);
while (this.resultSet.next()) {
IFlightDO flight = DOFactory.getInstance().getFlightDO();
copyResultFlightData(resultSet, flight);
list.add(flight);
}
} catch (SQLException e) {
throw new TransactionException(e);
}
return list;
}
@Override
public List<IFlightDO> getFlightsByRoute(int routeID) throws TransactionException {
List<IFlightDO> list = new ArrayList<IFlightDO>();
String query = "SELECT * FROM flight WHERE routeID ='"+routeID+"'";
try {
this.resultSet = this.statement.executeQuery(query);
while (this.resultSet.next()) {
IFlightDO flight = DOFactory.getInstance().getFlightDO();
copyResultFlightData(resultSet, flight);
list.add(flight);
}
} catch (SQLException e) {
throw new TransactionException(e);
}
return list;
}
@Override
public boolean removeFlight(int id) throws TransactionException {
boolean deleteActionResult = false;
String query = "DELETE FROM flight"
+ " WHERE flightID = '" + id + "'";
try {
int numRows = this.statement.executeUpdate(query);
if (numRows > 0) {
deleteActionResult = true;
}
} catch (SQLException ex) {
throw new TransactionException(ex);
}
return deleteActionResult;
}
@Override
public boolean persistFlight(IFlightDO flight) throws TransactionException {
boolean InsertActionResult = false;
String query = "";
if(this.getFlightByID(flight.getFlightID()) != null){
query = "UPDATE flight SET "
+ "code = '" + flight.getCode() +"', "
+ "airlineID = '" + flight.getAirlineID()+"', "
+ "aircraftID = '" + flight.getAircraftID()+"', "
+ "routeID = '" + flight.getRouteID()+"', "
+ "date = '" + toSqlDate(flight.getDate())+"', "
+ "economyFare = '" + flight.getEconomyFare()+"', "
+ "businessFare = '" + flight.getBusinessFare()+"', "
+ "offerFare = '" + flight.getOfferFare()+"', "
+ "businessSeats = '" + flight.getBusinessSeats()+"' "
+ "WHERE flightID = '" + flight.getFlightID()+ "'";
}else{
query = "INSERT INTO flight"
+ " (`code`, `airlineID`,`aircraftID`,`routeID`,"
+ "`date`,`economyFare`,`businessFare`,`offerFare`,"
+ "`businessSeats`"
+ ") VALUES ("
+ "'" + flight.getCode()+ "', "
+ "'" + flight.getAirlineID() + "', "
+ "'" + flight.getAircraftID() + "', "
+ "'" + flight.getRouteID() + "', "
+ "'" + toSqlDate(flight.getDate()) + "', "
+ "'" + flight.getEconomyFare() + "', "
+ "'" + flight.getBusinessFare() + "', "
+ "'" + flight.getOfferFare() + "', "
+ "'" + flight.getBusinessSeats() + "'"
+ ")";
}
try {
int numRows = this.statement.executeUpdate(query);
if (numRows > 0) {
InsertActionResult = true;
}
} catch (SQLException ex) {
throw new TransactionException(ex);
}
return InsertActionResult;
}
}
| palbaladejo/tripbooker | src/main/java/com/palbaladejo/tripbooker/integration/flight/FlightDAOImp.java | Java | gpl-3.0 | 7,129 |
/*
* Hasher - Hashes and verifies entire directory trees.
* Copyright (C) 2014 Oliver Konz <[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 it.konz.hasher;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Compares the hash files in directory structures.
*/
public class CompareVisitor implements FileVisitor<Path> {
private static final Logger logger = Logger.getLogger(CompareVisitor.class.getName());
private Scanner scanner;
private final Map<Path, Map<String, HashEntry>> hashFiles = new HashMap<>();
private long compareErrors = 0L;
private long otherErrors = 0L;
public CompareVisitor(final Scanner scanner) {
this.scanner = scanner;
}
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
Path hashFilePath = dir.resolve(scanner.getHashFileName());
File hashFile = hashFilePath.toFile();
Map<String, HashEntry> hashEntries = new HashMap<>();
if (hashFile.exists()) {
otherErrors += HashEntry.parseHashesFile(hashFilePath, hashEntries);
} else {
logger.info("Unhashed directory: " + dir.toString());
}
hashFiles.put(dir, hashEntries);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}
| Oliver-Konz/hasher | src/main/java/it/konz/hasher/CompareVisitor.java | Java | gpl-3.0 | 2,670 |
/**
* File ./src/main/java/de/lemo/apps/restws/proxies/service/ServiceVersion.java
* Lemo-Application-Server for learning analytics.
* Copyright (C) 2015
* Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff
*
* 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/>.
**/
/**
* File ServiceVersion.java
* Date Feb 14, 2013
* Project Lemo Learning Analytics
*/
package de.lemo.apps.restws.proxies.service;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* @author Andreas Pursian
*
*/
public interface ServiceVersion {
@GET
@Produces(MediaType.APPLICATION_JSON)
String getDMSVersion();
@GET
@Produces(MediaType.APPLICATION_JSON)
String getDBVersion();
}
| LemoProject/Lemo-Application-Server | src/main/java/de/lemo/apps/restws/proxies/service/ServiceVersion.java | Java | gpl-3.0 | 1,364 |
/*
* Copyright (C) 2015-2017 PÂRIS Quentin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.phoenicis.javafx;
import javafx.application.Application;
import javafx.scene.image.Image;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.phoenicis.javafx.controller.MainController;
import org.phoenicis.multithreading.ControlledThreadPoolExecutorServiceCloser;
import org.phoenicis.tools.system.OperatingSystemFetcher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class JavaFXApplication extends Application {
public static void main(String[] args) {
Application.launch(JavaFXApplication.class);
}
@Override
public void start(Stage primaryStage) {
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("views/common/phoenicis.png")));
primaryStage.setTitle("Phoenicis");
loadFonts();
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
final MainController mainController = applicationContext.getBean(MainController.class);
mainController.show();
mainController.setOnClose(() -> {
applicationContext.getBean(ControlledThreadPoolExecutorServiceCloser.class).setCloseImmediately(true);
applicationContext.close();
});
}
private void loadFonts() {
Font.loadFont(getClass().getResource("views/common/mavenpro/MavenPro-Medium.ttf").toExternalForm(), 12);
Font.loadFont(getClass().getResource("views/common/roboto/Roboto-Medium.ttf").toExternalForm(), 12);
Font.loadFont(getClass().getResource("views/common/roboto/Roboto-Light.ttf").toExternalForm(), 12);
Font.loadFont(getClass().getResource("views/common/roboto/Roboto-Bold.ttf").toExternalForm(), 12);
}
}
| RoninDusette/POL-POM-5 | phoenicis-javafx/src/main/java/org/phoenicis/javafx/JavaFXApplication.java | Java | gpl-3.0 | 2,610 |
/*
* TURNUS - www.turnus.co
*
* Copyright (C) 2010-2016 EPFL SCI STI MM
*
* This file is part of TURNUS.
*
* TURNUS 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.
*
* TURNUS 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 TURNUS. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it
* with Eclipse (or a modified version of Eclipse or an Eclipse plugin or
* an Eclipse library), containing parts covered by the terms of the
* Eclipse Public License (EPL), the licensors of this Program grant you
* additional permission to convey the resulting work. Corresponding Source
* for a non-source form of such a combination shall include the source code
* for the parts of Eclipse libraries used as well as that of the covered work.
*
*/
package turnus.orcc.util;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "turnus.orcc.utils"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| turnus/turnus.orcc | turnus.orcc.util/src/turnus/orcc/util/Activator.java | Java | gpl-3.0 | 2,374 |
/*
* https://github.com/achatain/catalog
*
* Copyright (C) 2017 Antoine Chatain (achatain [at] outlook [dot] com)
*
* 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.github.achatain.catalog.service.impl;
import com.github.achatain.catalog.dao.ItemDao;
import com.github.achatain.catalog.dto.ItemDto;
import com.github.achatain.catalog.entity.Item;
import com.github.achatain.catalog.service.ItemService;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.String.format;
public class ItemServiceImpl implements ItemService {
private final ItemDao itemDao;
@Inject
ItemServiceImpl(final ItemDao itemDao) {
this.itemDao = itemDao;
}
@Override
public List<ItemDto> listItems(final String userId, final String collectionId) {
return itemDao
.listItems(userId, collectionId)
.stream()
.map(item -> ItemDto.create()
.withId(item.getId())
.withAttributes(item.getAttributes())
.build())
.collect(Collectors.toList());
}
@Override
public void createItem(final String userId, final String collectionId, final ItemDto itemDto) {
final Item item = Item.create()
.withAttributes(itemDto.getAttributes())
.build();
itemDao.createItem(userId, collectionId, item);
}
@Override
public Optional<ItemDto> readItem(final String userId, final String collectionId, final String itemId) {
return itemDao.readItem(userId, collectionId, itemId).map(item -> ItemDto.create().withId(item.getId()).withAttributes(item.getAttributes()).build());
}
@Override
public void updateItem(final String userId, final String collectionId, final String itemId, final ItemDto itemDto) {
itemDao.readItem(userId, collectionId, itemId).orElseThrow(() -> new RuntimeException(format("No item found with id [%s] in collection [%s]", itemId, collectionId)));
final Item item = Item.create()
.withId(itemDto.getId())
.withAttributes(itemDto.getAttributes())
.build();
itemDao.updateItem(userId, collectionId, itemId, item);
}
@Override
public void deleteItem(final String userId, final String collectionId, final String itemId) {
itemDao.deleteItem(userId, collectionId, itemId);
}
}
| achatain/catalog | src/main/java/com/github/achatain/catalog/service/impl/ItemServiceImpl.java | Java | gpl-3.0 | 3,120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.