file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
61965_3 | //package util;
//
//import service.interfaces.IDeliveryService;
//
//import javax.annotation.PostConstruct;
//import javax.ejb.Singleton;
//import javax.ejb.Startup;
//import javax.inject.Inject;
//import java.util.Arrays;
//import java.util.HashSet;
//import java.util.Set;
//
//@Singleton
//@Startup
//public class InitData {
// @Inject
// private IDeliveryService deliveryService;
//
// @PostConstruct
// public void initTestDeliveries() {
// String string = "Dit zijn slechts test strings die als orderId worden gebruikt, normaal zijn dit UUIDs";
// String[] list1 = string.split(" ");
//
// Set<String> orderIds = new HashSet<>(Arrays.asList(list1));
// deliveryService.addDelivery(orderIds);
//
// String string2 = "En dit is een andere delivery";
// String[] list2 = string2.split(" ");
//
// Set<String> orderIds2 = new HashSet<>(Arrays.asList(list2));
// deliveryService.addDelivery(orderIds2);
// }
//} | next-lvl-dining/multiProject | deliver/src/main/java/util/InitData.java | 314 | // String string = "Dit zijn slechts test strings die als orderId worden gebruikt, normaal zijn dit UUIDs"; | line_comment | nl | //package util;
//
//import service.interfaces.IDeliveryService;
//
//import javax.annotation.PostConstruct;
//import javax.ejb.Singleton;
//import javax.ejb.Startup;
//import javax.inject.Inject;
//import java.util.Arrays;
//import java.util.HashSet;
//import java.util.Set;
//
//@Singleton
//@Startup
//public class InitData {
// @Inject
// private IDeliveryService deliveryService;
//
// @PostConstruct
// public void initTestDeliveries() {
// String string<SUF>
// String[] list1 = string.split(" ");
//
// Set<String> orderIds = new HashSet<>(Arrays.asList(list1));
// deliveryService.addDelivery(orderIds);
//
// String string2 = "En dit is een andere delivery";
// String[] list2 = string2.split(" ");
//
// Set<String> orderIds2 = new HashSet<>(Arrays.asList(list2));
// deliveryService.addDelivery(orderIds2);
// }
//} |
26580_1 | /*
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted.image;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.graalvm.compiler.core.common.NumUtil;
import org.graalvm.nativeimage.c.function.CFunctionPointer;
import org.graalvm.nativeimage.c.function.RelocatedPointer;
import com.oracle.objectfile.ObjectFile;
import com.oracle.svm.hosted.meta.HostedMethod;
import com.oracle.svm.hosted.meta.MethodPointer;
public final class RelocatableBuffer {
public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) {
return new RelocatableBuffer(name, size, byteOrder);
}
/*
* Map methods.
*/
public RelocatableBuffer.Info getInfo(final int key) {
return getMap().get(key);
}
// The only place is is used is to add the ObjectHeader bits to a DynamicHub,
// which is otherwise just a reference to a class.
// In the future, this could be used for any offset from a relocated object reference.
public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public int mapSize() {
return getMap().size();
}
// TODO: Replace with a visitor pattern rather than exposing the entrySet.
public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() {
return getMap().entrySet();
}
/** Raw map access. */
private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) {
return getMap().put(key, value);
}
/** Raw map access. */
protected Map<Integer, RelocatableBuffer.Info> getMap() {
return map;
}
/*
* ByteBuffer methods.
*/
public byte getByte(final int index) {
return getBuffer().get(index);
}
public RelocatableBuffer putByte(final byte value) {
getBuffer().put(value);
return this;
}
public RelocatableBuffer putByte(final int index, final byte value) {
getBuffer().put(index, value);
return this;
}
public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) {
getBuffer().put(source, offset, length);
return this;
}
public RelocatableBuffer putInt(final int index, final int value) {
getBuffer().putInt(index, value);
return this;
}
public int getPosition() {
return getBuffer().position();
}
public RelocatableBuffer setPosition(final int newPosition) {
getBuffer().position(newPosition);
return this;
}
// TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer.
protected byte[] getBytes() {
return getBuffer().array();
}
// TODO: This should become a private method.
protected ByteBuffer getBuffer() {
return buffer;
}
/*
* Info factory.
*/
private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
return new Info(kind, relocationSize, explicitAddend, targetObject);
}
/*
* Debugging.
*/
public String getName() {
return name;
}
protected static String targetObjectClassification(final Object targetObject) {
final StringBuilder result = new StringBuilder();
if (targetObject == null) {
result.append("null");
} else {
if (targetObject instanceof CFunctionPointer) {
result.append("pointer to function");
if (targetObject instanceof MethodPointer) {
final MethodPointer mp = (MethodPointer) targetObject;
final HostedMethod hm = mp.getMethod();
result.append(" name: ");
result.append(hm.getName());
}
} else {
result.append("pointer to data");
}
}
return result.toString();
}
/** Constructor. */
private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) {
this.name = name;
this.size = size;
final int intSize = NumUtil.safeToInt(size);
this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder);
this.map = new TreeMap<>();
}
// Immutable fields.
/** For debugging. */
protected final String name;
/** The size of the ByteBuffer. */
protected final long size;
/** The ByteBuffer itself. */
protected final ByteBuffer buffer;
/** The map itself. */
private final TreeMap<Integer, RelocatableBuffer.Info> map;
// Constants.
static final long serialVersionUID = 0;
static final int WORD_SIZE = 8; // HACK: hard-code for now
// Note: A non-static inner class.
// Note: To keep the RelocatableBuffer from getting separated from this Info.
public class Info {
/*
* Access methods.
*/
public int getRelocationSize() {
return relocationSize;
}
public ObjectFile.RelocationKind getRelocationKind() {
return relocationKind;
}
public boolean hasExplicitAddend() {
return (explicitAddend != null);
}
// May return null.
public Long getExplicitAddend() {
return explicitAddend;
}
public Object getTargetObject() {
return targetObject;
}
// Protected constructor called only from RelocatableBuffer.infoFactory method.
protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
this.relocationKind = kind;
this.relocationSize = relocationSize;
this.explicitAddend = explicitAddend;
this.targetObject = targetObject;
}
// Immutable state.
private final int relocationSize;
private final ObjectFile.RelocationKind relocationKind;
private final Long explicitAddend;
/**
* The referenced object on the heap. If this is an instance of a {@link RelocatedPointer},
* than the relocation is not treated as a data relocation but has a special meaning, e.g. a
* code (text section) or constants (rodata section) relocation.
*/
private final Object targetObject;
}
}
| nezihyigitbasi/graal | substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/image/RelocatableBuffer.java | 2,283 | /*
* Map methods.
*/ | block_comment | nl | /*
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted.image;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.graalvm.compiler.core.common.NumUtil;
import org.graalvm.nativeimage.c.function.CFunctionPointer;
import org.graalvm.nativeimage.c.function.RelocatedPointer;
import com.oracle.objectfile.ObjectFile;
import com.oracle.svm.hosted.meta.HostedMethod;
import com.oracle.svm.hosted.meta.MethodPointer;
public final class RelocatableBuffer {
public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) {
return new RelocatableBuffer(name, size, byteOrder);
}
/*
* Map methods.
<SUF>*/
public RelocatableBuffer.Info getInfo(final int key) {
return getMap().get(key);
}
// The only place is is used is to add the ObjectHeader bits to a DynamicHub,
// which is otherwise just a reference to a class.
// In the future, this could be used for any offset from a relocated object reference.
public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public int mapSize() {
return getMap().size();
}
// TODO: Replace with a visitor pattern rather than exposing the entrySet.
public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() {
return getMap().entrySet();
}
/** Raw map access. */
private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) {
return getMap().put(key, value);
}
/** Raw map access. */
protected Map<Integer, RelocatableBuffer.Info> getMap() {
return map;
}
/*
* ByteBuffer methods.
*/
public byte getByte(final int index) {
return getBuffer().get(index);
}
public RelocatableBuffer putByte(final byte value) {
getBuffer().put(value);
return this;
}
public RelocatableBuffer putByte(final int index, final byte value) {
getBuffer().put(index, value);
return this;
}
public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) {
getBuffer().put(source, offset, length);
return this;
}
public RelocatableBuffer putInt(final int index, final int value) {
getBuffer().putInt(index, value);
return this;
}
public int getPosition() {
return getBuffer().position();
}
public RelocatableBuffer setPosition(final int newPosition) {
getBuffer().position(newPosition);
return this;
}
// TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer.
protected byte[] getBytes() {
return getBuffer().array();
}
// TODO: This should become a private method.
protected ByteBuffer getBuffer() {
return buffer;
}
/*
* Info factory.
*/
private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
return new Info(kind, relocationSize, explicitAddend, targetObject);
}
/*
* Debugging.
*/
public String getName() {
return name;
}
protected static String targetObjectClassification(final Object targetObject) {
final StringBuilder result = new StringBuilder();
if (targetObject == null) {
result.append("null");
} else {
if (targetObject instanceof CFunctionPointer) {
result.append("pointer to function");
if (targetObject instanceof MethodPointer) {
final MethodPointer mp = (MethodPointer) targetObject;
final HostedMethod hm = mp.getMethod();
result.append(" name: ");
result.append(hm.getName());
}
} else {
result.append("pointer to data");
}
}
return result.toString();
}
/** Constructor. */
private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) {
this.name = name;
this.size = size;
final int intSize = NumUtil.safeToInt(size);
this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder);
this.map = new TreeMap<>();
}
// Immutable fields.
/** For debugging. */
protected final String name;
/** The size of the ByteBuffer. */
protected final long size;
/** The ByteBuffer itself. */
protected final ByteBuffer buffer;
/** The map itself. */
private final TreeMap<Integer, RelocatableBuffer.Info> map;
// Constants.
static final long serialVersionUID = 0;
static final int WORD_SIZE = 8; // HACK: hard-code for now
// Note: A non-static inner class.
// Note: To keep the RelocatableBuffer from getting separated from this Info.
public class Info {
/*
* Access methods.
*/
public int getRelocationSize() {
return relocationSize;
}
public ObjectFile.RelocationKind getRelocationKind() {
return relocationKind;
}
public boolean hasExplicitAddend() {
return (explicitAddend != null);
}
// May return null.
public Long getExplicitAddend() {
return explicitAddend;
}
public Object getTargetObject() {
return targetObject;
}
// Protected constructor called only from RelocatableBuffer.infoFactory method.
protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
this.relocationKind = kind;
this.relocationSize = relocationSize;
this.explicitAddend = explicitAddend;
this.targetObject = targetObject;
}
// Immutable state.
private final int relocationSize;
private final ObjectFile.RelocationKind relocationKind;
private final Long explicitAddend;
/**
* The referenced object on the heap. If this is an instance of a {@link RelocatedPointer},
* than the relocation is not treated as a data relocation but has a special meaning, e.g. a
* code (text section) or constants (rodata section) relocation.
*/
private final Object targetObject;
}
}
|
126171_7 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness, DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness, _extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| ngageoint/geotools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,553 | /* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */ | block_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness, DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness, _extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of<SUF>*/
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
|
6093_1 | package com.newegg.ec.redis.schedule;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.newegg.ec.redis.entity.*;
import com.newegg.ec.redis.plugin.alert.entity.AlertChannel;
import com.newegg.ec.redis.plugin.alert.entity.AlertRecord;
import com.newegg.ec.redis.plugin.alert.entity.AlertRule;
import com.newegg.ec.redis.plugin.alert.service.IAlertChannelService;
import com.newegg.ec.redis.plugin.alert.service.IAlertRecordService;
import com.newegg.ec.redis.plugin.alert.service.IAlertRuleService;
import com.newegg.ec.redis.plugin.alert.service.IAlertService;
import com.newegg.ec.redis.service.*;
import com.newegg.ec.redis.util.RedisUtil;
import com.newegg.ec.redis.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.newegg.ec.redis.entity.NodeRole.MASTER;
import static com.newegg.ec.redis.entity.NodeRole.SLAVE;
import static com.newegg.ec.redis.entity.RedisNode.CONNECTED;
import static com.newegg.ec.redis.util.RedisUtil.REDIS_MODE_SENTINEL;
import static com.newegg.ec.redis.util.SignUtil.EQUAL_SIGN;
import static com.newegg.ec.redis.util.TimeUtil.FIVE_SECONDS;
import static javax.management.timer.Timer.ONE_MINUTE;
import static javax.management.timer.Timer.ONE_SECOND;
/**
* @author Jay.H.Zou
* @date 7/30/2019
*/
@Component
public class AlertMessageSchedule implements IDataCollection, IDataCleanup, ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LoggerFactory.getLogger(AlertMessageSchedule.class);
/**
* 0: email
* 1: wechat web hook
* 2: dingding web hook
* 3: wechat app
*/
private static final int EMAIL = 0;
private static final int WECHAT_WEB_HOOK = 1;
private static final int DINGDING_WEB_HOOK = 2;
private static final int WECHAT_APP = 3;
private static final int ALERT_RECORD_LIMIT = 16;
@Autowired
private IGroupService groupService;
@Autowired
private IClusterService clusterService;
@Autowired
private IRedisNodeService redisNodeService;
@Autowired
private ISentinelMastersService sentinelMastersService;
@Autowired
private IAlertRuleService alertRuleService;
@Autowired
private IAlertChannelService alertChannelService;
@Autowired
private IAlertRecordService alertRecordService;
@Autowired
private INodeInfoService nodeInfoService;
@Autowired
private IAlertService emailAlert;
@Autowired
private IAlertService wechatWebHookAlert;
@Autowired
private IAlertService dingDingWebHookAlert;
@Autowired
private IAlertService wechatAppAlert;
private ExecutorService threadPool;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
int coreSize = Runtime.getRuntime().availableProcessors();
threadPool = new ThreadPoolExecutor(coreSize, coreSize, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
new ThreadFactoryBuilder().setNameFormat("redis-notify-pool-thread-%d").build());
}
/**
*
* 获取 node info 进行计算
* 获取 node status 计算
*/
@Async
@Scheduled(cron = "0 0/1 * * * ? ")
@Override
public void collect() {
List<Group> allGroup = groupService.getAllGroup();
if (allGroup != null && !allGroup.isEmpty()) {
logger.info("Start to check alert rules...");
allGroup.forEach(group -> {
threadPool.submit(new AlertTask(group));
});
}
}
/**
* 每天凌晨0点实行一次,清理数据
*/
@Async
@Scheduled(cron = "0 0 0 * * ?")
@Override
public void cleanup() {
alertRecordService.cleanAlertRecordByTime();
}
private class AlertTask implements Runnable {
private Group group;
AlertTask(Group group) {
this.group = group;
}
@Override
public void run() {
try {
Integer groupId = group.getGroupId();
// 获取 cluster
List<Cluster> clusterList = clusterService.getClusterListByGroupId(groupId);
if (clusterList == null || clusterList.isEmpty()) {
return;
}
// 获取有效的规则
List<AlertRule> validAlertRuleList = getValidAlertRuleList(groupId);
if (validAlertRuleList == null || validAlertRuleList.isEmpty()) {
return;
}
// 更新规则
updateRuleLastCheckTime(validAlertRuleList);
// 获取 AlertChannel
List<AlertChannel> validAlertChannelList = alertChannelService.getAlertChannelByGroupId(groupId);
clusterList.forEach(cluster -> {
List<Integer> ruleIdList = idsToIntegerList(cluster.getRuleIds());
// 获取集群规则
List<AlertRule> alertRuleList = validAlertRuleList.stream()
.filter(alertRule -> alertRule.getGlobal() || ruleIdList.contains(alertRule.getRuleId()))
.collect(Collectors.toList());
if (alertRuleList.isEmpty()) {
return;
}
List<AlertRecord> alertRecordList = getAlertRecords(group, cluster, alertRuleList);
if (alertRecordList.isEmpty()) {
return;
}
// save to database
saveRecordToDB(cluster.getClusterName(), alertRecordList);
logger.info("Start to send alert message...");
// 获取告警通道并发送消息
Multimap<Integer, AlertChannel> channelMultimap = getAlertChannelByIds(validAlertChannelList, cluster.getChannelIds());
if (channelMultimap != null && !channelMultimap.isEmpty() && !alertRecordList.isEmpty()) {
distribution(channelMultimap, alertRecordList);
}
});
} catch (Exception e) {
logger.error("Alert task failed, group name = " + group.getGroupName(), e);
}
}
}
private List<AlertRecord> getAlertRecords(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
// 获取 node info 级别告警
alertRecordList.addAll(getNodeInfoAlertRecord(group, cluster, alertRuleList));
// 获取集群级别的告警
alertRecordList.addAll(getClusterAlertRecord(group, cluster, alertRuleList));
return alertRecordList;
}
private List<AlertRecord> getNodeInfoAlertRecord(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
// 获取 node info 列表
NodeInfoParam nodeInfoParam = new NodeInfoParam(cluster.getClusterId(), TimeType.MINUTE, null);
List<NodeInfo> lastTimeNodeInfoList = nodeInfoService.getLastTimeNodeInfoList(nodeInfoParam);
// 构建告警记录
for (AlertRule alertRule : alertRuleList) {
if (alertRule.getClusterAlert()) {
continue;
}
for (NodeInfo nodeInfo : lastTimeNodeInfoList) {
if (isNotify(nodeInfo, alertRule)) {
alertRecordList.add(buildNodeInfoAlertRecord(group, cluster, nodeInfo, alertRule));
}
}
}
return alertRecordList;
}
/**
* cluster/standalone check
* <p>
* 1.connect cluster/standalone failed
* 2.cluster(mode) cluster_state isn't ok
* 3.node not in cluster/standalone
* 4.node shutdown, not in cluster, bad flags, bad link state, unknown role
*
* @param group
* @param cluster
* @param alertRuleList
* @return
*/
private List<AlertRecord> getClusterAlertRecord(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
String seedNodes = cluster.getNodes();
for (AlertRule alertRule : alertRuleList) {
if (!alertRule.getClusterAlert()) {
continue;
}
Cluster.ClusterState clusterState = cluster.getClusterState();
if (!Objects.equals(Cluster.ClusterState.HEALTH, clusterState)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, seedNodes, "Cluster state is " + clusterState));
}
List<RedisNode> redisNodeList = redisNodeService.getRedisNodeList(cluster.getClusterId());
redisNodeList.forEach(redisNode -> {
String node = RedisUtil.getNodeString(redisNode);
boolean runStatus = redisNode.getRunStatus();
boolean inCluster = redisNode.getInCluster();
String flags = redisNode.getFlags();
boolean flagsNormal = Objects.equals(flags, SLAVE.getValue()) || Objects.equals(flags, MASTER.getValue());
String linkState = redisNode.getLinkState();
NodeRole nodeRole = redisNode.getNodeRole();
// 节点角色为 UNKNOWN
boolean nodeRoleNormal = Objects.equals(nodeRole, MASTER) || Objects.equals(nodeRole, SLAVE);
String reason = "";
if (!runStatus) {
reason = node + " is shutdown;\n";
}
if (!inCluster) {
reason += node + " not in cluster;\n";
}
if (!flagsNormal) {
reason += node + " has bad flags: " + flags + ";\n";
}
if (!Objects.equals(linkState, CONNECTED)) {
reason += node + " " + linkState + ";\n";
}
if (!nodeRoleNormal) {
reason += node + " role is " + nodeRole + ";\n";
}
if (!Strings.isNullOrEmpty(reason)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, node, reason));
}
});
if (Objects.equals(REDIS_MODE_SENTINEL, cluster.getRedisMode())) {
List<AlertRecord> sentinelMasterRecord = getSentinelMasterRecord(group, cluster, alertRule);
alertRecordList.addAll(sentinelMasterRecord);
}
}
return alertRecordList;
}
/**
* 1. not monitor
* 2. master changed
* 3. status or state not ok
*
* @param group
* @param cluster
* @param alertRule
* @return
*/
private List<AlertRecord> getSentinelMasterRecord(Group group, Cluster cluster, AlertRule alertRule) {
List<AlertRecord> alertRecordList = new ArrayList<>();
List<SentinelMaster> sentinelMasterList = sentinelMastersService.getSentinelMasterByClusterId(cluster.getClusterId());
sentinelMasterList.forEach(sentinelMaster -> {
String node = RedisUtil.getNodeString(sentinelMaster.getHost(), sentinelMaster.getPort());
String masterName = sentinelMaster.getName();
String flags = sentinelMaster.getFlags();
String status = sentinelMaster.getStatus();
String reason = "";
if (!sentinelMaster.getMonitor()) {
reason += masterName + " is not being monitored now.\n";
}
if (sentinelMaster.getMasterChanged()) {
reason += masterName + " failover, old master: " + sentinelMaster.getLastMasterNode() + ", new master: " + node + ".\n";
}
if (!Objects.equals(flags, MASTER.getValue())) {
reason += masterName + " flags: " + flags + ".\n";
}
if (!Objects.equals("ok", status)) {
reason += masterName + " status: " + status + ".\n";
}
if (!Strings.isNullOrEmpty(reason)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, node, reason));
}
});
return alertRecordList;
}
/**
* 获取 group 下没有冻结(valid == true)且满足时间周期(nowTime - lastCheckTime >= cycleTime)的规则
*
* @param groupId
* @return
*/
private List<AlertRule> getValidAlertRuleList(Integer groupId) {
List<AlertRule> validAlertRuleList = alertRuleService.getAlertRuleByGroupId(groupId);
if (validAlertRuleList == null || validAlertRuleList.isEmpty()) {
return null;
}
validAlertRuleList.removeIf(alertRule -> !isRuleValid(alertRule));
return validAlertRuleList;
}
private Multimap<Integer, AlertChannel> getAlertChannelByIds(List<AlertChannel> validAlertChannelList, String channelIds) {
List<Integer> channelIdList = idsToIntegerList(channelIds);
List<AlertChannel> alertChannelList = new ArrayList<>();
if (validAlertChannelList == null || validAlertChannelList.isEmpty()) {
return null;
}
validAlertChannelList.forEach(alertChannel -> {
if (channelIdList.contains(alertChannel.getChannelId())) {
alertChannelList.add(alertChannel);
}
});
return classifyChannel(alertChannelList);
}
private Multimap<Integer, AlertChannel> classifyChannel(List<AlertChannel> alertChannelList) {
Multimap<Integer, AlertChannel> channelMultimap = ArrayListMultimap.create();
alertChannelList.forEach(alertChannel -> {
channelMultimap.put(alertChannel.getChannelType(), alertChannel);
});
return channelMultimap;
}
/**
* "1,2,3,4" => [1, 2, 3, 4]
*
* @param ids
* @return
*/
private List<Integer> idsToIntegerList(String ids) {
List<Integer> idList = new ArrayList<>();
if (Strings.isNullOrEmpty(ids)) {
return idList;
}
String[] idArr = SignUtil.splitByCommas(ids);
for (String id : idArr) {
idList.add(Integer.parseInt(id));
}
return idList;
}
/**
* 校验监控指标是否达到阈值
*
* @param nodeInfo
* @param alertRule
* @return
*/
private boolean isNotify(NodeInfo nodeInfo, AlertRule alertRule) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(nodeInfo));
String alertKey = alertRule.getRuleKey();
double alertValue = alertRule.getRuleValue();
String nodeInfoField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, alertKey);
Double actualVal = jsonObject.getDouble(nodeInfoField);
if (actualVal == null) {
return false;
}
int compareType = alertRule.getCompareType();
return compare(alertValue, actualVal, compareType);
}
/**
* 检验规则是否可用
*
* @param alertRule
* @return
*/
private boolean isRuleValid(AlertRule alertRule) {
// 规则状态是否有效
if (!alertRule.getValid()) {
return false;
}
// 检测时间
long lastCheckTime = alertRule.getLastCheckTime().getTime();
long checkCycle = alertRule.getCheckCycle() * ONE_MINUTE;
long duration = System.currentTimeMillis() - lastCheckTime;
return duration >= checkCycle;
}
/**
* 比较类型
* 0: 相等
* 1: 大于
* -1: 小于
* 2: 不等于
*/
private boolean compare(double alertValue, double actualValue, int compareType) {
BigDecimal alertValueBigDecimal = BigDecimal.valueOf(alertValue);
BigDecimal actualValueBigDecimal = BigDecimal.valueOf(actualValue);
switch (compareType) {
case 0:
return alertValueBigDecimal.equals(actualValueBigDecimal);
case 1:
return actualValueBigDecimal.compareTo(alertValueBigDecimal) > 0;
case -1:
return actualValueBigDecimal.compareTo(alertValueBigDecimal) < 0;
case 2:
return !alertValueBigDecimal.equals(actualValueBigDecimal);
default:
return false;
}
}
private AlertRecord buildNodeInfoAlertRecord(Group group, Cluster cluster, NodeInfo nodeInfo, AlertRule rule) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(nodeInfo));
AlertRecord record = new AlertRecord();
String alertKey = rule.getRuleKey();
String nodeInfoField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, alertKey);
Double actualVal = jsonObject.getDouble(nodeInfoField);
record.setGroupId(group.getGroupId());
record.setGroupName(group.getGroupName());
record.setClusterId(cluster.getClusterId());
record.setClusterName(cluster.getClusterName());
record.setRuleId(rule.getRuleId());
record.setRedisNode(nodeInfo.getNode());
record.setAlertRule(rule.getRuleKey() + getCompareSign(rule.getCompareType()) + rule.getRuleValue());
record.setActualData(rule.getRuleKey() + EQUAL_SIGN + actualVal);
record.setCheckCycle(rule.getCheckCycle());
record.setRuleInfo(rule.getRuleInfo());
record.setClusterAlert(rule.getClusterAlert());
return record;
}
private AlertRecord buildClusterAlertRecord(Group group, Cluster cluster, AlertRule rule, String nodes, String reason) {
AlertRecord record = new AlertRecord();
record.setGroupId(group.getGroupId());
record.setGroupName(group.getGroupName());
record.setClusterId(cluster.getClusterId());
record.setClusterName(cluster.getClusterName());
record.setRuleId(rule.getRuleId());
record.setRedisNode(nodes);
record.setAlertRule("Cluster Alert");
record.setActualData(reason);
record.setCheckCycle(rule.getCheckCycle());
record.setRuleInfo(rule.getRuleInfo());
record.setClusterAlert(rule.getClusterAlert());
return record;
}
/**
* 0: =
* 1: >
* -1: <
* 2: !=
*
* @param compareType
* @return
*/
private String getCompareSign(Integer compareType) {
switch (compareType) {
case 0:
return "=";
case 1:
return ">";
case -1:
return "<";
case 2:
return "!=";
default:
return "/";
}
}
/**
* 给各通道发送消息
* 由于部分通道对于消息长度、频率等有限制,此处做了分批、微延迟处理
*
* @param channelMultimap
* @param alertRecordList
*/
private void distribution(Multimap<Integer, AlertChannel> channelMultimap, List<AlertRecord> alertRecordList) {
alert(emailAlert, channelMultimap.get(EMAIL), alertRecordList);
List<List<AlertRecord>> partition = Lists.partition(alertRecordList, ALERT_RECORD_LIMIT);
int size = partition.size();
long waitSecond = size > 10 ? FIVE_SECONDS : ONE_SECOND;
partition.forEach(partAlertRecordList -> {
alert(wechatWebHookAlert, channelMultimap.get(WECHAT_WEB_HOOK), partAlertRecordList);
alert(dingDingWebHookAlert, channelMultimap.get(DINGDING_WEB_HOOK), partAlertRecordList);
alert(wechatAppAlert, channelMultimap.get(WECHAT_APP), partAlertRecordList);
try {
Thread.sleep(waitSecond);
} catch (InterruptedException ignored) {
}
});
}
private void alert(IAlertService alertService, Collection<AlertChannel> alertChannelCollection, List<AlertRecord> alertRecordList) {
alertChannelCollection.forEach(alertChannel -> alertService.alert(alertChannel, alertRecordList));
}
private void saveRecordToDB(String clusterName, List<AlertRecord> alertRecordList) {
if (alertRecordList.isEmpty()) {
return;
}
try {
alertRecordService.addAlertRecord(alertRecordList);
} catch (Exception e) {
logger.error("Save alert to db failed, cluster name = " + clusterName, e);
}
}
private void updateRuleLastCheckTime(List<AlertRule> validAlertRuleList) {
try {
List<Integer> ruleIdList = validAlertRuleList.stream().map(AlertRule::getRuleId).collect(Collectors.toList());
alertRuleService.updateAlertRuleLastCheckTime(ruleIdList);
} catch (Exception e) {
logger.error("Update alert rule last check time, " + validAlertRuleList, e);
}
}
}
| ngbdf/redis-manager | redis-manager-dashboard/src/main/java/com/newegg/ec/redis/schedule/AlertMessageSchedule.java | 6,035 | /**
* 0: email
* 1: wechat web hook
* 2: dingding web hook
* 3: wechat app
*/ | block_comment | nl | package com.newegg.ec.redis.schedule;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.newegg.ec.redis.entity.*;
import com.newegg.ec.redis.plugin.alert.entity.AlertChannel;
import com.newegg.ec.redis.plugin.alert.entity.AlertRecord;
import com.newegg.ec.redis.plugin.alert.entity.AlertRule;
import com.newegg.ec.redis.plugin.alert.service.IAlertChannelService;
import com.newegg.ec.redis.plugin.alert.service.IAlertRecordService;
import com.newegg.ec.redis.plugin.alert.service.IAlertRuleService;
import com.newegg.ec.redis.plugin.alert.service.IAlertService;
import com.newegg.ec.redis.service.*;
import com.newegg.ec.redis.util.RedisUtil;
import com.newegg.ec.redis.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.newegg.ec.redis.entity.NodeRole.MASTER;
import static com.newegg.ec.redis.entity.NodeRole.SLAVE;
import static com.newegg.ec.redis.entity.RedisNode.CONNECTED;
import static com.newegg.ec.redis.util.RedisUtil.REDIS_MODE_SENTINEL;
import static com.newegg.ec.redis.util.SignUtil.EQUAL_SIGN;
import static com.newegg.ec.redis.util.TimeUtil.FIVE_SECONDS;
import static javax.management.timer.Timer.ONE_MINUTE;
import static javax.management.timer.Timer.ONE_SECOND;
/**
* @author Jay.H.Zou
* @date 7/30/2019
*/
@Component
public class AlertMessageSchedule implements IDataCollection, IDataCleanup, ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LoggerFactory.getLogger(AlertMessageSchedule.class);
/**
* 0: email
<SUF>*/
private static final int EMAIL = 0;
private static final int WECHAT_WEB_HOOK = 1;
private static final int DINGDING_WEB_HOOK = 2;
private static final int WECHAT_APP = 3;
private static final int ALERT_RECORD_LIMIT = 16;
@Autowired
private IGroupService groupService;
@Autowired
private IClusterService clusterService;
@Autowired
private IRedisNodeService redisNodeService;
@Autowired
private ISentinelMastersService sentinelMastersService;
@Autowired
private IAlertRuleService alertRuleService;
@Autowired
private IAlertChannelService alertChannelService;
@Autowired
private IAlertRecordService alertRecordService;
@Autowired
private INodeInfoService nodeInfoService;
@Autowired
private IAlertService emailAlert;
@Autowired
private IAlertService wechatWebHookAlert;
@Autowired
private IAlertService dingDingWebHookAlert;
@Autowired
private IAlertService wechatAppAlert;
private ExecutorService threadPool;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
int coreSize = Runtime.getRuntime().availableProcessors();
threadPool = new ThreadPoolExecutor(coreSize, coreSize, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
new ThreadFactoryBuilder().setNameFormat("redis-notify-pool-thread-%d").build());
}
/**
*
* 获取 node info 进行计算
* 获取 node status 计算
*/
@Async
@Scheduled(cron = "0 0/1 * * * ? ")
@Override
public void collect() {
List<Group> allGroup = groupService.getAllGroup();
if (allGroup != null && !allGroup.isEmpty()) {
logger.info("Start to check alert rules...");
allGroup.forEach(group -> {
threadPool.submit(new AlertTask(group));
});
}
}
/**
* 每天凌晨0点实行一次,清理数据
*/
@Async
@Scheduled(cron = "0 0 0 * * ?")
@Override
public void cleanup() {
alertRecordService.cleanAlertRecordByTime();
}
private class AlertTask implements Runnable {
private Group group;
AlertTask(Group group) {
this.group = group;
}
@Override
public void run() {
try {
Integer groupId = group.getGroupId();
// 获取 cluster
List<Cluster> clusterList = clusterService.getClusterListByGroupId(groupId);
if (clusterList == null || clusterList.isEmpty()) {
return;
}
// 获取有效的规则
List<AlertRule> validAlertRuleList = getValidAlertRuleList(groupId);
if (validAlertRuleList == null || validAlertRuleList.isEmpty()) {
return;
}
// 更新规则
updateRuleLastCheckTime(validAlertRuleList);
// 获取 AlertChannel
List<AlertChannel> validAlertChannelList = alertChannelService.getAlertChannelByGroupId(groupId);
clusterList.forEach(cluster -> {
List<Integer> ruleIdList = idsToIntegerList(cluster.getRuleIds());
// 获取集群规则
List<AlertRule> alertRuleList = validAlertRuleList.stream()
.filter(alertRule -> alertRule.getGlobal() || ruleIdList.contains(alertRule.getRuleId()))
.collect(Collectors.toList());
if (alertRuleList.isEmpty()) {
return;
}
List<AlertRecord> alertRecordList = getAlertRecords(group, cluster, alertRuleList);
if (alertRecordList.isEmpty()) {
return;
}
// save to database
saveRecordToDB(cluster.getClusterName(), alertRecordList);
logger.info("Start to send alert message...");
// 获取告警通道并发送消息
Multimap<Integer, AlertChannel> channelMultimap = getAlertChannelByIds(validAlertChannelList, cluster.getChannelIds());
if (channelMultimap != null && !channelMultimap.isEmpty() && !alertRecordList.isEmpty()) {
distribution(channelMultimap, alertRecordList);
}
});
} catch (Exception e) {
logger.error("Alert task failed, group name = " + group.getGroupName(), e);
}
}
}
private List<AlertRecord> getAlertRecords(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
// 获取 node info 级别告警
alertRecordList.addAll(getNodeInfoAlertRecord(group, cluster, alertRuleList));
// 获取集群级别的告警
alertRecordList.addAll(getClusterAlertRecord(group, cluster, alertRuleList));
return alertRecordList;
}
private List<AlertRecord> getNodeInfoAlertRecord(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
// 获取 node info 列表
NodeInfoParam nodeInfoParam = new NodeInfoParam(cluster.getClusterId(), TimeType.MINUTE, null);
List<NodeInfo> lastTimeNodeInfoList = nodeInfoService.getLastTimeNodeInfoList(nodeInfoParam);
// 构建告警记录
for (AlertRule alertRule : alertRuleList) {
if (alertRule.getClusterAlert()) {
continue;
}
for (NodeInfo nodeInfo : lastTimeNodeInfoList) {
if (isNotify(nodeInfo, alertRule)) {
alertRecordList.add(buildNodeInfoAlertRecord(group, cluster, nodeInfo, alertRule));
}
}
}
return alertRecordList;
}
/**
* cluster/standalone check
* <p>
* 1.connect cluster/standalone failed
* 2.cluster(mode) cluster_state isn't ok
* 3.node not in cluster/standalone
* 4.node shutdown, not in cluster, bad flags, bad link state, unknown role
*
* @param group
* @param cluster
* @param alertRuleList
* @return
*/
private List<AlertRecord> getClusterAlertRecord(Group group, Cluster cluster, List<AlertRule> alertRuleList) {
List<AlertRecord> alertRecordList = new ArrayList<>();
String seedNodes = cluster.getNodes();
for (AlertRule alertRule : alertRuleList) {
if (!alertRule.getClusterAlert()) {
continue;
}
Cluster.ClusterState clusterState = cluster.getClusterState();
if (!Objects.equals(Cluster.ClusterState.HEALTH, clusterState)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, seedNodes, "Cluster state is " + clusterState));
}
List<RedisNode> redisNodeList = redisNodeService.getRedisNodeList(cluster.getClusterId());
redisNodeList.forEach(redisNode -> {
String node = RedisUtil.getNodeString(redisNode);
boolean runStatus = redisNode.getRunStatus();
boolean inCluster = redisNode.getInCluster();
String flags = redisNode.getFlags();
boolean flagsNormal = Objects.equals(flags, SLAVE.getValue()) || Objects.equals(flags, MASTER.getValue());
String linkState = redisNode.getLinkState();
NodeRole nodeRole = redisNode.getNodeRole();
// 节点角色为 UNKNOWN
boolean nodeRoleNormal = Objects.equals(nodeRole, MASTER) || Objects.equals(nodeRole, SLAVE);
String reason = "";
if (!runStatus) {
reason = node + " is shutdown;\n";
}
if (!inCluster) {
reason += node + " not in cluster;\n";
}
if (!flagsNormal) {
reason += node + " has bad flags: " + flags + ";\n";
}
if (!Objects.equals(linkState, CONNECTED)) {
reason += node + " " + linkState + ";\n";
}
if (!nodeRoleNormal) {
reason += node + " role is " + nodeRole + ";\n";
}
if (!Strings.isNullOrEmpty(reason)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, node, reason));
}
});
if (Objects.equals(REDIS_MODE_SENTINEL, cluster.getRedisMode())) {
List<AlertRecord> sentinelMasterRecord = getSentinelMasterRecord(group, cluster, alertRule);
alertRecordList.addAll(sentinelMasterRecord);
}
}
return alertRecordList;
}
/**
* 1. not monitor
* 2. master changed
* 3. status or state not ok
*
* @param group
* @param cluster
* @param alertRule
* @return
*/
private List<AlertRecord> getSentinelMasterRecord(Group group, Cluster cluster, AlertRule alertRule) {
List<AlertRecord> alertRecordList = new ArrayList<>();
List<SentinelMaster> sentinelMasterList = sentinelMastersService.getSentinelMasterByClusterId(cluster.getClusterId());
sentinelMasterList.forEach(sentinelMaster -> {
String node = RedisUtil.getNodeString(sentinelMaster.getHost(), sentinelMaster.getPort());
String masterName = sentinelMaster.getName();
String flags = sentinelMaster.getFlags();
String status = sentinelMaster.getStatus();
String reason = "";
if (!sentinelMaster.getMonitor()) {
reason += masterName + " is not being monitored now.\n";
}
if (sentinelMaster.getMasterChanged()) {
reason += masterName + " failover, old master: " + sentinelMaster.getLastMasterNode() + ", new master: " + node + ".\n";
}
if (!Objects.equals(flags, MASTER.getValue())) {
reason += masterName + " flags: " + flags + ".\n";
}
if (!Objects.equals("ok", status)) {
reason += masterName + " status: " + status + ".\n";
}
if (!Strings.isNullOrEmpty(reason)) {
alertRecordList.add(buildClusterAlertRecord(group, cluster, alertRule, node, reason));
}
});
return alertRecordList;
}
/**
* 获取 group 下没有冻结(valid == true)且满足时间周期(nowTime - lastCheckTime >= cycleTime)的规则
*
* @param groupId
* @return
*/
private List<AlertRule> getValidAlertRuleList(Integer groupId) {
List<AlertRule> validAlertRuleList = alertRuleService.getAlertRuleByGroupId(groupId);
if (validAlertRuleList == null || validAlertRuleList.isEmpty()) {
return null;
}
validAlertRuleList.removeIf(alertRule -> !isRuleValid(alertRule));
return validAlertRuleList;
}
private Multimap<Integer, AlertChannel> getAlertChannelByIds(List<AlertChannel> validAlertChannelList, String channelIds) {
List<Integer> channelIdList = idsToIntegerList(channelIds);
List<AlertChannel> alertChannelList = new ArrayList<>();
if (validAlertChannelList == null || validAlertChannelList.isEmpty()) {
return null;
}
validAlertChannelList.forEach(alertChannel -> {
if (channelIdList.contains(alertChannel.getChannelId())) {
alertChannelList.add(alertChannel);
}
});
return classifyChannel(alertChannelList);
}
private Multimap<Integer, AlertChannel> classifyChannel(List<AlertChannel> alertChannelList) {
Multimap<Integer, AlertChannel> channelMultimap = ArrayListMultimap.create();
alertChannelList.forEach(alertChannel -> {
channelMultimap.put(alertChannel.getChannelType(), alertChannel);
});
return channelMultimap;
}
/**
* "1,2,3,4" => [1, 2, 3, 4]
*
* @param ids
* @return
*/
private List<Integer> idsToIntegerList(String ids) {
List<Integer> idList = new ArrayList<>();
if (Strings.isNullOrEmpty(ids)) {
return idList;
}
String[] idArr = SignUtil.splitByCommas(ids);
for (String id : idArr) {
idList.add(Integer.parseInt(id));
}
return idList;
}
/**
* 校验监控指标是否达到阈值
*
* @param nodeInfo
* @param alertRule
* @return
*/
private boolean isNotify(NodeInfo nodeInfo, AlertRule alertRule) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(nodeInfo));
String alertKey = alertRule.getRuleKey();
double alertValue = alertRule.getRuleValue();
String nodeInfoField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, alertKey);
Double actualVal = jsonObject.getDouble(nodeInfoField);
if (actualVal == null) {
return false;
}
int compareType = alertRule.getCompareType();
return compare(alertValue, actualVal, compareType);
}
/**
* 检验规则是否可用
*
* @param alertRule
* @return
*/
private boolean isRuleValid(AlertRule alertRule) {
// 规则状态是否有效
if (!alertRule.getValid()) {
return false;
}
// 检测时间
long lastCheckTime = alertRule.getLastCheckTime().getTime();
long checkCycle = alertRule.getCheckCycle() * ONE_MINUTE;
long duration = System.currentTimeMillis() - lastCheckTime;
return duration >= checkCycle;
}
/**
* 比较类型
* 0: 相等
* 1: 大于
* -1: 小于
* 2: 不等于
*/
private boolean compare(double alertValue, double actualValue, int compareType) {
BigDecimal alertValueBigDecimal = BigDecimal.valueOf(alertValue);
BigDecimal actualValueBigDecimal = BigDecimal.valueOf(actualValue);
switch (compareType) {
case 0:
return alertValueBigDecimal.equals(actualValueBigDecimal);
case 1:
return actualValueBigDecimal.compareTo(alertValueBigDecimal) > 0;
case -1:
return actualValueBigDecimal.compareTo(alertValueBigDecimal) < 0;
case 2:
return !alertValueBigDecimal.equals(actualValueBigDecimal);
default:
return false;
}
}
private AlertRecord buildNodeInfoAlertRecord(Group group, Cluster cluster, NodeInfo nodeInfo, AlertRule rule) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(nodeInfo));
AlertRecord record = new AlertRecord();
String alertKey = rule.getRuleKey();
String nodeInfoField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, alertKey);
Double actualVal = jsonObject.getDouble(nodeInfoField);
record.setGroupId(group.getGroupId());
record.setGroupName(group.getGroupName());
record.setClusterId(cluster.getClusterId());
record.setClusterName(cluster.getClusterName());
record.setRuleId(rule.getRuleId());
record.setRedisNode(nodeInfo.getNode());
record.setAlertRule(rule.getRuleKey() + getCompareSign(rule.getCompareType()) + rule.getRuleValue());
record.setActualData(rule.getRuleKey() + EQUAL_SIGN + actualVal);
record.setCheckCycle(rule.getCheckCycle());
record.setRuleInfo(rule.getRuleInfo());
record.setClusterAlert(rule.getClusterAlert());
return record;
}
private AlertRecord buildClusterAlertRecord(Group group, Cluster cluster, AlertRule rule, String nodes, String reason) {
AlertRecord record = new AlertRecord();
record.setGroupId(group.getGroupId());
record.setGroupName(group.getGroupName());
record.setClusterId(cluster.getClusterId());
record.setClusterName(cluster.getClusterName());
record.setRuleId(rule.getRuleId());
record.setRedisNode(nodes);
record.setAlertRule("Cluster Alert");
record.setActualData(reason);
record.setCheckCycle(rule.getCheckCycle());
record.setRuleInfo(rule.getRuleInfo());
record.setClusterAlert(rule.getClusterAlert());
return record;
}
/**
* 0: =
* 1: >
* -1: <
* 2: !=
*
* @param compareType
* @return
*/
private String getCompareSign(Integer compareType) {
switch (compareType) {
case 0:
return "=";
case 1:
return ">";
case -1:
return "<";
case 2:
return "!=";
default:
return "/";
}
}
/**
* 给各通道发送消息
* 由于部分通道对于消息长度、频率等有限制,此处做了分批、微延迟处理
*
* @param channelMultimap
* @param alertRecordList
*/
private void distribution(Multimap<Integer, AlertChannel> channelMultimap, List<AlertRecord> alertRecordList) {
alert(emailAlert, channelMultimap.get(EMAIL), alertRecordList);
List<List<AlertRecord>> partition = Lists.partition(alertRecordList, ALERT_RECORD_LIMIT);
int size = partition.size();
long waitSecond = size > 10 ? FIVE_SECONDS : ONE_SECOND;
partition.forEach(partAlertRecordList -> {
alert(wechatWebHookAlert, channelMultimap.get(WECHAT_WEB_HOOK), partAlertRecordList);
alert(dingDingWebHookAlert, channelMultimap.get(DINGDING_WEB_HOOK), partAlertRecordList);
alert(wechatAppAlert, channelMultimap.get(WECHAT_APP), partAlertRecordList);
try {
Thread.sleep(waitSecond);
} catch (InterruptedException ignored) {
}
});
}
private void alert(IAlertService alertService, Collection<AlertChannel> alertChannelCollection, List<AlertRecord> alertRecordList) {
alertChannelCollection.forEach(alertChannel -> alertService.alert(alertChannel, alertRecordList));
}
private void saveRecordToDB(String clusterName, List<AlertRecord> alertRecordList) {
if (alertRecordList.isEmpty()) {
return;
}
try {
alertRecordService.addAlertRecord(alertRecordList);
} catch (Exception e) {
logger.error("Save alert to db failed, cluster name = " + clusterName, e);
}
}
private void updateRuleLastCheckTime(List<AlertRule> validAlertRuleList) {
try {
List<Integer> ruleIdList = validAlertRuleList.stream().map(AlertRule::getRuleId).collect(Collectors.toList());
alertRuleService.updateAlertRuleLastCheckTime(ruleIdList);
} catch (Exception e) {
logger.error("Update alert rule last check time, " + validAlertRuleList, e);
}
}
}
|
10275_12 | package jmri.jmrix.zimo;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a single command or response to the Zimo Binary Protocol.
* <P>
* Content is represented with ints to avoid the problems with sign-extension
* that bytes have, and because a Java char is actually a variable number of
* bytes in Unicode.
*
* @author Kevin Dickerson Copyright (C) 2014
*
* Adapted by Sip Bosch for use with zimo MX-1
*
*/
public class Mx1Message extends jmri.jmrix.NetMessage implements Serializable {
public Mx1Message(int len) {
this(len, Mx1Packetizer.ASCII);
}
/**
* Create a new object, representing a specific-length message.
*
* @param len Total bytes in message, including opcode and error-detection
* byte.
*/
public Mx1Message(int len, boolean protocol) {
super(len);
this.protocol = protocol;
if (!protocol) {
if (len > 15 || len < 0) {
log.error("Invalid length in ctor: " + len);
}
}
}
boolean protocol = Mx1Packetizer.ASCII;
//Version 5 and above allow for a message size greater than 15 bytes
public Mx1Message(Integer[] contents) {
super(contents.length);
protocol = Mx1Packetizer.BINARY;
for (int i = 0; i < contents.length; i++) {
this.setElement(i, contents[i]);
}
}
//Version 5 and above allow for a message size greater than 15 bytes
public Mx1Message(byte[] contents) {
super(contents.length);
protocol = Mx1Packetizer.BINARY;
for (int i = 0; i < contents.length; i++) {
this.setElement(i, (contents[i] & 0xff));
}
}
public boolean getLongMessage() {
if (protocol == Mx1Packetizer.BINARY) {
if ((getElement(1) & 0x80) == 0x80) {
return true;
}
}
return false;
}
final static int PRIMARY = 0x00;
final static int ACKREP1 = 0x40;
final static int REPLY2 = 0x20;
final static int ACK2 = 0x60;
/**
* Indicates where the message is to/from in the header byte.
*<p>
* Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the
* first test, which is really 0 == 0 and always true.
* At that point it was changed to just check the bottom two bits.
*/
public int getModule() {
int mod = getElement(1) & 0x0F;
if ((mod & 0x03) == MX1) {
return MX1;
}
if ((mod & 0x03) == MX8) {
return MX8;
}
if ((mod & 0x03) == MX9) {
return MX9;
}
return mod;
}
public int getMessageType() {
return getElement(1) & 0x60;
}
public int getPrimaryMessage() {
return getElement(2);
}
/**
* Message to/from Command Station MX1
*/
static final int MX1 = 0x00;
/**
* Message to/from Accessory module MX8
*/
static final int MX8 = 0x01;
/**
* Message to/from Track Section module MX9
*/
static final int MX9 = 0x02;
final static boolean CS = true;
final static boolean PC = false;
/**
* Indicates the source of the message.
*/
public boolean messageSource() {
if ((getElement(0) & 0x08) == 0x08) {
return PC;
}
return CS;
}
long timeStamp = 0l;
protected long getTimeStamp() {
return timeStamp;
}
protected void setTimeStamp(long ts) {
timeStamp = ts;
}
int retries = 3;
public int getRetry() {
return retries;
}
public void setRetries(int i) {
retries = i;
}
//byte sequenceNo = 0x00;
public boolean replyL1Expected() {
return true;
}
byte[] rawPacket;
public void setRawPacket(byte[] b) {
rawPacket = b;
}
protected byte[] getRawPacket() {
return rawPacket;
}
public void setSequenceNo(byte s) {
setElement(0, (s & 0xff));
}
public int getSequenceNo() {
return (getElement(0) & 0xff);
}
boolean crcError = false;
public void setCRCError() {
crcError = true;
}
public boolean isCRCError() {
return crcError;
}
/**
* check whether the message has a valid parity in fact check for CR or LF
* as end of message
*/
public boolean checkParity() {
//javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!");
int len = getNumDataElements();
return (getElement(len - 1) == (0x0D | 0x0A));
}
// programma komt hier volgens mij nooit
// in fact set CR as end of message
public void setParity() {
javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!");
int len = getNumDataElements();
setElement(len - 1, 0x0D);
}
// decode messages of a particular form
public String getStringMsg() {
StringBuilder txt = new StringBuilder();
if (protocol == Mx1Packetizer.BINARY) {
if (isCRCError()) {
txt.append(" === CRC ERROR === ");
}
if (getNumDataElements() <= 3) {
txt.append("Short Packet ");
return txt.toString();
}
if ((getElement(1) & 0x10) == 0x10) {
txt.append("From PC");
} else {
txt.append("From CS");
}
txt.append(" Seq " + (getElement(0) & 0xff));
if (getLongMessage()) {
txt.append(" (L)");
} else {
txt.append(" (S)");
}
int offset = 0;
if (getMessageType() == PRIMARY) {
txt.append(" Prim");
} else if (getMessageType() == ACKREP1) {
txt.append(" Ack/Reply 1");
} else if (getMessageType() == REPLY2) {
txt.append(" Reply 2");
} else if (getMessageType() == ACK2) {
txt.append(" Ack 2");
} else {
txt.append(" Unknown msg");
}
if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00
txt.append(" to/from CS (MX1)");
switch (getPrimaryMessage()) { //was getElement(2)
case TRACKCTL:
offset = 0;
if (getMessageType() == ACKREP1) {
offset++;
}
txt.append(" Track Control ");
if ((getElement(3 + offset) & 0x03) == 0x03) {
txt.append(" Query Track Status ");
} else if ((getElement(3 + offset) & 0x01) == 0x01) {
txt.append(" Turn Track Off ");
} else if ((getElement(3 + offset) & 0x02) == 0x02) {
txt.append(" Turn Track On ");
} else {
txt.append(" Stop All Locos ");
}
break;
case 3:
txt.append(" Loco Control : ");
if (getMessageType() == PRIMARY) {
txt.append("" + getLocoAddress(getElement((3)), getElement(4)));
txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev ");
txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off ");
txt.append(decodeFunctionStates(getElement(7), getElement(8)));
}
break;
case 4:
txt.append(" Loco Funct ");
break;
case 5:
txt.append(" Loco Acc/Dec ");
break;
case 6:
txt.append(" Shuttle ");
break;
case 7:
txt.append(" Accessory ");
if (getMessageType() == PRIMARY) {
txt.append("" + getLocoAddress(getElement((3)), getElement(4)));
txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed ");
}
break;
case 8:
txt.append(" Loco Status ");
break;
case 9:
txt.append(" Acc Status ");
break;
case 10:
txt.append(" Address Control ");
break;
case 11:
txt.append(" CS State ");
break;
case 12:
txt.append(" Read/Write CS CV ");
break;
case 13:
txt.append(" CS Equip Query ");
break;
case 17:
txt.append(" Tool Type ");
break;
case PROGCMD:
offset = 0;
if (getMessageType() == ACKREP1) {
txt.append(" Prog CV ");
break;
}
if (getMessageType() == REPLY2) {
offset++;
}
if (getMessageType() == ACK2) {
txt.append("Ack to CS Message");
break;
}
if (getNumDataElements() == 7 && getMessageType() == ACKREP1) {
txt.append(" Error Occured ");
txt.append(getErrorCode(getElement(6)));
txt.append(" Loco: " + getLocoAddress(getElement((3 + offset)), getElement(4 + offset)));
break;
}
/*if(getNumDataElements()<7){
txt.append(" Ack L1 ");
break;
}*/
if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) {
txt.append(" Write CV ");
} else {
txt.append(" Read CV ");
}
txt.append("Loco: " + getLocoAddress(getElement((3 + offset)), getElement(4 + offset)));
if ((getElement(3 + offset) & 0x80) == 0x80) {
txt.append(" DCC");
}
int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff));
txt.append(" CV: " + Integer.toString(cv));
if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet
txt.append(" Set To: " + (getElement(7 + offset) & 0xff));
}
break;
case 254:
txt.append(" Cur Acc Memory ");
break;
case 255:
txt.append(" Cur Loco Memory ");
break;
default:
txt.append(" Unknown ");
}
} else if ((getElement(1) & 0x01) == 0x01) {
txt.append(" to/from Accessory Mod (MX8)");
} else if ((getElement(1) & 0x02) == 0x02) {
txt.append(" to/from Track Section (MX9)");
} else {
txt.append(" unknown");
}
}
//int type = getElement(2);
return txt.toString();
}
private String decodeFunctionStates(int cData2, int cData3) {
StringBuilder txt = new StringBuilder();
txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off ");
txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off ");
txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off ");
txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off ");
txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off ");
txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off ");
txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off ");
txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off ");
txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off ");
txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off ");
txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off ");
txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off ");
return txt.toString();
}
public int getLocoAddress() {
int offset = 0;
if (getMessageType() == REPLY2) {
offset++;
} else if (getMessageType() == ACKREP1) {
offset = +2;
}
if (getNumDataElements() == (4 + offset)) {
return getLocoAddress(getElement(3 + offset), getElement(4 + offset));
}
return -1;
}
public int getCvValue() {
int offset = 0;
if (getMessageType() == REPLY2) {
offset++;
} else if (getMessageType() == ACKREP1) {
offset = +2;
}
if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet
return (getElement(7 + offset) & 0xff);
}
return -1;
}
int getLocoAddress(int hi, int lo) {
hi = hi & 0x3F;
if (hi == 0) {
return lo;
} else {
hi = (((hi & 255) - 192) << 8);
hi = hi + (lo & 255);
return hi;
}
}
String getErrorCode(int i) {
switch (i) {
case NO_ERROR:
return "No Error";
case ERR_ADDRESS:
return "Invalid Address";
case ERR_INDEX:
return "Invalid Index";
case ERR_FORWARD:
return "Could not be Forwarded";
case ERR_BUSY:
return "CMD Busy";
case ERR_NO_MOT:
return "Motorola Jump Off";
case ERR_NO_DCC:
return "DCC Jump Off";
case ERR_CV_ADDRESS:
return "Invalid CV";
case ERR_SECTION:
return "Invalid Section";
case ERR_NO_MODUL:
return "No Module Found";
case ERR_MESSAGE:
return "Error in Message";
case ERR_SPEED:
return "Invalid Speed";
default:
return "Unknown Error";
}
}
final static int NO_ERROR = 0x00;
final static int ERR_ADDRESS = 0x01;
final static int ERR_INDEX = 0x02;
final static int ERR_FORWARD = 0x03;
final static int ERR_BUSY = 0x04;
final static int ERR_NO_MOT = 0x05;
final static int ERR_NO_DCC = 0x06;
final static int ERR_CV_ADDRESS = 0x07;
final static int ERR_SECTION = 0x08;
final static int ERR_NO_MODUL = 0x09;
final static int ERR_MESSAGE = 0x0a;
final static int ERR_SPEED = 0x0b;
final static int TRACKCTL = 0x02;
final static int PROGCMD = 0x13;
final static int LOCOCMD = 0x03;
final static int ACCCMD = 0x07;
static public Mx1Message getCmdStnDetails() {
Mx1Message m = new Mx1Message(4);
m.setElement(1, 0x10);
m.setElement(2, 0x13);
m.setElement(3, 0x00);
return m;
}
/**
* Set Track Power Off/Emergency Stop
*
* @return MrcMessage
*/
static public Mx1Message setPowerOff() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x01);
return m;
}
static public Mx1Message setPowerOn() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x02);
return m;
}
static public Mx1Message getTrackStatus() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x03);
return m;
}
/**
* @param locoAddress : address of the loco, if left blank then programming
* track is used
* @param cv : CV that is to be either read in or written
* @param value : Value to be written to the CV, if set to -1, then a
* read is done
* @param dcc : Is the decoder Protocol DCC, true = DCC, false =
* Motorola
*/
static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) {
Mx1Message m;
if (value == -1) {
m = new Mx1Message(7, Mx1Packetizer.BINARY);
} else {
m = new Mx1Message(8, Mx1Packetizer.BINARY);
}
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, PROGCMD);
int locoHi = locoAddress >> 8;
if (dcc) {
locoHi = locoHi + 128;
} else {
locoHi = locoHi + 64;
}
m.setElement(3, (locoHi));
m.setElement(4, (locoAddress & 0xff));
m.setElement(5, cv >> 8);
m.setElement(6, cv & 0xff);
if (value != -1) {
m.setElement(7, value);
}
return m;
}
/**
*
* @param locoAddress Address of the loco that we are issuing the command
* too.
* @param speed Speed Step in the actual Speed Step System
* @param dcc Is this a packet for a DCC or Motorola device
* @param cData2 - Functions Output 0-7
* @param cData3 - Functions Output 9-12
* @return Mx1Message
*/
static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) {
Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY);
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, LOCOCMD);
//High add 80 to indicate DCC
int locoHi = locoAddress >> 8;
if (dcc) {
locoHi = locoHi + 128;
} else {
locoHi = locoHi + 64;
}
m.setElement(3, (locoHi));
m.setElement(4, (locoAddress & 0xff));
m.setElement(5, speed);
m.setElement(6, cData1);
m.setElement(7, cData2);
m.setElement(8, cData3);
return m;
}
static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) {
Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY);
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, ACCCMD);
//High add 80 to indicate DCC
int accHi = accAddress >> 8;
if (dcc) {
accHi = accHi + 128;
} else {
accHi = accHi + 64;
}
m.setElement(3, (accHi));
m.setElement(4, (accAddress & 0xff));
m.setElement(5, 0x00);
if (setting == jmri.Turnout.THROWN) {
m.setElement(5, 0x04);
}
return m;
}
// initialize logging
private final static Logger log = LoggerFactory.getLogger(Mx1Message.class.getName());
}
| ngi644/JMRI | java/src/jmri/jmrix/zimo/Mx1Message.java | 6,236 | // programma komt hier volgens mij nooit | line_comment | nl | package jmri.jmrix.zimo;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a single command or response to the Zimo Binary Protocol.
* <P>
* Content is represented with ints to avoid the problems with sign-extension
* that bytes have, and because a Java char is actually a variable number of
* bytes in Unicode.
*
* @author Kevin Dickerson Copyright (C) 2014
*
* Adapted by Sip Bosch for use with zimo MX-1
*
*/
public class Mx1Message extends jmri.jmrix.NetMessage implements Serializable {
public Mx1Message(int len) {
this(len, Mx1Packetizer.ASCII);
}
/**
* Create a new object, representing a specific-length message.
*
* @param len Total bytes in message, including opcode and error-detection
* byte.
*/
public Mx1Message(int len, boolean protocol) {
super(len);
this.protocol = protocol;
if (!protocol) {
if (len > 15 || len < 0) {
log.error("Invalid length in ctor: " + len);
}
}
}
boolean protocol = Mx1Packetizer.ASCII;
//Version 5 and above allow for a message size greater than 15 bytes
public Mx1Message(Integer[] contents) {
super(contents.length);
protocol = Mx1Packetizer.BINARY;
for (int i = 0; i < contents.length; i++) {
this.setElement(i, contents[i]);
}
}
//Version 5 and above allow for a message size greater than 15 bytes
public Mx1Message(byte[] contents) {
super(contents.length);
protocol = Mx1Packetizer.BINARY;
for (int i = 0; i < contents.length; i++) {
this.setElement(i, (contents[i] & 0xff));
}
}
public boolean getLongMessage() {
if (protocol == Mx1Packetizer.BINARY) {
if ((getElement(1) & 0x80) == 0x80) {
return true;
}
}
return false;
}
final static int PRIMARY = 0x00;
final static int ACKREP1 = 0x40;
final static int REPLY2 = 0x20;
final static int ACK2 = 0x60;
/**
* Indicates where the message is to/from in the header byte.
*<p>
* Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the
* first test, which is really 0 == 0 and always true.
* At that point it was changed to just check the bottom two bits.
*/
public int getModule() {
int mod = getElement(1) & 0x0F;
if ((mod & 0x03) == MX1) {
return MX1;
}
if ((mod & 0x03) == MX8) {
return MX8;
}
if ((mod & 0x03) == MX9) {
return MX9;
}
return mod;
}
public int getMessageType() {
return getElement(1) & 0x60;
}
public int getPrimaryMessage() {
return getElement(2);
}
/**
* Message to/from Command Station MX1
*/
static final int MX1 = 0x00;
/**
* Message to/from Accessory module MX8
*/
static final int MX8 = 0x01;
/**
* Message to/from Track Section module MX9
*/
static final int MX9 = 0x02;
final static boolean CS = true;
final static boolean PC = false;
/**
* Indicates the source of the message.
*/
public boolean messageSource() {
if ((getElement(0) & 0x08) == 0x08) {
return PC;
}
return CS;
}
long timeStamp = 0l;
protected long getTimeStamp() {
return timeStamp;
}
protected void setTimeStamp(long ts) {
timeStamp = ts;
}
int retries = 3;
public int getRetry() {
return retries;
}
public void setRetries(int i) {
retries = i;
}
//byte sequenceNo = 0x00;
public boolean replyL1Expected() {
return true;
}
byte[] rawPacket;
public void setRawPacket(byte[] b) {
rawPacket = b;
}
protected byte[] getRawPacket() {
return rawPacket;
}
public void setSequenceNo(byte s) {
setElement(0, (s & 0xff));
}
public int getSequenceNo() {
return (getElement(0) & 0xff);
}
boolean crcError = false;
public void setCRCError() {
crcError = true;
}
public boolean isCRCError() {
return crcError;
}
/**
* check whether the message has a valid parity in fact check for CR or LF
* as end of message
*/
public boolean checkParity() {
//javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!");
int len = getNumDataElements();
return (getElement(len - 1) == (0x0D | 0x0A));
}
// programma komt<SUF>
// in fact set CR as end of message
public void setParity() {
javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!");
int len = getNumDataElements();
setElement(len - 1, 0x0D);
}
// decode messages of a particular form
public String getStringMsg() {
StringBuilder txt = new StringBuilder();
if (protocol == Mx1Packetizer.BINARY) {
if (isCRCError()) {
txt.append(" === CRC ERROR === ");
}
if (getNumDataElements() <= 3) {
txt.append("Short Packet ");
return txt.toString();
}
if ((getElement(1) & 0x10) == 0x10) {
txt.append("From PC");
} else {
txt.append("From CS");
}
txt.append(" Seq " + (getElement(0) & 0xff));
if (getLongMessage()) {
txt.append(" (L)");
} else {
txt.append(" (S)");
}
int offset = 0;
if (getMessageType() == PRIMARY) {
txt.append(" Prim");
} else if (getMessageType() == ACKREP1) {
txt.append(" Ack/Reply 1");
} else if (getMessageType() == REPLY2) {
txt.append(" Reply 2");
} else if (getMessageType() == ACK2) {
txt.append(" Ack 2");
} else {
txt.append(" Unknown msg");
}
if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00
txt.append(" to/from CS (MX1)");
switch (getPrimaryMessage()) { //was getElement(2)
case TRACKCTL:
offset = 0;
if (getMessageType() == ACKREP1) {
offset++;
}
txt.append(" Track Control ");
if ((getElement(3 + offset) & 0x03) == 0x03) {
txt.append(" Query Track Status ");
} else if ((getElement(3 + offset) & 0x01) == 0x01) {
txt.append(" Turn Track Off ");
} else if ((getElement(3 + offset) & 0x02) == 0x02) {
txt.append(" Turn Track On ");
} else {
txt.append(" Stop All Locos ");
}
break;
case 3:
txt.append(" Loco Control : ");
if (getMessageType() == PRIMARY) {
txt.append("" + getLocoAddress(getElement((3)), getElement(4)));
txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev ");
txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off ");
txt.append(decodeFunctionStates(getElement(7), getElement(8)));
}
break;
case 4:
txt.append(" Loco Funct ");
break;
case 5:
txt.append(" Loco Acc/Dec ");
break;
case 6:
txt.append(" Shuttle ");
break;
case 7:
txt.append(" Accessory ");
if (getMessageType() == PRIMARY) {
txt.append("" + getLocoAddress(getElement((3)), getElement(4)));
txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed ");
}
break;
case 8:
txt.append(" Loco Status ");
break;
case 9:
txt.append(" Acc Status ");
break;
case 10:
txt.append(" Address Control ");
break;
case 11:
txt.append(" CS State ");
break;
case 12:
txt.append(" Read/Write CS CV ");
break;
case 13:
txt.append(" CS Equip Query ");
break;
case 17:
txt.append(" Tool Type ");
break;
case PROGCMD:
offset = 0;
if (getMessageType() == ACKREP1) {
txt.append(" Prog CV ");
break;
}
if (getMessageType() == REPLY2) {
offset++;
}
if (getMessageType() == ACK2) {
txt.append("Ack to CS Message");
break;
}
if (getNumDataElements() == 7 && getMessageType() == ACKREP1) {
txt.append(" Error Occured ");
txt.append(getErrorCode(getElement(6)));
txt.append(" Loco: " + getLocoAddress(getElement((3 + offset)), getElement(4 + offset)));
break;
}
/*if(getNumDataElements()<7){
txt.append(" Ack L1 ");
break;
}*/
if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) {
txt.append(" Write CV ");
} else {
txt.append(" Read CV ");
}
txt.append("Loco: " + getLocoAddress(getElement((3 + offset)), getElement(4 + offset)));
if ((getElement(3 + offset) & 0x80) == 0x80) {
txt.append(" DCC");
}
int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff));
txt.append(" CV: " + Integer.toString(cv));
if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet
txt.append(" Set To: " + (getElement(7 + offset) & 0xff));
}
break;
case 254:
txt.append(" Cur Acc Memory ");
break;
case 255:
txt.append(" Cur Loco Memory ");
break;
default:
txt.append(" Unknown ");
}
} else if ((getElement(1) & 0x01) == 0x01) {
txt.append(" to/from Accessory Mod (MX8)");
} else if ((getElement(1) & 0x02) == 0x02) {
txt.append(" to/from Track Section (MX9)");
} else {
txt.append(" unknown");
}
}
//int type = getElement(2);
return txt.toString();
}
private String decodeFunctionStates(int cData2, int cData3) {
StringBuilder txt = new StringBuilder();
txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off ");
txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off ");
txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off ");
txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off ");
txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off ");
txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off ");
txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off ");
txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off ");
txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off ");
txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off ");
txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off ");
txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off ");
return txt.toString();
}
public int getLocoAddress() {
int offset = 0;
if (getMessageType() == REPLY2) {
offset++;
} else if (getMessageType() == ACKREP1) {
offset = +2;
}
if (getNumDataElements() == (4 + offset)) {
return getLocoAddress(getElement(3 + offset), getElement(4 + offset));
}
return -1;
}
public int getCvValue() {
int offset = 0;
if (getMessageType() == REPLY2) {
offset++;
} else if (getMessageType() == ACKREP1) {
offset = +2;
}
if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet
return (getElement(7 + offset) & 0xff);
}
return -1;
}
int getLocoAddress(int hi, int lo) {
hi = hi & 0x3F;
if (hi == 0) {
return lo;
} else {
hi = (((hi & 255) - 192) << 8);
hi = hi + (lo & 255);
return hi;
}
}
String getErrorCode(int i) {
switch (i) {
case NO_ERROR:
return "No Error";
case ERR_ADDRESS:
return "Invalid Address";
case ERR_INDEX:
return "Invalid Index";
case ERR_FORWARD:
return "Could not be Forwarded";
case ERR_BUSY:
return "CMD Busy";
case ERR_NO_MOT:
return "Motorola Jump Off";
case ERR_NO_DCC:
return "DCC Jump Off";
case ERR_CV_ADDRESS:
return "Invalid CV";
case ERR_SECTION:
return "Invalid Section";
case ERR_NO_MODUL:
return "No Module Found";
case ERR_MESSAGE:
return "Error in Message";
case ERR_SPEED:
return "Invalid Speed";
default:
return "Unknown Error";
}
}
final static int NO_ERROR = 0x00;
final static int ERR_ADDRESS = 0x01;
final static int ERR_INDEX = 0x02;
final static int ERR_FORWARD = 0x03;
final static int ERR_BUSY = 0x04;
final static int ERR_NO_MOT = 0x05;
final static int ERR_NO_DCC = 0x06;
final static int ERR_CV_ADDRESS = 0x07;
final static int ERR_SECTION = 0x08;
final static int ERR_NO_MODUL = 0x09;
final static int ERR_MESSAGE = 0x0a;
final static int ERR_SPEED = 0x0b;
final static int TRACKCTL = 0x02;
final static int PROGCMD = 0x13;
final static int LOCOCMD = 0x03;
final static int ACCCMD = 0x07;
static public Mx1Message getCmdStnDetails() {
Mx1Message m = new Mx1Message(4);
m.setElement(1, 0x10);
m.setElement(2, 0x13);
m.setElement(3, 0x00);
return m;
}
/**
* Set Track Power Off/Emergency Stop
*
* @return MrcMessage
*/
static public Mx1Message setPowerOff() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x01);
return m;
}
static public Mx1Message setPowerOn() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x02);
return m;
}
static public Mx1Message getTrackStatus() {
Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, TRACKCTL);
m.setElement(3, 0x03);
return m;
}
/**
* @param locoAddress : address of the loco, if left blank then programming
* track is used
* @param cv : CV that is to be either read in or written
* @param value : Value to be written to the CV, if set to -1, then a
* read is done
* @param dcc : Is the decoder Protocol DCC, true = DCC, false =
* Motorola
*/
static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) {
Mx1Message m;
if (value == -1) {
m = new Mx1Message(7, Mx1Packetizer.BINARY);
} else {
m = new Mx1Message(8, Mx1Packetizer.BINARY);
}
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, PROGCMD);
int locoHi = locoAddress >> 8;
if (dcc) {
locoHi = locoHi + 128;
} else {
locoHi = locoHi + 64;
}
m.setElement(3, (locoHi));
m.setElement(4, (locoAddress & 0xff));
m.setElement(5, cv >> 8);
m.setElement(6, cv & 0xff);
if (value != -1) {
m.setElement(7, value);
}
return m;
}
/**
*
* @param locoAddress Address of the loco that we are issuing the command
* too.
* @param speed Speed Step in the actual Speed Step System
* @param dcc Is this a packet for a DCC or Motorola device
* @param cData2 - Functions Output 0-7
* @param cData3 - Functions Output 9-12
* @return Mx1Message
*/
static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) {
Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY);
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, LOCOCMD);
//High add 80 to indicate DCC
int locoHi = locoAddress >> 8;
if (dcc) {
locoHi = locoHi + 128;
} else {
locoHi = locoHi + 64;
}
m.setElement(3, (locoHi));
m.setElement(4, (locoAddress & 0xff));
m.setElement(5, speed);
m.setElement(6, cData1);
m.setElement(7, cData2);
m.setElement(8, cData3);
return m;
}
static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) {
Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY);
m.setElement(0, 0x00);
m.setElement(1, 0x10); /* PC control short message */
m.setElement(2, ACCCMD);
//High add 80 to indicate DCC
int accHi = accAddress >> 8;
if (dcc) {
accHi = accHi + 128;
} else {
accHi = accHi + 64;
}
m.setElement(3, (accHi));
m.setElement(4, (accAddress & 0xff));
m.setElement(5, 0x00);
if (setting == jmri.Turnout.THROWN) {
m.setElement(5, 0x04);
}
return m;
}
// initialize logging
private final static Logger log = LoggerFactory.getLogger(Mx1Message.class.getName());
}
|
209835_29 | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package nginx.clojure.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| nginx-clojure/nginx-clojure | src/java/nginx/clojure/asm/tree/analysis/SmallSet.java | 1,901 | /**
* Constructs a new {@link SmallSet}.
*
* @param element1 see {@link #element1}.
* @param element2 see {@link #element2}.
*/ | block_comment | nl | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package nginx.clojure.asm.tree.analysis;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An immutable set of at most two elements, optimized for speed compared to a generic set
* implementation.
*
* @author Eric Bruneton
*/
final class SmallSet<T> extends AbstractSet<T> {
/** The first element of this set, maybe {@literal null}. */
private final T element1;
/**
* The second element of this set, maybe {@literal null}. If {@link #element1} is {@literal null}
* then this field must be {@literal null}, otherwise it must be different from {@link #element1}.
*/
private final T element2;
// -----------------------------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------------------------
/** Constructs an empty set. */
SmallSet() {
this.element1 = null;
this.element2 = null;
}
/**
* Constructs a set with exactly one element.
*
* @param element the unique set element.
*/
SmallSet(final T element) {
this.element1 = element;
this.element2 = null;
}
/**
* Constructs a new<SUF>*/
private SmallSet(final T element1, final T element2) {
this.element1 = element1;
this.element2 = element2;
}
// -----------------------------------------------------------------------------------------------
// Implementation of the inherited abstract methods
// -----------------------------------------------------------------------------------------------
@Override
public Iterator<T> iterator() {
return new IteratorImpl<>(element1, element2);
}
@Override
public int size() {
if (element1 == null) {
return 0;
} else if (element2 == null) {
return 1;
} else {
return 2;
}
}
// -----------------------------------------------------------------------------------------------
// Utility methods
// -----------------------------------------------------------------------------------------------
/**
* Returns the union of this set and of the given set.
*
* @param otherSet another small set.
* @return the union of this set and of otherSet.
*/
Set<T> union(final SmallSet<T> otherSet) {
// If the two sets are equal, return this set.
if ((otherSet.element1 == element1 && otherSet.element2 == element2)
|| (otherSet.element1 == element2 && otherSet.element2 == element1)) {
return this;
}
// If one set is empty, return the other.
if (otherSet.element1 == null) {
return this;
}
if (element1 == null) {
return otherSet;
}
// At this point we know that the two sets are non empty and are different.
// If otherSet contains exactly one element:
if (otherSet.element2 == null) {
// If this set also contains exactly one element, we have two distinct elements.
if (element2 == null) {
return new SmallSet<>(element1, otherSet.element1);
}
// If otherSet is included in this set, return this set.
if (otherSet.element1 == element1 || otherSet.element1 == element2) {
return this;
}
}
// If this set contains exactly one element, then otherSet contains two elements (because of the
// above tests). Thus, if otherSet contains this set, return otherSet:
if (element2 == null && (element1 == otherSet.element1 || element1 == otherSet.element2)) {
return otherSet;
}
// At this point we know that there are at least 3 distinct elements, so we need a generic set
// to store the result.
HashSet<T> result = new HashSet<>(4);
result.add(element1);
if (element2 != null) {
result.add(element2);
}
result.add(otherSet.element1);
if (otherSet.element2 != null) {
result.add(otherSet.element2);
}
return result;
}
static class IteratorImpl<T> implements Iterator<T> {
/** The next element to return in {@link #next}. Maybe {@literal null}. */
private T firstElement;
/**
* The element to return in {@link #next}, after {@link #firstElement} is returned. If {@link
* #firstElement} is {@literal null} then this field must be {@literal null}, otherwise it must
* be different from {@link #firstElement}.
*/
private T secondElement;
IteratorImpl(final T firstElement, final T secondElement) {
this.firstElement = firstElement;
this.secondElement = secondElement;
}
@Override
public boolean hasNext() {
return firstElement != null;
}
@Override
public T next() {
if (firstElement == null) {
throw new NoSuchElementException();
}
T element = firstElement;
firstElement = secondElement;
secondElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
18664_8 | /*
This file is part of WOW! based on AHA! (Adaptive Hypermedia for All) which is free software (GNU General Public License) developed by Paul De Bra - Eindhoven University of Technology and University
WOW! is also open source software;
*/
/**
* CRTSetDefault.java 1.0, June 1, 2008
*
*Copyright (c) 2006 by Eindhoven University of Technology and modified by University of Science, 2008, Vietnam.
* All Rights Reserved.
*
* This software is proprietary information of Eindhoven University of Technology and University
* of Science. It may be used according to the GNU license of Eindhoven University of Technology
*/
package vn.spring.WOW.graphauthor.author;
/**
* ConceptDivideInfo data class to store the setdefault values of a crt.
*
*/
public class CRTSetDefault {
/**
* Contains the location of setDefault
*/
public String location;
/**
* AND | OR combination if there are multiple setdefaults
*/
public String combination;
/**
* The default value of an attribute
*/
public String setdefault;
/**
* Default constructor with emptey var init.
*/
public CRTSetDefault() {
location = "";
combination = "NONE";
setdefault = "";
}
/**
* Extract the attribute out of the location variable.
*
* @return The attribute
*/
public String getAttribute() {
String returnS = "";
if (location.equals("")) {
return returnS;
}
int firstDotPlace = location.indexOf(".");
int lastDotPlace = location.lastIndexOf(".");
try {
if (firstDotPlace == lastDotPlace) {
firstDotPlace++;
returnS = location.substring(firstDotPlace);
} else {
firstDotPlace++;
// lastDotPlace--;
returnS = location.substring(firstDotPlace, lastDotPlace);
}
} catch (Exception e) {
// System.out.println("kan geen attribute vinden");
}
return returnS;
}
} | ngphloc/zebra | source/vn/spring/WOW/graphauthor/author/CRTSetDefault.java | 573 | // System.out.println("kan geen attribute vinden"); | line_comment | nl | /*
This file is part of WOW! based on AHA! (Adaptive Hypermedia for All) which is free software (GNU General Public License) developed by Paul De Bra - Eindhoven University of Technology and University
WOW! is also open source software;
*/
/**
* CRTSetDefault.java 1.0, June 1, 2008
*
*Copyright (c) 2006 by Eindhoven University of Technology and modified by University of Science, 2008, Vietnam.
* All Rights Reserved.
*
* This software is proprietary information of Eindhoven University of Technology and University
* of Science. It may be used according to the GNU license of Eindhoven University of Technology
*/
package vn.spring.WOW.graphauthor.author;
/**
* ConceptDivideInfo data class to store the setdefault values of a crt.
*
*/
public class CRTSetDefault {
/**
* Contains the location of setDefault
*/
public String location;
/**
* AND | OR combination if there are multiple setdefaults
*/
public String combination;
/**
* The default value of an attribute
*/
public String setdefault;
/**
* Default constructor with emptey var init.
*/
public CRTSetDefault() {
location = "";
combination = "NONE";
setdefault = "";
}
/**
* Extract the attribute out of the location variable.
*
* @return The attribute
*/
public String getAttribute() {
String returnS = "";
if (location.equals("")) {
return returnS;
}
int firstDotPlace = location.indexOf(".");
int lastDotPlace = location.lastIndexOf(".");
try {
if (firstDotPlace == lastDotPlace) {
firstDotPlace++;
returnS = location.substring(firstDotPlace);
} else {
firstDotPlace++;
// lastDotPlace--;
returnS = location.substring(firstDotPlace, lastDotPlace);
}
} catch (Exception e) {
// System.out.println("kan geen<SUF>
}
return returnS;
}
} |
113787_3 | package gem.sparseboolean.math;
import java.util.ArrayList;
public class Algorithm {
public static int pointInside2DPolygon(ArrayList<Point2D> polygon, int n,
Point2D pt, int onEdge) {
if (n < 3)
return 0;
// cross points count of x
int __count = 0;
// neighbor bound vertices
Point2D p1, p2;
// left vertex
p1 = polygon.get(0);
// check all rays
for (int i = 1; i <= n; ++i) {
// point is an vertex
if (pt == p1)
return onEdge;
// right vertex
p2 = polygon.get(i % n);
// ray is outside of our interests
if (pt.getY() < Math.min(p1.getY(), p2.getY())
|| pt.getY() > Math.max(p1.getY(), p2.getY())) {
// next ray left point
p1 = p2;
continue;
}
// ray is crossing over by the algorithm (common part of)
if (pt.getY() > Math.min(p1.getY(), p2.getY())
&& pt.getY() < Math.max(p1.getY(), p2.getY())) {
// x is before of ray
if (pt.getX() <= Math.max(p1.getX(), p2.getX())) {
// overlies on a horizontal ray
if (p1.getY() == p2.getY()
&& pt.getX() >= Math.min(p1.getX(), p2.getX()))
return onEdge;
// ray is vertical
if (p1.getX() == p2.getX()) {
// overlies on a ray
if (p1.getX() == pt.getX())
return onEdge;
// before ray
else
++__count;
}
// cross point on the left side
else {
// cross point of x
double xinters = (pt.getY() - p1.getY())
* (p2.getX() - p1.getX())
/ (p2.getY() - p1.getY()) + p1.getX();
// overlies on a ray
if (Math.abs(pt.getX() - xinters) < Constants.DBL_EPSILON)
return onEdge;
// before ray
if (pt.getX() < xinters)
++__count;
}
}
}
// special case when ray is crossing through the vertex
else {
// p crossing over p2
if (pt.getY() == p2.getY() && pt.getX() <= p2.getX()) {
// next vertex
Point2D p3 = polygon.get((i + 1) % n);
if (pt.getY() >= Math.min(p1.getY(), p3.getY())
&& pt.getY() <= Math.max(p1.getY(), p3.getY())) {
++__count;
} else {
__count += 2;
}
}
}
// next ray left point
p1 = p2;
}
// EVEN
if (__count % 2 == 0) {
return (0);
}
// ODD
else {
return (1);
}
}
}
| nichollyn/chameleonbox | chameleonbox-library/src/gem/sparseboolean/math/Algorithm.java | 946 | // point is an vertex | line_comment | nl | package gem.sparseboolean.math;
import java.util.ArrayList;
public class Algorithm {
public static int pointInside2DPolygon(ArrayList<Point2D> polygon, int n,
Point2D pt, int onEdge) {
if (n < 3)
return 0;
// cross points count of x
int __count = 0;
// neighbor bound vertices
Point2D p1, p2;
// left vertex
p1 = polygon.get(0);
// check all rays
for (int i = 1; i <= n; ++i) {
// point is<SUF>
if (pt == p1)
return onEdge;
// right vertex
p2 = polygon.get(i % n);
// ray is outside of our interests
if (pt.getY() < Math.min(p1.getY(), p2.getY())
|| pt.getY() > Math.max(p1.getY(), p2.getY())) {
// next ray left point
p1 = p2;
continue;
}
// ray is crossing over by the algorithm (common part of)
if (pt.getY() > Math.min(p1.getY(), p2.getY())
&& pt.getY() < Math.max(p1.getY(), p2.getY())) {
// x is before of ray
if (pt.getX() <= Math.max(p1.getX(), p2.getX())) {
// overlies on a horizontal ray
if (p1.getY() == p2.getY()
&& pt.getX() >= Math.min(p1.getX(), p2.getX()))
return onEdge;
// ray is vertical
if (p1.getX() == p2.getX()) {
// overlies on a ray
if (p1.getX() == pt.getX())
return onEdge;
// before ray
else
++__count;
}
// cross point on the left side
else {
// cross point of x
double xinters = (pt.getY() - p1.getY())
* (p2.getX() - p1.getX())
/ (p2.getY() - p1.getY()) + p1.getX();
// overlies on a ray
if (Math.abs(pt.getX() - xinters) < Constants.DBL_EPSILON)
return onEdge;
// before ray
if (pt.getX() < xinters)
++__count;
}
}
}
// special case when ray is crossing through the vertex
else {
// p crossing over p2
if (pt.getY() == p2.getY() && pt.getX() <= p2.getX()) {
// next vertex
Point2D p3 = polygon.get((i + 1) % n);
if (pt.getY() >= Math.min(p1.getY(), p3.getY())
&& pt.getY() <= Math.max(p1.getY(), p3.getY())) {
++__count;
} else {
__count += 2;
}
}
}
// next ray left point
p1 = p2;
}
// EVEN
if (__count % 2 == 0) {
return (0);
}
// ODD
else {
return (1);
}
}
}
|
37488_2 | /*
* Copyright 2018 Google LLC
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. The ASF licenses this
* file to you under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.plaidapp.core.ui.widget;
import android.content.Context;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import io.plaidapp.core.util.ViewOffsetHelper;
/**
* A {@link FrameLayout} whose content can be dragged downward to be dismissed (either directly or
* via a nested scrolling child). It must contain a single child view and exposes {@link Callbacks}
* to respond to it's movement & dismissal.
*
* Only implements the modal bottom sheet behavior from the material spec, not the persistent
* behavior (yet).
*/
public class BottomSheet extends FrameLayout {
// constants
private static final float SETTLE_STIFFNESS = 800f;
private static final int MIN_FLING_DISMISS_VELOCITY = 500; // dp/s
private final int SCALED_MIN_FLING_DISMISS_VELOCITY; // px/s
// child views & helpers
View sheet;
ViewOffsetHelper sheetOffsetHelper;
private ViewDragHelper sheetDragHelper;
// state
int sheetExpandedTop;
int sheetBottom;
int dismissOffset;
boolean settling = false;
boolean initialHeightChecked = false;
boolean hasInteractedWithSheet = false;
private int nestedScrollInitialTop;
private boolean isNestedScrolling = false;
private List<Callbacks> callbacks;
public BottomSheet(Context context) {
this(context, null, 0);
}
public BottomSheet(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomSheet(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
SCALED_MIN_FLING_DISMISS_VELOCITY =
(int) (context.getResources().getDisplayMetrics().density * MIN_FLING_DISMISS_VELOCITY);
}
/**
* Callbacks for responding to interactions with the bottom sheet.
*/
public static abstract class Callbacks {
public void onSheetDismissed() { }
public void onSheetPositionChanged(int sheetTop, boolean userInteracted) { }
}
public void registerCallback(Callbacks callback) {
if (callbacks == null) {
callbacks = new CopyOnWriteArrayList<>();
}
callbacks.add(callback);
}
public void unregisterCallback(Callbacks callback) {
if (callbacks != null && !callbacks.isEmpty()) {
callbacks.remove(callback);
}
}
public void dismiss() {
animateSettle(dismissOffset, 0);
}
public void expand() {
animateSettle(0, 0);
}
public boolean isExpanded() {
return sheet.getTop() == sheetExpandedTop;
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (sheet != null) {
throw new UnsupportedOperationException("BottomSheet must only have 1 child view");
}
sheet = child;
sheetOffsetHelper = new ViewOffsetHelper(sheet);
sheet.addOnLayoutChangeListener(sheetLayout);
// force the sheet contents to be gravity bottom. This ain't a top sheet.
((LayoutParams) params).gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
super.addView(child, index, params);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
hasInteractedWithSheet = true;
if (isNestedScrolling) return false; /* prefer nested scrolling to dragging */
final int action = ev.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
sheetDragHelper.cancel();
return false;
}
return isDraggableViewUnder((int) ev.getX(), (int) ev.getY())
&& (sheetDragHelper.shouldInterceptTouchEvent(ev));
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
sheetDragHelper.processTouchEvent(ev);
return sheetDragHelper.getCapturedView() != null || super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (sheetDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if ((nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0) {
isNestedScrolling = true;
nestedScrollInitialTop = sheet.getTop();
return true;
}
return false;
}
@Override
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
// if scrolling downward, use any unconsumed (i.e. not used by the scrolling child)
// to drag the sheet downward
if (dyUnconsumed < 0) {
sheetOffsetHelper.offsetTopAndBottom(-dyUnconsumed);
dispatchPositionChangedCallback();
}
}
@Override
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
// if scrolling upward & the sheet has been dragged downward
// then drag back into place before allowing scrolls
if (dy > 0) {
final int upwardDragRange = sheet.getTop() - sheetExpandedTop;
if (upwardDragRange > 0) {
final int consume = Math.min(upwardDragRange, dy);
sheetOffsetHelper.offsetTopAndBottom(-consume);
dispatchPositionChangedCallback();
consumed[1] = consume;
}
}
}
@Override
public void onStopNestedScroll(View child) {
isNestedScrolling = false;
if (!settling /* fling might have occurred */
&& sheet.getTop() != nestedScrollInitialTop) { /* don't expand after a tap */
expand();
}
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY <= -SCALED_MIN_FLING_DISMISS_VELOCITY /* flinging downward */
&& !target.canScrollVertically(-1)) { /* nested scrolling child can't scroll up */
animateSettle(dismissOffset, velocityY);
return true;
} else if (velocityY > 0 && !isExpanded()) {
animateSettle(0, velocityY);
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
sheetDragHelper = ViewDragHelper.create(this, dragHelperCallbacks);
}
private boolean isDraggableViewUnder(int x, int y) {
return getVisibility() == VISIBLE && sheetDragHelper.isViewUnder(this, x, y);
}
void animateSettle(int targetOffset, float initialVelocity) {
if (settling) return;
if (sheetOffsetHelper.getTopAndBottomOffset() == targetOffset) {
if (targetOffset >= dismissOffset) {
dispatchDismissCallback();
}
return;
}
settling = true;
final boolean dismissing = targetOffset == dismissOffset;
// if we're dismissing, we don't want the view to decelerate as it reaches the bottom
// so set a target position that actually overshoots a little
final float finalPosition = dismissing ? dismissOffset * 1.1f : targetOffset;
SpringAnimation anim = new SpringAnimation(
sheetOffsetHelper, ViewOffsetHelper.OFFSET_Y, finalPosition)
.setStartValue(sheetOffsetHelper.getTopAndBottomOffset())
.setStartVelocity(initialVelocity)
.setMinimumVisibleChange(DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS);
anim.getSpring()
.setStiffness(SETTLE_STIFFNESS)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
anim.addEndListener((animation, canceled, value, velocity) -> {
dispatchPositionChangedCallback();
if (dismissing) {
dispatchDismissCallback();
}
settling = false;
});
if (callbacks != null && !callbacks.isEmpty()) {
anim.addUpdateListener((animation, value, velocity) -> dispatchPositionChangedCallback());
}
anim.start();
}
private final ViewDragHelper.Callback dragHelperCallbacks = new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
return child == sheet;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return Math.min(Math.max(top, sheetExpandedTop), sheetBottom);
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return sheet.getLeft();
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return sheetBottom - sheetExpandedTop;
}
@Override
public void onViewPositionChanged(@NonNull View child, int left, int top, int dx, int dy) {
// notify the offset helper that the sheets offsets have been changed externally
sheetOffsetHelper.resyncOffsets();
dispatchPositionChangedCallback();
}
@Override
public void onViewReleased(@NonNull View releasedChild, float velocityX, float velocityY) {
// dismiss on downward fling, otherwise settle back to expanded position
final boolean dismiss = velocityY >= SCALED_MIN_FLING_DISMISS_VELOCITY;
animateSettle(dismiss ? dismissOffset : 0, velocityY);
}
};
private final OnLayoutChangeListener sheetLayout = new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
sheetExpandedTop = top;
sheetBottom = bottom;
dismissOffset = bottom - top;
sheetOffsetHelper.onViewLayout();
// modal bottom sheet content should not initially be taller than the 16:9 keyline
if (!initialHeightChecked) {
applySheetInitialHeightOffset(false, -1);
initialHeightChecked = true;
} else if (!hasInteractedWithSheet
&& (oldBottom - oldTop) != (bottom - top)) { /* sheet height changed */
/* if the sheet content's height changes before the user has interacted with it
then consider this still in the 'initial' state and apply the height constraint,
but in this case, animate to it */
applySheetInitialHeightOffset(true, oldTop - sheetExpandedTop);
}
}
};
void applySheetInitialHeightOffset(boolean animateChange, int previousOffset) {
final int minimumGap = sheet.getMeasuredWidth() / 16 * 9;
if (sheet.getTop() < minimumGap) {
final int offset = minimumGap - sheet.getTop();
if (animateChange) {
sheetOffsetHelper.setTopAndBottomOffset(previousOffset);
animateSettle(offset, 0);
} else {
sheetOffsetHelper.setTopAndBottomOffset(offset);
}
}
}
void dispatchDismissCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetDismissed();
}
}
}
void dispatchPositionChangedCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetPositionChanged(sheet.getTop(), hasInteractedWithSheet);
}
}
}
}
| nickbutcher/plaid | core/src/main/java/io/plaidapp/core/ui/widget/BottomSheet.java | 3,515 | // child views & helpers | line_comment | nl | /*
* Copyright 2018 Google LLC
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. The ASF licenses this
* file to you under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.plaidapp.core.ui.widget;
import android.content.Context;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import io.plaidapp.core.util.ViewOffsetHelper;
/**
* A {@link FrameLayout} whose content can be dragged downward to be dismissed (either directly or
* via a nested scrolling child). It must contain a single child view and exposes {@link Callbacks}
* to respond to it's movement & dismissal.
*
* Only implements the modal bottom sheet behavior from the material spec, not the persistent
* behavior (yet).
*/
public class BottomSheet extends FrameLayout {
// constants
private static final float SETTLE_STIFFNESS = 800f;
private static final int MIN_FLING_DISMISS_VELOCITY = 500; // dp/s
private final int SCALED_MIN_FLING_DISMISS_VELOCITY; // px/s
// child views<SUF>
View sheet;
ViewOffsetHelper sheetOffsetHelper;
private ViewDragHelper sheetDragHelper;
// state
int sheetExpandedTop;
int sheetBottom;
int dismissOffset;
boolean settling = false;
boolean initialHeightChecked = false;
boolean hasInteractedWithSheet = false;
private int nestedScrollInitialTop;
private boolean isNestedScrolling = false;
private List<Callbacks> callbacks;
public BottomSheet(Context context) {
this(context, null, 0);
}
public BottomSheet(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomSheet(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
SCALED_MIN_FLING_DISMISS_VELOCITY =
(int) (context.getResources().getDisplayMetrics().density * MIN_FLING_DISMISS_VELOCITY);
}
/**
* Callbacks for responding to interactions with the bottom sheet.
*/
public static abstract class Callbacks {
public void onSheetDismissed() { }
public void onSheetPositionChanged(int sheetTop, boolean userInteracted) { }
}
public void registerCallback(Callbacks callback) {
if (callbacks == null) {
callbacks = new CopyOnWriteArrayList<>();
}
callbacks.add(callback);
}
public void unregisterCallback(Callbacks callback) {
if (callbacks != null && !callbacks.isEmpty()) {
callbacks.remove(callback);
}
}
public void dismiss() {
animateSettle(dismissOffset, 0);
}
public void expand() {
animateSettle(0, 0);
}
public boolean isExpanded() {
return sheet.getTop() == sheetExpandedTop;
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (sheet != null) {
throw new UnsupportedOperationException("BottomSheet must only have 1 child view");
}
sheet = child;
sheetOffsetHelper = new ViewOffsetHelper(sheet);
sheet.addOnLayoutChangeListener(sheetLayout);
// force the sheet contents to be gravity bottom. This ain't a top sheet.
((LayoutParams) params).gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
super.addView(child, index, params);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
hasInteractedWithSheet = true;
if (isNestedScrolling) return false; /* prefer nested scrolling to dragging */
final int action = ev.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
sheetDragHelper.cancel();
return false;
}
return isDraggableViewUnder((int) ev.getX(), (int) ev.getY())
&& (sheetDragHelper.shouldInterceptTouchEvent(ev));
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
sheetDragHelper.processTouchEvent(ev);
return sheetDragHelper.getCapturedView() != null || super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (sheetDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if ((nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0) {
isNestedScrolling = true;
nestedScrollInitialTop = sheet.getTop();
return true;
}
return false;
}
@Override
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
// if scrolling downward, use any unconsumed (i.e. not used by the scrolling child)
// to drag the sheet downward
if (dyUnconsumed < 0) {
sheetOffsetHelper.offsetTopAndBottom(-dyUnconsumed);
dispatchPositionChangedCallback();
}
}
@Override
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
// if scrolling upward & the sheet has been dragged downward
// then drag back into place before allowing scrolls
if (dy > 0) {
final int upwardDragRange = sheet.getTop() - sheetExpandedTop;
if (upwardDragRange > 0) {
final int consume = Math.min(upwardDragRange, dy);
sheetOffsetHelper.offsetTopAndBottom(-consume);
dispatchPositionChangedCallback();
consumed[1] = consume;
}
}
}
@Override
public void onStopNestedScroll(View child) {
isNestedScrolling = false;
if (!settling /* fling might have occurred */
&& sheet.getTop() != nestedScrollInitialTop) { /* don't expand after a tap */
expand();
}
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY <= -SCALED_MIN_FLING_DISMISS_VELOCITY /* flinging downward */
&& !target.canScrollVertically(-1)) { /* nested scrolling child can't scroll up */
animateSettle(dismissOffset, velocityY);
return true;
} else if (velocityY > 0 && !isExpanded()) {
animateSettle(0, velocityY);
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
sheetDragHelper = ViewDragHelper.create(this, dragHelperCallbacks);
}
private boolean isDraggableViewUnder(int x, int y) {
return getVisibility() == VISIBLE && sheetDragHelper.isViewUnder(this, x, y);
}
void animateSettle(int targetOffset, float initialVelocity) {
if (settling) return;
if (sheetOffsetHelper.getTopAndBottomOffset() == targetOffset) {
if (targetOffset >= dismissOffset) {
dispatchDismissCallback();
}
return;
}
settling = true;
final boolean dismissing = targetOffset == dismissOffset;
// if we're dismissing, we don't want the view to decelerate as it reaches the bottom
// so set a target position that actually overshoots a little
final float finalPosition = dismissing ? dismissOffset * 1.1f : targetOffset;
SpringAnimation anim = new SpringAnimation(
sheetOffsetHelper, ViewOffsetHelper.OFFSET_Y, finalPosition)
.setStartValue(sheetOffsetHelper.getTopAndBottomOffset())
.setStartVelocity(initialVelocity)
.setMinimumVisibleChange(DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS);
anim.getSpring()
.setStiffness(SETTLE_STIFFNESS)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
anim.addEndListener((animation, canceled, value, velocity) -> {
dispatchPositionChangedCallback();
if (dismissing) {
dispatchDismissCallback();
}
settling = false;
});
if (callbacks != null && !callbacks.isEmpty()) {
anim.addUpdateListener((animation, value, velocity) -> dispatchPositionChangedCallback());
}
anim.start();
}
private final ViewDragHelper.Callback dragHelperCallbacks = new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
return child == sheet;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return Math.min(Math.max(top, sheetExpandedTop), sheetBottom);
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return sheet.getLeft();
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return sheetBottom - sheetExpandedTop;
}
@Override
public void onViewPositionChanged(@NonNull View child, int left, int top, int dx, int dy) {
// notify the offset helper that the sheets offsets have been changed externally
sheetOffsetHelper.resyncOffsets();
dispatchPositionChangedCallback();
}
@Override
public void onViewReleased(@NonNull View releasedChild, float velocityX, float velocityY) {
// dismiss on downward fling, otherwise settle back to expanded position
final boolean dismiss = velocityY >= SCALED_MIN_FLING_DISMISS_VELOCITY;
animateSettle(dismiss ? dismissOffset : 0, velocityY);
}
};
private final OnLayoutChangeListener sheetLayout = new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
sheetExpandedTop = top;
sheetBottom = bottom;
dismissOffset = bottom - top;
sheetOffsetHelper.onViewLayout();
// modal bottom sheet content should not initially be taller than the 16:9 keyline
if (!initialHeightChecked) {
applySheetInitialHeightOffset(false, -1);
initialHeightChecked = true;
} else if (!hasInteractedWithSheet
&& (oldBottom - oldTop) != (bottom - top)) { /* sheet height changed */
/* if the sheet content's height changes before the user has interacted with it
then consider this still in the 'initial' state and apply the height constraint,
but in this case, animate to it */
applySheetInitialHeightOffset(true, oldTop - sheetExpandedTop);
}
}
};
void applySheetInitialHeightOffset(boolean animateChange, int previousOffset) {
final int minimumGap = sheet.getMeasuredWidth() / 16 * 9;
if (sheet.getTop() < minimumGap) {
final int offset = minimumGap - sheet.getTop();
if (animateChange) {
sheetOffsetHelper.setTopAndBottomOffset(previousOffset);
animateSettle(offset, 0);
} else {
sheetOffsetHelper.setTopAndBottomOffset(offset);
}
}
}
void dispatchDismissCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetDismissed();
}
}
}
void dispatchPositionChangedCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetPositionChanged(sheet.getTop(), hasInteractedWithSheet);
}
}
}
}
|
28761_1 | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Dashboard.Dashboard;
import nl.han.ica.OOPDProcessingEngineHAN.Engine.GameEngine;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.FilePersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.IPersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileMap;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileType;
import nl.han.ica.OOPDProcessingEngineHAN.View.EdgeFollowingViewport;
import nl.han.ica.OOPDProcessingEngineHAN.View.View;
import nl.han.ica.waterworld.tiles.BoardsTile;
import processing.core.PApplet;
/**
* @author Ralph Niels
*/
@SuppressWarnings("serial")
public class WaterWorld extends GameEngine {
private Sound backgroundSound;
private Sound bubblePopSound;
private TextObject dashboardText;
private BubbleSpawner bubbleSpawner;
private int bubblesPopped;
private IPersistence persistence;
private Player player;
public static void main(String[] args) {
PApplet.main(new String[]{"nl.han.ica.waterworld.WaterWorld"});
}
/**
* In deze methode worden de voor het spel
* noodzakelijke zaken geïnitialiseerd
*/
@Override
public void setupGame() {
int worldWidth=1204;
int worldHeight=903;
initializeSound();
createDashboard(worldWidth, 100);
initializeTileMap();
initializePersistence();
createObjects();
createBubbleSpawner();
createViewWithoutViewport(worldWidth, worldHeight);
//createViewWithViewport(worldWidth, worldHeight, 800, 800, 1.1f);
}
/**
* Creeërt de view zonder viewport
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
*/
private void createViewWithoutViewport(int screenWidth, int screenHeight) {
View view = new View(screenWidth,screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
setView(view);
size(screenWidth, screenHeight);
}
/**
* Creeërt de view met viewport
* @param worldWidth Totale breedte van de wereld
* @param worldHeight Totale hoogte van de wereld
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
* @param zoomFactor Factor waarmee wordt ingezoomd
*/
private void createViewWithViewport(int worldWidth,int worldHeight,int screenWidth,int screenHeight,float zoomFactor) {
EdgeFollowingViewport viewPort = new EdgeFollowingViewport(player, (int)Math.ceil(screenWidth/zoomFactor),(int)Math.ceil(screenHeight/zoomFactor),0,0);
viewPort.setTolerance(50, 50, 50, 50);
View view = new View(viewPort, worldWidth,worldHeight);
setView(view);
size(screenWidth, screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
}
/**
* Initialiseert geluid
*/
private void initializeSound() {
backgroundSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/Waterworld.mp3");
backgroundSound.loop(-1);
bubblePopSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/pop.mp3");
}
/**
* Maakt de spelobjecten aan
*/
private void createObjects() {
player = new Player(this);
addGameObject(player, 100, 100);
Swordfish sf=new Swordfish(this);
addGameObject(sf,200,200);
}
/**
* Maakt de spawner voor de bellen aan
*/
public void createBubbleSpawner() {
bubbleSpawner=new BubbleSpawner(this,bubblePopSound,2);
}
/**
* Maakt het dashboard aan
* @param dashboardWidth Gewenste breedte van dashboard
* @param dashboardHeight Gewenste hoogte van dashboard
*/
private void createDashboard(int dashboardWidth,int dashboardHeight) {
Dashboard dashboard = new Dashboard(0,0, dashboardWidth, dashboardHeight);
dashboardText=new TextObject("");
dashboard.addGameObject(dashboardText);
addDashboard(dashboard);
}
/**
* Initialiseert de opslag van de bellenteller
* en laadt indien mogelijk de eerder opgeslagen
* waarde
*/
private void initializePersistence() {
persistence = new FilePersistence("main/java/nl/han/ica/waterworld/media/bubblesPopped.txt");
if (persistence.fileExists()) {
bubblesPopped = Integer.parseInt(persistence.loadDataString());
refreshDasboardText();
}
}
/**
* Initialiseert de tilemap
*/
private void initializeTileMap() {
/* TILES */
Sprite boardsSprite = new Sprite("src/main/java/nl/han/ica/waterworld/media/boards.jpg");
TileType<BoardsTile> boardTileType = new TileType<>(BoardsTile.class, boardsSprite);
TileType[] tileTypes = { boardTileType };
int tileSize=50;
int tilesMap[][]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1, 0, 0, 0, 0,-1,0 , 0},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}
};
tileMap = new TileMap(tileSize, tileTypes, tilesMap);
}
@Override
public void update() {
}
/**
* Vernieuwt het dashboard
*/
private void refreshDasboardText() {
dashboardText.setText("Bubbles popped: "+bubblesPopped);
}
/**
* Verhoogt de teller voor het aantal
* geknapte bellen met 1
*/
public void increaseBubblesPopped() {
bubblesPopped++;
persistence.saveData(Integer.toString(bubblesPopped));
refreshDasboardText();
}
}
| nickhartjes/OOPD-GameEngine | src/main/java/nl/han/ica/waterworld/WaterWorld.java | 2,092 | /**
* In deze methode worden de voor het spel
* noodzakelijke zaken geïnitialiseerd
*/ | block_comment | nl | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Dashboard.Dashboard;
import nl.han.ica.OOPDProcessingEngineHAN.Engine.GameEngine;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.FilePersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.IPersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileMap;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileType;
import nl.han.ica.OOPDProcessingEngineHAN.View.EdgeFollowingViewport;
import nl.han.ica.OOPDProcessingEngineHAN.View.View;
import nl.han.ica.waterworld.tiles.BoardsTile;
import processing.core.PApplet;
/**
* @author Ralph Niels
*/
@SuppressWarnings("serial")
public class WaterWorld extends GameEngine {
private Sound backgroundSound;
private Sound bubblePopSound;
private TextObject dashboardText;
private BubbleSpawner bubbleSpawner;
private int bubblesPopped;
private IPersistence persistence;
private Player player;
public static void main(String[] args) {
PApplet.main(new String[]{"nl.han.ica.waterworld.WaterWorld"});
}
/**
* In deze methode<SUF>*/
@Override
public void setupGame() {
int worldWidth=1204;
int worldHeight=903;
initializeSound();
createDashboard(worldWidth, 100);
initializeTileMap();
initializePersistence();
createObjects();
createBubbleSpawner();
createViewWithoutViewport(worldWidth, worldHeight);
//createViewWithViewport(worldWidth, worldHeight, 800, 800, 1.1f);
}
/**
* Creeërt de view zonder viewport
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
*/
private void createViewWithoutViewport(int screenWidth, int screenHeight) {
View view = new View(screenWidth,screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
setView(view);
size(screenWidth, screenHeight);
}
/**
* Creeërt de view met viewport
* @param worldWidth Totale breedte van de wereld
* @param worldHeight Totale hoogte van de wereld
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
* @param zoomFactor Factor waarmee wordt ingezoomd
*/
private void createViewWithViewport(int worldWidth,int worldHeight,int screenWidth,int screenHeight,float zoomFactor) {
EdgeFollowingViewport viewPort = new EdgeFollowingViewport(player, (int)Math.ceil(screenWidth/zoomFactor),(int)Math.ceil(screenHeight/zoomFactor),0,0);
viewPort.setTolerance(50, 50, 50, 50);
View view = new View(viewPort, worldWidth,worldHeight);
setView(view);
size(screenWidth, screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
}
/**
* Initialiseert geluid
*/
private void initializeSound() {
backgroundSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/Waterworld.mp3");
backgroundSound.loop(-1);
bubblePopSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/pop.mp3");
}
/**
* Maakt de spelobjecten aan
*/
private void createObjects() {
player = new Player(this);
addGameObject(player, 100, 100);
Swordfish sf=new Swordfish(this);
addGameObject(sf,200,200);
}
/**
* Maakt de spawner voor de bellen aan
*/
public void createBubbleSpawner() {
bubbleSpawner=new BubbleSpawner(this,bubblePopSound,2);
}
/**
* Maakt het dashboard aan
* @param dashboardWidth Gewenste breedte van dashboard
* @param dashboardHeight Gewenste hoogte van dashboard
*/
private void createDashboard(int dashboardWidth,int dashboardHeight) {
Dashboard dashboard = new Dashboard(0,0, dashboardWidth, dashboardHeight);
dashboardText=new TextObject("");
dashboard.addGameObject(dashboardText);
addDashboard(dashboard);
}
/**
* Initialiseert de opslag van de bellenteller
* en laadt indien mogelijk de eerder opgeslagen
* waarde
*/
private void initializePersistence() {
persistence = new FilePersistence("main/java/nl/han/ica/waterworld/media/bubblesPopped.txt");
if (persistence.fileExists()) {
bubblesPopped = Integer.parseInt(persistence.loadDataString());
refreshDasboardText();
}
}
/**
* Initialiseert de tilemap
*/
private void initializeTileMap() {
/* TILES */
Sprite boardsSprite = new Sprite("src/main/java/nl/han/ica/waterworld/media/boards.jpg");
TileType<BoardsTile> boardTileType = new TileType<>(BoardsTile.class, boardsSprite);
TileType[] tileTypes = { boardTileType };
int tileSize=50;
int tilesMap[][]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1, 0, 0, 0, 0,-1,0 , 0},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}
};
tileMap = new TileMap(tileSize, tileTypes, tilesMap);
}
@Override
public void update() {
}
/**
* Vernieuwt het dashboard
*/
private void refreshDasboardText() {
dashboardText.setText("Bubbles popped: "+bubblesPopped);
}
/**
* Verhoogt de teller voor het aantal
* geknapte bellen met 1
*/
public void increaseBubblesPopped() {
bubblesPopped++;
persistence.saveData(Integer.toString(bubblesPopped));
refreshDasboardText();
}
}
|
15099_2 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bruynhuis.galago.ui.effect;
import com.bruynhuis.galago.ui.Widget;
/**
* This effect can be added to a TouchButton.
* When the button is clicked it will scale up and down.
*
* @author NideBruyn
*/
public class TouchEffect extends Effect {
/**
*
* @param widget
*/
public TouchEffect(Widget widget) {
super(widget);
}
@Override
protected void doShow() {
}
@Override
protected void doHide() {
}
@Override
protected void doTouchDown() {
widget.setScale(0.96f);
}
@Override
protected void doTouchUp() {
widget.setScale(1f);
}
@Override
protected void doEnabled(boolean enabled) {
}
@Override
protected void controlUpdate(float tpf) {
}
@Override
protected void doSelected() {
}
@Override
protected void doUnselected() {
}
}
| nickidebruyn/galago | Galago3.0/src/com/bruynhuis/galago/ui/effect/TouchEffect.java | 317 | /**
*
* @param widget
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bruynhuis.galago.ui.effect;
import com.bruynhuis.galago.ui.Widget;
/**
* This effect can be added to a TouchButton.
* When the button is clicked it will scale up and down.
*
* @author NideBruyn
*/
public class TouchEffect extends Effect {
/**
*
* @param widget <SUF>*/
public TouchEffect(Widget widget) {
super(widget);
}
@Override
protected void doShow() {
}
@Override
protected void doHide() {
}
@Override
protected void doTouchDown() {
widget.setScale(0.96f);
}
@Override
protected void doTouchUp() {
widget.setScale(1f);
}
@Override
protected void doEnabled(boolean enabled) {
}
@Override
protected void controlUpdate(float tpf) {
}
@Override
protected void doSelected() {
}
@Override
protected void doUnselected() {
}
}
|
55511_31 | /**
* Title: efa - elektronisches Fahrtenbuch für Ruderer
* Copyright: Copyright (c) 2001-2011 by Nicolas Michael
* Website: http://efa.nmichael.de/
* License: GNU General Public License v2
*
* @author Nicolas Michael
* @version 2
*/
package de.nmichael.efa.data;
import java.util.ArrayList;
import java.util.UUID;
import java.util.Vector;
import de.nmichael.efa.Daten;
import de.nmichael.efa.data.storage.DataKey;
import de.nmichael.efa.data.storage.DataRecord;
import de.nmichael.efa.data.storage.MetaData;
import de.nmichael.efa.data.storage.StorageObject;
import de.nmichael.efa.data.types.DataTypeDate;
import de.nmichael.efa.data.types.DataTypeTime;
import de.nmichael.efa.ex.EfaModifyException;
import de.nmichael.efa.util.International;
import de.nmichael.efa.util.Logger;
// @i18n complete
public class BoatReservations extends StorageObject {
public static final String DATATYPE = "efa2boatreservations";
public BoatReservations(int storageType,
String storageLocation,
String storageUsername,
String storagePassword,
String storageObjectName) {
super(storageType, storageLocation, storageUsername, storagePassword, storageObjectName, DATATYPE, International.getString("Bootsreservierungen"));
BoatReservationRecord.initialize();
dataAccess.setMetaData(MetaData.getMetaData(DATATYPE));
}
public DataRecord createNewRecord() {
return new BoatReservationRecord(this, MetaData.getMetaData(DATATYPE));
}
public BoatReservationRecord createBoatReservationsRecord(UUID id) {
AutoIncrement autoIncrement = getProject().getAutoIncrement(false);
int tries = 0;
int val = 0;
try {
while (tries++ < 100) {
// usually autoincrement should always give a unique new id.
// but in case our id's got out of sync, we try up to 100 times to fine a
// new unique reservation id.
val = autoIncrement.nextAutoIncrementIntValue(data().getStorageObjectType());
if (val <= 0) {
break;
}
if (data().get(BoatReservationRecord.getKey(id, val)) == null) {
break;
}
}
} catch (Exception e) {
Logger.logdebug(e);
}
if (val > 0) {
return createBoatReservationsRecord(id, val);
}
return null;
}
public BoatReservationRecord createBoatReservationsRecord(UUID id, int reservation) {
BoatReservationRecord r = new BoatReservationRecord(this, MetaData.getMetaData(DATATYPE));
r.setBoatId(id);
r.setReservation(reservation);
return r;
}
public BoatReservationRecord[] getBoatReservations(UUID boatId) {
try {
DataKey[] keys = data().getByFields(BoatReservationRecord.IDX_BOATID, new Object[] { boatId });
if (keys == null || keys.length == 0) {
return null;
}
BoatReservationRecord[] recs = new BoatReservationRecord[keys.length];
for (int i=0; i<keys.length; i++) {
recs[i] = (BoatReservationRecord)data().get(keys[i]);
}
return recs;
} catch(Exception e) {
Logger.logdebug(e);
return null;
}
}
public BoatReservationRecord[] getBoatReservations(UUID boatId, long now, long lookAheadMinutes) {
BoatReservationRecord[] reservations = getBoatReservations(boatId);
Vector<BoatReservationRecord> activeReservations = new Vector<BoatReservationRecord>();
for (int i = 0; reservations != null && i < reservations.length; i++) {
BoatReservationRecord r = reservations[i];
if (r.getReservationValidInMinutes(now, lookAheadMinutes) >= 0) {
activeReservations.add(r);
}
}
if (activeReservations.size() == 0) {
return null;
}
BoatReservationRecord[] a = new BoatReservationRecord[activeReservations.size()];
for (int i=0; i<a.length; i++) {
a[i] = activeReservations.get(i);
}
return a;
}
public int purgeObsoleteReservations(UUID boatId, long now) {
BoatReservationRecord[] reservations = getBoatReservations(boatId);
int purged = 0;
for (int i = 0; reservations != null && i < reservations.length; i++) {
BoatReservationRecord r = reservations[i];
if (r.isObsolete(now)) {
try {
data().delete(r.getKey());
purged++;
} catch(Exception e) {
Logger.log(e);
}
}
}
return purged;
}
private String buildOverlappingReservationInfo(BoatReservationRecord reservation) {
String result = "";
if (reservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY)
|| reservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
result = "\n\n" + reservation.getBoatName() + " / " + reservation.getPersonAsName() + " ("
+ Daten.efaTypes.getValueWeekday(reservation.getDayOfWeek()) + " " + reservation.getTimeFrom() + " -- " + reservation.getTimeTo() + ")"
+ "\n" + International.getString("Reservierungsgrund") + ": " + reservation.getReason()
+ "\n" + International.getString("Telefon für Rückfragen") + ": " + reservation.getContact();
} else if (reservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
result = "\n\n" + reservation.getBoatName() + " / " + reservation.getPersonAsName() + " (" + reservation.getDateFrom().getWeekdayAsString() + " " + reservation.getDateFrom() + " " + reservation.getTimeFrom() + " -- " + reservation.getDateTo().getWeekdayAsString() + " " + reservation.getDateTo() + " " + reservation.getTimeTo() + ")"
+ "\n" + International.getString("Reservierungsgrund") + ": " + reservation.getReason()
+ "\n" + International.getString("Telefon für Rückfragen") + ": " + reservation.getContact();
}
return result;
}
public void preModifyRecordCallback(DataRecord record, boolean add, boolean update, boolean delete) throws EfaModifyException {
if (add || update) {
assertFieldNotEmpty(record, BoatReservationRecord.BOATID);
assertFieldNotEmpty(record, BoatReservationRecord.RESERVATION);
assertFieldNotEmpty(record, BoatReservationRecord.TYPE);
checkOverlappingReservationsFor(record);
// no overlapping reservations, clean up some unused attributes for one-time and weekly reservation
BoatReservationRecord r = ((BoatReservationRecord)record);
//one time reservations shall not have a weekday set
if (r.getType().equals(BoatReservationRecord.TYPE_ONETIME) &&
r.getDayOfWeek() != null) {
r.setDayOfWeek(null);
}
//weekly, unlimited reservations shall not have a datefrom/dateto set
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY) &&
r.getDateFrom() != null) {
r.setDateFrom(null);
}
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY) &&
r.getDateTo() != null) {
r.setDateTo(null);
}
}
}
/**
* Checks for overlapping reservations for the current reservation and all other reservations for the same boat
* Throws an efaModifyException if an overlapping is detected.
*
* @param record BoatReservationRecord
*
*/
public void checkOverlappingReservationsFor(DataRecord record) throws EfaModifyException {
BoatReservationRecord r = ((BoatReservationRecord)record);
BoatReservationRecord[] br = this.getBoatReservations(r.getBoatId());
for (int i=0; br != null && i<br.length; i++) {
// are reservations identical records? then ignore.
if (br[i].getReservation() == r.getReservation()) {
continue;
}
// check if reservations have different type and overlap
if (!r.getType().equals(br[i].getType())) {
checkMixedTypeReservations(r, br[i]); //throws an EfaModifyException, if overlapping
continue; // if no exception is thrown, we're done here and proceed to the next item on the list.
}
// check if both reservations are weekly reservations and overlap. if true, throw exception
checkWeeklyReservationsOverlap(r, br[i]);
// check if both reservations are weekly reservations with a limiting period. if true, throw exception
checkWeeklyLimitedReservationsOverlap(r, br[i]);
// check if two one-time reservations overlap. if true, throw exception
checkOnetimeReservationsOverlap(r, br[i]);
}
}
/**
* Throws an exception, if there is an overlap between two WEEKLY reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkWeeklyReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY)) {
assertFieldNotEmpty(r, BoatReservationRecord.DAYOFWEEK);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
if (!r.getDayOfWeek().equals(br_i.getDayOfWeek())) {
return;
}
if (DataTypeTime.isRangeOverlap(r.getTimeFrom(), r.getTimeTo(),
br_i.getTimeFrom(), br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/**
* Throws an exception, if there is an overlap between two WEEKLY_LIMITED Reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkWeeklyLimitedReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
assertFieldNotEmpty(r, BoatReservationRecord.DATEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.DATETO);
assertFieldNotEmpty(r, BoatReservationRecord.DAYOFWEEK);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
//date range of the reservations must be overlapping
if (!DataTypeDate.isRangeOverlap(
r.getDateFrom(),
r.getDateTo(),
br_i.getDateFrom(),
br_i.getDateTo())) {
return;
}
// then weekday of reservation must be identical
if (!r.getDayOfWeek().equals(br_i.getDayOfWeek())) {
return;
}
// then time of day must be overlapping
if (DataTypeTime.isRangeOverlap(r.getTimeFrom(), r.getTimeTo(),
br_i.getTimeFrom(), br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/**
* Throws an exception, if there is an overlap between two ONETIME reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkOnetimeReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
assertFieldNotEmpty(r, BoatReservationRecord.DATEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.DATETO);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
if (DataTypeDate.isRangeOverlap(r.getDateFrom(),
r.getTimeFrom(),
r.getDateTo(),
r.getTimeTo(),
br_i.getDateFrom(),
br_i.getTimeFrom(),
br_i.getDateTo(),
br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/*
* Returns a list of Weekdays (as EFA Types) which are within a period defined by two dates.
*
* Intention: determine whether a one-time reservation overlaps with a weekly reservation.
*/
/**
* Returns a list of Weekdays (as EFA Types) which are within a period defined by two dates.
*
* Intention: determine whether a one-time reservation overlaps with a weekly reservation.
*
* @param from Date From
* @param to Date To
* @return Array list of weekdays (EFA TYpes) between two dates. Maximum of 7 entries in returned array.
*/
private ArrayList<String> getWeekdaysOfTimePeriod(DataTypeDate from, DataTypeDate to) {
ArrayList<String> result=new ArrayList<String>();
result.add(from.getWeekdayAsEfaType());
int daysAdded=1;
DataTypeDate nextDay=from;
nextDay.addDays(1);
while (daysAdded <7 && nextDay.compareTo(to) <=0) {
result.add(nextDay.getWeekdayAsEfaType());
nextDay.addDays(1);
daysAdded = daysAdded+1;
}
return result;
}
/**
* Checks if a WEEKLY reservations overlaps with a current or future WEEKLY_LIMITED reservation
* @param weeklyRes - the weekly reservation
* @param weeklyLimitedRes - the weekly_limited reservation
* @return true if overlapping exists
*/
private boolean isWeeklyReservationOverlappingWithWeeklyLimited(BoatReservationRecord weeklyRes, BoatReservationRecord weeklyLimitedRes) {
if (!weeklyRes.getDayOfWeek().equals(weeklyLimitedRes.getDayOfWeek())) {
return false; // no matching weekday. conflict impossible.
}
if (!weeklyLimitedRes.isWeeklyLimitedReservationValidNowOrInFuture(System.currentTimeMillis())) {
return false; // limited weekly reservation's end date is in the past - so no conflict
}
//if we are here, we need to check for overlapping begin and end times.
return (DataTypeTime.isRangeOverlap(weeklyRes.getTimeFrom(), weeklyRes.getTimeTo(),
weeklyLimitedRes.getTimeFrom(), weeklyLimitedRes.getTimeTo()));
}
/**
* Checks if a WEEKLY reservations overlaps with a current or future WEEKLY_LIMITED reservation
* @param oneTimeRes - the onetime reservation
* @param periodRes - the weekly or weekly_limited reservation
* @return true if overlapping exists
*/
private boolean isOneTimeReservationOverlappingWithWeeklyReservation(BoatReservationRecord oneTimeRes, BoatReservationRecord periodRes) {
boolean overLapping=false;
if (periodRes.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
//first we have to check, if the oneTimeReservation period covers the period of the weekly reservation
//if not, this weekly reservation is not overlapping.
DataTypeDate myFromDate=periodRes.getDateFrom();
DataTypeDate myToDate=periodRes.getDateTo();
//determine from and to, if left empty
myFromDate=(myFromDate==null ? new DataTypeDate(01,01,1970) : myFromDate);
myToDate=(myToDate==null ? new DataTypeDate(31,12,3000): myToDate);
if (!DataTypeDate.isRangeOverlap(oneTimeRes.getDateFrom(), oneTimeRes.getDateTo(), myFromDate, myToDate)) {
return false;
}
// else we continue
}
//Proceed, treat periodRes as a standard WEEKLY reservation
ArrayList <String> theWeekDays= getWeekdaysOfTimePeriod(oneTimeRes.getDateFrom(), oneTimeRes.getDateTo());
//if weekday of the weekly reservation is within the list of determined weekdays,
//and the time period matches, then we have a conflict.
if (theWeekDays.contains(periodRes.getDayOfWeek())) {
if (theWeekDays.size()==1) {
// one-time-reservation only covers a single day.
// so we have to check only for this single day.
if (theWeekDays.indexOf(periodRes.getDayOfWeek())==0) {
// one-time reservation covers a single day, and this day is a weekday covered by the weekly reservation
overLapping= DataTypeTime.isRangeOverlap(oneTimeRes.getTimeFrom(), oneTimeRes.getTimeTo(),
periodRes.getTimeFrom(), periodRes.getTimeTo());
} else {
overLapping=false;
}
} else {
// Check position of the overlap
int pos = theWeekDays.indexOf(periodRes.getDayOfWeek());
if (pos==0) {
// with an overlap on the first day of the reservation,
// we need to cover START_TIME to 23:59
overLapping= DataTypeTime.isRangeOverlap(oneTimeRes.getTimeFrom(), new DataTypeTime(23,59,59),
periodRes.getTimeFrom(), periodRes.getTimeTo());
}
else if (pos==theWeekDays.size()-1) {
// with an overlap on the last day of the reservation,
// we need to cover from 00:00 to END_TIME
overLapping= DataTypeTime.isRangeOverlap(new DataTypeTime(00,00,00),oneTimeRes.getTimeTo(),
periodRes.getTimeFrom(), periodRes.getTimeTo());
}
else {
// overlapping part is a day somewhere else in the onetime-reservation.
// so onetime-reservation is multiday, and by this we have an overlap if the day
// as such has an overlap
overLapping=true;
}
}
}
return overLapping;
}
/**
* Checks mixed types of reservations for overlaps. Throws an exceptions if an overlap exists,
* depending on the config for handling overlapping reservations in efaConfig.
*
* cases covered for mixed type reservations by this method
* ONETIME - WEEKLY
* ONETIME - WEEKLY_LIMITED
*
* WEEKLY - WEEKLY_LIMITED
*
* @param oneReservation
* @param otherReservation
* @throws EfaModifyException
*/
private void checkMixedTypeReservations (BoatReservationRecord oneReservation, BoatReservationRecord otherReservation) throws EfaModifyException {
// we know the "other reservation" is a WEEKLY or WEEKLY_LIMITED reservation.
if (oneReservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
// new reservation is ONE_TIME, but the other one is a WEEKLY or WEEKLY_LIMITED reservation.
// we calculate the weekdays that are covered by the ONE_TIME reservation
if (isOneTimeReservationOverlappingWithWeeklyReservation (oneReservation, otherReservation)) {
String CONFLICT_HANDLING_TYPE = Daten.efaConfig.getWeeklyReservationConflictBehaviour();
if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_IGNORE)) {
return; //ignore the conflict
} else if ((CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_STRICT)) ||
(CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_PRIORITIZE_WEEKLY))) {
// both handling types are the same if the NEW reservation type is one-time
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
}
}
}
else if (((oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY))||(oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)))
&& otherReservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
// in this case the new reservation is a weekly or weekly_limited which may cover an existing onetime_reservation
// we re-use the existing method but switch the parameters. First parameter must be a one_time reservation, second a weekly or weekly_limited
if (isOneTimeReservationOverlappingWithWeeklyReservation (otherReservation,oneReservation)) {
String CONFLICT_HANDLING_TYPE = Daten.efaConfig.getWeeklyReservationConflictBehaviour();
if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_IGNORE)) {
return; //ignore the conflict
} else if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_STRICT)) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
} else if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_PRIORITIZE_WEEKLY)) {
// new reservation is weekly. this is prioritized - we ignore an EXISTING one-time reservation for the same boat
return;
}
return;
}
}
else { //one reservation is weekly, the second is weekly_limited
boolean conflict =false;
//use the identical methods, but the first parameter must be the weekly reservation, the second the weekly_limited one
if (oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY)) {
conflict = isWeeklyReservationOverlappingWithWeeklyLimited(oneReservation, otherReservation);
} else {
conflict = isWeeklyReservationOverlappingWithWeeklyLimited(otherReservation, oneReservation);
}
if (conflict) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
}
}
}
}
| nicmichael/efa | de/nmichael/efa/data/BoatReservations.java | 7,097 | // else we continue | line_comment | nl | /**
* Title: efa - elektronisches Fahrtenbuch für Ruderer
* Copyright: Copyright (c) 2001-2011 by Nicolas Michael
* Website: http://efa.nmichael.de/
* License: GNU General Public License v2
*
* @author Nicolas Michael
* @version 2
*/
package de.nmichael.efa.data;
import java.util.ArrayList;
import java.util.UUID;
import java.util.Vector;
import de.nmichael.efa.Daten;
import de.nmichael.efa.data.storage.DataKey;
import de.nmichael.efa.data.storage.DataRecord;
import de.nmichael.efa.data.storage.MetaData;
import de.nmichael.efa.data.storage.StorageObject;
import de.nmichael.efa.data.types.DataTypeDate;
import de.nmichael.efa.data.types.DataTypeTime;
import de.nmichael.efa.ex.EfaModifyException;
import de.nmichael.efa.util.International;
import de.nmichael.efa.util.Logger;
// @i18n complete
public class BoatReservations extends StorageObject {
public static final String DATATYPE = "efa2boatreservations";
public BoatReservations(int storageType,
String storageLocation,
String storageUsername,
String storagePassword,
String storageObjectName) {
super(storageType, storageLocation, storageUsername, storagePassword, storageObjectName, DATATYPE, International.getString("Bootsreservierungen"));
BoatReservationRecord.initialize();
dataAccess.setMetaData(MetaData.getMetaData(DATATYPE));
}
public DataRecord createNewRecord() {
return new BoatReservationRecord(this, MetaData.getMetaData(DATATYPE));
}
public BoatReservationRecord createBoatReservationsRecord(UUID id) {
AutoIncrement autoIncrement = getProject().getAutoIncrement(false);
int tries = 0;
int val = 0;
try {
while (tries++ < 100) {
// usually autoincrement should always give a unique new id.
// but in case our id's got out of sync, we try up to 100 times to fine a
// new unique reservation id.
val = autoIncrement.nextAutoIncrementIntValue(data().getStorageObjectType());
if (val <= 0) {
break;
}
if (data().get(BoatReservationRecord.getKey(id, val)) == null) {
break;
}
}
} catch (Exception e) {
Logger.logdebug(e);
}
if (val > 0) {
return createBoatReservationsRecord(id, val);
}
return null;
}
public BoatReservationRecord createBoatReservationsRecord(UUID id, int reservation) {
BoatReservationRecord r = new BoatReservationRecord(this, MetaData.getMetaData(DATATYPE));
r.setBoatId(id);
r.setReservation(reservation);
return r;
}
public BoatReservationRecord[] getBoatReservations(UUID boatId) {
try {
DataKey[] keys = data().getByFields(BoatReservationRecord.IDX_BOATID, new Object[] { boatId });
if (keys == null || keys.length == 0) {
return null;
}
BoatReservationRecord[] recs = new BoatReservationRecord[keys.length];
for (int i=0; i<keys.length; i++) {
recs[i] = (BoatReservationRecord)data().get(keys[i]);
}
return recs;
} catch(Exception e) {
Logger.logdebug(e);
return null;
}
}
public BoatReservationRecord[] getBoatReservations(UUID boatId, long now, long lookAheadMinutes) {
BoatReservationRecord[] reservations = getBoatReservations(boatId);
Vector<BoatReservationRecord> activeReservations = new Vector<BoatReservationRecord>();
for (int i = 0; reservations != null && i < reservations.length; i++) {
BoatReservationRecord r = reservations[i];
if (r.getReservationValidInMinutes(now, lookAheadMinutes) >= 0) {
activeReservations.add(r);
}
}
if (activeReservations.size() == 0) {
return null;
}
BoatReservationRecord[] a = new BoatReservationRecord[activeReservations.size()];
for (int i=0; i<a.length; i++) {
a[i] = activeReservations.get(i);
}
return a;
}
public int purgeObsoleteReservations(UUID boatId, long now) {
BoatReservationRecord[] reservations = getBoatReservations(boatId);
int purged = 0;
for (int i = 0; reservations != null && i < reservations.length; i++) {
BoatReservationRecord r = reservations[i];
if (r.isObsolete(now)) {
try {
data().delete(r.getKey());
purged++;
} catch(Exception e) {
Logger.log(e);
}
}
}
return purged;
}
private String buildOverlappingReservationInfo(BoatReservationRecord reservation) {
String result = "";
if (reservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY)
|| reservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
result = "\n\n" + reservation.getBoatName() + " / " + reservation.getPersonAsName() + " ("
+ Daten.efaTypes.getValueWeekday(reservation.getDayOfWeek()) + " " + reservation.getTimeFrom() + " -- " + reservation.getTimeTo() + ")"
+ "\n" + International.getString("Reservierungsgrund") + ": " + reservation.getReason()
+ "\n" + International.getString("Telefon für Rückfragen") + ": " + reservation.getContact();
} else if (reservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
result = "\n\n" + reservation.getBoatName() + " / " + reservation.getPersonAsName() + " (" + reservation.getDateFrom().getWeekdayAsString() + " " + reservation.getDateFrom() + " " + reservation.getTimeFrom() + " -- " + reservation.getDateTo().getWeekdayAsString() + " " + reservation.getDateTo() + " " + reservation.getTimeTo() + ")"
+ "\n" + International.getString("Reservierungsgrund") + ": " + reservation.getReason()
+ "\n" + International.getString("Telefon für Rückfragen") + ": " + reservation.getContact();
}
return result;
}
public void preModifyRecordCallback(DataRecord record, boolean add, boolean update, boolean delete) throws EfaModifyException {
if (add || update) {
assertFieldNotEmpty(record, BoatReservationRecord.BOATID);
assertFieldNotEmpty(record, BoatReservationRecord.RESERVATION);
assertFieldNotEmpty(record, BoatReservationRecord.TYPE);
checkOverlappingReservationsFor(record);
// no overlapping reservations, clean up some unused attributes for one-time and weekly reservation
BoatReservationRecord r = ((BoatReservationRecord)record);
//one time reservations shall not have a weekday set
if (r.getType().equals(BoatReservationRecord.TYPE_ONETIME) &&
r.getDayOfWeek() != null) {
r.setDayOfWeek(null);
}
//weekly, unlimited reservations shall not have a datefrom/dateto set
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY) &&
r.getDateFrom() != null) {
r.setDateFrom(null);
}
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY) &&
r.getDateTo() != null) {
r.setDateTo(null);
}
}
}
/**
* Checks for overlapping reservations for the current reservation and all other reservations for the same boat
* Throws an efaModifyException if an overlapping is detected.
*
* @param record BoatReservationRecord
*
*/
public void checkOverlappingReservationsFor(DataRecord record) throws EfaModifyException {
BoatReservationRecord r = ((BoatReservationRecord)record);
BoatReservationRecord[] br = this.getBoatReservations(r.getBoatId());
for (int i=0; br != null && i<br.length; i++) {
// are reservations identical records? then ignore.
if (br[i].getReservation() == r.getReservation()) {
continue;
}
// check if reservations have different type and overlap
if (!r.getType().equals(br[i].getType())) {
checkMixedTypeReservations(r, br[i]); //throws an EfaModifyException, if overlapping
continue; // if no exception is thrown, we're done here and proceed to the next item on the list.
}
// check if both reservations are weekly reservations and overlap. if true, throw exception
checkWeeklyReservationsOverlap(r, br[i]);
// check if both reservations are weekly reservations with a limiting period. if true, throw exception
checkWeeklyLimitedReservationsOverlap(r, br[i]);
// check if two one-time reservations overlap. if true, throw exception
checkOnetimeReservationsOverlap(r, br[i]);
}
}
/**
* Throws an exception, if there is an overlap between two WEEKLY reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkWeeklyReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY)) {
assertFieldNotEmpty(r, BoatReservationRecord.DAYOFWEEK);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
if (!r.getDayOfWeek().equals(br_i.getDayOfWeek())) {
return;
}
if (DataTypeTime.isRangeOverlap(r.getTimeFrom(), r.getTimeTo(),
br_i.getTimeFrom(), br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/**
* Throws an exception, if there is an overlap between two WEEKLY_LIMITED Reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkWeeklyLimitedReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
assertFieldNotEmpty(r, BoatReservationRecord.DATEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.DATETO);
assertFieldNotEmpty(r, BoatReservationRecord.DAYOFWEEK);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
//date range of the reservations must be overlapping
if (!DataTypeDate.isRangeOverlap(
r.getDateFrom(),
r.getDateTo(),
br_i.getDateFrom(),
br_i.getDateTo())) {
return;
}
// then weekday of reservation must be identical
if (!r.getDayOfWeek().equals(br_i.getDayOfWeek())) {
return;
}
// then time of day must be overlapping
if (DataTypeTime.isRangeOverlap(r.getTimeFrom(), r.getTimeTo(),
br_i.getTimeFrom(), br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/**
* Throws an exception, if there is an overlap between two ONETIME reservations
* @param r new reservation
* @param br_i an existing reservation
* @throws EfaModifyException if there is an overlap
*/
private void checkOnetimeReservationsOverlap(BoatReservationRecord r, BoatReservationRecord br_i) throws EfaModifyException {
if (r.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
assertFieldNotEmpty(r, BoatReservationRecord.DATEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.DATETO);
assertFieldNotEmpty(r, BoatReservationRecord.TIMEFROM);
assertFieldNotEmpty(r, BoatReservationRecord.TIMETO);
if (DataTypeDate.isRangeOverlap(r.getDateFrom(),
r.getTimeFrom(),
r.getDateTo(),
r.getTimeTo(),
br_i.getDateFrom(),
br_i.getTimeFrom(),
br_i.getDateTo(),
br_i.getTimeTo())) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die Reservierung ueberschneidet sich mit einer anderen Reservierung") + buildOverlappingReservationInfo(br_i),
Thread.currentThread().getStackTrace());
}
}
}
/*
* Returns a list of Weekdays (as EFA Types) which are within a period defined by two dates.
*
* Intention: determine whether a one-time reservation overlaps with a weekly reservation.
*/
/**
* Returns a list of Weekdays (as EFA Types) which are within a period defined by two dates.
*
* Intention: determine whether a one-time reservation overlaps with a weekly reservation.
*
* @param from Date From
* @param to Date To
* @return Array list of weekdays (EFA TYpes) between two dates. Maximum of 7 entries in returned array.
*/
private ArrayList<String> getWeekdaysOfTimePeriod(DataTypeDate from, DataTypeDate to) {
ArrayList<String> result=new ArrayList<String>();
result.add(from.getWeekdayAsEfaType());
int daysAdded=1;
DataTypeDate nextDay=from;
nextDay.addDays(1);
while (daysAdded <7 && nextDay.compareTo(to) <=0) {
result.add(nextDay.getWeekdayAsEfaType());
nextDay.addDays(1);
daysAdded = daysAdded+1;
}
return result;
}
/**
* Checks if a WEEKLY reservations overlaps with a current or future WEEKLY_LIMITED reservation
* @param weeklyRes - the weekly reservation
* @param weeklyLimitedRes - the weekly_limited reservation
* @return true if overlapping exists
*/
private boolean isWeeklyReservationOverlappingWithWeeklyLimited(BoatReservationRecord weeklyRes, BoatReservationRecord weeklyLimitedRes) {
if (!weeklyRes.getDayOfWeek().equals(weeklyLimitedRes.getDayOfWeek())) {
return false; // no matching weekday. conflict impossible.
}
if (!weeklyLimitedRes.isWeeklyLimitedReservationValidNowOrInFuture(System.currentTimeMillis())) {
return false; // limited weekly reservation's end date is in the past - so no conflict
}
//if we are here, we need to check for overlapping begin and end times.
return (DataTypeTime.isRangeOverlap(weeklyRes.getTimeFrom(), weeklyRes.getTimeTo(),
weeklyLimitedRes.getTimeFrom(), weeklyLimitedRes.getTimeTo()));
}
/**
* Checks if a WEEKLY reservations overlaps with a current or future WEEKLY_LIMITED reservation
* @param oneTimeRes - the onetime reservation
* @param periodRes - the weekly or weekly_limited reservation
* @return true if overlapping exists
*/
private boolean isOneTimeReservationOverlappingWithWeeklyReservation(BoatReservationRecord oneTimeRes, BoatReservationRecord periodRes) {
boolean overLapping=false;
if (periodRes.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)) {
//first we have to check, if the oneTimeReservation period covers the period of the weekly reservation
//if not, this weekly reservation is not overlapping.
DataTypeDate myFromDate=periodRes.getDateFrom();
DataTypeDate myToDate=periodRes.getDateTo();
//determine from and to, if left empty
myFromDate=(myFromDate==null ? new DataTypeDate(01,01,1970) : myFromDate);
myToDate=(myToDate==null ? new DataTypeDate(31,12,3000): myToDate);
if (!DataTypeDate.isRangeOverlap(oneTimeRes.getDateFrom(), oneTimeRes.getDateTo(), myFromDate, myToDate)) {
return false;
}
// else we<SUF>
}
//Proceed, treat periodRes as a standard WEEKLY reservation
ArrayList <String> theWeekDays= getWeekdaysOfTimePeriod(oneTimeRes.getDateFrom(), oneTimeRes.getDateTo());
//if weekday of the weekly reservation is within the list of determined weekdays,
//and the time period matches, then we have a conflict.
if (theWeekDays.contains(periodRes.getDayOfWeek())) {
if (theWeekDays.size()==1) {
// one-time-reservation only covers a single day.
// so we have to check only for this single day.
if (theWeekDays.indexOf(periodRes.getDayOfWeek())==0) {
// one-time reservation covers a single day, and this day is a weekday covered by the weekly reservation
overLapping= DataTypeTime.isRangeOverlap(oneTimeRes.getTimeFrom(), oneTimeRes.getTimeTo(),
periodRes.getTimeFrom(), periodRes.getTimeTo());
} else {
overLapping=false;
}
} else {
// Check position of the overlap
int pos = theWeekDays.indexOf(periodRes.getDayOfWeek());
if (pos==0) {
// with an overlap on the first day of the reservation,
// we need to cover START_TIME to 23:59
overLapping= DataTypeTime.isRangeOverlap(oneTimeRes.getTimeFrom(), new DataTypeTime(23,59,59),
periodRes.getTimeFrom(), periodRes.getTimeTo());
}
else if (pos==theWeekDays.size()-1) {
// with an overlap on the last day of the reservation,
// we need to cover from 00:00 to END_TIME
overLapping= DataTypeTime.isRangeOverlap(new DataTypeTime(00,00,00),oneTimeRes.getTimeTo(),
periodRes.getTimeFrom(), periodRes.getTimeTo());
}
else {
// overlapping part is a day somewhere else in the onetime-reservation.
// so onetime-reservation is multiday, and by this we have an overlap if the day
// as such has an overlap
overLapping=true;
}
}
}
return overLapping;
}
/**
* Checks mixed types of reservations for overlaps. Throws an exceptions if an overlap exists,
* depending on the config for handling overlapping reservations in efaConfig.
*
* cases covered for mixed type reservations by this method
* ONETIME - WEEKLY
* ONETIME - WEEKLY_LIMITED
*
* WEEKLY - WEEKLY_LIMITED
*
* @param oneReservation
* @param otherReservation
* @throws EfaModifyException
*/
private void checkMixedTypeReservations (BoatReservationRecord oneReservation, BoatReservationRecord otherReservation) throws EfaModifyException {
// we know the "other reservation" is a WEEKLY or WEEKLY_LIMITED reservation.
if (oneReservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
// new reservation is ONE_TIME, but the other one is a WEEKLY or WEEKLY_LIMITED reservation.
// we calculate the weekdays that are covered by the ONE_TIME reservation
if (isOneTimeReservationOverlappingWithWeeklyReservation (oneReservation, otherReservation)) {
String CONFLICT_HANDLING_TYPE = Daten.efaConfig.getWeeklyReservationConflictBehaviour();
if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_IGNORE)) {
return; //ignore the conflict
} else if ((CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_STRICT)) ||
(CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_PRIORITIZE_WEEKLY))) {
// both handling types are the same if the NEW reservation type is one-time
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
}
}
}
else if (((oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY))||(oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY_LIMITED)))
&& otherReservation.getType().equals(BoatReservationRecord.TYPE_ONETIME)) {
// in this case the new reservation is a weekly or weekly_limited which may cover an existing onetime_reservation
// we re-use the existing method but switch the parameters. First parameter must be a one_time reservation, second a weekly or weekly_limited
if (isOneTimeReservationOverlappingWithWeeklyReservation (otherReservation,oneReservation)) {
String CONFLICT_HANDLING_TYPE = Daten.efaConfig.getWeeklyReservationConflictBehaviour();
if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_IGNORE)) {
return; //ignore the conflict
} else if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_STRICT)) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
} else if (CONFLICT_HANDLING_TYPE.equalsIgnoreCase(Daten.efaConfig.WEEKLY_RESERVATION_CONFLICT_PRIORITIZE_WEEKLY)) {
// new reservation is weekly. this is prioritized - we ignore an EXISTING one-time reservation for the same boat
return;
}
return;
}
}
else { //one reservation is weekly, the second is weekly_limited
boolean conflict =false;
//use the identical methods, but the first parameter must be the weekly reservation, the second the weekly_limited one
if (oneReservation.getType().equals(BoatReservationRecord.TYPE_WEEKLY)) {
conflict = isWeeklyReservationOverlappingWithWeeklyLimited(oneReservation, otherReservation);
} else {
conflict = isWeeklyReservationOverlappingWithWeeklyLimited(otherReservation, oneReservation);
}
if (conflict) {
throw new EfaModifyException(Logger.MSG_DATA_MODIFYEXCEPTION,
International.getString("Die_Reservierung_ueberschneidet_sich_mit_einer_anderen_Reservierung") + buildOverlappingReservationInfo(otherReservation),
Thread.currentThread().getStackTrace());
}
}
}
}
|
76776_3 | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange scheduleSelf --");
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
| nicolas-raoul/AnyMemo | src/org/color/ColorDialog.java | 2,476 | // Log.d(TAG, "onLevelChange scheduleSelf --"); | line_comment | nl | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange<SUF>
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
|
109778_2 | package herddb.utils;
import io.netty.buffer.ByteBuf;
/**
* Utilities for write variable length values on {@link ByteBuf}.
*
* @author diego.salvi
*/
public class ByteBufUtils {
public static final void writeArray(ByteBuf buffer, byte[] array) {
writeVInt(buffer, array.length);
buffer.writeBytes(array);
}
public static final byte[] readArray(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return array;
}
public static final void writeVInt(ByteBuf buffer, int i) {
while ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final int readVInt(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = buffer.readByte();
i |= (b & 0x7F) << shift;
}
return i;
}
public static final void writeZInt(ByteBuf buffer, int i) {
writeVInt(buffer, zigZagEncode(i));
}
public static final int readZInt(ByteBuf buffer) {
return zigZagDecode(readVInt(buffer));
}
public static final void writeVLong(ByteBuf buffer, long i) {
if (i < 0) {
throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")");
}
writeSignedVLong(buffer, i);
}
// write a potentially negative vLong
private static final void writeSignedVLong(ByteBuf buffer, long i) {
while ((i & ~0x7FL) != 0L) {
buffer.writeByte((byte) ((i & 0x7FL) | 0x80L));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final long readVLong(ByteBuf buffer) {
return readVLong(buffer, false);
}
private static final long readVLong(ByteBuf buffer, boolean allowNegative) {
byte b = buffer.readByte();
if (b >= 0) {
return b;
}
long i = b & 0x7FL;
b = buffer.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 56;
if (b >= 0) {
return i;
}
if (allowNegative) {
b = buffer.readByte();
i |= (b & 0x7FL) << 63;
if (b == 0 || b == 1) {
return i;
}
throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)");
} else {
throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)");
}
}
public static final void writeZLong(ByteBuf buffer, long i) {
writeVLong(buffer, zigZagEncode(i));
}
public static final long readZLong(ByteBuf buffer) {
return zigZagDecode(readVLong(buffer));
}
public static final void writeDouble(ByteBuf buffer, double i) {
writeZLong(buffer, Double.doubleToLongBits(i));
}
public static final double readDouble(ByteBuf buffer) {
return Double.longBitsToDouble(readZLong(buffer));
}
/** Same as {@link #zigZagEncode(long)} but on integers. */
private static final int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
private static final long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
private static final int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
private static final long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
| nicoloboschi/herddb | herddb-net/src/main/java/herddb/utils/ByteBufUtils.java | 1,643 | /** Same as {@link #zigZagEncode(long)} but on integers. */ | block_comment | nl | package herddb.utils;
import io.netty.buffer.ByteBuf;
/**
* Utilities for write variable length values on {@link ByteBuf}.
*
* @author diego.salvi
*/
public class ByteBufUtils {
public static final void writeArray(ByteBuf buffer, byte[] array) {
writeVInt(buffer, array.length);
buffer.writeBytes(array);
}
public static final byte[] readArray(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return array;
}
public static final void writeVInt(ByteBuf buffer, int i) {
while ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final int readVInt(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = buffer.readByte();
i |= (b & 0x7F) << shift;
}
return i;
}
public static final void writeZInt(ByteBuf buffer, int i) {
writeVInt(buffer, zigZagEncode(i));
}
public static final int readZInt(ByteBuf buffer) {
return zigZagDecode(readVInt(buffer));
}
public static final void writeVLong(ByteBuf buffer, long i) {
if (i < 0) {
throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")");
}
writeSignedVLong(buffer, i);
}
// write a potentially negative vLong
private static final void writeSignedVLong(ByteBuf buffer, long i) {
while ((i & ~0x7FL) != 0L) {
buffer.writeByte((byte) ((i & 0x7FL) | 0x80L));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final long readVLong(ByteBuf buffer) {
return readVLong(buffer, false);
}
private static final long readVLong(ByteBuf buffer, boolean allowNegative) {
byte b = buffer.readByte();
if (b >= 0) {
return b;
}
long i = b & 0x7FL;
b = buffer.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 56;
if (b >= 0) {
return i;
}
if (allowNegative) {
b = buffer.readByte();
i |= (b & 0x7FL) << 63;
if (b == 0 || b == 1) {
return i;
}
throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)");
} else {
throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)");
}
}
public static final void writeZLong(ByteBuf buffer, long i) {
writeVLong(buffer, zigZagEncode(i));
}
public static final long readZLong(ByteBuf buffer) {
return zigZagDecode(readVLong(buffer));
}
public static final void writeDouble(ByteBuf buffer, double i) {
writeZLong(buffer, Double.doubleToLongBits(i));
}
public static final double readDouble(ByteBuf buffer) {
return Double.longBitsToDouble(readZLong(buffer));
}
/** Same as {@link<SUF>*/
private static final int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
private static final long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
private static final int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
private static final long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
|
23611_5 | package ship;
/**
* @author Nico van Ommen - 1030808
* @since 04/09/2022
*/
public class TankerShip extends BaseShip
{
private int _capacity;
private boolean _departed;
/**
* Constructor
*
* @param name
*/
public TankerShip(String name)
{
super(name);
this.setCapacity(2000);
this.setDeparted(false);
}
/**
* Methode voor het leeghalen van het schip
*
* @param liters
* @return int
*/
public int depleate(int liters)
{
int t = this.getCapacity();
this.setCapacity(t-=liters);
return this.getCapacity();
}
/**
* Methode om de checken of het schip leeg is
*
* @return boolean
*/
public boolean isEmpty()
{
if (this._capacity == 0)
{
return true;
}
return false;
}
/**
* Methode om de capacity te zetten voor het tankerschip
*
* @param liters
*/
public void setCapacity(int liters)
{
this._capacity = liters;
}
/**
* Methode voor het ophalen van de capacity van het schip
*
* @return int
*/
public int getCapacity()
{
return this._capacity;
}
/**
* Methode voor het zetten dat het schip kan vertrekken
*
* @param departed
*/
public void setDeparted(boolean departed)
{
this._departed = departed;
}
/**
* Methode om te kijken of het schip al vertrokken is
*
* @return
*/
public boolean getDeparted()
{
return this._departed;
}
}
| nicoripkip/TINPRO03-3 | src/ship/TankerShip.java | 547 | /**
* Methode voor het ophalen van de capacity van het schip
*
* @return int
*/ | block_comment | nl | package ship;
/**
* @author Nico van Ommen - 1030808
* @since 04/09/2022
*/
public class TankerShip extends BaseShip
{
private int _capacity;
private boolean _departed;
/**
* Constructor
*
* @param name
*/
public TankerShip(String name)
{
super(name);
this.setCapacity(2000);
this.setDeparted(false);
}
/**
* Methode voor het leeghalen van het schip
*
* @param liters
* @return int
*/
public int depleate(int liters)
{
int t = this.getCapacity();
this.setCapacity(t-=liters);
return this.getCapacity();
}
/**
* Methode om de checken of het schip leeg is
*
* @return boolean
*/
public boolean isEmpty()
{
if (this._capacity == 0)
{
return true;
}
return false;
}
/**
* Methode om de capacity te zetten voor het tankerschip
*
* @param liters
*/
public void setCapacity(int liters)
{
this._capacity = liters;
}
/**
* Methode voor het<SUF>*/
public int getCapacity()
{
return this._capacity;
}
/**
* Methode voor het zetten dat het schip kan vertrekken
*
* @param departed
*/
public void setDeparted(boolean departed)
{
this._departed = departed;
}
/**
* Methode om te kijken of het schip al vertrokken is
*
* @return
*/
public boolean getDeparted()
{
return this._departed;
}
}
|
35873_0 | import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Stat {
public BufferedImage img; // Een plaatje van de Statistieken (in child gedefineerd)
public int x, y, breedte, hoogte; // De plaats en afmeting van de Enemy in px (in child gedefineerd)
public Stat(BufferedImage image, int x, int y, int breedte, int hoogte){
this.img = image;
this.x = x;
this.y = y;
this.breedte = breedte;
this.hoogte = hoogte;
}
public void teken(Graphics2D tekenObject){
tekenObject.drawImage(img, x, y, breedte, hoogte, null);
}
}
| niekbr/Mario | Game/src/Stat.java | 219 | // Een plaatje van de Statistieken (in child gedefineerd) | line_comment | nl | import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Stat {
public BufferedImage img; // Een plaatje<SUF>
public int x, y, breedte, hoogte; // De plaats en afmeting van de Enemy in px (in child gedefineerd)
public Stat(BufferedImage image, int x, int y, int breedte, int hoogte){
this.img = image;
this.x = x;
this.y = y;
this.breedte = breedte;
this.hoogte = hoogte;
}
public void teken(Graphics2D tekenObject){
tekenObject.drawImage(img, x, y, breedte, hoogte, null);
}
}
|
31941_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Magazijn;
import java.util.ArrayList;
import magazijnapplicatie.IFactuur;
import magazijnapplicatie.IFactuurRegel;
/**
*
* @author Rob Maas
*/
public class Factuur implements IFactuur{
/**
* De datum van het factuur.
*/
private String datum;
/**
* Het ID van de klant.
*/
private int klantId;
/**
* Het ID van de factuur.
*/
private int factuurId;
/**
* De lijst met IFactuurRegel-objecten (bevat Onderdeel + aantal).
*/
private ArrayList<IFactuurRegel> onderdelen;
/**
* Nieuw Factuur-object met ingevoerde waardes.
* @param datum De datum van de factuur.
* @param klantId Het ID van de klant.
* @param factuurId Het ID van de factuur.
* @param onderdelen Lijst met IFactuurRegel objecten die bij de factuur horen.
*/
public Factuur(String datum, int klantId, int factuurId, ArrayList<IFactuurRegel> onderdelen){
this.datum = datum;
this.klantId = klantId;
this.factuurId = factuurId;
if(onderdelen != null)
{
this.onderdelen = onderdelen;
}
else
{
this.onderdelen = new ArrayList<IFactuurRegel>();
}
}
/**
* Geeft de datum van de factuur.
* @return De datum van de factuur.
*/
public String getDatum(){
return this.datum;
}
/**
* Geeft de ID van de klant.
* @return De ID van de klant.
*/
public int getKlantId(){
return this.klantId;
}
/**
* Geeft de ID van de factuur.
* @return De ID van de factuur.
*/
public int getFactuurId(){
return this.factuurId;
}
/**
* Geeft een lijst met IFactuurRegel-objecten.
* @return Lijst met IFactuurRegel-objecten.
*/
public ArrayList<IFactuurRegel> getOnderdelen(){
return this.onderdelen;
}
}
| niekert/AIDaS-PTS-SEI | src/main/java/Magazijn/Factuur.java | 661 | /**
* De lijst met IFactuurRegel-objecten (bevat Onderdeel + aantal).
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Magazijn;
import java.util.ArrayList;
import magazijnapplicatie.IFactuur;
import magazijnapplicatie.IFactuurRegel;
/**
*
* @author Rob Maas
*/
public class Factuur implements IFactuur{
/**
* De datum van het factuur.
*/
private String datum;
/**
* Het ID van de klant.
*/
private int klantId;
/**
* Het ID van de factuur.
*/
private int factuurId;
/**
* De lijst met<SUF>*/
private ArrayList<IFactuurRegel> onderdelen;
/**
* Nieuw Factuur-object met ingevoerde waardes.
* @param datum De datum van de factuur.
* @param klantId Het ID van de klant.
* @param factuurId Het ID van de factuur.
* @param onderdelen Lijst met IFactuurRegel objecten die bij de factuur horen.
*/
public Factuur(String datum, int klantId, int factuurId, ArrayList<IFactuurRegel> onderdelen){
this.datum = datum;
this.klantId = klantId;
this.factuurId = factuurId;
if(onderdelen != null)
{
this.onderdelen = onderdelen;
}
else
{
this.onderdelen = new ArrayList<IFactuurRegel>();
}
}
/**
* Geeft de datum van de factuur.
* @return De datum van de factuur.
*/
public String getDatum(){
return this.datum;
}
/**
* Geeft de ID van de klant.
* @return De ID van de klant.
*/
public int getKlantId(){
return this.klantId;
}
/**
* Geeft de ID van de factuur.
* @return De ID van de factuur.
*/
public int getFactuurId(){
return this.factuurId;
}
/**
* Geeft een lijst met IFactuurRegel-objecten.
* @return Lijst met IFactuurRegel-objecten.
*/
public ArrayList<IFactuurRegel> getOnderdelen(){
return this.onderdelen;
}
}
|
78974_1 | package infoborden;
import tijdtools.InfobordTijdFuncties;
public class JSONBericht {
private int tijd;
private int aankomsttijd;
private String lijnNaam;
private String busID;
private String bedrijf;
private String eindpunt;
public JSONBericht(int tijd, int aankomsttijd, String lijnNaam, String busID, String bedrijf, String eindpunt) {
super();
this.tijd = tijd;
this.aankomsttijd = aankomsttijd;
this.lijnNaam = lijnNaam;
this.busID = busID;
this.bedrijf = bedrijf;
this.eindpunt = eindpunt;
}
public JSONBericht(){
}
public int getTijd() {
return tijd;
}
public void setTijd(int tijd) {
this.tijd = tijd;
}
public int getAankomsttijd() {
return aankomsttijd;
}
public void setAankomsttijd(int aankomsttijd) {
this.aankomsttijd = aankomsttijd;
}
public String getLijnNaam() {
return lijnNaam;
}
public void setLijnNaam(String lijnNaam) {
this.lijnNaam = lijnNaam;
}
public String getBusID() {
return busID;
}
public void setBusID(String busID) {
this.busID = busID;
}
public String getBedrijf() {
return bedrijf;
}
public void setBedrijf(String bedrijf) {
this.bedrijf = bedrijf;
}
public String getEindpunt() {
return eindpunt;
}
public void setEindpunt(String eindpunt) {
this.eindpunt = eindpunt;
}
public String getInfoRegel() {
// Code voor opdracht 3:
InfobordTijdFuncties tijdFuncties = new InfobordTijdFuncties();
String tijd = tijdFuncties.getFormattedTimeFromCounter(aankomsttijd);
//String tijd = "" + aankomsttijd;
String regel = String.format("%8s - %5s - %12s", this.lijnNaam, this.eindpunt, tijd);
return regel;
}
@Override
public String toString() {
return "JSONBericht [tijd=" + tijd + ", aankomsttijd=" + aankomsttijd + ", lijnNaam=" + lijnNaam + ", busID="
+ busID + ", bedrijf=" + bedrijf + ", eindpunt=" + eindpunt + "]";
}
}
| niekschoemaker/eai_bussimulator | InfobordSysteem/infoborden/JSONBericht.java | 735 | //String tijd = "" + aankomsttijd; | line_comment | nl | package infoborden;
import tijdtools.InfobordTijdFuncties;
public class JSONBericht {
private int tijd;
private int aankomsttijd;
private String lijnNaam;
private String busID;
private String bedrijf;
private String eindpunt;
public JSONBericht(int tijd, int aankomsttijd, String lijnNaam, String busID, String bedrijf, String eindpunt) {
super();
this.tijd = tijd;
this.aankomsttijd = aankomsttijd;
this.lijnNaam = lijnNaam;
this.busID = busID;
this.bedrijf = bedrijf;
this.eindpunt = eindpunt;
}
public JSONBericht(){
}
public int getTijd() {
return tijd;
}
public void setTijd(int tijd) {
this.tijd = tijd;
}
public int getAankomsttijd() {
return aankomsttijd;
}
public void setAankomsttijd(int aankomsttijd) {
this.aankomsttijd = aankomsttijd;
}
public String getLijnNaam() {
return lijnNaam;
}
public void setLijnNaam(String lijnNaam) {
this.lijnNaam = lijnNaam;
}
public String getBusID() {
return busID;
}
public void setBusID(String busID) {
this.busID = busID;
}
public String getBedrijf() {
return bedrijf;
}
public void setBedrijf(String bedrijf) {
this.bedrijf = bedrijf;
}
public String getEindpunt() {
return eindpunt;
}
public void setEindpunt(String eindpunt) {
this.eindpunt = eindpunt;
}
public String getInfoRegel() {
// Code voor opdracht 3:
InfobordTijdFuncties tijdFuncties = new InfobordTijdFuncties();
String tijd = tijdFuncties.getFormattedTimeFromCounter(aankomsttijd);
//String tijd<SUF>
String regel = String.format("%8s - %5s - %12s", this.lijnNaam, this.eindpunt, tijd);
return regel;
}
@Override
public String toString() {
return "JSONBericht [tijd=" + tijd + ", aankomsttijd=" + aankomsttijd + ", lijnNaam=" + lijnNaam + ", busID="
+ busID + ", bedrijf=" + bedrijf + ", eindpunt=" + eindpunt + "]";
}
}
|
84746_5 | package nl.vlessert.vigamup;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GameCollection {
private int activeGame = 0;
private ArrayList<Game> gameObjects;
private ArrayList<Game> gameObjectsWithTrackInformation;
private ArrayList<Game> gameObjectsWithoutTrackInformation;
private Context ctx;
private boolean gameCollectionCreated = false;
private List<String> randomizedGameAndTrackList = new ArrayList<>();
private int randomizedGameAndTrackListPosition = 0;
private final String LOG_TAG = "ViGaMuP game collection";
private ArrayList<Integer> foundMusicTypes = new ArrayList<>();
private int musicTypeToDisplay = 0;
public void setMusicTypeToDisplay(int musicType) {
this.musicTypeToDisplay = musicType;
}
public GameCollection(Context ctx) {
this.ctx = ctx;
}
private void searchForMusicTypeAndAddToListIfFound(String directory, String extension, int typeToAdd) {
Log.d(LOG_TAG, "directory: " + directory + " - extension:" + extension + "typeToAdd: " + typeToAdd);
File parentDir;
File[] files;
String[] strings;
int position = 0;
parentDir = new File(directory);
files = parentDir.listFiles();
if (typeToAdd != 4) {
if (files != null) {
for (File file : files) {
if (!extension.equals("")) {
if (file.getName().endsWith(extension)) {
strings = file.getName().split("\\.");
Log.d(LOG_TAG, "wow " + strings[1] + " found...");
gameObjects.add(new Game(strings[0], typeToAdd, 0, strings[1]));
position++;
}
}
}
}
} else {
for (File file : files) {
Log.d(LOG_TAG, "file: " + file);
if (file.isDirectory()) {
Log.d(LOG_TAG, "wow some tracker directory found: " + file.getName());
gameObjects.add(new Game(file.getName(), typeToAdd, 0, "Tracker"));
}
position++;
}
}
if (position>0 && !foundMusicTypes.contains(typeToAdd)) {
Log.d(LOG_TAG,"adding "+extension+" to foundMusicTypes");
foundMusicTypes.add(typeToAdd);
}
}
public void createGameCollection() {
gameObjects = new ArrayList<>();
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/KSS/", "kss", Constants.PLATFORM.KSS);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/SPC/", "rsn", Constants.PLATFORM.SPC);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/VGM/", "zip", Constants.PLATFORM.VGM);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/NSF/", "nsf", Constants.PLATFORM.NSF);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/Trackers/", "", Constants.PLATFORM.TRACKERS);
gameObjectsWithTrackInformation = new ArrayList<>();
gameObjectsWithoutTrackInformation = new ArrayList<>();
Log.d(LOG_TAG, "hmm: " + gameObjects.size());
for (Game game : gameObjects){
if (game.hasTrackInformationList()){
gameObjectsWithTrackInformation.add(game);
Log.d(LOG_TAG,"adding: " + game.gameName + " " + game.position);
} else gameObjectsWithoutTrackInformation.add(game);
}
Collections.sort(gameObjectsWithTrackInformation, new GameCollectionTitleComperator());
Collections.sort(gameObjectsWithoutTrackInformation, new GameCollectionTitleComperator());
gameObjects = new ArrayList<>(gameObjectsWithTrackInformation);
gameObjects.addAll(gameObjectsWithoutTrackInformation);
int a, b = 0;
for (Game game : gameObjectsWithTrackInformation){
List<GameTrack> list = game.getGameTrackList();
for (a = 0; a < list.size(); a++){
randomizedGameAndTrackList.add(b+","+a);
//Log.d(LOG_TAG, "game title: " + game.getTitle() + ", track position: " + a);
}
b++;
}
Collections.shuffle(randomizedGameAndTrackList);
gameCollectionCreated = true;
//Log.d(LOG_TAG,"hmmmm " + gameObjects.size() + " == " + gameObjectsWithTrackInformation.size() + "?");
/*Log.d(LOG_TAG, "non random: " + Arrays.toString(gameObjectsWithTrackInformation.toArray()));
Log.d(LOG_TAG, "random: " + Arrays.toString(gameObjectsWithTrackInformationRandomized.toArray()));*/
}
public boolean isGameCollectionCreated(){
return gameCollectionCreated;
}
public void deleteGameCollectionObjects() {
gameObjects = null;
gameObjectsWithoutTrackInformation = null;
gameObjectsWithTrackInformation = null;
gameCollectionCreated = false;
foundMusicTypes = new ArrayList<>();
}
public void setCurrentGame(int position){
activeGame = position;
}
public Game getCurrentGame(){
Log.d(LOG_TAG, "active game: " + activeGame + " title: " + gameObjectsWithTrackInformation.get(activeGame).gameName);
return gameObjectsWithTrackInformation.get(activeGame);
}
public Game getGameAtPosition(int position){ return gameObjectsWithTrackInformation.get(position); }
//public Game getGameAtPosition(int position){ return gameObjects.get(position); }
public void setNextGame(){
Log.d(LOG_TAG, "active game: "+activeGame);
for (Game game: gameObjectsWithTrackInformation){
Log.d(LOG_TAG, "Game info: "+ gameObjectsWithTrackInformation.indexOf(game)+ " " + game.gameName);
}
if (activeGame == gameObjectsWithTrackInformation.size()-1) activeGame = 0;
else activeGame++;
}
public void setPreviousGame(){
if (activeGame == 0) activeGame = gameObjectsWithTrackInformation.size()-1;
else activeGame--;
}
public ArrayList<Game> getGameObjects(){
//Log.d("KSS","test vanuit getGameObjects: " + getCurrentGameName());
return gameObjects;
}
public ArrayList<Game> getGameObjectsWithTrackInformation(){
//Log.d("KSS","test vanuit getGameObjects: " + getCurrentGameName());
return gameObjectsWithTrackInformation;
}
public String getNextRandomGameAndTrack(){
if (randomizedGameAndTrackListPosition == randomizedGameAndTrackList.size()-1) randomizedGameAndTrackListPosition = 0;
else randomizedGameAndTrackListPosition++;
return randomizedGameAndTrackList.get(randomizedGameAndTrackListPosition);
}
public String getPreviousRandomGameAndTrack(){
if (randomizedGameAndTrackListPosition == 0) randomizedGameAndTrackListPosition = randomizedGameAndTrackList.size()-1;
else randomizedGameAndTrackListPosition--;
return randomizedGameAndTrackList.get(randomizedGameAndTrackListPosition);
}
public ArrayList<Integer> getFoundMusicTypes(){
return foundMusicTypes;
}
}
class GameCollectionTitleComperator implements Comparator<Game>
{
public int compare(Game left, Game right) {
return left.getTitle().compareTo(right.getTitle());
}
} | niekvlessert/ViGaMuP | app/src/main/java/nl/vlessert/vigamup/GameCollection.java | 2,199 | //Log.d("KSS","test vanuit getGameObjects: " + getCurrentGameName()); | line_comment | nl | package nl.vlessert.vigamup;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GameCollection {
private int activeGame = 0;
private ArrayList<Game> gameObjects;
private ArrayList<Game> gameObjectsWithTrackInformation;
private ArrayList<Game> gameObjectsWithoutTrackInformation;
private Context ctx;
private boolean gameCollectionCreated = false;
private List<String> randomizedGameAndTrackList = new ArrayList<>();
private int randomizedGameAndTrackListPosition = 0;
private final String LOG_TAG = "ViGaMuP game collection";
private ArrayList<Integer> foundMusicTypes = new ArrayList<>();
private int musicTypeToDisplay = 0;
public void setMusicTypeToDisplay(int musicType) {
this.musicTypeToDisplay = musicType;
}
public GameCollection(Context ctx) {
this.ctx = ctx;
}
private void searchForMusicTypeAndAddToListIfFound(String directory, String extension, int typeToAdd) {
Log.d(LOG_TAG, "directory: " + directory + " - extension:" + extension + "typeToAdd: " + typeToAdd);
File parentDir;
File[] files;
String[] strings;
int position = 0;
parentDir = new File(directory);
files = parentDir.listFiles();
if (typeToAdd != 4) {
if (files != null) {
for (File file : files) {
if (!extension.equals("")) {
if (file.getName().endsWith(extension)) {
strings = file.getName().split("\\.");
Log.d(LOG_TAG, "wow " + strings[1] + " found...");
gameObjects.add(new Game(strings[0], typeToAdd, 0, strings[1]));
position++;
}
}
}
}
} else {
for (File file : files) {
Log.d(LOG_TAG, "file: " + file);
if (file.isDirectory()) {
Log.d(LOG_TAG, "wow some tracker directory found: " + file.getName());
gameObjects.add(new Game(file.getName(), typeToAdd, 0, "Tracker"));
}
position++;
}
}
if (position>0 && !foundMusicTypes.contains(typeToAdd)) {
Log.d(LOG_TAG,"adding "+extension+" to foundMusicTypes");
foundMusicTypes.add(typeToAdd);
}
}
public void createGameCollection() {
gameObjects = new ArrayList<>();
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/KSS/", "kss", Constants.PLATFORM.KSS);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/SPC/", "rsn", Constants.PLATFORM.SPC);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/VGM/", "zip", Constants.PLATFORM.VGM);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/NSF/", "nsf", Constants.PLATFORM.NSF);
searchForMusicTypeAndAddToListIfFound(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/ViGaMuP/Trackers/", "", Constants.PLATFORM.TRACKERS);
gameObjectsWithTrackInformation = new ArrayList<>();
gameObjectsWithoutTrackInformation = new ArrayList<>();
Log.d(LOG_TAG, "hmm: " + gameObjects.size());
for (Game game : gameObjects){
if (game.hasTrackInformationList()){
gameObjectsWithTrackInformation.add(game);
Log.d(LOG_TAG,"adding: " + game.gameName + " " + game.position);
} else gameObjectsWithoutTrackInformation.add(game);
}
Collections.sort(gameObjectsWithTrackInformation, new GameCollectionTitleComperator());
Collections.sort(gameObjectsWithoutTrackInformation, new GameCollectionTitleComperator());
gameObjects = new ArrayList<>(gameObjectsWithTrackInformation);
gameObjects.addAll(gameObjectsWithoutTrackInformation);
int a, b = 0;
for (Game game : gameObjectsWithTrackInformation){
List<GameTrack> list = game.getGameTrackList();
for (a = 0; a < list.size(); a++){
randomizedGameAndTrackList.add(b+","+a);
//Log.d(LOG_TAG, "game title: " + game.getTitle() + ", track position: " + a);
}
b++;
}
Collections.shuffle(randomizedGameAndTrackList);
gameCollectionCreated = true;
//Log.d(LOG_TAG,"hmmmm " + gameObjects.size() + " == " + gameObjectsWithTrackInformation.size() + "?");
/*Log.d(LOG_TAG, "non random: " + Arrays.toString(gameObjectsWithTrackInformation.toArray()));
Log.d(LOG_TAG, "random: " + Arrays.toString(gameObjectsWithTrackInformationRandomized.toArray()));*/
}
public boolean isGameCollectionCreated(){
return gameCollectionCreated;
}
public void deleteGameCollectionObjects() {
gameObjects = null;
gameObjectsWithoutTrackInformation = null;
gameObjectsWithTrackInformation = null;
gameCollectionCreated = false;
foundMusicTypes = new ArrayList<>();
}
public void setCurrentGame(int position){
activeGame = position;
}
public Game getCurrentGame(){
Log.d(LOG_TAG, "active game: " + activeGame + " title: " + gameObjectsWithTrackInformation.get(activeGame).gameName);
return gameObjectsWithTrackInformation.get(activeGame);
}
public Game getGameAtPosition(int position){ return gameObjectsWithTrackInformation.get(position); }
//public Game getGameAtPosition(int position){ return gameObjects.get(position); }
public void setNextGame(){
Log.d(LOG_TAG, "active game: "+activeGame);
for (Game game: gameObjectsWithTrackInformation){
Log.d(LOG_TAG, "Game info: "+ gameObjectsWithTrackInformation.indexOf(game)+ " " + game.gameName);
}
if (activeGame == gameObjectsWithTrackInformation.size()-1) activeGame = 0;
else activeGame++;
}
public void setPreviousGame(){
if (activeGame == 0) activeGame = gameObjectsWithTrackInformation.size()-1;
else activeGame--;
}
public ArrayList<Game> getGameObjects(){
//Log.d("KSS","test vanuit getGameObjects: " + getCurrentGameName());
return gameObjects;
}
public ArrayList<Game> getGameObjectsWithTrackInformation(){
//Log.d("KSS","test vanuit<SUF>
return gameObjectsWithTrackInformation;
}
public String getNextRandomGameAndTrack(){
if (randomizedGameAndTrackListPosition == randomizedGameAndTrackList.size()-1) randomizedGameAndTrackListPosition = 0;
else randomizedGameAndTrackListPosition++;
return randomizedGameAndTrackList.get(randomizedGameAndTrackListPosition);
}
public String getPreviousRandomGameAndTrack(){
if (randomizedGameAndTrackListPosition == 0) randomizedGameAndTrackListPosition = randomizedGameAndTrackList.size()-1;
else randomizedGameAndTrackListPosition--;
return randomizedGameAndTrackList.get(randomizedGameAndTrackListPosition);
}
public ArrayList<Integer> getFoundMusicTypes(){
return foundMusicTypes;
}
}
class GameCollectionTitleComperator implements Comparator<Game>
{
public int compare(Game left, Game right) {
return left.getTitle().compareTo(right.getTitle());
}
} |
27626_0 | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| nielsdos/Semisplay-tree | src/semisplay/SearchTree.java | 203 | /** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */ | block_comment | nl | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven<SUF>*/
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
|
76556_10 | /*
* Copyright 2012 - 2020 Manuel Laggner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinymediamanager.scraper.moviemeter;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.core.entities.MediaGenres;
import org.tinymediamanager.core.entities.MediaRating;
import org.tinymediamanager.core.entities.Person;
import org.tinymediamanager.core.movie.MovieSearchAndScrapeOptions;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaProviderInfo;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.entities.MediaArtwork;
import org.tinymediamanager.scraper.exceptions.MissingIdException;
import org.tinymediamanager.scraper.exceptions.NothingFoundException;
import org.tinymediamanager.scraper.exceptions.ScrapeException;
import org.tinymediamanager.scraper.interfaces.IMovieImdbMetadataProvider;
import org.tinymediamanager.scraper.interfaces.IMovieMetadataProvider;
import org.tinymediamanager.scraper.moviemeter.entities.MMActor;
import org.tinymediamanager.scraper.moviemeter.entities.MMDirector;
import org.tinymediamanager.scraper.moviemeter.entities.MMFilm;
import org.tinymediamanager.scraper.util.ApiKey;
import org.tinymediamanager.scraper.util.LanguageUtils;
import org.tinymediamanager.scraper.util.MetadataUtil;
/**
* The Class MoviemeterMetadataProvider. A meta data provider for the site moviemeter.nl
*
* @author Myron Boyle ([email protected])
*/
public class MovieMeterMetadataProvider implements IMovieMetadataProvider, IMovieImdbMetadataProvider {
public static final String ID = "moviemeter";
private static final Logger LOGGER = LoggerFactory.getLogger(MovieMeterMetadataProvider.class);
private static final String TMM_API_KEY = ApiKey.decryptApikey("GK5bRYdcKs3WZzOCa1fOQfIeAJVsBP7buUYjc0q4x2/jX66BlSUDKDAcgN/L0JnM");
private static MovieMeter api;
private static MediaProviderInfo providerInfo = createMediaProviderInfo();
private static MediaProviderInfo createMediaProviderInfo() {
MediaProviderInfo providerInfo = new MediaProviderInfo(ID, "moviemeter.nl",
"<html><h3>Moviemeter.nl</h3><br />A dutch movie database.<br /><br />Available languages: NL</html>",
MovieMeterMetadataProvider.class.getResource("/org/tinymediamanager/scraper/moviemeter_nl.png"));
// configure/load settings
providerInfo.getConfig().addText("apiKey", "", true);
providerInfo.getConfig().addBoolean("scrapeLanguageNames", true);
providerInfo.getConfig().load();
return providerInfo;
}
// thread safe initialization of the API
private static synchronized void initAPI() throws ScrapeException {
if (api == null) {
try {
api = new MovieMeter();
// api.setIsDebug(true);
}
catch (Exception e) {
LOGGER.error("MoviemeterMetadataProvider", e);
throw new ScrapeException(e);
}
}
String userApiKey = providerInfo.getConfig().getValue("apiKey");
// check if the API should change from current key to user key
if (StringUtils.isNotBlank(userApiKey) && !userApiKey.equals(api.getApiKey())) {
api.setApiKey(userApiKey);
}
// check if the API should change from current key to tmm key
if (StringUtils.isBlank(userApiKey) && !TMM_API_KEY.equals(api.getApiKey())) {
api.setApiKey(TMM_API_KEY);
}
}
@Override
public MediaProviderInfo getProviderInfo() {
return providerInfo;
}
@Override
public String getId() {
return ID;
}
@Override
public MediaMetadata getMetadata(MovieSearchAndScrapeOptions options) throws ScrapeException, MissingIdException, NothingFoundException {
// lazy loading of the api
initAPI();
LOGGER.debug("getMetadata(): {}", options);
// check if there is a md in the result
if (options.getMetadata() != null) {
LOGGER.debug("MovieMeter: getMetadata from cache");
return options.getMetadata();
}
// get ids to scrape
MediaMetadata md = new MediaMetadata(providerInfo.getId());
int mmId = options.getIdAsInt(providerInfo.getId());
// imdbid
String imdbId = options.getImdbId();
if (StringUtils.isBlank(imdbId) && mmId == 0) {
LOGGER.warn("not possible to scrape from Moviemeter.bl - no mmId/imdbId found");
throw new MissingIdException(MediaMetadata.IMDB, providerInfo.getId());
}
// scrape
MMFilm fd = null;
Exception savedException = null;
synchronized (api) {
if (mmId != 0) {
LOGGER.debug("getMetadata(mmId): {}", mmId);
try {
fd = api.getFilmService().getMovieInfo(mmId).execute().body();
}
catch (Exception e) {
LOGGER.warn("Error getting movie via MovieMeter id: {}", e.getMessage());
savedException = e;
}
}
else if (StringUtils.isNotBlank(imdbId)) {
LOGGER.debug("filmSearchImdb(imdbId): {}", imdbId);
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdbId).execute().body();
}
catch (Exception e) {
LOGGER.warn("Error getting movie via IMDB id: {}", e.getMessage());
savedException = e;
}
}
}
// if there has been a saved exception and we did not find anything - throw the exception
if (fd == null && savedException != null) {
throw new ScrapeException(savedException);
}
if (fd == null) {
LOGGER.warn("did not find anything");
throw new NothingFoundException();
}
md.setId(MediaMetadata.IMDB, fd.imdb);
md.setTitle(fd.title);
md.setYear(fd.year);
md.setPlot(fd.plot);
md.setTagline(fd.plot.length() > 150 ? fd.plot.substring(0, 150) : fd.plot);
MediaRating mediaRating = new MediaRating("moviemeter");
mediaRating.setRating((float) fd.average);
mediaRating.setMaxValue(5);
mediaRating.setVotes(fd.votes_count);
md.addRating(mediaRating);
md.setId(providerInfo.getId(), fd.id);
try {
md.setRuntime(fd.duration);
}
catch (Exception e) {
md.setRuntime(0);
}
for (String g : fd.genres) {
md.addGenre(getTmmGenre(g));
}
// Poster
MediaArtwork ma = new MediaArtwork(providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
ma.setPreviewUrl(fd.posters.small);
ma.setDefaultUrl(fd.posters.large);
ma.setLanguage(options.getLanguage().getLanguage());
md.addMediaArt(ma);
for (String country : fd.countries) {
if (providerInfo.getConfig().getValueAsBool("scrapeLanguageNames")) {
md.addCountry(LanguageUtils.getLocalizedCountryForLanguage(options.getLanguage().getLanguage(), country));
}
else {
md.addCountry(country);
}
}
for (MMActor a : fd.actors) {
Person cm = new Person(Person.Type.ACTOR, a.name);
md.addCastMember(cm);
}
for (MMDirector d : fd.directors) {
Person cm = new Person(Person.Type.DIRECTOR, d.name);
md.addCastMember(cm);
}
return md;
}
@Override
public SortedSet<MediaSearchResult> search(MovieSearchAndScrapeOptions options) throws ScrapeException {
// lazy loading of the api
initAPI();
LOGGER.debug("search(): {}", options);
SortedSet<MediaSearchResult> results = new TreeSet<>();
String imdb = options.getImdbId();
String searchString = options.getSearchQuery();
int myear = options.getSearchYear();
if (StringUtils.isBlank(searchString) && !MetadataUtil.isValidImdbId(imdb)) {
LOGGER.debug("cannot search without a search string");
return results;
}
searchString = MetadataUtil.removeNonSearchCharacters(searchString);
if (MetadataUtil.isValidImdbId(searchString)) {
// hej, our entered value was an IMDBid :)
imdb = searchString;
}
List<MMFilm> moviesFound = new ArrayList<>();
MMFilm fd = null;
Exception savedException = null;
synchronized (api) {
// 1. "search" with IMDBid (get details, well)
if (StringUtils.isNotEmpty(imdb)) {
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdb).execute().body();
LOGGER.debug("found result with IMDB id");
}
catch (Exception e) {
LOGGER.warn("Error searching by IMDB id: {}", e.getMessage());
savedException = e;
}
}
// 2. try with searchString
if (fd == null) {
try {
moviesFound.addAll(api.getSearchService().searchFilm(searchString).execute().body());
LOGGER.debug("found {} results", moviesFound.size());
}
catch (Exception e) {
LOGGER.warn("Error searching: {}", e.getMessage());
savedException = e;
}
}
}
// if there has been a saved exception and we did not find anything - throw the exception
if (fd == null && savedException != null) {
throw new ScrapeException(savedException);
}
if (fd != null) { // imdb film detail page
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), options.getMediaType());
sr.setId(String.valueOf(fd.id));
sr.setIMDBId(imdb);
sr.setTitle(fd.title);
sr.setUrl(fd.url);
sr.setYear(fd.year);
sr.setScore(1);
results.add(sr);
}
for (MMFilm film : moviesFound) {
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), options.getMediaType());
sr.setId(String.valueOf(film.id));
sr.setIMDBId(imdb);
sr.setTitle(film.title);
sr.setUrl(film.url);
sr.setYear(film.year);
// compare score based on names
sr.calculateScore(options);
results.add(sr);
}
return results;
}
/*
* Maps scraper Genres to internal TMM genres
*/
private MediaGenres getTmmGenre(String genre) {
MediaGenres g = null;
if (genre.isEmpty()) {
return g;
}
// @formatter:off
else if (genre.equals("Actie")) {
g = MediaGenres.ACTION;
} else if (genre.equals("Animatie")) {
g = MediaGenres.ANIMATION;
} else if (genre.equals("Avontuur")) {
g = MediaGenres.ADVENTURE;
} else if (genre.equals("Documentaire")) {
g = MediaGenres.DOCUMENTARY;
} else if (genre.equals("Drama")) {
g = MediaGenres.DRAMA;
} else if (genre.equals("Erotiek")) {
g = MediaGenres.EROTIC;
} else if (genre.equals("Familie")) {
g = MediaGenres.FAMILY;
} else if (genre.equals("Fantasy")) {
g = MediaGenres.FANTASY;
} else if (genre.equals("Film noir")) {
g = MediaGenres.FILM_NOIR;
} else if (genre.equals("Horror")) {
g = MediaGenres.HORROR;
} else if (genre.equals("Komedie")) {
g = MediaGenres.COMEDY;
} else if (genre.equals("Misdaad")) {
g = MediaGenres.CRIME;
} else if (genre.equals("Muziek")) {
g = MediaGenres.MUSIC;
} else if (genre.equals("Mystery")) {
g = MediaGenres.MYSTERY;
} else if (genre.equals("Oorlog")) {
g = MediaGenres.WAR;
} else if (genre.equals("Roadmovie")) {
g = MediaGenres.ROAD_MOVIE;
} else if (genre.equals("Romantiek")) {
g = MediaGenres.ROMANCE;
} else if (genre.equals("Sciencefiction")) {
g = MediaGenres.SCIENCE_FICTION;
} else if (genre.equals("Thriller")) {
g = MediaGenres.THRILLER;
} else if (genre.equals("Western")) {
g = MediaGenres.WESTERN;
}
// @formatter:on
if (g == null) {
g = MediaGenres.getGenre(genre);
}
return g;
}
}
| nielsmeima/tinyMediaManagerSME | src/main/java/org/tinymediamanager/scraper/moviemeter/MovieMeterMetadataProvider.java | 4,056 | // hej, our entered value was an IMDBid :) | line_comment | nl | /*
* Copyright 2012 - 2020 Manuel Laggner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinymediamanager.scraper.moviemeter;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.core.entities.MediaGenres;
import org.tinymediamanager.core.entities.MediaRating;
import org.tinymediamanager.core.entities.Person;
import org.tinymediamanager.core.movie.MovieSearchAndScrapeOptions;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaProviderInfo;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.entities.MediaArtwork;
import org.tinymediamanager.scraper.exceptions.MissingIdException;
import org.tinymediamanager.scraper.exceptions.NothingFoundException;
import org.tinymediamanager.scraper.exceptions.ScrapeException;
import org.tinymediamanager.scraper.interfaces.IMovieImdbMetadataProvider;
import org.tinymediamanager.scraper.interfaces.IMovieMetadataProvider;
import org.tinymediamanager.scraper.moviemeter.entities.MMActor;
import org.tinymediamanager.scraper.moviemeter.entities.MMDirector;
import org.tinymediamanager.scraper.moviemeter.entities.MMFilm;
import org.tinymediamanager.scraper.util.ApiKey;
import org.tinymediamanager.scraper.util.LanguageUtils;
import org.tinymediamanager.scraper.util.MetadataUtil;
/**
* The Class MoviemeterMetadataProvider. A meta data provider for the site moviemeter.nl
*
* @author Myron Boyle ([email protected])
*/
public class MovieMeterMetadataProvider implements IMovieMetadataProvider, IMovieImdbMetadataProvider {
public static final String ID = "moviemeter";
private static final Logger LOGGER = LoggerFactory.getLogger(MovieMeterMetadataProvider.class);
private static final String TMM_API_KEY = ApiKey.decryptApikey("GK5bRYdcKs3WZzOCa1fOQfIeAJVsBP7buUYjc0q4x2/jX66BlSUDKDAcgN/L0JnM");
private static MovieMeter api;
private static MediaProviderInfo providerInfo = createMediaProviderInfo();
private static MediaProviderInfo createMediaProviderInfo() {
MediaProviderInfo providerInfo = new MediaProviderInfo(ID, "moviemeter.nl",
"<html><h3>Moviemeter.nl</h3><br />A dutch movie database.<br /><br />Available languages: NL</html>",
MovieMeterMetadataProvider.class.getResource("/org/tinymediamanager/scraper/moviemeter_nl.png"));
// configure/load settings
providerInfo.getConfig().addText("apiKey", "", true);
providerInfo.getConfig().addBoolean("scrapeLanguageNames", true);
providerInfo.getConfig().load();
return providerInfo;
}
// thread safe initialization of the API
private static synchronized void initAPI() throws ScrapeException {
if (api == null) {
try {
api = new MovieMeter();
// api.setIsDebug(true);
}
catch (Exception e) {
LOGGER.error("MoviemeterMetadataProvider", e);
throw new ScrapeException(e);
}
}
String userApiKey = providerInfo.getConfig().getValue("apiKey");
// check if the API should change from current key to user key
if (StringUtils.isNotBlank(userApiKey) && !userApiKey.equals(api.getApiKey())) {
api.setApiKey(userApiKey);
}
// check if the API should change from current key to tmm key
if (StringUtils.isBlank(userApiKey) && !TMM_API_KEY.equals(api.getApiKey())) {
api.setApiKey(TMM_API_KEY);
}
}
@Override
public MediaProviderInfo getProviderInfo() {
return providerInfo;
}
@Override
public String getId() {
return ID;
}
@Override
public MediaMetadata getMetadata(MovieSearchAndScrapeOptions options) throws ScrapeException, MissingIdException, NothingFoundException {
// lazy loading of the api
initAPI();
LOGGER.debug("getMetadata(): {}", options);
// check if there is a md in the result
if (options.getMetadata() != null) {
LOGGER.debug("MovieMeter: getMetadata from cache");
return options.getMetadata();
}
// get ids to scrape
MediaMetadata md = new MediaMetadata(providerInfo.getId());
int mmId = options.getIdAsInt(providerInfo.getId());
// imdbid
String imdbId = options.getImdbId();
if (StringUtils.isBlank(imdbId) && mmId == 0) {
LOGGER.warn("not possible to scrape from Moviemeter.bl - no mmId/imdbId found");
throw new MissingIdException(MediaMetadata.IMDB, providerInfo.getId());
}
// scrape
MMFilm fd = null;
Exception savedException = null;
synchronized (api) {
if (mmId != 0) {
LOGGER.debug("getMetadata(mmId): {}", mmId);
try {
fd = api.getFilmService().getMovieInfo(mmId).execute().body();
}
catch (Exception e) {
LOGGER.warn("Error getting movie via MovieMeter id: {}", e.getMessage());
savedException = e;
}
}
else if (StringUtils.isNotBlank(imdbId)) {
LOGGER.debug("filmSearchImdb(imdbId): {}", imdbId);
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdbId).execute().body();
}
catch (Exception e) {
LOGGER.warn("Error getting movie via IMDB id: {}", e.getMessage());
savedException = e;
}
}
}
// if there has been a saved exception and we did not find anything - throw the exception
if (fd == null && savedException != null) {
throw new ScrapeException(savedException);
}
if (fd == null) {
LOGGER.warn("did not find anything");
throw new NothingFoundException();
}
md.setId(MediaMetadata.IMDB, fd.imdb);
md.setTitle(fd.title);
md.setYear(fd.year);
md.setPlot(fd.plot);
md.setTagline(fd.plot.length() > 150 ? fd.plot.substring(0, 150) : fd.plot);
MediaRating mediaRating = new MediaRating("moviemeter");
mediaRating.setRating((float) fd.average);
mediaRating.setMaxValue(5);
mediaRating.setVotes(fd.votes_count);
md.addRating(mediaRating);
md.setId(providerInfo.getId(), fd.id);
try {
md.setRuntime(fd.duration);
}
catch (Exception e) {
md.setRuntime(0);
}
for (String g : fd.genres) {
md.addGenre(getTmmGenre(g));
}
// Poster
MediaArtwork ma = new MediaArtwork(providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
ma.setPreviewUrl(fd.posters.small);
ma.setDefaultUrl(fd.posters.large);
ma.setLanguage(options.getLanguage().getLanguage());
md.addMediaArt(ma);
for (String country : fd.countries) {
if (providerInfo.getConfig().getValueAsBool("scrapeLanguageNames")) {
md.addCountry(LanguageUtils.getLocalizedCountryForLanguage(options.getLanguage().getLanguage(), country));
}
else {
md.addCountry(country);
}
}
for (MMActor a : fd.actors) {
Person cm = new Person(Person.Type.ACTOR, a.name);
md.addCastMember(cm);
}
for (MMDirector d : fd.directors) {
Person cm = new Person(Person.Type.DIRECTOR, d.name);
md.addCastMember(cm);
}
return md;
}
@Override
public SortedSet<MediaSearchResult> search(MovieSearchAndScrapeOptions options) throws ScrapeException {
// lazy loading of the api
initAPI();
LOGGER.debug("search(): {}", options);
SortedSet<MediaSearchResult> results = new TreeSet<>();
String imdb = options.getImdbId();
String searchString = options.getSearchQuery();
int myear = options.getSearchYear();
if (StringUtils.isBlank(searchString) && !MetadataUtil.isValidImdbId(imdb)) {
LOGGER.debug("cannot search without a search string");
return results;
}
searchString = MetadataUtil.removeNonSearchCharacters(searchString);
if (MetadataUtil.isValidImdbId(searchString)) {
// hej, our<SUF>
imdb = searchString;
}
List<MMFilm> moviesFound = new ArrayList<>();
MMFilm fd = null;
Exception savedException = null;
synchronized (api) {
// 1. "search" with IMDBid (get details, well)
if (StringUtils.isNotEmpty(imdb)) {
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdb).execute().body();
LOGGER.debug("found result with IMDB id");
}
catch (Exception e) {
LOGGER.warn("Error searching by IMDB id: {}", e.getMessage());
savedException = e;
}
}
// 2. try with searchString
if (fd == null) {
try {
moviesFound.addAll(api.getSearchService().searchFilm(searchString).execute().body());
LOGGER.debug("found {} results", moviesFound.size());
}
catch (Exception e) {
LOGGER.warn("Error searching: {}", e.getMessage());
savedException = e;
}
}
}
// if there has been a saved exception and we did not find anything - throw the exception
if (fd == null && savedException != null) {
throw new ScrapeException(savedException);
}
if (fd != null) { // imdb film detail page
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), options.getMediaType());
sr.setId(String.valueOf(fd.id));
sr.setIMDBId(imdb);
sr.setTitle(fd.title);
sr.setUrl(fd.url);
sr.setYear(fd.year);
sr.setScore(1);
results.add(sr);
}
for (MMFilm film : moviesFound) {
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), options.getMediaType());
sr.setId(String.valueOf(film.id));
sr.setIMDBId(imdb);
sr.setTitle(film.title);
sr.setUrl(film.url);
sr.setYear(film.year);
// compare score based on names
sr.calculateScore(options);
results.add(sr);
}
return results;
}
/*
* Maps scraper Genres to internal TMM genres
*/
private MediaGenres getTmmGenre(String genre) {
MediaGenres g = null;
if (genre.isEmpty()) {
return g;
}
// @formatter:off
else if (genre.equals("Actie")) {
g = MediaGenres.ACTION;
} else if (genre.equals("Animatie")) {
g = MediaGenres.ANIMATION;
} else if (genre.equals("Avontuur")) {
g = MediaGenres.ADVENTURE;
} else if (genre.equals("Documentaire")) {
g = MediaGenres.DOCUMENTARY;
} else if (genre.equals("Drama")) {
g = MediaGenres.DRAMA;
} else if (genre.equals("Erotiek")) {
g = MediaGenres.EROTIC;
} else if (genre.equals("Familie")) {
g = MediaGenres.FAMILY;
} else if (genre.equals("Fantasy")) {
g = MediaGenres.FANTASY;
} else if (genre.equals("Film noir")) {
g = MediaGenres.FILM_NOIR;
} else if (genre.equals("Horror")) {
g = MediaGenres.HORROR;
} else if (genre.equals("Komedie")) {
g = MediaGenres.COMEDY;
} else if (genre.equals("Misdaad")) {
g = MediaGenres.CRIME;
} else if (genre.equals("Muziek")) {
g = MediaGenres.MUSIC;
} else if (genre.equals("Mystery")) {
g = MediaGenres.MYSTERY;
} else if (genre.equals("Oorlog")) {
g = MediaGenres.WAR;
} else if (genre.equals("Roadmovie")) {
g = MediaGenres.ROAD_MOVIE;
} else if (genre.equals("Romantiek")) {
g = MediaGenres.ROMANCE;
} else if (genre.equals("Sciencefiction")) {
g = MediaGenres.SCIENCE_FICTION;
} else if (genre.equals("Thriller")) {
g = MediaGenres.THRILLER;
} else if (genre.equals("Western")) {
g = MediaGenres.WESTERN;
}
// @formatter:on
if (g == null) {
g = MediaGenres.getGenre(genre);
}
return g;
}
}
|
6376_5 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utilities {
public static Pattern pattern = Pattern.compile("[\\-0-9]+");
public static SecureRandom random = new SecureRandom();
public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong());
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue");
public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue");
private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
static {
try {
File URANDOM_FILE = new File("/dev/urandom");
FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE);
byte[] buffer = new byte[1024];
sUrandomIn.read(buffer);
sUrandomIn.close();
random.setSeed(buffer);
} catch (Exception e) {
FileLog.e(e);
}
}
public native static int pinBitmap(Bitmap bitmap);
public native static void unpinBitmap(Bitmap bitmap);
public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride);
public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride);
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer);
public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length);
public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n);
private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt);
public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt);
public native static String readlink(String path);
public native static String readlinkFd(int fd);
public native static long getDirSize(String path, int docType, boolean subdirs);
public native static void clearDir(String path, int docType, long time, boolean subdirs);
private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations);
public static native void stackBlurBitmap(Bitmap bitmap, int radius);
public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY);
public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path);
public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors);
public static Bitmap blurWallpaper(Bitmap src) {
if (src == null) {
return null;
}
Bitmap b;
if (src.getHeight() > src.getWidth()) {
b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888);
} else {
b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888);
}
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
new Canvas(b).drawBitmap(src, null, rect, paint);
stackBlurBitmap(b, 12);
return b;
}
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) {
aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt);
}
public static Integer parseInt(CharSequence value) {
if (value == null) {
return 0;
}
int val = 0;
try {
int start = -1, end;
for (end = 0; end < value.length(); ++end) {
char character = value.charAt(end);
boolean allowedChar = character == '-' || character >= '0' && character <= '9';
if (allowedChar && start < 0) {
start = end;
} else if (!allowedChar && start >= 0) {
end++;
break;
}
}
if (start >= 0) {
String str = value.subSequence(start, end).toString();
// val = parseInt(str);
val = Integer.parseInt(str);
}
// Matcher matcher = pattern.matcher(value);
// if (matcher.find()) {
// String num = matcher.group(0);
// val = Integer.parseInt(num);
// }
} catch (Exception ignore) {}
return val;
}
private static int parseInt(final String s) {
int num = 0;
boolean negative = true;
final int len = s.length();
final char ch = s.charAt(0);
if (ch == '-') {
negative = false;
} else {
num = '0' - ch;
}
int i = 1;
while (i < len) {
num = num * 10 + '0' - s.charAt(i++);
}
return negative ? -num : num;
}
public static Long parseLong(String value) {
if (value == null) {
return 0L;
}
long val = 0L;
try {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Long.parseLong(num);
}
} catch (Exception ignore) {
}
return val;
}
public static String parseIntToString(String value) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return matcher.group(0);
}
return null;
}
public static String bytesToHex(byte[] bytes) {
if (bytes == null) {
return "";
}
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String hex) {
if (hex == null) {
return null;
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
public static boolean isGoodPrime(byte[] prime, int g) {
if (!(g >= 2 && g <= 7)) {
return false;
}
if (prime.length != 256 || prime[0] >= 0) {
return false;
}
BigInteger dhBI = new BigInteger(1, prime);
if (g == 2) { // p mod 8 = 7 for g = 2;
BigInteger res = dhBI.mod(BigInteger.valueOf(8));
if (res.intValue() != 7) {
return false;
}
} else if (g == 3) { // p mod 3 = 2 for g = 3;
BigInteger res = dhBI.mod(BigInteger.valueOf(3));
if (res.intValue() != 2) {
return false;
}
} else if (g == 5) { // p mod 5 = 1 or 4 for g = 5;
BigInteger res = dhBI.mod(BigInteger.valueOf(5));
int val = res.intValue();
if (val != 1 && val != 4) {
return false;
}
} else if (g == 6) { // p mod 24 = 19 or 23 for g = 6;
BigInteger res = dhBI.mod(BigInteger.valueOf(24));
int val = res.intValue();
if (val != 19 && val != 23) {
return false;
}
} else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7.
BigInteger res = dhBI.mod(BigInteger.valueOf(7));
int val = res.intValue();
if (val != 3 && val != 5 && val != 6) {
return false;
}
}
String hex = bytesToHex(prime);
if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) {
return true;
}
BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2));
return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30));
}
public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) {
return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0);
}
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) {
return false;
}
boolean result = true;
for (int a = offset1; a < arr1.length; a++) {
if (arr1[a + offset1] != arr2[a + offset2]) {
result = false;
}
}
return result;
}
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(convertme, offset, len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
int oldp = convertme.position();
int oldl = convertme.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
convertme.position(offset);
convertme.limit(len);
md.update(convertme);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
convertme.limit(oldl);
convertme.position(oldp);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme) {
return computeSHA1(convertme, 0, convertme.limit());
}
public static byte[] computeSHA1(byte[] convertme) {
return computeSHA1(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme) {
return computeSHA256(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme, int offset, long len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertme, offset, (int) len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA256(byte[]... args) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (int a = 0; a < args.length; a++) {
md.update(args[a], 0, args[a].length);
}
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA512(byte[] convertme) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computePBKDF2(byte[] password, byte[] salt) {
byte[] dst = new byte[64];
Utilities.pbkdf2(password, salt, dst, 100000);
return dst;
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
md.update(convertme3, 0, convertme3.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) {
int oldp = b2.position();
int oldl = b2.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(b1, o1, l1);
b2.position(o2);
b2.limit(l2);
md.update(b2);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
b2.limit(oldl);
b2.position(oldp);
}
return new byte[32];
}
public static long bytesToLong(byte[] bytes) {
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
}
public static int bytesToInt(byte[] bytes) {
return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF);
}
public static byte[] intToBytes(int value) {
return new byte[]{
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value};
}
public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(AndroidUtilities.getStringBytes(md5));
StringBuilder sb = new StringBuilder();
for (int a = 0; a < array.length; a++) {
sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
FileLog.e(e);
}
return null;
}
public static float clamp(float value, float maxValue, float minValue) {
if (Float.isNaN(value)) {
return minValue;
}
if (Float.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static String generateRandomString() {
return generateRandomString(16);
}
public static String generateRandomString(int chars) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars; i++) {
sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length())));
}
return sb.toString();
}
}
| nikitasius/Telegraher | TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java | 5,656 | // val = Integer.parseInt(num); | line_comment | nl | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utilities {
public static Pattern pattern = Pattern.compile("[\\-0-9]+");
public static SecureRandom random = new SecureRandom();
public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong());
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue");
public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue");
private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
static {
try {
File URANDOM_FILE = new File("/dev/urandom");
FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE);
byte[] buffer = new byte[1024];
sUrandomIn.read(buffer);
sUrandomIn.close();
random.setSeed(buffer);
} catch (Exception e) {
FileLog.e(e);
}
}
public native static int pinBitmap(Bitmap bitmap);
public native static void unpinBitmap(Bitmap bitmap);
public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride);
public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride);
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer);
public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length);
public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n);
private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt);
public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt);
public native static String readlink(String path);
public native static String readlinkFd(int fd);
public native static long getDirSize(String path, int docType, boolean subdirs);
public native static void clearDir(String path, int docType, long time, boolean subdirs);
private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations);
public static native void stackBlurBitmap(Bitmap bitmap, int radius);
public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY);
public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path);
public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors);
public static Bitmap blurWallpaper(Bitmap src) {
if (src == null) {
return null;
}
Bitmap b;
if (src.getHeight() > src.getWidth()) {
b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888);
} else {
b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888);
}
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
new Canvas(b).drawBitmap(src, null, rect, paint);
stackBlurBitmap(b, 12);
return b;
}
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) {
aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt);
}
public static Integer parseInt(CharSequence value) {
if (value == null) {
return 0;
}
int val = 0;
try {
int start = -1, end;
for (end = 0; end < value.length(); ++end) {
char character = value.charAt(end);
boolean allowedChar = character == '-' || character >= '0' && character <= '9';
if (allowedChar && start < 0) {
start = end;
} else if (!allowedChar && start >= 0) {
end++;
break;
}
}
if (start >= 0) {
String str = value.subSequence(start, end).toString();
// val = parseInt(str);
val = Integer.parseInt(str);
}
// Matcher matcher = pattern.matcher(value);
// if (matcher.find()) {
// String num = matcher.group(0);
// val =<SUF>
// }
} catch (Exception ignore) {}
return val;
}
private static int parseInt(final String s) {
int num = 0;
boolean negative = true;
final int len = s.length();
final char ch = s.charAt(0);
if (ch == '-') {
negative = false;
} else {
num = '0' - ch;
}
int i = 1;
while (i < len) {
num = num * 10 + '0' - s.charAt(i++);
}
return negative ? -num : num;
}
public static Long parseLong(String value) {
if (value == null) {
return 0L;
}
long val = 0L;
try {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Long.parseLong(num);
}
} catch (Exception ignore) {
}
return val;
}
public static String parseIntToString(String value) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return matcher.group(0);
}
return null;
}
public static String bytesToHex(byte[] bytes) {
if (bytes == null) {
return "";
}
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String hex) {
if (hex == null) {
return null;
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
public static boolean isGoodPrime(byte[] prime, int g) {
if (!(g >= 2 && g <= 7)) {
return false;
}
if (prime.length != 256 || prime[0] >= 0) {
return false;
}
BigInteger dhBI = new BigInteger(1, prime);
if (g == 2) { // p mod 8 = 7 for g = 2;
BigInteger res = dhBI.mod(BigInteger.valueOf(8));
if (res.intValue() != 7) {
return false;
}
} else if (g == 3) { // p mod 3 = 2 for g = 3;
BigInteger res = dhBI.mod(BigInteger.valueOf(3));
if (res.intValue() != 2) {
return false;
}
} else if (g == 5) { // p mod 5 = 1 or 4 for g = 5;
BigInteger res = dhBI.mod(BigInteger.valueOf(5));
int val = res.intValue();
if (val != 1 && val != 4) {
return false;
}
} else if (g == 6) { // p mod 24 = 19 or 23 for g = 6;
BigInteger res = dhBI.mod(BigInteger.valueOf(24));
int val = res.intValue();
if (val != 19 && val != 23) {
return false;
}
} else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7.
BigInteger res = dhBI.mod(BigInteger.valueOf(7));
int val = res.intValue();
if (val != 3 && val != 5 && val != 6) {
return false;
}
}
String hex = bytesToHex(prime);
if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) {
return true;
}
BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2));
return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30));
}
public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) {
return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0);
}
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) {
return false;
}
boolean result = true;
for (int a = offset1; a < arr1.length; a++) {
if (arr1[a + offset1] != arr2[a + offset2]) {
result = false;
}
}
return result;
}
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(convertme, offset, len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
int oldp = convertme.position();
int oldl = convertme.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
convertme.position(offset);
convertme.limit(len);
md.update(convertme);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
convertme.limit(oldl);
convertme.position(oldp);
}
return new byte[20];
}
public static byte[] computeSHA1(ByteBuffer convertme) {
return computeSHA1(convertme, 0, convertme.limit());
}
public static byte[] computeSHA1(byte[] convertme) {
return computeSHA1(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme) {
return computeSHA256(convertme, 0, convertme.length);
}
public static byte[] computeSHA256(byte[] convertme, int offset, long len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertme, offset, (int) len);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA256(byte[]... args) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (int a = 0; a < args.length; a++) {
md.update(args[a], 0, args[a].length);
}
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[32];
}
public static byte[] computeSHA512(byte[] convertme) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computePBKDF2(byte[] password, byte[] salt) {
byte[] dst = new byte[64];
Utilities.pbkdf2(password, salt, dst, 100000);
return dst;
}
public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(convertme, 0, convertme.length);
md.update(convertme2, 0, convertme2.length);
md.update(convertme3, 0, convertme3.length);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
}
return new byte[64];
}
public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) {
int oldp = b2.position();
int oldl = b2.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(b1, o1, l1);
b2.position(o2);
b2.limit(l2);
md.update(b2);
return md.digest();
} catch (Exception e) {
FileLog.e(e);
} finally {
b2.limit(oldl);
b2.position(oldp);
}
return new byte[32];
}
public static long bytesToLong(byte[] bytes) {
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
}
public static int bytesToInt(byte[] bytes) {
return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF);
}
public static byte[] intToBytes(int value) {
return new byte[]{
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value};
}
public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(AndroidUtilities.getStringBytes(md5));
StringBuilder sb = new StringBuilder();
for (int a = 0; a < array.length; a++) {
sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
FileLog.e(e);
}
return null;
}
public static float clamp(float value, float maxValue, float minValue) {
if (Float.isNaN(value)) {
return minValue;
}
if (Float.isInfinite(value)) {
return maxValue;
}
return Math.max(Math.min(value, maxValue), minValue);
}
public static String generateRandomString() {
return generateRandomString(16);
}
public static String generateRandomString(int chars) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars; i++) {
sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length())));
}
return sb.toString();
}
}
|
158066_44 | package dimerSim;
import java.io.File;
import org.checkerframework.checker.units.qual.A;
import de.jtem.mfc.field.Complex;
import de.jtem.riemann.schottky.SchottkyData;
import de.jtem.riemann.schottky.SchottkyDimers;
import de.jtem.riemann.schottky.SchottkyDimersDoubleCoverUnitary;
import de.jtem.riemann.schottky.SchottkyDimersQuad;
import de.jtem.riemann.schottky.SchottkyDimersQuadUnitary;
import de.jtem.riemann.schottky.SchottkyDimersUnitary;
public class RunSimulations {
public static void main(String[] args) {
// Create SchottkyDimers
String baseFolder = "experimentExport/";
// String experimentName = "Hexagon/01_starfish/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Hexagon/02_growingLargeBubble/mu005/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Hexagon/03_convergenceToUniform/";
// int size = 600;
// int numSteps = (int)1e6;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Hexagon/04_growingStarfishHoles/mu06/";
// int size = 300;
// int numSteps = (int)5e6;
// int interval = 0;
// int numTimes = 10;
// --------------------------------------------------
// String experimentName = "Aztec/01_LargeHoleG1/";
// int size = 604;
// int numSteps = (int) 1e7;
// int interval = (int) 0;
// int numTimes = 10;
// String experimentName = "Aztec/02_LargeHole2AnglesElongated/";
// int size = 1000;
// int numSteps = (int)1e6;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Aztec/03_uniform/";
// String experimentName = "Aztec/05_growing1LargeHole/mu004/";
// int size = 500;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Aztec/06_growing2LargeHolesFromUnitary/mu01/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Aztec/07_growing2LargeHolesFromUnitarySymmetric/mu01/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 1;
String experimentName = "Aztec/08_growing2LargeHolesFromUnitarySymmetric1Angle/mu02/";
int size = 600;
int numSteps = (int) 1e7;
int interval = 0;
int numTimes = 1;
System.out.println("Running experiment " + experimentName + " of size " + size);
String folderName = baseFolder + experimentName;
// SchottkyDimers schottkyDimers = createSchottkyQuad();
// SchottkyDimers schottkyDimers = createSchottkyHex();
// SimulationManager man = new SimulationManager(schottkyDimers, folderName);
continueSimulation(folderName, size, numSteps, interval, numTimes);
}
public static void continueSimulation(String folder, int size, int numSteps, int interval, int numTimes) {
SimulationManager man = new SimulationManager(folder);
man.setSavePictureInterval(interval);
for (int i = 0; i < numTimes; i++) {
man.simulateAndSave(numSteps, size);
}
}
public static void growHoles(String baseFolder, int size, int numSteps, int interval, int numTimes, double[] mus) {
for (int i = 1; i < mus.length; i++) {
String muFolder = new File(baseFolder, String.format("%0.5f", mus[i])).toString();
}
}
public static SchottkyDimers createSchottkyHex(){
// Starfish:
// Complex A = new Complex(Math.cos(Math.PI / 3 + 0.01), Math.sin(Math.PI / 3 + 0.01)).times(0.5);
// double d = 0.07;
// double[][] angles = {{d, Math.PI / 3 - d}, {Math.PI / 3 + d, 2 * Math.PI / 3 - d}, {2 * Math.PI / 3 + d, 3 * Math.PI / 3 - d}};
// One bubble with angles
Complex A = new Complex(Math.cos(2 * Math.PI / 3 + 0.1), Math.sin(2 * Math.PI / 3 + 0.1)).times(0.5);
double[][] angles = {{0, 0}, {Math.PI / 3 - 0.6, Math.PI / 3 + 0.6}, {2 * Math.PI / 3, 2 * Math.PI / 3}};
Complex B = A.invert().conjugate();
double[] schottkyParams = {A.re, A.im, B.re, B.im, 0.05, 0};
double[] sizes = {1, 1, 1};
// double[] sizes = {1, 0.8, 0.6};
double[] boundaryResidues = {sizes[0], -sizes[1], sizes[2], -sizes[0], sizes[1], -sizes[2]};
SchottkyDimersUnitary schottkyDimers = new SchottkyDimersUnitary(new SchottkyData(schottkyParams), angles, boundaryResidues);
SchottkyDimersDoubleCoverUnitary doubleCover = schottkyDimers.getSimpleDoubleCover();
return doubleCover;
}
public static SchottkyDimers createSchottkyQuad(){
// G1LargeHole
// double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.08, 0};
// double a = Math.sqrt(2 / (1.5 + Math.sqrt(2)));
// double x = a * (1 + Math.sqrt(2));
// double firstAngle = -x - (a/2);
// double[][] angles = {{firstAngle}, {firstAngle + x}, {firstAngle + x + a}, {firstAngle + x + a + x}};
// double[][] angles = {{-2.4}, {-0.4}, {0.6}, {2.4}};
// G1LargeHole2Angles
// double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.15, 0};
// double[][] angles = {{-2.4, -0.5}, {-0.4, -0.4}, {0.5, 1.3}, {1.4, 1.4}};
// SchottkyDimersQuad schottkyDimers = new SchottkyDimersQuad(new SchottkyData(schottkyParamsCol), angles);
// // G1Unitary
// double theta = Math.PI / 4;
// Complex A = new Complex(Math.cos(theta), Math.sin(theta)).times(0.3);
// Complex ARefl = A.invert().conjugate();
// double[] schottkyParamsCol = {A.re, A.im, ARefl.re, ARefl.im, 0.00000004, 0};
// double[][] angles = {{0}, {Math.PI / 2}, {Math.PI}, {3 * Math.PI / 2}};
// G2Unitary
double theta1 = Math.PI / 2 + 0.7;
Complex A1 = new Complex(Math.cos(theta1), Math.sin(theta1)).times(0.3);
Complex A1Refl = A1.invert().conjugate();
double theta2 = -Math.PI / 4;
Complex A2 = new Complex(Math.cos(theta2), Math.sin(theta2)).times(0.3);
Complex A2Refl = A2.invert().conjugate();
double[] schottkyParamsCol = {A1.re, A1.im, A1Refl.re, A1Refl.im, 0.02, 0, A2.re, A2.im, A2Refl.re, A2Refl.im, 0.02, 0};
double[][] angles = {{0, 0}, {Math.PI / 2 - 0.9, Math.PI / 2 + 0.4}, {Math.PI, Math.PI}, {3 * Math.PI / 2, 3 * Math.PI / 2}};
SchottkyDimersQuadUnitary schottkyDimers = new SchottkyDimersQuadUnitary(new SchottkyData(schottkyParamsCol), angles);
return schottkyDimers;
}
}
| nikolaibobenko/FockDimerSimulation | src/main/java/dimerSim/RunSimulations.java | 2,567 | // int interval = 0; | line_comment | nl | package dimerSim;
import java.io.File;
import org.checkerframework.checker.units.qual.A;
import de.jtem.mfc.field.Complex;
import de.jtem.riemann.schottky.SchottkyData;
import de.jtem.riemann.schottky.SchottkyDimers;
import de.jtem.riemann.schottky.SchottkyDimersDoubleCoverUnitary;
import de.jtem.riemann.schottky.SchottkyDimersQuad;
import de.jtem.riemann.schottky.SchottkyDimersQuadUnitary;
import de.jtem.riemann.schottky.SchottkyDimersUnitary;
public class RunSimulations {
public static void main(String[] args) {
// Create SchottkyDimers
String baseFolder = "experimentExport/";
// String experimentName = "Hexagon/01_starfish/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Hexagon/02_growingLargeBubble/mu005/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Hexagon/03_convergenceToUniform/";
// int size = 600;
// int numSteps = (int)1e6;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Hexagon/04_growingStarfishHoles/mu06/";
// int size = 300;
// int numSteps = (int)5e6;
// int interval = 0;
// int numTimes = 10;
// --------------------------------------------------
// String experimentName = "Aztec/01_LargeHoleG1/";
// int size = 604;
// int numSteps = (int) 1e7;
// int interval = (int) 0;
// int numTimes = 10;
// String experimentName = "Aztec/02_LargeHole2AnglesElongated/";
// int size = 1000;
// int numSteps = (int)1e6;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Aztec/03_uniform/";
// String experimentName = "Aztec/05_growing1LargeHole/mu004/";
// int size = 500;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 10;
// String experimentName = "Aztec/06_growing2LargeHolesFromUnitary/mu01/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval = 0;
// int numTimes = 1;
// String experimentName = "Aztec/07_growing2LargeHolesFromUnitarySymmetric/mu01/";
// int size = 600;
// int numSteps = (int) 1e7;
// int interval<SUF>
// int numTimes = 1;
String experimentName = "Aztec/08_growing2LargeHolesFromUnitarySymmetric1Angle/mu02/";
int size = 600;
int numSteps = (int) 1e7;
int interval = 0;
int numTimes = 1;
System.out.println("Running experiment " + experimentName + " of size " + size);
String folderName = baseFolder + experimentName;
// SchottkyDimers schottkyDimers = createSchottkyQuad();
// SchottkyDimers schottkyDimers = createSchottkyHex();
// SimulationManager man = new SimulationManager(schottkyDimers, folderName);
continueSimulation(folderName, size, numSteps, interval, numTimes);
}
public static void continueSimulation(String folder, int size, int numSteps, int interval, int numTimes) {
SimulationManager man = new SimulationManager(folder);
man.setSavePictureInterval(interval);
for (int i = 0; i < numTimes; i++) {
man.simulateAndSave(numSteps, size);
}
}
public static void growHoles(String baseFolder, int size, int numSteps, int interval, int numTimes, double[] mus) {
for (int i = 1; i < mus.length; i++) {
String muFolder = new File(baseFolder, String.format("%0.5f", mus[i])).toString();
}
}
public static SchottkyDimers createSchottkyHex(){
// Starfish:
// Complex A = new Complex(Math.cos(Math.PI / 3 + 0.01), Math.sin(Math.PI / 3 + 0.01)).times(0.5);
// double d = 0.07;
// double[][] angles = {{d, Math.PI / 3 - d}, {Math.PI / 3 + d, 2 * Math.PI / 3 - d}, {2 * Math.PI / 3 + d, 3 * Math.PI / 3 - d}};
// One bubble with angles
Complex A = new Complex(Math.cos(2 * Math.PI / 3 + 0.1), Math.sin(2 * Math.PI / 3 + 0.1)).times(0.5);
double[][] angles = {{0, 0}, {Math.PI / 3 - 0.6, Math.PI / 3 + 0.6}, {2 * Math.PI / 3, 2 * Math.PI / 3}};
Complex B = A.invert().conjugate();
double[] schottkyParams = {A.re, A.im, B.re, B.im, 0.05, 0};
double[] sizes = {1, 1, 1};
// double[] sizes = {1, 0.8, 0.6};
double[] boundaryResidues = {sizes[0], -sizes[1], sizes[2], -sizes[0], sizes[1], -sizes[2]};
SchottkyDimersUnitary schottkyDimers = new SchottkyDimersUnitary(new SchottkyData(schottkyParams), angles, boundaryResidues);
SchottkyDimersDoubleCoverUnitary doubleCover = schottkyDimers.getSimpleDoubleCover();
return doubleCover;
}
public static SchottkyDimers createSchottkyQuad(){
// G1LargeHole
// double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.08, 0};
// double a = Math.sqrt(2 / (1.5 + Math.sqrt(2)));
// double x = a * (1 + Math.sqrt(2));
// double firstAngle = -x - (a/2);
// double[][] angles = {{firstAngle}, {firstAngle + x}, {firstAngle + x + a}, {firstAngle + x + a + x}};
// double[][] angles = {{-2.4}, {-0.4}, {0.6}, {2.4}};
// G1LargeHole2Angles
// double[] schottkyParamsCol = {0.9, 1, 0.9, -1, 0.15, 0};
// double[][] angles = {{-2.4, -0.5}, {-0.4, -0.4}, {0.5, 1.3}, {1.4, 1.4}};
// SchottkyDimersQuad schottkyDimers = new SchottkyDimersQuad(new SchottkyData(schottkyParamsCol), angles);
// // G1Unitary
// double theta = Math.PI / 4;
// Complex A = new Complex(Math.cos(theta), Math.sin(theta)).times(0.3);
// Complex ARefl = A.invert().conjugate();
// double[] schottkyParamsCol = {A.re, A.im, ARefl.re, ARefl.im, 0.00000004, 0};
// double[][] angles = {{0}, {Math.PI / 2}, {Math.PI}, {3 * Math.PI / 2}};
// G2Unitary
double theta1 = Math.PI / 2 + 0.7;
Complex A1 = new Complex(Math.cos(theta1), Math.sin(theta1)).times(0.3);
Complex A1Refl = A1.invert().conjugate();
double theta2 = -Math.PI / 4;
Complex A2 = new Complex(Math.cos(theta2), Math.sin(theta2)).times(0.3);
Complex A2Refl = A2.invert().conjugate();
double[] schottkyParamsCol = {A1.re, A1.im, A1Refl.re, A1Refl.im, 0.02, 0, A2.re, A2.im, A2Refl.re, A2Refl.im, 0.02, 0};
double[][] angles = {{0, 0}, {Math.PI / 2 - 0.9, Math.PI / 2 + 0.4}, {Math.PI, Math.PI}, {3 * Math.PI / 2, 3 * Math.PI / 2}};
SchottkyDimersQuadUnitary schottkyDimers = new SchottkyDimersQuadUnitary(new SchottkyData(schottkyParamsCol), angles);
return schottkyDimers;
}
}
|
197231_2 | package Kompendie;
import Kompendie.Hjelpeklasser.Liste;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
public class TabellListe<T> implements Liste<T> {
private T[] a;
private int antall;
private int endringer; //ny variabel
/**
* 3.2.2b
*/
// konstruktører og metoder kommer her
@SuppressWarnings("unchecked") // pga. konverteringen: Object[] -> T[]
public TabellListe(int størrelse) { // konstruktør
a = (T[])new Object[størrelse]; // oppretter tabellen
antall = 0; // foreløpig ingen verdier
}
public TabellListe() { // standardkonstruktør
this(10); // startstørrelse på 10
}
/**
* 3.2.2c
*/
//String[] navn = {"Per", "Kari", "Ole", "Azra"};
//Liste<String> liste = new TabellListe<>(navn);
/**
* 3.2.2d
*/
public TabellListe(T[] b){ // en T-tabell som parameter
this(b.length); // kaller den andre konstruktøren
for (T verdi : b) {
if (verdi != null) a[antall++] = verdi; // hopper over null-verdier
}
}
/**
* 3.2.2e
*/
public int antall() {
return antall; // returnerer antallet
}
public boolean tom() {
return antall == 0; // listen er tom hvis antall er 0
}
/**
* 3.2.2f
*/
public T hent(int indeks) {
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
return a[indeks]; // returnerer er tabellelement
}
/**
* 3.2.2g
*/
public int indeksTil(T verdi) {
for (int i = 0; i < antall; i++) {
if (a[i].equals(verdi)) return i; // funnet!
}
return -1; // ikke funnet!
}
public boolean inneholder(T verdi) {
return indeksTil(verdi) != -1;
}
/**
* 3.2.3b
*/
public boolean leggInn(T verdi) { // inn bakerst
Objects.requireNonNull(verdi, "null er ulovlig!");
if (antall == a.length) { // En full tabell utvides med 50%
a = Arrays.copyOf(a,(3*antall)/2 + 1);
}
a[antall++] = verdi; // setter inn ny verdi
return true; // vellykket innlegging
}
public void leggInn(int indeks, T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
indeksKontroll(indeks, true); // true: indeks = antall er lovlig
// En full tabell utvides med 50%
if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1);
// rydder plass til den nye verdien
System.arraycopy(a, indeks, a, indeks + 1, antall - indeks);
a[indeks] = verdi; // setter inn ny verdi
antall++; // vellykket innlegging
}
/**
* 3.2.3c
*/
public T oppdater(int indeks, T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
T gammelverdi = a[indeks]; // tar vare på den gamle verdien
a[indeks] = verdi; // oppdaterer
return gammelverdi; // returnerer den gamle verdien
}
public T fjern(int indeks) {
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
T verdi = a[indeks];
antall--; // sletter ved å flytte verdier mot venstre
System.arraycopy(a, indeks + 1, a, indeks, antall - indeks);
a[antall] = null; // tilrettelegger for "søppeltømming"
return verdi;
}
/**
* 3.2.3 --> Oppgaver
*/
public boolean fjern(T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
for (int i = 0; i < antall; i++)
{
if (a[i].equals(verdi)) {
antall--;
System.arraycopy(a, i + 1, a, i, antall - i);
a[antall] = null;
return true;
}
}
return false;
}
public void nullstill() {
if (a.length > 10)
a = (T[])new Object[10];
else
for (int i = 0; i < antall; i++) a[i] = null;
antall = 0;
}
/**
* 3.2.4a
*/
// Skal ligge som en indre klasse i class TabellListe
private class TabellListeIterator implements Iterator<T> {
private int denne = 0; // instansvariabel
private boolean fjernOk = false;
private int iteratorendringer = endringer; //ny variabel
public boolean hasNext() { // sjekker om det er flere igjen
return denne < antall; // sjekker verdien til denne
}
public T next() { // returnerer aktuell verdi
if (!hasNext())
throw new NoSuchElementException("Tomt eller ingen verdier igjen!");
return a[denne++]; // a[denne] returneres før denne++
}
/**
* 3.2.4c
*/
/*private boolean fjernOK = false; // ny instansvariabel i TabellListeIterator
public T next() // ny versjon
{
if (!hasNext())
throw new NoSuchElementException("Tomt eller ingen verdier igjen!");
T denneVerdi = a[denne]; // henter aktuell verdi
denne++; // flytter indeksen
fjernOK = true; // nå kan remove() kalles
return denneVerdi; // returnerer verdien
}
public void remove() // ny versjon
{
if (!fjernOK) throw
new IllegalStateException("Ulovlig tilstand!");
fjernOK = false; // remove() kan ikke kalles på nytt
// verdien i denne - 1 skal fjernes da den ble returnert i siste kall
// på next(), verdiene fra og med denne flyttes derfor en mot venstre
antall--; // en verdi vil bli fjernet
denne--; // denne må flyttes til venstre
System.arraycopy(a, denne + 1, a, denne, antall - denne); // tetter igjen
a[antall] = null; // verdien som lå lengst til høyre nulles
}*/
} // TabellListeIterator
/**
* 3.2.4b
*/
public Iterator<T> iterator() {
return new TabellListeIterator();
}
}
| nikolasekiw/AlgoritmerOgDatastrukturer_DATS2300 | src/Kompendie/TabellListe.java | 2,156 | // pga. konverteringen: Object[] -> T[] | line_comment | nl | package Kompendie;
import Kompendie.Hjelpeklasser.Liste;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
public class TabellListe<T> implements Liste<T> {
private T[] a;
private int antall;
private int endringer; //ny variabel
/**
* 3.2.2b
*/
// konstruktører og metoder kommer her
@SuppressWarnings("unchecked") // pga. konverteringen:<SUF>
public TabellListe(int størrelse) { // konstruktør
a = (T[])new Object[størrelse]; // oppretter tabellen
antall = 0; // foreløpig ingen verdier
}
public TabellListe() { // standardkonstruktør
this(10); // startstørrelse på 10
}
/**
* 3.2.2c
*/
//String[] navn = {"Per", "Kari", "Ole", "Azra"};
//Liste<String> liste = new TabellListe<>(navn);
/**
* 3.2.2d
*/
public TabellListe(T[] b){ // en T-tabell som parameter
this(b.length); // kaller den andre konstruktøren
for (T verdi : b) {
if (verdi != null) a[antall++] = verdi; // hopper over null-verdier
}
}
/**
* 3.2.2e
*/
public int antall() {
return antall; // returnerer antallet
}
public boolean tom() {
return antall == 0; // listen er tom hvis antall er 0
}
/**
* 3.2.2f
*/
public T hent(int indeks) {
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
return a[indeks]; // returnerer er tabellelement
}
/**
* 3.2.2g
*/
public int indeksTil(T verdi) {
for (int i = 0; i < antall; i++) {
if (a[i].equals(verdi)) return i; // funnet!
}
return -1; // ikke funnet!
}
public boolean inneholder(T verdi) {
return indeksTil(verdi) != -1;
}
/**
* 3.2.3b
*/
public boolean leggInn(T verdi) { // inn bakerst
Objects.requireNonNull(verdi, "null er ulovlig!");
if (antall == a.length) { // En full tabell utvides med 50%
a = Arrays.copyOf(a,(3*antall)/2 + 1);
}
a[antall++] = verdi; // setter inn ny verdi
return true; // vellykket innlegging
}
public void leggInn(int indeks, T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
indeksKontroll(indeks, true); // true: indeks = antall er lovlig
// En full tabell utvides med 50%
if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1);
// rydder plass til den nye verdien
System.arraycopy(a, indeks, a, indeks + 1, antall - indeks);
a[indeks] = verdi; // setter inn ny verdi
antall++; // vellykket innlegging
}
/**
* 3.2.3c
*/
public T oppdater(int indeks, T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
T gammelverdi = a[indeks]; // tar vare på den gamle verdien
a[indeks] = verdi; // oppdaterer
return gammelverdi; // returnerer den gamle verdien
}
public T fjern(int indeks) {
indeksKontroll(indeks, false); // false: indeks = antall er ulovlig
T verdi = a[indeks];
antall--; // sletter ved å flytte verdier mot venstre
System.arraycopy(a, indeks + 1, a, indeks, antall - indeks);
a[antall] = null; // tilrettelegger for "søppeltømming"
return verdi;
}
/**
* 3.2.3 --> Oppgaver
*/
public boolean fjern(T verdi) {
Objects.requireNonNull(verdi, "null er ulovlig!");
for (int i = 0; i < antall; i++)
{
if (a[i].equals(verdi)) {
antall--;
System.arraycopy(a, i + 1, a, i, antall - i);
a[antall] = null;
return true;
}
}
return false;
}
public void nullstill() {
if (a.length > 10)
a = (T[])new Object[10];
else
for (int i = 0; i < antall; i++) a[i] = null;
antall = 0;
}
/**
* 3.2.4a
*/
// Skal ligge som en indre klasse i class TabellListe
private class TabellListeIterator implements Iterator<T> {
private int denne = 0; // instansvariabel
private boolean fjernOk = false;
private int iteratorendringer = endringer; //ny variabel
public boolean hasNext() { // sjekker om det er flere igjen
return denne < antall; // sjekker verdien til denne
}
public T next() { // returnerer aktuell verdi
if (!hasNext())
throw new NoSuchElementException("Tomt eller ingen verdier igjen!");
return a[denne++]; // a[denne] returneres før denne++
}
/**
* 3.2.4c
*/
/*private boolean fjernOK = false; // ny instansvariabel i TabellListeIterator
public T next() // ny versjon
{
if (!hasNext())
throw new NoSuchElementException("Tomt eller ingen verdier igjen!");
T denneVerdi = a[denne]; // henter aktuell verdi
denne++; // flytter indeksen
fjernOK = true; // nå kan remove() kalles
return denneVerdi; // returnerer verdien
}
public void remove() // ny versjon
{
if (!fjernOK) throw
new IllegalStateException("Ulovlig tilstand!");
fjernOK = false; // remove() kan ikke kalles på nytt
// verdien i denne - 1 skal fjernes da den ble returnert i siste kall
// på next(), verdiene fra og med denne flyttes derfor en mot venstre
antall--; // en verdi vil bli fjernet
denne--; // denne må flyttes til venstre
System.arraycopy(a, denne + 1, a, denne, antall - denne); // tetter igjen
a[antall] = null; // verdien som lå lengst til høyre nulles
}*/
} // TabellListeIterator
/**
* 3.2.4b
*/
public Iterator<T> iterator() {
return new TabellListeIterator();
}
}
|
142650_9 | class Variable
{
public static void main(String[] args)
{ System.setOut(new FiveCodePrintStream(System.out));
/** * Verzwickte Anwendung von pre/post in/decrement-Operatoren * <br>
* Dokumentieren Sie die Ergebnisse im Code, <br>
* um sie beim späteren Nachschlagen sofort zur Hand zu haben. <br>*/
int i = 55; // Variable definieren und sofort auf einen Anfangswert setzen
int j = 67;
i = j+34; // Welche Werte haben die Variablen i = 101 j = 67
///" vars = " + i + " " + j
System.out.println("1. i =" + i + " j =" + j );
j = i + j + 12; // Erwartung: i = 101 j = 180
// Ergebnis: i = 101 j = 180
System.out.println("2. i =" + i + " j =" + j );
i = j++ + 17; // Erwartung: i = 198 j = 181 <--!!!!!!!!!!!
// Ergebnis: i = 197 j = 181
System.out.println("3. i =" + i + " j =" + j );
j = --i; // Erwartung: i = 196 j = 196
// Ergebnis: i = ? j = ?
System.out.println("4. i =" + i + " j =" + j );
// Es folgt eine knifflige Kombination von Operationen.
// Sie sollte Ihnen vor allem zeigen, dass solche Operatoren
// mit Bedacht zu verwenden sind.
System.out.println("5. i =" + (++i) + " i =" + (i--) );
// Erwartung: 197 = ? j = 196 <--!!!!!!!!!!!
// Ergebnis: i = 197 j = 197
}
Variable() {
}
} | nilsreichardt/hsd-oop | OOP1/02_Variablen und Datentypen_v16p/_generated/02_Variablen und Datentypen_v16p/_generated/exec/Variable.java | 519 | // Ergebnis: i = ? j = ? | line_comment | nl | class Variable
{
public static void main(String[] args)
{ System.setOut(new FiveCodePrintStream(System.out));
/** * Verzwickte Anwendung von pre/post in/decrement-Operatoren * <br>
* Dokumentieren Sie die Ergebnisse im Code, <br>
* um sie beim späteren Nachschlagen sofort zur Hand zu haben. <br>*/
int i = 55; // Variable definieren und sofort auf einen Anfangswert setzen
int j = 67;
i = j+34; // Welche Werte haben die Variablen i = 101 j = 67
///" vars = " + i + " " + j
System.out.println("1. i =" + i + " j =" + j );
j = i + j + 12; // Erwartung: i = 101 j = 180
// Ergebnis: i = 101 j = 180
System.out.println("2. i =" + i + " j =" + j );
i = j++ + 17; // Erwartung: i = 198 j = 181 <--!!!!!!!!!!!
// Ergebnis: i = 197 j = 181
System.out.println("3. i =" + i + " j =" + j );
j = --i; // Erwartung: i = 196 j = 196
// Ergebnis: <SUF>
System.out.println("4. i =" + i + " j =" + j );
// Es folgt eine knifflige Kombination von Operationen.
// Sie sollte Ihnen vor allem zeigen, dass solche Operatoren
// mit Bedacht zu verwenden sind.
System.out.println("5. i =" + (++i) + " i =" + (i--) );
// Erwartung: 197 = ? j = 196 <--!!!!!!!!!!!
// Ergebnis: i = 197 j = 197
}
Variable() {
}
} |
17886_6 | package com.feut.server.communication.handlers;
import com.feut.server.communication.GebruikerStateManager;
import com.feut.server.db.facades.GebruikerFacade;
import com.feut.shared.connection.Client;
import com.feut.shared.connection.IReceivePacket;
import com.feut.shared.connection.packets.*;
import com.feut.shared.models.Gebruiker;
import com.feut.shared.models.HuisGebruiker;
public class GebruikerPacketHandler implements IReceivePacket {
GebruikerStateManager gebruikerStateManager = GebruikerStateManager.getInstance();
@Override
public void onReceivePacket(Client client, Packet packet) throws Exception {
switch (packet.getClass().getSimpleName()) {
case "LoginRequest": {
LoginRequest request = (LoginRequest) packet;
Gebruiker gebruiker = GebruikerFacade.byEmailWachtwoord(request.email, request.password);
LoginResponse loginResponse = new LoginResponse();
if (gebruiker != null) {
loginResponse.success = true;
gebruiker.password = ""; // Het wachtwoord lijkt me geen goed idee om mee te sturen..
loginResponse.gebruiker = gebruiker;
// In de ingelogde gebruiker lijst zetten
gebruikerStateManager.handleGebruikerLogin(client, gebruiker);
// Direct een huis selecteren. Dit kan evt ooit nog via een scherm op de app gaan
HuisGebruiker huisGebruiker = GebruikerFacade.getHuisGebruiker(gebruiker.gebruikerId);
gebruikerStateManager.handleGebruikerSelectHuis(client, huisGebruiker);
} else {
loginResponse.success = false;
}
client.sendPacket(loginResponse);
break;
}
case "RegisterRequest": {
// Pakket ontvangen en casten naar RegisterRequest
RegisterRequest registerRequest = (RegisterRequest) packet;
// Gebruiker aanmaken, dit object gebruikt de db om queries te doen
Gebruiker gebruiker = new Gebruiker();
gebruiker.voornaam = registerRequest.firstName;
gebruiker.achternaam = registerRequest.lastName;
gebruiker.email = registerRequest.email;
gebruiker.password = registerRequest.password;
// Pakket voor response klaarmaken, en afhankelijk van exception in query waarde geven
RegisterResponse registerResponse = new RegisterResponse();
try {
GebruikerFacade.registreerGebruiker(gebruiker);
registerResponse.success = true;
} catch (Exception e) {
registerResponse.success = false;
}
client.sendPacket(registerResponse);
break;
}
case "CheckinPacket": {
CheckinPacket checkinPacket = (CheckinPacket)packet;
System.out.println("Checkin ontvangen: " + checkinPacket.chipId);
break;
}
case "PresentRequest": {
// Pakket welke ontvangen wordt casten, en de nieuwe direct klaarzetten voor gebruik.
PresentRequest presentRequest = (PresentRequest) packet;
// We spreken de gebruikersfacade aan om vervolgens de functie toggleAanwezigheid te gebruiken.
// Deze functie heeft het userid nodig van de gebruiker, welke wordt vergaard tijdens inloggen.
Gebruiker gebruiker = gebruikerStateManager.getGebruiker(client);
HuisGebruiker huisGebruiker = gebruikerStateManager.getHuisGebruiker(client);
try {
GebruikerFacade.toggleAanwezigheid(gebruiker.gebruikerId, huisGebruiker.huisId, presentRequest.aanwezig);
} catch (Exception e) {
e.printStackTrace();
break;
}
// TODO: Broadcast naar iedereen?
PresentResponse presentResponse = new PresentResponse();
presentResponse.aanwezig = presentRequest.aanwezig;
presentResponse.gebruikerId = gebruiker.gebruikerId;
client.sendPacket(presentResponse);
break;
}
}
}
}
| nilsve/feut | Server/src/main/java/com/feut/server/communication/handlers/GebruikerPacketHandler.java | 1,139 | // Pakket welke ontvangen wordt casten, en de nieuwe direct klaarzetten voor gebruik. | line_comment | nl | package com.feut.server.communication.handlers;
import com.feut.server.communication.GebruikerStateManager;
import com.feut.server.db.facades.GebruikerFacade;
import com.feut.shared.connection.Client;
import com.feut.shared.connection.IReceivePacket;
import com.feut.shared.connection.packets.*;
import com.feut.shared.models.Gebruiker;
import com.feut.shared.models.HuisGebruiker;
public class GebruikerPacketHandler implements IReceivePacket {
GebruikerStateManager gebruikerStateManager = GebruikerStateManager.getInstance();
@Override
public void onReceivePacket(Client client, Packet packet) throws Exception {
switch (packet.getClass().getSimpleName()) {
case "LoginRequest": {
LoginRequest request = (LoginRequest) packet;
Gebruiker gebruiker = GebruikerFacade.byEmailWachtwoord(request.email, request.password);
LoginResponse loginResponse = new LoginResponse();
if (gebruiker != null) {
loginResponse.success = true;
gebruiker.password = ""; // Het wachtwoord lijkt me geen goed idee om mee te sturen..
loginResponse.gebruiker = gebruiker;
// In de ingelogde gebruiker lijst zetten
gebruikerStateManager.handleGebruikerLogin(client, gebruiker);
// Direct een huis selecteren. Dit kan evt ooit nog via een scherm op de app gaan
HuisGebruiker huisGebruiker = GebruikerFacade.getHuisGebruiker(gebruiker.gebruikerId);
gebruikerStateManager.handleGebruikerSelectHuis(client, huisGebruiker);
} else {
loginResponse.success = false;
}
client.sendPacket(loginResponse);
break;
}
case "RegisterRequest": {
// Pakket ontvangen en casten naar RegisterRequest
RegisterRequest registerRequest = (RegisterRequest) packet;
// Gebruiker aanmaken, dit object gebruikt de db om queries te doen
Gebruiker gebruiker = new Gebruiker();
gebruiker.voornaam = registerRequest.firstName;
gebruiker.achternaam = registerRequest.lastName;
gebruiker.email = registerRequest.email;
gebruiker.password = registerRequest.password;
// Pakket voor response klaarmaken, en afhankelijk van exception in query waarde geven
RegisterResponse registerResponse = new RegisterResponse();
try {
GebruikerFacade.registreerGebruiker(gebruiker);
registerResponse.success = true;
} catch (Exception e) {
registerResponse.success = false;
}
client.sendPacket(registerResponse);
break;
}
case "CheckinPacket": {
CheckinPacket checkinPacket = (CheckinPacket)packet;
System.out.println("Checkin ontvangen: " + checkinPacket.chipId);
break;
}
case "PresentRequest": {
// Pakket welke<SUF>
PresentRequest presentRequest = (PresentRequest) packet;
// We spreken de gebruikersfacade aan om vervolgens de functie toggleAanwezigheid te gebruiken.
// Deze functie heeft het userid nodig van de gebruiker, welke wordt vergaard tijdens inloggen.
Gebruiker gebruiker = gebruikerStateManager.getGebruiker(client);
HuisGebruiker huisGebruiker = gebruikerStateManager.getHuisGebruiker(client);
try {
GebruikerFacade.toggleAanwezigheid(gebruiker.gebruikerId, huisGebruiker.huisId, presentRequest.aanwezig);
} catch (Exception e) {
e.printStackTrace();
break;
}
// TODO: Broadcast naar iedereen?
PresentResponse presentResponse = new PresentResponse();
presentResponse.aanwezig = presentRequest.aanwezig;
presentResponse.gebruikerId = gebruiker.gebruikerId;
client.sendPacket(presentResponse);
break;
}
}
}
}
|
84018_10 | package com.mario.pizza.hut;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
public class Gui extends JFrame {
// Mainpanel and tabbedPane
private JPanel mainPanel;
private JTabbedPane tabbedPane;
// Tab 1
private JPanel tab1;
private JScrollPane scrollPane;
private JTable table;
private DefaultTableModel tableModel;
private TableRowSorter<DefaultTableModel> sorter;
private JTextField sortField;
// Tab 2
private final String chartDisplay1 = "Filialen per woonplaats", chartDisplay2 = "Productenprijzen";
private JPanel tab2;
private JFreeChart pieChart;
private ChartPanel chartPanel;
private DefaultPieDataset pieDataset = new DefaultPieDataset();
private static ArrayList<String> viewDisplay = new ArrayList<>();
private static ArrayList<String> viewNames = new ArrayList<>();
private static ArrayList<String> chartDisplay = new ArrayList<>();
private Gui(){
// Set windows look
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
// Fill all ArrayLists.
viewNames.add("vw_alle_producten");
viewNames.add("vw_klantbestellingen");
viewNames.add("vw_standaard_pizzas");
viewDisplay.add("Alle producten");
viewDisplay.add("Klantbestellingen");
viewDisplay.add("Standaardpizza's");
chartDisplay.add(chartDisplay1);
chartDisplay.add(chartDisplay2);
// Fill the actual viewList with display data
JList viewList = new JList();
fillList(viewList, viewDisplay);
// Add listener
viewList.addListSelectionListener(e -> {
boolean adjust = e.getValueIsAdjusting();
if (!adjust) {
JList tempList = (JList) e.getSource();
int selections[] = tempList.getSelectedIndices();
Object selectionValues[] = tempList.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
// Get index of chosen displayValue
int index = viewDisplay.indexOf(selectionValues[i]);
// Use that index to fill the table with the value from viewNames
fillTable("select * from " + viewNames.get(index));
}
}
});
JList chartList = new JList();
fillList(chartList, chartDisplay);
// Add listener
chartList.addListSelectionListener(e -> {
boolean adjust = e.getValueIsAdjusting();
if (!adjust) {
// Figure out selection
JList tempList = (JList) e.getSource();
int selections[] = tempList.getSelectedIndices();
String selection = "";
Object selectionValues[] = tempList.getSelectedValues();
// Setting selection value to String
for (int i = 0, n = selections.length; i < n; i++) {
selection = selectionValues[i].toString();
}
// Switch on String
switch (selection) {
case chartDisplay1 :
ResultSet filiaalSet = Connector.executeQuery(
"select * from vw_filialen_per_woonplaats group by woonplaats having filialen > 1\n"
// "union all\n" +
// "select 'OVERIG' woonplaats, count(woonplaats) filialen from vw_filialen_per_woonplaats where filialen = 1"
);
pieDataset.clear();
fillPieChart(pieDataset, filiaalSet, "Filialen","woonplaats", "filialen");
break;
case chartDisplay2 :
ResultSet productSet = Connector.executeQuery("select prijs, count(prijs) producten from vw_alle_producten group by prijs");
pieDataset.clear();
fillPieChart(pieDataset, productSet, "Producten","prijs", "producten");
break;
}
pieChart.fireChartChanged();
}
});
// Fill the table with a helping select query
fillTable("select 'Selecteer een rapportage'");
// Make table scrollable through scrollPane
scrollPane.setViewportView(table);
// Add ViewList and sortField to separate panel
sortField = new JTextField("Filter...");
sortField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) { sort(); }
@Override
public void removeUpdate(DocumentEvent e) { sort(); }
@Override
public void changedUpdate(DocumentEvent e) { sort(); }
private void sort() {
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(((DefaultTableModel) table.getModel()));
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + sortField.getText()));
table.setRowSorter(sorter);
}
});
JPanel listFilter = new JPanel();
listFilter.setLayout(new BoxLayout(listFilter, BoxLayout.Y_AXIS));
listFilter.add(viewList);
listFilter.add(sortField);
// Add scrollPane with table and viewList to tab1
tab1 = new JPanel(new BorderLayout());
tab1.add(scrollPane, BorderLayout.CENTER);
tab1.add(listFilter, BorderLayout.NORTH);
// Add pieChart and chartList to tab2
tab2 = new JPanel(new BorderLayout());
tab2.add(chartList, BorderLayout.NORTH);
fillPieChart(
pieDataset,
Connector.executeQuery("select 'Selecteer een grafiek' as naam, 1 hoeveelheid"),
"Selecteer een grafiek",
"naam",
"hoeveelheid"
);
chartPanel = new ChartPanel(pieChart);
tab2.add(chartPanel, BorderLayout.CENTER);
// Add tab1 and tab2 to tabbedPane
tabbedPane = new JTabbedPane();
tabbedPane.add(tab1, "Rapportages");
tabbedPane.add(tab2, "Grafieken");
// Add tabbedPane to mainPanel
mainPanel = new JPanel(new BorderLayout());
mainPanel.add(tabbedPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(() -> {
// Create database connection
Connector.getConnection();
// Create JFrame to put our panel inside.
JFrame gui = new Gui();
// Set title, close operation, our panel as Contentpane and maximazing on start
gui.setTitle("Mario's Sappige Pizza's - Backoffice");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setContentPane(((Gui) gui).mainPanel);
gui.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Pack and set visible
gui.pack();
gui.setVisible(true);
});
}
private void fillTable(String query) {
ResultSet resultSet = Connector.executeQuery(query);
tableModel = Connector.buildTableModel(resultSet);
table.setModel(tableModel);
tableModel.fireTableDataChanged();
}
private void fillList(JList list, ArrayList<String> data) {
// Turn ArrayList into normal Array for JList
String[] temp = new String[data.size()];
data.toArray(temp);
// Instantiate JList and adjust some settings
list.setListData(temp);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(1);
list.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
private void fillPieChart(DefaultPieDataset dataset, ResultSet resultSet, String title, String key, String dataColumn) {
// Fill pieDataSet with resultSet
try {
while (resultSet.next()) {
// Debug Query result
// System.out.printf("%20s - %20s\n", resultSet.getString(key), resultSet.getString(dataColumn));
dataset.setValue(
resultSet.getString(key),
Double.parseDouble(resultSet.getString(dataColumn)));
}
} catch (SQLException e) {
System.out.println("Error executing SQL query");
e.printStackTrace();
};
pieChart = ChartFactory.createPieChart(title, dataset, true, true, false);
pieChart.fireChartChanged();
}
}
| nilsve/marios-pizza-hut | backoffice_applicatie/src/com/mario/pizza/hut/Gui.java | 2,518 | // "select 'OVERIG' woonplaats, count(woonplaats) filialen from vw_filialen_per_woonplaats where filialen = 1" | line_comment | nl | package com.mario.pizza.hut;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
public class Gui extends JFrame {
// Mainpanel and tabbedPane
private JPanel mainPanel;
private JTabbedPane tabbedPane;
// Tab 1
private JPanel tab1;
private JScrollPane scrollPane;
private JTable table;
private DefaultTableModel tableModel;
private TableRowSorter<DefaultTableModel> sorter;
private JTextField sortField;
// Tab 2
private final String chartDisplay1 = "Filialen per woonplaats", chartDisplay2 = "Productenprijzen";
private JPanel tab2;
private JFreeChart pieChart;
private ChartPanel chartPanel;
private DefaultPieDataset pieDataset = new DefaultPieDataset();
private static ArrayList<String> viewDisplay = new ArrayList<>();
private static ArrayList<String> viewNames = new ArrayList<>();
private static ArrayList<String> chartDisplay = new ArrayList<>();
private Gui(){
// Set windows look
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
// Fill all ArrayLists.
viewNames.add("vw_alle_producten");
viewNames.add("vw_klantbestellingen");
viewNames.add("vw_standaard_pizzas");
viewDisplay.add("Alle producten");
viewDisplay.add("Klantbestellingen");
viewDisplay.add("Standaardpizza's");
chartDisplay.add(chartDisplay1);
chartDisplay.add(chartDisplay2);
// Fill the actual viewList with display data
JList viewList = new JList();
fillList(viewList, viewDisplay);
// Add listener
viewList.addListSelectionListener(e -> {
boolean adjust = e.getValueIsAdjusting();
if (!adjust) {
JList tempList = (JList) e.getSource();
int selections[] = tempList.getSelectedIndices();
Object selectionValues[] = tempList.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
// Get index of chosen displayValue
int index = viewDisplay.indexOf(selectionValues[i]);
// Use that index to fill the table with the value from viewNames
fillTable("select * from " + viewNames.get(index));
}
}
});
JList chartList = new JList();
fillList(chartList, chartDisplay);
// Add listener
chartList.addListSelectionListener(e -> {
boolean adjust = e.getValueIsAdjusting();
if (!adjust) {
// Figure out selection
JList tempList = (JList) e.getSource();
int selections[] = tempList.getSelectedIndices();
String selection = "";
Object selectionValues[] = tempList.getSelectedValues();
// Setting selection value to String
for (int i = 0, n = selections.length; i < n; i++) {
selection = selectionValues[i].toString();
}
// Switch on String
switch (selection) {
case chartDisplay1 :
ResultSet filiaalSet = Connector.executeQuery(
"select * from vw_filialen_per_woonplaats group by woonplaats having filialen > 1\n"
// "union all\n" +
// "select 'OVERIG'<SUF>
);
pieDataset.clear();
fillPieChart(pieDataset, filiaalSet, "Filialen","woonplaats", "filialen");
break;
case chartDisplay2 :
ResultSet productSet = Connector.executeQuery("select prijs, count(prijs) producten from vw_alle_producten group by prijs");
pieDataset.clear();
fillPieChart(pieDataset, productSet, "Producten","prijs", "producten");
break;
}
pieChart.fireChartChanged();
}
});
// Fill the table with a helping select query
fillTable("select 'Selecteer een rapportage'");
// Make table scrollable through scrollPane
scrollPane.setViewportView(table);
// Add ViewList and sortField to separate panel
sortField = new JTextField("Filter...");
sortField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) { sort(); }
@Override
public void removeUpdate(DocumentEvent e) { sort(); }
@Override
public void changedUpdate(DocumentEvent e) { sort(); }
private void sort() {
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(((DefaultTableModel) table.getModel()));
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + sortField.getText()));
table.setRowSorter(sorter);
}
});
JPanel listFilter = new JPanel();
listFilter.setLayout(new BoxLayout(listFilter, BoxLayout.Y_AXIS));
listFilter.add(viewList);
listFilter.add(sortField);
// Add scrollPane with table and viewList to tab1
tab1 = new JPanel(new BorderLayout());
tab1.add(scrollPane, BorderLayout.CENTER);
tab1.add(listFilter, BorderLayout.NORTH);
// Add pieChart and chartList to tab2
tab2 = new JPanel(new BorderLayout());
tab2.add(chartList, BorderLayout.NORTH);
fillPieChart(
pieDataset,
Connector.executeQuery("select 'Selecteer een grafiek' as naam, 1 hoeveelheid"),
"Selecteer een grafiek",
"naam",
"hoeveelheid"
);
chartPanel = new ChartPanel(pieChart);
tab2.add(chartPanel, BorderLayout.CENTER);
// Add tab1 and tab2 to tabbedPane
tabbedPane = new JTabbedPane();
tabbedPane.add(tab1, "Rapportages");
tabbedPane.add(tab2, "Grafieken");
// Add tabbedPane to mainPanel
mainPanel = new JPanel(new BorderLayout());
mainPanel.add(tabbedPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(() -> {
// Create database connection
Connector.getConnection();
// Create JFrame to put our panel inside.
JFrame gui = new Gui();
// Set title, close operation, our panel as Contentpane and maximazing on start
gui.setTitle("Mario's Sappige Pizza's - Backoffice");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setContentPane(((Gui) gui).mainPanel);
gui.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Pack and set visible
gui.pack();
gui.setVisible(true);
});
}
private void fillTable(String query) {
ResultSet resultSet = Connector.executeQuery(query);
tableModel = Connector.buildTableModel(resultSet);
table.setModel(tableModel);
tableModel.fireTableDataChanged();
}
private void fillList(JList list, ArrayList<String> data) {
// Turn ArrayList into normal Array for JList
String[] temp = new String[data.size()];
data.toArray(temp);
// Instantiate JList and adjust some settings
list.setListData(temp);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(1);
list.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
private void fillPieChart(DefaultPieDataset dataset, ResultSet resultSet, String title, String key, String dataColumn) {
// Fill pieDataSet with resultSet
try {
while (resultSet.next()) {
// Debug Query result
// System.out.printf("%20s - %20s\n", resultSet.getString(key), resultSet.getString(dataColumn));
dataset.setValue(
resultSet.getString(key),
Double.parseDouble(resultSet.getString(dataColumn)));
}
} catch (SQLException e) {
System.out.println("Error executing SQL query");
e.printStackTrace();
};
pieChart = ChartFactory.createPieChart(title, dataset, true, true, false);
pieChart.fireChartChanged();
}
}
|
169104_2 | package co.edu.udea.compumovil.gr08_20171.lab3;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by nilto on 14/03/2017.
*/
public class AdaptadorRv
extends RecyclerView.Adapter<AdaptadorRv.EventsViewHolder>
implements View.OnClickListener {
private View.OnClickListener listener;
private List<Events> listaEvents;
public static class EventsViewHolder extends RecyclerView.ViewHolder {
// Campos respectivos de un item
public ImageView imagen;
public TextView tvNombre,tvFecha,tvInformacion,tvOrganizador,tvPais,tvDepartamento,tvCiudad,
tvLugar,tvPuntuacion;
public EventsViewHolder(View v) {
super(v);
imagen = (ImageView) v.findViewById(R.id.imagenEventWidget);
tvNombre = (TextView) v.findViewById(R.id.nombreEventWidget);
tvInformacion = (TextView) v.findViewById(R.id.informacionEventWidget);
tvPuntuacion=(TextView) v.findViewById(R.id.puntuacionEventWidget);
}
}
public AdaptadorRv(List<Events> items) {
this.listaEvents = items;
}
@Override
public int getItemCount() {
return listaEvents.size();
}
@Override
public EventsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.vistarv, viewGroup, false);
v.setOnClickListener(this);
return new EventsViewHolder(v);
}
@Override
public void onBindViewHolder(EventsViewHolder viewHolder, int i) {
viewHolder.imagen.setImageBitmap(byteImgToBitmap(listaEvents.get(i).getFoto()));
viewHolder.tvNombre.setText(listaEvents.get(i).getNombre());
// viewHolder.tvFecha.setText(listaEvents.get(i).getFecha());
viewHolder.tvInformacion.setText(listaEvents.get(i).getInformación());
/* viewHolder.tvOrganizador.setText(listaEvents.get(i).getOrganizador());
viewHolder.tvPais.setText(listaEvents.get(i).getPais());
viewHolder.tvDepartamento.setText(listaEvents.get(i).getDepartamento());
viewHolder.tvCiudad.setText(listaEvents.get(i).getCiudad());
viewHolder.tvLugar.setText(listaEvents.get(i).getLugar());*/
viewHolder.tvPuntuacion.setText(listaEvents.get(i).getPuntuacion());
}
public Bitmap byteImgToBitmap(byte[] blob) {
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
return bitmap;
}
public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}
@Override
public void onClick(View view) {
if(listener != null)
listener.onClick(view);
}
} | niltonsteveen/LaboratoriosCompuMovil | Lab3Services/src/main/java/co/edu/udea/compumovil/gr08_20171/lab3/AdaptadorRv.java | 955 | /* viewHolder.tvOrganizador.setText(listaEvents.get(i).getOrganizador());
viewHolder.tvPais.setText(listaEvents.get(i).getPais());
viewHolder.tvDepartamento.setText(listaEvents.get(i).getDepartamento());
viewHolder.tvCiudad.setText(listaEvents.get(i).getCiudad());
viewHolder.tvLugar.setText(listaEvents.get(i).getLugar());*/ | block_comment | nl | package co.edu.udea.compumovil.gr08_20171.lab3;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by nilto on 14/03/2017.
*/
public class AdaptadorRv
extends RecyclerView.Adapter<AdaptadorRv.EventsViewHolder>
implements View.OnClickListener {
private View.OnClickListener listener;
private List<Events> listaEvents;
public static class EventsViewHolder extends RecyclerView.ViewHolder {
// Campos respectivos de un item
public ImageView imagen;
public TextView tvNombre,tvFecha,tvInformacion,tvOrganizador,tvPais,tvDepartamento,tvCiudad,
tvLugar,tvPuntuacion;
public EventsViewHolder(View v) {
super(v);
imagen = (ImageView) v.findViewById(R.id.imagenEventWidget);
tvNombre = (TextView) v.findViewById(R.id.nombreEventWidget);
tvInformacion = (TextView) v.findViewById(R.id.informacionEventWidget);
tvPuntuacion=(TextView) v.findViewById(R.id.puntuacionEventWidget);
}
}
public AdaptadorRv(List<Events> items) {
this.listaEvents = items;
}
@Override
public int getItemCount() {
return listaEvents.size();
}
@Override
public EventsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.vistarv, viewGroup, false);
v.setOnClickListener(this);
return new EventsViewHolder(v);
}
@Override
public void onBindViewHolder(EventsViewHolder viewHolder, int i) {
viewHolder.imagen.setImageBitmap(byteImgToBitmap(listaEvents.get(i).getFoto()));
viewHolder.tvNombre.setText(listaEvents.get(i).getNombre());
// viewHolder.tvFecha.setText(listaEvents.get(i).getFecha());
viewHolder.tvInformacion.setText(listaEvents.get(i).getInformación());
/* viewHolder.tvOrganizador.setText(listaEvents.get(i).getOrganizador());
<SUF>*/
viewHolder.tvPuntuacion.setText(listaEvents.get(i).getPuntuacion());
}
public Bitmap byteImgToBitmap(byte[] blob) {
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
return bitmap;
}
public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}
@Override
public void onClick(View view) {
if(listener != null)
listener.onClick(view);
}
} |
136296_17 | //MIT License
//
//Copyright (c) 2022 Zuehlke, Nicolas Marty
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
import com.jcraft.jsch.*;
/**
* Simple SFTP client for the raging-rachel challenge
*
* @author Nicolas Favre
* @version 1.0.0
* @date 03.07.2023
* @email [email protected]
* @userid khronozz
*/
public class SftpClient {
private static final int SFTP_PORT = 22;
private static final String SFTP_USER = "rachel";
private static final String SFTP_PASSWORD = "Wolf7-Popper-Pantry";
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Pass Raspberry Pi's IP address as argument!");
return;
}
String host = args[0];
JSch jsch = new JSch();
Session session = null;
ChannelSftp sftpChannel = null;
try {
// Connect to the remote SFTP server
session = jsch.getSession(SFTP_USER, host, SFTP_PORT);
session.setPassword(SFTP_PASSWORD);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Open an SFTP channel
sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
// Retrieve the file on the /home/rachel directory
sftpChannel.get("/home/rachel/file.txt", "file.txt");
System.out.println("File file.txt retrieved from " + host);
} catch (JSchException | SftpException e) {
System.out.println("Make sure the IP address format is right !");
System.out.println("Exception :");
e.printStackTrace();
} finally {
// Exit channel and quit session
if (sftpChannel != null && sftpChannel.isConnected()) {
sftpChannel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
}
| nimarty/hackypi | tools/raging-rachel/SftpClient.java | 876 | // Open an SFTP channel | line_comment | nl | //MIT License
//
//Copyright (c) 2022 Zuehlke, Nicolas Marty
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
import com.jcraft.jsch.*;
/**
* Simple SFTP client for the raging-rachel challenge
*
* @author Nicolas Favre
* @version 1.0.0
* @date 03.07.2023
* @email [email protected]
* @userid khronozz
*/
public class SftpClient {
private static final int SFTP_PORT = 22;
private static final String SFTP_USER = "rachel";
private static final String SFTP_PASSWORD = "Wolf7-Popper-Pantry";
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Pass Raspberry Pi's IP address as argument!");
return;
}
String host = args[0];
JSch jsch = new JSch();
Session session = null;
ChannelSftp sftpChannel = null;
try {
// Connect to the remote SFTP server
session = jsch.getSession(SFTP_USER, host, SFTP_PORT);
session.setPassword(SFTP_PASSWORD);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Open an<SUF>
sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
// Retrieve the file on the /home/rachel directory
sftpChannel.get("/home/rachel/file.txt", "file.txt");
System.out.println("File file.txt retrieved from " + host);
} catch (JSchException | SftpException e) {
System.out.println("Make sure the IP address format is right !");
System.out.println("Exception :");
e.printStackTrace();
} finally {
// Exit channel and quit session
if (sftpChannel != null && sftpChannel.isConnected()) {
sftpChannel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
}
|
74558_10 | /**
* Copyright (C) the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import ninja.ControllerMethods.ControllerMethod;
import ninja.ReverseRouter.Builder;
import ninja.utils.LambdaRoute;
import ninja.utils.MethodReference;
import ninja.utils.NinjaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
/**
* Reverse routing. Lookup the uri associated with a controller method.
*
* @author Joe Lauer (jjlauer)
*/
public class ReverseRouter implements WithControllerMethod<Builder> {
static private final Logger log = LoggerFactory.getLogger(ReverseRouter.class);
static public class Builder {
private final String contextPath;
private final Route route;
private String scheme;
private String hostname;
private Map<String,String> pathParams;
private Map<String,String> queryParams;
public Builder(String contextPath, Route route) {
this.contextPath = contextPath;
this.route = route;
}
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
/**
* Make this an absolute route by including the current scheme (e.g. http)
* and hostname (e.g. www.example.com).
* @param scheme The scheme such as "http" or "https"
* @param hostname The hostname such as "www.example.com" or "www.example.com:8080"
* @return This builder
*/
public Builder absolute(String scheme, String hostname) {
this.scheme = scheme;
this.hostname = hostname;
return this;
}
/**
* Make this an absolute route by including the current scheme (e.g. http)
* and hostname (e.g. www.example.com). If the route is to a websocket
* then this will then return "ws" or "wss" if TLS is detected.
* @param context The current context
* @return This builder
*/
public Builder absolute(Context context) {
String s = context.getScheme();
String h = context.getHostname();
if (this.route.isHttpMethodWebSocket()) {
if ("https".equalsIgnoreCase(s)) {
s = "wss";
} else {
s = "ws";
}
}
return this.absolute(s, h);
}
public Route getRoute() {
return route;
}
public Map<String, String> getPathParams() {
return pathParams;
}
public Map<String, String> getQueryParams() {
return queryParams;
}
/**
* Add a parameter as a path replacement. Will validate the path parameter
* exists. This method will URL encode the values when building the final
* result.
* @param name The path parameter name
* @param value The path parameter value
* @return A reference to this builder
* @see #rawPathParam(java.lang.String, java.lang.Object)
*/
public Builder pathParam(String name, Object value) {
return setPathParam(name, value, false);
}
/**
* Identical to <code>path</code> except the path parameter value will
* NOT be url encoded when building the final url.
* @param name The path parameter name
* @param value The path parameter value
* @return A reference to this builder
* @see #pathParam(java.lang.String, java.lang.Object)
*/
public Builder rawPathParam(String name, Object value) {
return setPathParam(name, value, true);
}
private Builder setPathParam(String name, Object value, boolean raw) {
Objects.requireNonNull(name, "name required");
Objects.requireNonNull(value, "value required");
if (route.getParameters() == null || !route.getParameters().containsKey(name)) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " does not have a path parameter '" + name + "'");
}
if (this.pathParams == null) {
this.pathParams = new LinkedHashMap<>();
}
this.pathParams.put(name, safeValue(value, raw));
return this;
}
/**
* Add a parameter as a queryParam string value. This method will URL encode
* the values when building the final result.
* @param name The queryParam string parameter name
* @param value The queryParam string parameter value
* @return A reference to this builder
* @see #rawQueryParam(java.lang.String, java.lang.Object)
*/
public Builder queryParam(String name, Object value) {
return setQueryParam(name, value, false);
}
/**
* Identical to <code>queryParam</code> except the queryParam string value will
* NOT be url encoded when building the final url.
* @param name The queryParam string parameter name
* @param value The queryParam string parameter value
* @return A reference to this builder
* @see #queryParam(java.lang.String, java.lang.Object)
*/
public Builder rawQueryParam(String name, Object value) {
return setQueryParam(name, value, true);
}
private Builder setQueryParam(String name, Object value, boolean raw) {
Objects.requireNonNull(name, "name required");
if (this.queryParams == null) {
// retain ordering
this.queryParams = new LinkedHashMap<>();
}
this.queryParams.put(name, safeValue(value, raw));
return this;
}
private String safeValue(Object value, boolean raw) {
String s = (value == null ? null : value.toString());
if (!raw && s != null) {
try {
s = URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
return s;
}
private int safeMapSize(Map map) {
return (map != null ? map.size() : 0);
}
/**
* Builds the final url. Will validate expected parameters match actual.
* @return The final resulting url
*/
public String build() {
// number of pathOrQueryParams valid?
int expectedParamSize = safeMapSize(this.route.getParameters());
int actualParamSize = safeMapSize(this.pathParams);
if (expectedParamSize != actualParamSize) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " requires " + expectedParamSize + " parameters but got "
+ actualParamSize + " instead");
}
String rawUri = this.route.getUri();
StringBuilder buffer = new StringBuilder(rawUri.length());
// append scheme + hostname?
if (this.scheme != null && this.hostname != null) {
buffer.append(this.scheme);
buffer.append("://");
buffer.append(this.hostname);
}
// append contextPath
if (this.contextPath != null && this.contextPath.length() > 0) {
buffer.append(this.contextPath);
}
// replace path parameters
int lastIndex = 0;
if (this.pathParams != null) {
for (RouteParameter rp : this.route.getParameters().values()) {
String value = this.pathParams.get(rp.getName());
if (value == null) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " missing value for path parameter '" + rp.getName() + "'");
}
// append any text before this token
buffer.append(rawUri.substring(lastIndex, rp.getIndex()));
// append value
buffer.append(value);
// the next index to start from
lastIndex = rp.getIndex() + rp.getToken().length();
}
}
// append whatever remains
if (lastIndex < rawUri.length()) {
buffer.append(rawUri.substring(lastIndex));
}
// append queryParam pathOrQueryParams
if (this.queryParams != null) {
int i = 0;
for (Map.Entry<String,String> entry : this.queryParams.entrySet()) {
buffer.append((i == 0 ? '?' : '&'));
buffer.append(entry.getKey());
if (entry.getValue() != null) {
buffer.append('=');
buffer.append(entry.getValue());
}
i++;
}
}
return buffer.toString();
}
/**
* Builds the result as a <code>ninja.Result</code> redirect.
* @return A Ninja redirect result
*/
public Result redirect() {
return Results.redirect(build());
}
@Override
public String toString() {
return this.build();
}
}
private final NinjaProperties ninjaProperties;
private final Router router;
@Inject
public ReverseRouter(NinjaProperties ninjaProperties,
Router router) {
this.ninjaProperties = ninjaProperties;
this.router = router;
}
/**
* Retrieves a the reverse route for this controllerClass and method.
*
* @param controllerClass The controllerClass e.g. ApplicationController.class
* @param methodName the methodName of the class e.g. "index"
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
public Builder with(Class<?> controllerClass, String methodName) {
return builder(controllerClass, methodName);
}
/**
* Retrieves a the reverse route for the method reference (e.g. controller
* class and method name).
*
* @param methodRef The reference to a method
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
public Builder with(MethodReference methodRef) {
return builder(methodRef.getDeclaringClass(), methodRef.getMethodName());
}
/**
* Retrieves a the reverse route for a method referenced with Java-8
* lambdas (functional method references).
*
* @param controllerMethod The Java-8 style method reference such as
* <code>ApplicationController::index</code>.
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
@Override
public Builder with(ControllerMethod controllerMethod) {
LambdaRoute lambdaRoute = LambdaRoute.resolve(controllerMethod);
// only need the functional method for the reverse lookup
Method method = lambdaRoute.getFunctionalMethod();
return builder(method.getDeclaringClass(), method.getName());
}
private Builder builder(Class<?> controllerClass, String methodName) {
Optional<Route> route = this.router.getRouteForControllerClassAndMethod(
controllerClass, methodName);
if (route.isPresent()) {
return new Builder(this.ninjaProperties.getContextPath(), route.get());
}
throw new IllegalArgumentException("Reverse route not found for " +
controllerClass.getCanonicalName() + "." + methodName);
}
}
| ninjaframework/ninja | ninja-core/src/main/java/ninja/ReverseRouter.java | 3,239 | // append scheme + hostname? | line_comment | nl | /**
* Copyright (C) the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import ninja.ControllerMethods.ControllerMethod;
import ninja.ReverseRouter.Builder;
import ninja.utils.LambdaRoute;
import ninja.utils.MethodReference;
import ninja.utils.NinjaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
/**
* Reverse routing. Lookup the uri associated with a controller method.
*
* @author Joe Lauer (jjlauer)
*/
public class ReverseRouter implements WithControllerMethod<Builder> {
static private final Logger log = LoggerFactory.getLogger(ReverseRouter.class);
static public class Builder {
private final String contextPath;
private final Route route;
private String scheme;
private String hostname;
private Map<String,String> pathParams;
private Map<String,String> queryParams;
public Builder(String contextPath, Route route) {
this.contextPath = contextPath;
this.route = route;
}
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
/**
* Make this an absolute route by including the current scheme (e.g. http)
* and hostname (e.g. www.example.com).
* @param scheme The scheme such as "http" or "https"
* @param hostname The hostname such as "www.example.com" or "www.example.com:8080"
* @return This builder
*/
public Builder absolute(String scheme, String hostname) {
this.scheme = scheme;
this.hostname = hostname;
return this;
}
/**
* Make this an absolute route by including the current scheme (e.g. http)
* and hostname (e.g. www.example.com). If the route is to a websocket
* then this will then return "ws" or "wss" if TLS is detected.
* @param context The current context
* @return This builder
*/
public Builder absolute(Context context) {
String s = context.getScheme();
String h = context.getHostname();
if (this.route.isHttpMethodWebSocket()) {
if ("https".equalsIgnoreCase(s)) {
s = "wss";
} else {
s = "ws";
}
}
return this.absolute(s, h);
}
public Route getRoute() {
return route;
}
public Map<String, String> getPathParams() {
return pathParams;
}
public Map<String, String> getQueryParams() {
return queryParams;
}
/**
* Add a parameter as a path replacement. Will validate the path parameter
* exists. This method will URL encode the values when building the final
* result.
* @param name The path parameter name
* @param value The path parameter value
* @return A reference to this builder
* @see #rawPathParam(java.lang.String, java.lang.Object)
*/
public Builder pathParam(String name, Object value) {
return setPathParam(name, value, false);
}
/**
* Identical to <code>path</code> except the path parameter value will
* NOT be url encoded when building the final url.
* @param name The path parameter name
* @param value The path parameter value
* @return A reference to this builder
* @see #pathParam(java.lang.String, java.lang.Object)
*/
public Builder rawPathParam(String name, Object value) {
return setPathParam(name, value, true);
}
private Builder setPathParam(String name, Object value, boolean raw) {
Objects.requireNonNull(name, "name required");
Objects.requireNonNull(value, "value required");
if (route.getParameters() == null || !route.getParameters().containsKey(name)) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " does not have a path parameter '" + name + "'");
}
if (this.pathParams == null) {
this.pathParams = new LinkedHashMap<>();
}
this.pathParams.put(name, safeValue(value, raw));
return this;
}
/**
* Add a parameter as a queryParam string value. This method will URL encode
* the values when building the final result.
* @param name The queryParam string parameter name
* @param value The queryParam string parameter value
* @return A reference to this builder
* @see #rawQueryParam(java.lang.String, java.lang.Object)
*/
public Builder queryParam(String name, Object value) {
return setQueryParam(name, value, false);
}
/**
* Identical to <code>queryParam</code> except the queryParam string value will
* NOT be url encoded when building the final url.
* @param name The queryParam string parameter name
* @param value The queryParam string parameter value
* @return A reference to this builder
* @see #queryParam(java.lang.String, java.lang.Object)
*/
public Builder rawQueryParam(String name, Object value) {
return setQueryParam(name, value, true);
}
private Builder setQueryParam(String name, Object value, boolean raw) {
Objects.requireNonNull(name, "name required");
if (this.queryParams == null) {
// retain ordering
this.queryParams = new LinkedHashMap<>();
}
this.queryParams.put(name, safeValue(value, raw));
return this;
}
private String safeValue(Object value, boolean raw) {
String s = (value == null ? null : value.toString());
if (!raw && s != null) {
try {
s = URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
return s;
}
private int safeMapSize(Map map) {
return (map != null ? map.size() : 0);
}
/**
* Builds the final url. Will validate expected parameters match actual.
* @return The final resulting url
*/
public String build() {
// number of pathOrQueryParams valid?
int expectedParamSize = safeMapSize(this.route.getParameters());
int actualParamSize = safeMapSize(this.pathParams);
if (expectedParamSize != actualParamSize) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " requires " + expectedParamSize + " parameters but got "
+ actualParamSize + " instead");
}
String rawUri = this.route.getUri();
StringBuilder buffer = new StringBuilder(rawUri.length());
// append scheme<SUF>
if (this.scheme != null && this.hostname != null) {
buffer.append(this.scheme);
buffer.append("://");
buffer.append(this.hostname);
}
// append contextPath
if (this.contextPath != null && this.contextPath.length() > 0) {
buffer.append(this.contextPath);
}
// replace path parameters
int lastIndex = 0;
if (this.pathParams != null) {
for (RouteParameter rp : this.route.getParameters().values()) {
String value = this.pathParams.get(rp.getName());
if (value == null) {
throw new IllegalArgumentException("Reverse route " + route.getUri()
+ " missing value for path parameter '" + rp.getName() + "'");
}
// append any text before this token
buffer.append(rawUri.substring(lastIndex, rp.getIndex()));
// append value
buffer.append(value);
// the next index to start from
lastIndex = rp.getIndex() + rp.getToken().length();
}
}
// append whatever remains
if (lastIndex < rawUri.length()) {
buffer.append(rawUri.substring(lastIndex));
}
// append queryParam pathOrQueryParams
if (this.queryParams != null) {
int i = 0;
for (Map.Entry<String,String> entry : this.queryParams.entrySet()) {
buffer.append((i == 0 ? '?' : '&'));
buffer.append(entry.getKey());
if (entry.getValue() != null) {
buffer.append('=');
buffer.append(entry.getValue());
}
i++;
}
}
return buffer.toString();
}
/**
* Builds the result as a <code>ninja.Result</code> redirect.
* @return A Ninja redirect result
*/
public Result redirect() {
return Results.redirect(build());
}
@Override
public String toString() {
return this.build();
}
}
private final NinjaProperties ninjaProperties;
private final Router router;
@Inject
public ReverseRouter(NinjaProperties ninjaProperties,
Router router) {
this.ninjaProperties = ninjaProperties;
this.router = router;
}
/**
* Retrieves a the reverse route for this controllerClass and method.
*
* @param controllerClass The controllerClass e.g. ApplicationController.class
* @param methodName the methodName of the class e.g. "index"
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
public Builder with(Class<?> controllerClass, String methodName) {
return builder(controllerClass, methodName);
}
/**
* Retrieves a the reverse route for the method reference (e.g. controller
* class and method name).
*
* @param methodRef The reference to a method
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
public Builder with(MethodReference methodRef) {
return builder(methodRef.getDeclaringClass(), methodRef.getMethodName());
}
/**
* Retrieves a the reverse route for a method referenced with Java-8
* lambdas (functional method references).
*
* @param controllerMethod The Java-8 style method reference such as
* <code>ApplicationController::index</code>.
* @return A <code>Builder</code> allowing setting path placeholders and
queryParam string parameters.
*/
@Override
public Builder with(ControllerMethod controllerMethod) {
LambdaRoute lambdaRoute = LambdaRoute.resolve(controllerMethod);
// only need the functional method for the reverse lookup
Method method = lambdaRoute.getFunctionalMethod();
return builder(method.getDeclaringClass(), method.getName());
}
private Builder builder(Class<?> controllerClass, String methodName) {
Optional<Route> route = this.router.getRouteForControllerClassAndMethod(
controllerClass, methodName);
if (route.isPresent()) {
return new Builder(this.ninjaProperties.getContextPath(), route.get());
}
throw new IllegalArgumentException("Reverse route not found for " +
controllerClass.getCanonicalName() + "." + methodName);
}
}
|
68108_2 | package nisargpatel.deadreckoning.filewriting;
import android.os.Environment;
import android.text.format.Time;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import nisargpatel.deadreckoning.extra.ExtraFunctions;
public class DataFileWriter {
private BufferedWriter bufferedWriter;
private String folderName;
private HashMap<String, File> files;
public DataFileWriter() {
files = new HashMap<>();
folderName = null;
}
public DataFileWriter(String folderName, ArrayList<String> fileNames, ArrayList<String> fileHeadings) throws IOException {
this();
this.folderName = folderName;
createFiles(fileNames, fileHeadings);
}
public DataFileWriter(String folderName, String[] fileNames, String[] fileHeadings) throws IOException {
this();
this.folderName = folderName;
createFiles(ExtraFunctions.arrayToList(fileNames), ExtraFunctions.arrayToList(fileHeadings));
}
private File getFolder() {
File folder = new File(Environment.getExternalStorageDirectory(), folderName);
//create the folder is it doesn't exist
createFolder(folder);
return folder;
}
private void createFolder(File folder) {
if (!folder.exists()) {
if (folder.mkdirs()) {
Log.d("data_files", "folder created: " + folder.getName());
}
}
}
public void createFile(String fileName, String fileHeading) throws IOException {
String folderPath = getFolder().getPath();
String timestampedFileName = getTimestampedFileName(fileName);
File dataFile = new File(folderPath, timestampedFileName);
if (dataFile.createNewFile()) {
Log.d("data_files", "file created: " + timestampedFileName);
}
//storing the data file inside the HashMap
files.put(fileName, dataFile);
writeFileHeading(fileName, fileHeading);
}
private void writeFileHeading(String fileName, String fileHeading) {
writeToFile(fileName, fileHeading);
}
public void createFiles(ArrayList<String> fileNames, ArrayList<String> fileHeadings) throws IOException {
for (int i = 0; i < fileNames.size(); i++) {
createFile(fileNames.get(i), fileHeadings.get(i));
}
}
private String getTimestampedFileName(String fileName) {
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
String date = today.year + "-" + (today.month + 1) + "-" + today.monthDay;
String currentTime = today.format("%H-%M-%S");
return fileName + "_" + date + "_" + currentTime + ".txt";
}
//overridden write methods
public void writeToFile(String fileName, ArrayList<Float> values) {
File file = files.get(fileName);
try {
bufferedWriter = new BufferedWriter(new FileWriter(file, true));
for (float value : values)
bufferedWriter.write(value + ";");
bufferedWriter.write(System.getProperty("line.separator")); //create a line break
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile(String fileName, String line) {
File file = files.get(fileName);
try {
bufferedWriter = new BufferedWriter(new FileWriter(file, true));
bufferedWriter.write(line);
bufferedWriter.write(System.getProperty("line.separator")); //create a line break
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile(String fileName, float... args) {
ArrayList<Float> values = new ArrayList<>();
for (float arg : args)
values.add(arg);
writeToFile(fileName, values);
}
}
| nisargnp/DeadReckoning | app/src/main/java/nisargpatel/deadreckoning/filewriting/DataFileWriter.java | 1,100 | //overridden write methods | line_comment | nl | package nisargpatel.deadreckoning.filewriting;
import android.os.Environment;
import android.text.format.Time;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import nisargpatel.deadreckoning.extra.ExtraFunctions;
public class DataFileWriter {
private BufferedWriter bufferedWriter;
private String folderName;
private HashMap<String, File> files;
public DataFileWriter() {
files = new HashMap<>();
folderName = null;
}
public DataFileWriter(String folderName, ArrayList<String> fileNames, ArrayList<String> fileHeadings) throws IOException {
this();
this.folderName = folderName;
createFiles(fileNames, fileHeadings);
}
public DataFileWriter(String folderName, String[] fileNames, String[] fileHeadings) throws IOException {
this();
this.folderName = folderName;
createFiles(ExtraFunctions.arrayToList(fileNames), ExtraFunctions.arrayToList(fileHeadings));
}
private File getFolder() {
File folder = new File(Environment.getExternalStorageDirectory(), folderName);
//create the folder is it doesn't exist
createFolder(folder);
return folder;
}
private void createFolder(File folder) {
if (!folder.exists()) {
if (folder.mkdirs()) {
Log.d("data_files", "folder created: " + folder.getName());
}
}
}
public void createFile(String fileName, String fileHeading) throws IOException {
String folderPath = getFolder().getPath();
String timestampedFileName = getTimestampedFileName(fileName);
File dataFile = new File(folderPath, timestampedFileName);
if (dataFile.createNewFile()) {
Log.d("data_files", "file created: " + timestampedFileName);
}
//storing the data file inside the HashMap
files.put(fileName, dataFile);
writeFileHeading(fileName, fileHeading);
}
private void writeFileHeading(String fileName, String fileHeading) {
writeToFile(fileName, fileHeading);
}
public void createFiles(ArrayList<String> fileNames, ArrayList<String> fileHeadings) throws IOException {
for (int i = 0; i < fileNames.size(); i++) {
createFile(fileNames.get(i), fileHeadings.get(i));
}
}
private String getTimestampedFileName(String fileName) {
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
String date = today.year + "-" + (today.month + 1) + "-" + today.monthDay;
String currentTime = today.format("%H-%M-%S");
return fileName + "_" + date + "_" + currentTime + ".txt";
}
//overridden write<SUF>
public void writeToFile(String fileName, ArrayList<Float> values) {
File file = files.get(fileName);
try {
bufferedWriter = new BufferedWriter(new FileWriter(file, true));
for (float value : values)
bufferedWriter.write(value + ";");
bufferedWriter.write(System.getProperty("line.separator")); //create a line break
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile(String fileName, String line) {
File file = files.get(fileName);
try {
bufferedWriter = new BufferedWriter(new FileWriter(file, true));
bufferedWriter.write(line);
bufferedWriter.write(System.getProperty("line.separator")); //create a line break
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile(String fileName, float... args) {
ArrayList<Float> values = new ArrayList<>();
for (float arg : args)
values.add(arg);
writeToFile(fileName, values);
}
}
|
57450_2 | package org.interdictor.util;
import java.util.HashMap;
import java.util.Map;
public class Settings {
public static final boolean DEBUG = false;
public static final long ROUND_LENGTH = 2 * (DEBUG ? 10 : 60) * 1000; // 2 minute round
public static final int ROUND_LENGTH_PENALTY = 5 * 1000; // 5 sec shorter rounds after the first
public static final int POINTS_PER_WORD = 100;
public static final int POINTS_ALL_WORDS = 1000;
public static final int POINTS_PER_LETTER = 10;
public static final int POINT_NO_SHUFFLE = 250;
public static final int POINTS_PER_SECOND_LEFT = 5;
public static final Map<String, String> lookupURLs = new HashMap<String, String>();
public static final long TICK = 50; // milliseconds per event loop update
public static final int HINT_POINT_COST = 250;
static {
// lookupURLs.put("en", "http://m.dictionary.com/d/?q=%s");
// lookupURLs.put("en", "http://en.wiktionary.org/wiki/%s");
lookupURLs.put("en", "http://www.anagrammer.com/scrabble/%s");
lookupURLs.put("nl", "http://www.woorden.org/index.php?woord=%s");
lookupURLs.put("es", "http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA=%s");
}
}
| niven/texttwist | src/org/interdictor/util/Settings.java | 430 | // milliseconds per event loop update | line_comment | nl | package org.interdictor.util;
import java.util.HashMap;
import java.util.Map;
public class Settings {
public static final boolean DEBUG = false;
public static final long ROUND_LENGTH = 2 * (DEBUG ? 10 : 60) * 1000; // 2 minute round
public static final int ROUND_LENGTH_PENALTY = 5 * 1000; // 5 sec shorter rounds after the first
public static final int POINTS_PER_WORD = 100;
public static final int POINTS_ALL_WORDS = 1000;
public static final int POINTS_PER_LETTER = 10;
public static final int POINT_NO_SHUFFLE = 250;
public static final int POINTS_PER_SECOND_LEFT = 5;
public static final Map<String, String> lookupURLs = new HashMap<String, String>();
public static final long TICK = 50; // milliseconds per<SUF>
public static final int HINT_POINT_COST = 250;
static {
// lookupURLs.put("en", "http://m.dictionary.com/d/?q=%s");
// lookupURLs.put("en", "http://en.wiktionary.org/wiki/%s");
lookupURLs.put("en", "http://www.anagrammer.com/scrabble/%s");
lookupURLs.put("nl", "http://www.woorden.org/index.php?woord=%s");
lookupURLs.put("es", "http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA=%s");
}
}
|
169507_0 | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken)
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
| njtromp/AdventOfCode-2020 | src/main/java/nl/njtromp/adventofcode_2020/Infi.java | 436 | // Schuine zijden (4 halve driehoeken) | line_comment | nl | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden<SUF>
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
|
8390_2 | /*
* Copyright (c) 2014, Netherlands Forensic Institute
* All rights reserved.
*/
package nl.minvenj.nfi.prnu;
import java.awt.color.CMMException;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;
import nl.minvenj.nfi.prnu.filter.ImageFilter;
import nl.minvenj.nfi.prnu.filter.WienerFilter;
import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;
public final class PrnuExtract {
static final File TESTDATA_FOLDER = new File("testdata");
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");
public static void main(final String[] args) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
// Laad de input file in
final BufferedImage image = readImage(INPUT_FILE);
end = System.currentTimeMillis();
System.out.println("Load image: " + (end-start) + " ms.");
// Zet de input file om in 3 matrices (rood, groen, blauw)
start = System.currentTimeMillis();
final float[][][] rgbArrays = convertImageToFloatArrays(image);
end = System.currentTimeMillis();
System.out.println("Convert image:" + (end-start) + " ms.");
// Bereken van elke matrix het PRNU patroon (extractie stap)
start = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
extractImage(rgbArrays[i]);
}
end = System.currentTimeMillis();
System.out.println("PRNU extracted: " + (end-start) + " ms.");
// Schrijf het patroon weg als een Java object
writeJavaObject(rgbArrays, OUTPUT_FILE);
System.out.println("Pattern written");
// Controleer nu het gemaakte bestand
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);
for (int i = 0; i < 3; i++) {
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);
}
System.out.println("Validation completed");
//This exit is inserted because the program will otherwise hang for a about a minute
//most likely explanation for this is the fact that the FFT library spawns a couple
//of threads which cannot be properly destroyed
System.exit(0);
}
private static BufferedImage readImage(final File file) throws IOException {
final InputStream fileInputStream = new FileInputStream(file);
try {
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {
return image;
}
}
catch (final CMMException e) {
// Image file is unsupported or corrupt
}
catch (final RuntimeException e) {
// Internal error processing image file
}
catch (final IOException e) {
// Error reading image from disk
}
finally {
fileInputStream.close();
}
// Image unreadable or too smalld array
return null;
}
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {
final int width = image.getWidth();
final int height = image.getHeight();
final float[][][] pixels = new float[3][height][width];
final ColorModel colorModel = ColorModel.getRGBdefault();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int pixel = image.getRGB(x, y); // aa bb gg rr
pixels[0][y][x] = colorModel.getRed(pixel);
pixels[1][y][x] = colorModel.getGreen(pixel);
pixels[2][y][x] = colorModel.getBlue(pixel);
}
}
return pixels;
}
private static void extractImage(final float[][] pixels) {
final int width = pixels[0].length;
final int height = pixels.length;
long start = System.currentTimeMillis();
long end = 0;
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);
fastNoiseFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);
zeroMeanTotalFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter wienerFilter = new WienerFilter(width, height);
wienerFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Wiener Filter: " + (end-start) + " ms.");
}
public static Object readJavaObject(final File inputFile) throws IOException {
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
try {
return inputStream.readObject();
}
catch (final ClassNotFoundException e) {
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);
}
finally {
inputStream.close();
}
}
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {
final OutputStream outputStream = new FileOutputStream(outputFile);
try {
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
finally {
outputStream.close();
}
}
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {
for (int i = 0; i < expected.length; i++) {
for (int j = 0; j < expected[i].length; j++) {
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);
return false;
}
}
}
return true;
}
}
| nlesc-sherlock/cluster-analysis | prnuextract/src/nl/minvenj/nfi/prnu/PrnuExtract.java | 2,212 | // Laad de input file in
| line_comment | nl | /*
* Copyright (c) 2014, Netherlands Forensic Institute
* All rights reserved.
*/
package nl.minvenj.nfi.prnu;
import java.awt.color.CMMException;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;
import nl.minvenj.nfi.prnu.filter.ImageFilter;
import nl.minvenj.nfi.prnu.filter.WienerFilter;
import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;
public final class PrnuExtract {
static final File TESTDATA_FOLDER = new File("testdata");
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");
public static void main(final String[] args) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
// Laad de<SUF>
final BufferedImage image = readImage(INPUT_FILE);
end = System.currentTimeMillis();
System.out.println("Load image: " + (end-start) + " ms.");
// Zet de input file om in 3 matrices (rood, groen, blauw)
start = System.currentTimeMillis();
final float[][][] rgbArrays = convertImageToFloatArrays(image);
end = System.currentTimeMillis();
System.out.println("Convert image:" + (end-start) + " ms.");
// Bereken van elke matrix het PRNU patroon (extractie stap)
start = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
extractImage(rgbArrays[i]);
}
end = System.currentTimeMillis();
System.out.println("PRNU extracted: " + (end-start) + " ms.");
// Schrijf het patroon weg als een Java object
writeJavaObject(rgbArrays, OUTPUT_FILE);
System.out.println("Pattern written");
// Controleer nu het gemaakte bestand
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);
for (int i = 0; i < 3; i++) {
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);
}
System.out.println("Validation completed");
//This exit is inserted because the program will otherwise hang for a about a minute
//most likely explanation for this is the fact that the FFT library spawns a couple
//of threads which cannot be properly destroyed
System.exit(0);
}
private static BufferedImage readImage(final File file) throws IOException {
final InputStream fileInputStream = new FileInputStream(file);
try {
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {
return image;
}
}
catch (final CMMException e) {
// Image file is unsupported or corrupt
}
catch (final RuntimeException e) {
// Internal error processing image file
}
catch (final IOException e) {
// Error reading image from disk
}
finally {
fileInputStream.close();
}
// Image unreadable or too smalld array
return null;
}
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {
final int width = image.getWidth();
final int height = image.getHeight();
final float[][][] pixels = new float[3][height][width];
final ColorModel colorModel = ColorModel.getRGBdefault();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int pixel = image.getRGB(x, y); // aa bb gg rr
pixels[0][y][x] = colorModel.getRed(pixel);
pixels[1][y][x] = colorModel.getGreen(pixel);
pixels[2][y][x] = colorModel.getBlue(pixel);
}
}
return pixels;
}
private static void extractImage(final float[][] pixels) {
final int width = pixels[0].length;
final int height = pixels.length;
long start = System.currentTimeMillis();
long end = 0;
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);
fastNoiseFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);
zeroMeanTotalFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter wienerFilter = new WienerFilter(width, height);
wienerFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Wiener Filter: " + (end-start) + " ms.");
}
public static Object readJavaObject(final File inputFile) throws IOException {
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
try {
return inputStream.readObject();
}
catch (final ClassNotFoundException e) {
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);
}
finally {
inputStream.close();
}
}
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {
final OutputStream outputStream = new FileOutputStream(outputFile);
try {
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
finally {
outputStream.close();
}
}
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {
for (int i = 0; i < expected.length; i++) {
for (int j = 0; j < expected[i].length; j++) {
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);
return false;
}
}
}
return true;
}
}
|
7599_10 | package wiimote;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import wiiusej.WiiUseApiManager;
import wiiusej.Wiimote;
import wiiusej.utils.AccelerationPanel;
import wiiusej.utils.AccelerationWiimoteEventPanel;
import wiiusej.values.RawAcceleration;
import wiiusej.wiiusejevents.GenericEvent;
import wiiusej.wiiusejevents.physicalevents.ExpansionEvent;
import wiiusej.wiiusejevents.physicalevents.IREvent;
import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent;
import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent;
import wiiusej.wiiusejevents.utils.WiimoteListener;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.DisconnectionEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.StatusEvent;
public class Opdracht2 extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Opdracht 2");
JPanel panel = new Panel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
public Opdracht2() {
}
}
class Panel extends JPanel implements WiimoteListener, ActionListener {
Wiimote[] wiimotes;
AccelerationPanel aPanel;
Wiimote wiimote;
JPanel panel;
RawAcceleration rawAcc;
float yaw;
int x;
int y;
int z;
int xx;
int yy;
int zz;
short time;
short oldTime;
Timer timer = new Timer(1, this);
ArrayList<RawAcceleration> values;
Font bigFont;
Font smallFont;
int xTurns;
int zTurns;
boolean xTurned;
boolean zTurned;
public Panel() {
xTurned = false;
zTurned = false;
xTurns = 0;
zTurns = 0;
yaw = 0;
time = 0;
oldTime = 0;
setPreferredSize(new Dimension(1366, 768));
timer.start();
System.loadLibrary("WiiuseJ");
wiimotes = WiiUseApiManager.getWiimotes(1, false);
wiimote = wiimotes[0];
values = new ArrayList<>();
wiimote.activateMotionSensing();
wiimote.addWiiMoteEventListeners(this);
aPanel = new AccelerationWiimoteEventPanel();
rawAcc = new RawAcceleration();
values.add(rawAcc);
x = 0;
y = 0;
z = 0;
xx = 0;
yy = 0;
zz = 0;
smallFont = new Font("Arial", 0, 10);
bigFont = new Font("Arial", 0, 12);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
// x lijnen
g2.drawLine(0, 163, getWidth(), 163);
g2.drawLine(0, 363, getWidth(), 363);
g2.drawLine(0, 575, getWidth(), 575);
// hulp x lijnen voor x RawAcc
g2.setColor(Color.GREEN);
g2.drawLine(0, 100, getWidth(), 100);
g2.drawLine(0, 137, getWidth(), 137);
g2.drawLine(0, 200, getWidth(), 200);
// hulp x lijnen voor y RawAcc
g2.drawLine(0, 337, getWidth(), 337);
g2.drawLine(0, 400, getWidth(), 400);
// hulp x lijnen voor z RawAcc
g2.drawLine(0, 500, getWidth(), 500);
g2.drawLine(0, 550, getWidth(), 550);
g2.drawLine(0, 625, getWidth(), 625);
// y lijnen
g2.setColor(Color.BLACK);
for (int yl = 100; yl < 200; yl = yl + 300) {
g2.drawLine(yl, 100, yl, 200);
g2.drawLine(yl, 337, yl, 400);
g2.drawLine(yl, 500, yl, 625);
}
// font kleiner maken
g2.setFont(smallFont);
// x waardes
for (int xw = 105; xw < 200; xw = xw + 300) {
g2.drawString("0", xw, 100);
g2.drawString("75", xw, 137);
g2.drawString("125", xw, 163);
g2.drawString("200", xw, 200);
}
// y waardes
for (int yw = 105; yw < 200; yw = yw + 300) {
g2.drawString("75", yw, 337);
g2.drawString("125", yw, 363);
g2.drawString("200", yw, 400);
}
// z waardes
for (int zw = 105; zw < 200; zw = zw + 300) {
g2.drawString("0", zw, 500);
g2.drawString("100", zw, 550);
g2.drawString("150", zw, 575);
g2.drawString("250", zw, 625);
}
// font groter maken
g2.setFont(bigFont);
// telkens als er een nieuwe waarde in de arraylist wordt toegevoegd
// wordt deze toegevoegd en dus getekend.
for (int i = 0; i < values.size() && i < getWidth(); i++) {
// Uitlezen van RawAcceleration waarde
RawAcceleration r = values.get(i);
xx = x;
yy = y;
zz = z;
Short xShort = r.getX();
Short yShort = r.getY();
Short zShort = r.getZ();
x = (int) xShort / 2;
y = (int) yShort / 2;
z = (int) zShort / 2;
// hulp printline voor de waarde niet gedeeld door 2.
// System.out.println(xShort + " " + yShort + " " + zShort);
// RawAcceleration lijnen voor de x, y en z waarde van de RawAcc
g2.setColor(Color.RED);
g2.drawString("X lijn", 50, 75);
g2.drawString(xTurns + " ", 200, 75);
g2.drawLine(i - 1, xx + 100, i, x + 100);
g2.setColor(Color.MAGENTA);
g2.drawString("Y lijn", 50, 275);
g2.drawLine(i - 1, yy + 300, i, y + 300);
g2.setColor(Color.BLUE);
g2.drawString("Z lijn", 50, 475);
g2.drawString(zTurns + " ", 200, 475);
g2.drawLine(i - 1, zz + 500, i, z + 500);
}
System.out.println(xTurns + " " + zTurns);
// 95 155, 100 200
RawAcceleration rA = values.get(values.size() - 1);
short xShort = rA.getX();
if (xTurned) {
if (xShort > 165) {
xTurns++;
xTurned = false;
}
} else {
if (xShort > 85) {
xTurned = true;
}
}
short zShort = rA.getZ();
if (zTurned) {
if (zShort > 200) {
zTurns++;
zTurned = false;
}
} else {
if (zShort > 100) {
zTurned = true;
}
}
}
@Override
public void onButtonsEvent(WiimoteButtonsEvent arg0) {
}
@Override
public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent arg0) {
}
@Override
public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent arg0) {
}
@Override
public void onDisconnectionEvent(DisconnectionEvent arg0) {
values.clear();
repaint();
}
@Override
public void onExpansionEvent(ExpansionEvent arg0) {
draw(arg0);
}
@Override
public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent arg0) {
}
@Override
public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent arg0) {
}
@Override
public void onIrEvent(IREvent arg0) {
}
@Override
public void onMotionSensingEvent(MotionSensingEvent arg0) {
draw(arg0);
}
@Override
public void onNunchukInsertedEvent(NunchukInsertedEvent arg0) {
}
@Override
public void onNunchukRemovedEvent(NunchukRemovedEvent arg0) {
}
@Override
public void onStatusEvent(StatusEvent arg0) {
}
private void draw(GenericEvent arg0) {
if (values.size() >= getWidth()) {
// als de grafiek buiten beeld gaat de waarde verwijderen zodat
// de lijn weer vanaf links begint
values.clear();
}
RawAcceleration rawAcceleration = aPanel.getRawAccelerationValue(arg0);
// System.out.println(turns + " " + yaw);
if (rawAcceleration != null) {
// toevoegen van waarde om te tekenen
values.add(rawAcceleration);
}
repaint();
}
@Override
public void actionPerformed(ActionEvent arg0) {
time++;
repaint();
timer.restart();
}
}
| nlreturns/WiiMote | src/wiimote/Opdracht2.java | 3,081 | // RawAcceleration lijnen voor de x, y en z waarde van de RawAcc | line_comment | nl | package wiimote;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import wiiusej.WiiUseApiManager;
import wiiusej.Wiimote;
import wiiusej.utils.AccelerationPanel;
import wiiusej.utils.AccelerationWiimoteEventPanel;
import wiiusej.values.RawAcceleration;
import wiiusej.wiiusejevents.GenericEvent;
import wiiusej.wiiusejevents.physicalevents.ExpansionEvent;
import wiiusej.wiiusejevents.physicalevents.IREvent;
import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent;
import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent;
import wiiusej.wiiusejevents.utils.WiimoteListener;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.DisconnectionEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.StatusEvent;
public class Opdracht2 extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Opdracht 2");
JPanel panel = new Panel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
public Opdracht2() {
}
}
class Panel extends JPanel implements WiimoteListener, ActionListener {
Wiimote[] wiimotes;
AccelerationPanel aPanel;
Wiimote wiimote;
JPanel panel;
RawAcceleration rawAcc;
float yaw;
int x;
int y;
int z;
int xx;
int yy;
int zz;
short time;
short oldTime;
Timer timer = new Timer(1, this);
ArrayList<RawAcceleration> values;
Font bigFont;
Font smallFont;
int xTurns;
int zTurns;
boolean xTurned;
boolean zTurned;
public Panel() {
xTurned = false;
zTurned = false;
xTurns = 0;
zTurns = 0;
yaw = 0;
time = 0;
oldTime = 0;
setPreferredSize(new Dimension(1366, 768));
timer.start();
System.loadLibrary("WiiuseJ");
wiimotes = WiiUseApiManager.getWiimotes(1, false);
wiimote = wiimotes[0];
values = new ArrayList<>();
wiimote.activateMotionSensing();
wiimote.addWiiMoteEventListeners(this);
aPanel = new AccelerationWiimoteEventPanel();
rawAcc = new RawAcceleration();
values.add(rawAcc);
x = 0;
y = 0;
z = 0;
xx = 0;
yy = 0;
zz = 0;
smallFont = new Font("Arial", 0, 10);
bigFont = new Font("Arial", 0, 12);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
// x lijnen
g2.drawLine(0, 163, getWidth(), 163);
g2.drawLine(0, 363, getWidth(), 363);
g2.drawLine(0, 575, getWidth(), 575);
// hulp x lijnen voor x RawAcc
g2.setColor(Color.GREEN);
g2.drawLine(0, 100, getWidth(), 100);
g2.drawLine(0, 137, getWidth(), 137);
g2.drawLine(0, 200, getWidth(), 200);
// hulp x lijnen voor y RawAcc
g2.drawLine(0, 337, getWidth(), 337);
g2.drawLine(0, 400, getWidth(), 400);
// hulp x lijnen voor z RawAcc
g2.drawLine(0, 500, getWidth(), 500);
g2.drawLine(0, 550, getWidth(), 550);
g2.drawLine(0, 625, getWidth(), 625);
// y lijnen
g2.setColor(Color.BLACK);
for (int yl = 100; yl < 200; yl = yl + 300) {
g2.drawLine(yl, 100, yl, 200);
g2.drawLine(yl, 337, yl, 400);
g2.drawLine(yl, 500, yl, 625);
}
// font kleiner maken
g2.setFont(smallFont);
// x waardes
for (int xw = 105; xw < 200; xw = xw + 300) {
g2.drawString("0", xw, 100);
g2.drawString("75", xw, 137);
g2.drawString("125", xw, 163);
g2.drawString("200", xw, 200);
}
// y waardes
for (int yw = 105; yw < 200; yw = yw + 300) {
g2.drawString("75", yw, 337);
g2.drawString("125", yw, 363);
g2.drawString("200", yw, 400);
}
// z waardes
for (int zw = 105; zw < 200; zw = zw + 300) {
g2.drawString("0", zw, 500);
g2.drawString("100", zw, 550);
g2.drawString("150", zw, 575);
g2.drawString("250", zw, 625);
}
// font groter maken
g2.setFont(bigFont);
// telkens als er een nieuwe waarde in de arraylist wordt toegevoegd
// wordt deze toegevoegd en dus getekend.
for (int i = 0; i < values.size() && i < getWidth(); i++) {
// Uitlezen van RawAcceleration waarde
RawAcceleration r = values.get(i);
xx = x;
yy = y;
zz = z;
Short xShort = r.getX();
Short yShort = r.getY();
Short zShort = r.getZ();
x = (int) xShort / 2;
y = (int) yShort / 2;
z = (int) zShort / 2;
// hulp printline voor de waarde niet gedeeld door 2.
// System.out.println(xShort + " " + yShort + " " + zShort);
// RawAcceleration lijnen<SUF>
g2.setColor(Color.RED);
g2.drawString("X lijn", 50, 75);
g2.drawString(xTurns + " ", 200, 75);
g2.drawLine(i - 1, xx + 100, i, x + 100);
g2.setColor(Color.MAGENTA);
g2.drawString("Y lijn", 50, 275);
g2.drawLine(i - 1, yy + 300, i, y + 300);
g2.setColor(Color.BLUE);
g2.drawString("Z lijn", 50, 475);
g2.drawString(zTurns + " ", 200, 475);
g2.drawLine(i - 1, zz + 500, i, z + 500);
}
System.out.println(xTurns + " " + zTurns);
// 95 155, 100 200
RawAcceleration rA = values.get(values.size() - 1);
short xShort = rA.getX();
if (xTurned) {
if (xShort > 165) {
xTurns++;
xTurned = false;
}
} else {
if (xShort > 85) {
xTurned = true;
}
}
short zShort = rA.getZ();
if (zTurned) {
if (zShort > 200) {
zTurns++;
zTurned = false;
}
} else {
if (zShort > 100) {
zTurned = true;
}
}
}
@Override
public void onButtonsEvent(WiimoteButtonsEvent arg0) {
}
@Override
public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent arg0) {
}
@Override
public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent arg0) {
}
@Override
public void onDisconnectionEvent(DisconnectionEvent arg0) {
values.clear();
repaint();
}
@Override
public void onExpansionEvent(ExpansionEvent arg0) {
draw(arg0);
}
@Override
public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent arg0) {
}
@Override
public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent arg0) {
}
@Override
public void onIrEvent(IREvent arg0) {
}
@Override
public void onMotionSensingEvent(MotionSensingEvent arg0) {
draw(arg0);
}
@Override
public void onNunchukInsertedEvent(NunchukInsertedEvent arg0) {
}
@Override
public void onNunchukRemovedEvent(NunchukRemovedEvent arg0) {
}
@Override
public void onStatusEvent(StatusEvent arg0) {
}
private void draw(GenericEvent arg0) {
if (values.size() >= getWidth()) {
// als de grafiek buiten beeld gaat de waarde verwijderen zodat
// de lijn weer vanaf links begint
values.clear();
}
RawAcceleration rawAcceleration = aPanel.getRawAccelerationValue(arg0);
// System.out.println(turns + " " + yaw);
if (rawAcceleration != null) {
// toevoegen van waarde om te tekenen
values.add(rawAcceleration);
}
repaint();
}
@Override
public void actionPerformed(ActionEvent arg0) {
time++;
repaint();
timer.restart();
}
}
|
205048_17 | package hadoop.data.analysis.original;
import hadoop.data.analysis.ranges.HouseRanges;
import hadoop.data.analysis.ranges.RentRanges;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
public class IndividualDataReducer extends Reducer<Text, MapMultiple, Text, Text> {
private MultipleOutputs multipleOutputs;
private Map<Text, Double> elderlyMap = new HashMap<>();
private Text mostElderlyState = new Text();
private List<Double> averageList = new ArrayList<>();
private double currentMax = 0;
/**
* Writes answers to each question in their own files.
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
public void setup(Context context) throws IOException, InterruptedException {
multipleOutputs = new MultipleOutputs(context);
multipleOutputs.write("question1", new Text("\nQuestion 1:\n" +
"Percentage of residences rented vs. owned"), new Text(" \n"));
multipleOutputs.write("question2", new Text("\nQuestion 2:\n" +
"Percentage of males and females of the state population that never married"), new Text(" \n"));
multipleOutputs.write("question3a", new Text("\nQuestion 3a:\n" +
"Percentage of hispanic population <= 18 years old"), new Text(" \n"));
multipleOutputs.write("question3b", new Text("\nQuestion 3b:\n" +
"Percentage of hispanic population >= 19 and <= 29"), new Text(" \n"));
multipleOutputs.write("question3c", new Text("\nQuestion 3c:\n" +
"Percentage of hispanic population >= 30 and <= 39"), new Text(" \n"));
multipleOutputs.write("question4", new Text("\nQuestion 4:\n" +
"Percentage of rural households vs. urban households"), new Text(" \n"));
multipleOutputs.write("question5", new Text("\nQuestion 5:\n" +
"Median value of houses occupied by owners"), new Text(" \n"));
multipleOutputs.write("question6", new Text("\nQuestion 6:\n" +
"Median rent paid by households"), new Text(" \n"));
multipleOutputs.write("question7", new Text("\nQuestion 7:\n" +
"95th percentile of the average number of rooms per house"), new Text(" \n"));
multipleOutputs.write("question8", new Text("\nQuestion 8:\n" +
"State that has the highest percentage of people aged > 85"), new Text(" \n"));
multipleOutputs.write("question9", new Text("\nQuestion 9:\n" +
"Does the amount of urban and rural population influence the population of children < 17 per state?"),
new Text(" \n"));
}
/**
* Sums all values and sets the final values for each variable. Performs calculations as necessary and
* writes to output file.
* @param key state
* @param values MapMultiple objects that contain values for each state
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void reduce(Text key, Iterable<MapMultiple> values, Context context) throws IOException, InterruptedException {
MapMultiple mapMultiple = new MapMultiple();
Map<Integer, Double> houseRangeMap = new TreeMap<>();
Map<Integer, Double> rentRangeMap = new TreeMap<>();
HouseRanges houseRanges = HouseRanges.getInstance();
RentRanges rentRanges = RentRanges.getInstance();
double totalRent = 0;
double totalOwn = 0;
double population = 0;
double totalMalesNeverMarried = 0;
double totalFemalesNeverMarried = 0;
double insideUrban = 0;
double outsideUrban = 0;
double rural = 0;
double notDefined = 0;
double hispanicMalesUnder18 = 0;
double hispanicFemalesUnder18 = 0;
double hispanicMales19to29 = 0;
double hispanicFemales19to29 = 0;
double hispanicMales30to39 = 0;
double hispanicFemales30to39 = 0;
double totalHispanicPopulation = 0;
double totalOwnedHomes = 0;
double ownedHomeValue0 = 0;
double ownedHomeValue1 = 0;
double ownedHomeValue2 = 0;
double ownedHomeValue3 = 0;
double ownedHomeValue4 = 0;
double ownedHomeValue5 = 0;
double ownedHomeValue6 = 0;
double ownedHomeValue7 = 0;
double ownedHomeValue8 = 0;
double ownedHomeValue9 = 0;
double ownedHomeValue10 = 0;
double ownedHomeValue11 = 0;
double ownedHomeValue12 = 0;
double ownedHomeValue13 = 0;
double ownedHomeValue14 = 0;
double ownedHomeValue15 = 0;
double ownedHomeValue16 = 0;
double ownedHomeValue17 = 0;
double ownedHomeValue18 = 0;
double ownedHomeValue19 = 0;
double totalRenters = 0;
double rentValue0 = 0;
double rentValue1 = 0;
double rentValue2 = 0;
double rentValue3 = 0;
double rentValue4 = 0;
double rentValue5 = 0;
double rentValue6 = 0;
double rentValue7 = 0;
double rentValue8 = 0;
double rentValue9 = 0;
double rentValue10 = 0;
double rentValue11 = 0;
double rentValue12 = 0;
double rentValue13 = 0;
double rentValue14 = 0;
double rentValue15 = 0;
double rentValue16 = 0;
double totalRooms = 0;
double oneRoom = 0;
double twoRooms = 0;
double threeRooms = 0;
double fourRooms = 0;
double fiveRooms = 0;
double sixRooms = 0;
double sevenRooms = 0;
double eightRooms = 0;
double nineRooms = 0;
double averageRooms = 0;
double elderlyPopulation = 0;
double urbanPopulation = 0;
double ruralPopulation = 0;
double childrenUnder1To11 = 0;
double children12To17 = 0;
double hispanicChildrenUnder1To11 = 0;
double hispanicChildren12To17 = 0;
for (MapMultiple val : values) {
totalRent += val.getRent();
totalOwn += val.getOwn();
population += val.getPopulation();
totalMalesNeverMarried += val.getMaleNeverMarried();
totalFemalesNeverMarried += val.getFemaleNeverMarried();
hispanicMalesUnder18 += val.getHispanicMalesUnder18();
hispanicFemalesUnder18 += val.getHispanicFemalesUnder18();
hispanicMales19to29 += val.getHispanicMales19to29();
hispanicFemales19to29 += val.getHispanicFemales19to29();
hispanicMales30to39 += val.getHispanicMales30to39();
hispanicFemales30to39 += val.getHispanicFemales30to39();
totalHispanicPopulation += val.getTotalHispanicPopulation();
insideUrban += val.getInsideUrban();
outsideUrban += val.getOutsideUrban();
rural += val.getRural();
notDefined += val.getNotDefined();
totalOwnedHomes += val.getTotalOwnedHomes();
ownedHomeValue0 += val.getOwnedHomeValue0();
ownedHomeValue1 += val.getOwnedHomeValue1();
ownedHomeValue2 += val.getOwnedHomeValue2();
ownedHomeValue3 += val.getOwnedHomeValue3();
ownedHomeValue4 += val.getOwnedHomeValue4();
ownedHomeValue5 += val.getOwnedHomeValue5();
ownedHomeValue6 += val.getOwnedHomeValue6();
ownedHomeValue7 += val.getOwnedHomeValue7();
ownedHomeValue8 += val.getOwnedHomeValue8();
ownedHomeValue9 += val.getOwnedHomeValue9();
ownedHomeValue10 += val.getOwnedHomeValue10();
ownedHomeValue11 += val.getOwnedHomeValue11();
ownedHomeValue12 += val.getOwnedHomeValue12();
ownedHomeValue13 += val.getOwnedHomeValue13();
ownedHomeValue14 += val.getOwnedHomeValue14();
ownedHomeValue15 += val.getOwnedHomeValue15();
ownedHomeValue16 += val.getOwnedHomeValue16();
ownedHomeValue17 += val.getOwnedHomeValue17();
ownedHomeValue18 += val.getOwnedHomeValue18();
ownedHomeValue19 += val.getOwnedHomeValue19();
totalRenters += val.getTotalRenters();
rentValue0 += val.getRentValue0();
rentValue1 += val.getRentValue1();
rentValue2 += val.getRentValue2();
rentValue3 += val.getRentValue3();
rentValue4 += val.getRentValue4();
rentValue5 += val.getRentValue5();
rentValue6 += val.getRentValue6();
rentValue7 += val.getRentValue7();
rentValue8 += val.getRentValue8();
rentValue9 += val.getRentValue9();
rentValue10 += val.getRentValue10();
rentValue11 += val.getRentValue11();
rentValue12 += val.getRentValue12();
rentValue13 += val.getRentValue13();
rentValue14 += val.getRentValue14();
rentValue15 += val.getRentValue15();
rentValue16 += val.getRentValue16();
totalRooms += val.getTotalRooms();
oneRoom += val.getOneRoom();
twoRooms += val.getTwoRooms();
threeRooms += val.getThreeRooms();
fourRooms += val.getFourRooms();
fiveRooms += val.getFiveRooms();
sixRooms += val.getSixRooms();
sevenRooms += val.getSevenRooms();
eightRooms += val.getEightRooms();
nineRooms += val.getNineRooms();
elderlyPopulation += val.getElderlyPopulation();
elderlyMap.put(key, Double.parseDouble(calculatePercentage(elderlyPopulation, population)));
urbanPopulation += val.getUrbanPopulation();
ruralPopulation += val.getRuralPopulation();
childrenUnder1To11 += val.getChildrenUnder1To11();
children12To17 += val.getChildren12To17();
hispanicChildrenUnder1To11 += val.getHispanicChildrenUnder1To11();
hispanicChildren12To17 += val.getHispanicChildren12To17();
}
//determine how many rooms exist in the state so average can be calculated
Double[] roomArray = {oneRoom * 1, twoRooms * 2, threeRooms * 3, fourRooms * 4, fiveRooms * 5,
sixRooms * 6, sevenRooms * 7, eightRooms * 8, nineRooms * 9};
//calculate averages and add them to a list
DecimalFormat dF = new DecimalFormat("##.00");
double average = calculateAverageRooms(roomArray, totalRooms);
if (!Double.isNaN(average)) {
double formattedAverage = Double.parseDouble(dF.format(average));
averageRooms = formattedAverage;
} else {
averageRooms = 0;
}
if (averageRooms != 0) {
averageList.add(averageRooms);
}
//put home values into an array so they can be put into a map with the ranges
Double[] homeValueArray = {ownedHomeValue0, ownedHomeValue1, ownedHomeValue2, ownedHomeValue3,
ownedHomeValue4, ownedHomeValue5, ownedHomeValue6, ownedHomeValue7, ownedHomeValue8, ownedHomeValue9,
ownedHomeValue10, ownedHomeValue11, ownedHomeValue12, ownedHomeValue13, ownedHomeValue14,
ownedHomeValue15, ownedHomeValue16, ownedHomeValue17, ownedHomeValue18, ownedHomeValue19};
for (int i = 0; i < 20; i++) {
houseRangeMap.put(houseRanges.getHousingIntegers()[i], homeValueArray[i]);
}
//put rent values into an array so they can be put into a map with the ranges
Double[] rentPaidArray = {rentValue0, rentValue1, rentValue2, rentValue3, rentValue4, rentValue5,
rentValue6, rentValue7, rentValue8, rentValue9, rentValue10, rentValue11, rentValue12,
rentValue13, rentValue14, rentValue15, rentValue16};
for (int i = 0; i < 17; i++) {
rentRangeMap.put(rentRanges.getIntegerRents()[i], rentPaidArray[i]);
}
//write answers for each state
multipleOutputs.write("question1", key, new Text(
" rent: " + calculatePercentage(totalRent, (totalRent + totalOwn)) + "% | own: "
+ calculatePercentage(totalOwn, (totalRent + totalOwn)) + "%"));
multipleOutputs.write("question2", key, new Text(
" Males: " +
calculatePercentage(totalMalesNeverMarried, (population))
+ "% | Females: " +
calculatePercentage(totalFemalesNeverMarried, (population)) + "%"));
multipleOutputs.write("question3a", key, new Text(
" Males: " + calculatePercentage(hispanicMalesUnder18, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemalesUnder18, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question3b", key, new Text(
" Males: " + calculatePercentage(hispanicMales19to29, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemales19to29, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question3c", key, new Text(
" Males: " + calculatePercentage(hispanicMales30to39, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemales30to39, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question4", key, new Text(
" Rural: "
+ calculatePercentage(rural, (rural + insideUrban + outsideUrban + notDefined)) +
"% | Urban: " +
calculatePercentage((insideUrban + outsideUrban), (rural + insideUrban + outsideUrban + notDefined)) + "%"));
multipleOutputs.write("question5", key, new Text(
" " + calculateMedian(houseRangeMap, houseRanges.getRanges(), totalOwnedHomes)));
multipleOutputs.write("question6", key, new Text(
" " + calculateMedian(rentRangeMap, rentRanges.getRanges(), totalRenters)));
multipleOutputs.write("question9", key, new Text(
calculatePercentage(urbanPopulation, population) + ":" +
calculatePercentage(ruralPopulation, population) +
":" + calculatePercentage(childrenUnder1To11, population) +
":" + calculatePercentage(children12To17, population) +
":" + calculatePercentage(hispanicChildrenUnder1To11, population) +
":" + calculatePercentage(hispanicChildren12To17, population)));
stateWithMostElderlyPeople(elderlyMap);
}
/**
* Close multiple outputs, otherwise the results might not be written to output files.
* Also writes questions 7 and 8 because the answer only contains one data point instead of one
* for each state.
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
//question 7 and 8 written here so only one value's output
multipleOutputs.write("question7", "", new Text(calculateNinetyFifthPercentile(averageList) +
averageList + " rooms"));
multipleOutputs.write("question8", mostElderlyState, new Text(
" " + currentMax + "%"));
super.cleanup(context);
multipleOutputs.close();
}
/**
* Calculate percentage, ignores answer if impossible number is calculated (VI and PR
* generally cause this)
* @param numerator
* @param denominator
* @return
*/
private String calculatePercentage(double numerator, double denominator) {
DecimalFormat decimalFormat = new DecimalFormat("##.00");
double percentage = (numerator / denominator) * 100;
if (Double.isInfinite(percentage) || percentage > 100 || percentage < 0) {
return "N/A";
} else {
return decimalFormat.format(percentage);
}
}
/**
* Calculates median, returns N/A if no iterations were performed (no data was collected).
* The current count is tracked because this is calculating the median from ranges, not from
* each data point.
* @param map map of ranges (key) and quantity per range (value)
* @param dataArray array of ranges
* @param totalNumber total number of the variable that's being examined (home values or rent ranges)
* @return answer
*/
private String calculateMedian(Map<Integer, Double> map, String[] dataArray, double totalNumber) {
int currentCount = 0;
int iterations = 0;
double dividingPoint = totalNumber * 0.50;
for (Integer key : map.keySet()) {
currentCount += map.get(key);
iterations++;
if (currentCount > dividingPoint) {
break;
}
}
String relevantRange = "N/A";
if (iterations != 0) {
relevantRange = dataArray[iterations - 1];
}
//debug
// String test = "";
// test += iterations + ":" + dividingPoint + ":" + totalNumber + "\n" + map.values().toString() + "\n";
// for (Integer key : map.keySet()) {
// test += "[";
// test += key.toString() + ", ";
// test += map.get(key) + "]\n";
// }
// test += "***" + relevantRange + "***";
return relevantRange;
}
private double calculateAverageRooms(Double[] rooms, double totalHouses) {
double actualRoomQuantity = 0;
for (int i = 0; i < 9; i++) {
actualRoomQuantity += rooms[i];
}
return actualRoomQuantity / totalHouses;
}
/**
* Checks if the percentage of elderly population in the state is the most compared to all other
* states analyzed so far.
* @param stateElderlyMap Map of states' elderly population percentages
*/
private void stateWithMostElderlyPeople(Map<Text, Double> stateElderlyMap) {
for (Text state : stateElderlyMap.keySet()) {
if (stateElderlyMap.get(state) > currentMax) {
currentMax = stateElderlyMap.get(state);
mostElderlyState.set(state);
}
}
}
/**
* Calculates 95th percentile of the given list. If the result of list * .95 divides evenly,
* that number is the 95th percentile. Otherwise, the next result is in the 95th percentile.
* @param list list to calculate 95th percentile from
* @return
*/
private String calculateNinetyFifthPercentile(List<Double> list) {
Collections.sort(list);
BigDecimal ninetyFifthPercentile = null;
double rawPercentile = list.size() * 0.95;
if (rawPercentile % 1 == 0) {
ninetyFifthPercentile = new BigDecimal(rawPercentile).setScale(0);
}
if (rawPercentile % 1 != 0) {
ninetyFifthPercentile = new BigDecimal(rawPercentile).setScale(0, BigDecimal.ROUND_UP);
}
int ninetyFifthPercentilePosition = ninetyFifthPercentile.intValueExact();
double ninetyFifthPercentileNumber = list.get(ninetyFifthPercentilePosition - 1);
String answer = Double.toString(ninetyFifthPercentileNumber);
// debug
// String test = "";
// test += ninetyFifthPercentile + ":" + ninetyFifthPercentilePosition + "\n" + list.toString() + "\n";
// test += list.size() + "\n";
// test += "***" + ninetyFifthPercentileNumber + "***";
return answer;
}
} | nmalensek/Hadoop-Demographic-Analysis | src/hadoop/data/analysis/original/IndividualDataReducer.java | 5,703 | // test += "***" + relevantRange + "***"; | line_comment | nl | package hadoop.data.analysis.original;
import hadoop.data.analysis.ranges.HouseRanges;
import hadoop.data.analysis.ranges.RentRanges;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
public class IndividualDataReducer extends Reducer<Text, MapMultiple, Text, Text> {
private MultipleOutputs multipleOutputs;
private Map<Text, Double> elderlyMap = new HashMap<>();
private Text mostElderlyState = new Text();
private List<Double> averageList = new ArrayList<>();
private double currentMax = 0;
/**
* Writes answers to each question in their own files.
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
public void setup(Context context) throws IOException, InterruptedException {
multipleOutputs = new MultipleOutputs(context);
multipleOutputs.write("question1", new Text("\nQuestion 1:\n" +
"Percentage of residences rented vs. owned"), new Text(" \n"));
multipleOutputs.write("question2", new Text("\nQuestion 2:\n" +
"Percentage of males and females of the state population that never married"), new Text(" \n"));
multipleOutputs.write("question3a", new Text("\nQuestion 3a:\n" +
"Percentage of hispanic population <= 18 years old"), new Text(" \n"));
multipleOutputs.write("question3b", new Text("\nQuestion 3b:\n" +
"Percentage of hispanic population >= 19 and <= 29"), new Text(" \n"));
multipleOutputs.write("question3c", new Text("\nQuestion 3c:\n" +
"Percentage of hispanic population >= 30 and <= 39"), new Text(" \n"));
multipleOutputs.write("question4", new Text("\nQuestion 4:\n" +
"Percentage of rural households vs. urban households"), new Text(" \n"));
multipleOutputs.write("question5", new Text("\nQuestion 5:\n" +
"Median value of houses occupied by owners"), new Text(" \n"));
multipleOutputs.write("question6", new Text("\nQuestion 6:\n" +
"Median rent paid by households"), new Text(" \n"));
multipleOutputs.write("question7", new Text("\nQuestion 7:\n" +
"95th percentile of the average number of rooms per house"), new Text(" \n"));
multipleOutputs.write("question8", new Text("\nQuestion 8:\n" +
"State that has the highest percentage of people aged > 85"), new Text(" \n"));
multipleOutputs.write("question9", new Text("\nQuestion 9:\n" +
"Does the amount of urban and rural population influence the population of children < 17 per state?"),
new Text(" \n"));
}
/**
* Sums all values and sets the final values for each variable. Performs calculations as necessary and
* writes to output file.
* @param key state
* @param values MapMultiple objects that contain values for each state
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void reduce(Text key, Iterable<MapMultiple> values, Context context) throws IOException, InterruptedException {
MapMultiple mapMultiple = new MapMultiple();
Map<Integer, Double> houseRangeMap = new TreeMap<>();
Map<Integer, Double> rentRangeMap = new TreeMap<>();
HouseRanges houseRanges = HouseRanges.getInstance();
RentRanges rentRanges = RentRanges.getInstance();
double totalRent = 0;
double totalOwn = 0;
double population = 0;
double totalMalesNeverMarried = 0;
double totalFemalesNeverMarried = 0;
double insideUrban = 0;
double outsideUrban = 0;
double rural = 0;
double notDefined = 0;
double hispanicMalesUnder18 = 0;
double hispanicFemalesUnder18 = 0;
double hispanicMales19to29 = 0;
double hispanicFemales19to29 = 0;
double hispanicMales30to39 = 0;
double hispanicFemales30to39 = 0;
double totalHispanicPopulation = 0;
double totalOwnedHomes = 0;
double ownedHomeValue0 = 0;
double ownedHomeValue1 = 0;
double ownedHomeValue2 = 0;
double ownedHomeValue3 = 0;
double ownedHomeValue4 = 0;
double ownedHomeValue5 = 0;
double ownedHomeValue6 = 0;
double ownedHomeValue7 = 0;
double ownedHomeValue8 = 0;
double ownedHomeValue9 = 0;
double ownedHomeValue10 = 0;
double ownedHomeValue11 = 0;
double ownedHomeValue12 = 0;
double ownedHomeValue13 = 0;
double ownedHomeValue14 = 0;
double ownedHomeValue15 = 0;
double ownedHomeValue16 = 0;
double ownedHomeValue17 = 0;
double ownedHomeValue18 = 0;
double ownedHomeValue19 = 0;
double totalRenters = 0;
double rentValue0 = 0;
double rentValue1 = 0;
double rentValue2 = 0;
double rentValue3 = 0;
double rentValue4 = 0;
double rentValue5 = 0;
double rentValue6 = 0;
double rentValue7 = 0;
double rentValue8 = 0;
double rentValue9 = 0;
double rentValue10 = 0;
double rentValue11 = 0;
double rentValue12 = 0;
double rentValue13 = 0;
double rentValue14 = 0;
double rentValue15 = 0;
double rentValue16 = 0;
double totalRooms = 0;
double oneRoom = 0;
double twoRooms = 0;
double threeRooms = 0;
double fourRooms = 0;
double fiveRooms = 0;
double sixRooms = 0;
double sevenRooms = 0;
double eightRooms = 0;
double nineRooms = 0;
double averageRooms = 0;
double elderlyPopulation = 0;
double urbanPopulation = 0;
double ruralPopulation = 0;
double childrenUnder1To11 = 0;
double children12To17 = 0;
double hispanicChildrenUnder1To11 = 0;
double hispanicChildren12To17 = 0;
for (MapMultiple val : values) {
totalRent += val.getRent();
totalOwn += val.getOwn();
population += val.getPopulation();
totalMalesNeverMarried += val.getMaleNeverMarried();
totalFemalesNeverMarried += val.getFemaleNeverMarried();
hispanicMalesUnder18 += val.getHispanicMalesUnder18();
hispanicFemalesUnder18 += val.getHispanicFemalesUnder18();
hispanicMales19to29 += val.getHispanicMales19to29();
hispanicFemales19to29 += val.getHispanicFemales19to29();
hispanicMales30to39 += val.getHispanicMales30to39();
hispanicFemales30to39 += val.getHispanicFemales30to39();
totalHispanicPopulation += val.getTotalHispanicPopulation();
insideUrban += val.getInsideUrban();
outsideUrban += val.getOutsideUrban();
rural += val.getRural();
notDefined += val.getNotDefined();
totalOwnedHomes += val.getTotalOwnedHomes();
ownedHomeValue0 += val.getOwnedHomeValue0();
ownedHomeValue1 += val.getOwnedHomeValue1();
ownedHomeValue2 += val.getOwnedHomeValue2();
ownedHomeValue3 += val.getOwnedHomeValue3();
ownedHomeValue4 += val.getOwnedHomeValue4();
ownedHomeValue5 += val.getOwnedHomeValue5();
ownedHomeValue6 += val.getOwnedHomeValue6();
ownedHomeValue7 += val.getOwnedHomeValue7();
ownedHomeValue8 += val.getOwnedHomeValue8();
ownedHomeValue9 += val.getOwnedHomeValue9();
ownedHomeValue10 += val.getOwnedHomeValue10();
ownedHomeValue11 += val.getOwnedHomeValue11();
ownedHomeValue12 += val.getOwnedHomeValue12();
ownedHomeValue13 += val.getOwnedHomeValue13();
ownedHomeValue14 += val.getOwnedHomeValue14();
ownedHomeValue15 += val.getOwnedHomeValue15();
ownedHomeValue16 += val.getOwnedHomeValue16();
ownedHomeValue17 += val.getOwnedHomeValue17();
ownedHomeValue18 += val.getOwnedHomeValue18();
ownedHomeValue19 += val.getOwnedHomeValue19();
totalRenters += val.getTotalRenters();
rentValue0 += val.getRentValue0();
rentValue1 += val.getRentValue1();
rentValue2 += val.getRentValue2();
rentValue3 += val.getRentValue3();
rentValue4 += val.getRentValue4();
rentValue5 += val.getRentValue5();
rentValue6 += val.getRentValue6();
rentValue7 += val.getRentValue7();
rentValue8 += val.getRentValue8();
rentValue9 += val.getRentValue9();
rentValue10 += val.getRentValue10();
rentValue11 += val.getRentValue11();
rentValue12 += val.getRentValue12();
rentValue13 += val.getRentValue13();
rentValue14 += val.getRentValue14();
rentValue15 += val.getRentValue15();
rentValue16 += val.getRentValue16();
totalRooms += val.getTotalRooms();
oneRoom += val.getOneRoom();
twoRooms += val.getTwoRooms();
threeRooms += val.getThreeRooms();
fourRooms += val.getFourRooms();
fiveRooms += val.getFiveRooms();
sixRooms += val.getSixRooms();
sevenRooms += val.getSevenRooms();
eightRooms += val.getEightRooms();
nineRooms += val.getNineRooms();
elderlyPopulation += val.getElderlyPopulation();
elderlyMap.put(key, Double.parseDouble(calculatePercentage(elderlyPopulation, population)));
urbanPopulation += val.getUrbanPopulation();
ruralPopulation += val.getRuralPopulation();
childrenUnder1To11 += val.getChildrenUnder1To11();
children12To17 += val.getChildren12To17();
hispanicChildrenUnder1To11 += val.getHispanicChildrenUnder1To11();
hispanicChildren12To17 += val.getHispanicChildren12To17();
}
//determine how many rooms exist in the state so average can be calculated
Double[] roomArray = {oneRoom * 1, twoRooms * 2, threeRooms * 3, fourRooms * 4, fiveRooms * 5,
sixRooms * 6, sevenRooms * 7, eightRooms * 8, nineRooms * 9};
//calculate averages and add them to a list
DecimalFormat dF = new DecimalFormat("##.00");
double average = calculateAverageRooms(roomArray, totalRooms);
if (!Double.isNaN(average)) {
double formattedAverage = Double.parseDouble(dF.format(average));
averageRooms = formattedAverage;
} else {
averageRooms = 0;
}
if (averageRooms != 0) {
averageList.add(averageRooms);
}
//put home values into an array so they can be put into a map with the ranges
Double[] homeValueArray = {ownedHomeValue0, ownedHomeValue1, ownedHomeValue2, ownedHomeValue3,
ownedHomeValue4, ownedHomeValue5, ownedHomeValue6, ownedHomeValue7, ownedHomeValue8, ownedHomeValue9,
ownedHomeValue10, ownedHomeValue11, ownedHomeValue12, ownedHomeValue13, ownedHomeValue14,
ownedHomeValue15, ownedHomeValue16, ownedHomeValue17, ownedHomeValue18, ownedHomeValue19};
for (int i = 0; i < 20; i++) {
houseRangeMap.put(houseRanges.getHousingIntegers()[i], homeValueArray[i]);
}
//put rent values into an array so they can be put into a map with the ranges
Double[] rentPaidArray = {rentValue0, rentValue1, rentValue2, rentValue3, rentValue4, rentValue5,
rentValue6, rentValue7, rentValue8, rentValue9, rentValue10, rentValue11, rentValue12,
rentValue13, rentValue14, rentValue15, rentValue16};
for (int i = 0; i < 17; i++) {
rentRangeMap.put(rentRanges.getIntegerRents()[i], rentPaidArray[i]);
}
//write answers for each state
multipleOutputs.write("question1", key, new Text(
" rent: " + calculatePercentage(totalRent, (totalRent + totalOwn)) + "% | own: "
+ calculatePercentage(totalOwn, (totalRent + totalOwn)) + "%"));
multipleOutputs.write("question2", key, new Text(
" Males: " +
calculatePercentage(totalMalesNeverMarried, (population))
+ "% | Females: " +
calculatePercentage(totalFemalesNeverMarried, (population)) + "%"));
multipleOutputs.write("question3a", key, new Text(
" Males: " + calculatePercentage(hispanicMalesUnder18, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemalesUnder18, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question3b", key, new Text(
" Males: " + calculatePercentage(hispanicMales19to29, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemales19to29, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question3c", key, new Text(
" Males: " + calculatePercentage(hispanicMales30to39, totalHispanicPopulation) +
"% | Females: " + calculatePercentage(hispanicFemales30to39, totalHispanicPopulation) +
"%"));
multipleOutputs.write("question4", key, new Text(
" Rural: "
+ calculatePercentage(rural, (rural + insideUrban + outsideUrban + notDefined)) +
"% | Urban: " +
calculatePercentage((insideUrban + outsideUrban), (rural + insideUrban + outsideUrban + notDefined)) + "%"));
multipleOutputs.write("question5", key, new Text(
" " + calculateMedian(houseRangeMap, houseRanges.getRanges(), totalOwnedHomes)));
multipleOutputs.write("question6", key, new Text(
" " + calculateMedian(rentRangeMap, rentRanges.getRanges(), totalRenters)));
multipleOutputs.write("question9", key, new Text(
calculatePercentage(urbanPopulation, population) + ":" +
calculatePercentage(ruralPopulation, population) +
":" + calculatePercentage(childrenUnder1To11, population) +
":" + calculatePercentage(children12To17, population) +
":" + calculatePercentage(hispanicChildrenUnder1To11, population) +
":" + calculatePercentage(hispanicChildren12To17, population)));
stateWithMostElderlyPeople(elderlyMap);
}
/**
* Close multiple outputs, otherwise the results might not be written to output files.
* Also writes questions 7 and 8 because the answer only contains one data point instead of one
* for each state.
* @param context MapReduce context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
//question 7 and 8 written here so only one value's output
multipleOutputs.write("question7", "", new Text(calculateNinetyFifthPercentile(averageList) +
averageList + " rooms"));
multipleOutputs.write("question8", mostElderlyState, new Text(
" " + currentMax + "%"));
super.cleanup(context);
multipleOutputs.close();
}
/**
* Calculate percentage, ignores answer if impossible number is calculated (VI and PR
* generally cause this)
* @param numerator
* @param denominator
* @return
*/
private String calculatePercentage(double numerator, double denominator) {
DecimalFormat decimalFormat = new DecimalFormat("##.00");
double percentage = (numerator / denominator) * 100;
if (Double.isInfinite(percentage) || percentage > 100 || percentage < 0) {
return "N/A";
} else {
return decimalFormat.format(percentage);
}
}
/**
* Calculates median, returns N/A if no iterations were performed (no data was collected).
* The current count is tracked because this is calculating the median from ranges, not from
* each data point.
* @param map map of ranges (key) and quantity per range (value)
* @param dataArray array of ranges
* @param totalNumber total number of the variable that's being examined (home values or rent ranges)
* @return answer
*/
private String calculateMedian(Map<Integer, Double> map, String[] dataArray, double totalNumber) {
int currentCount = 0;
int iterations = 0;
double dividingPoint = totalNumber * 0.50;
for (Integer key : map.keySet()) {
currentCount += map.get(key);
iterations++;
if (currentCount > dividingPoint) {
break;
}
}
String relevantRange = "N/A";
if (iterations != 0) {
relevantRange = dataArray[iterations - 1];
}
//debug
// String test = "";
// test += iterations + ":" + dividingPoint + ":" + totalNumber + "\n" + map.values().toString() + "\n";
// for (Integer key : map.keySet()) {
// test += "[";
// test += key.toString() + ", ";
// test += map.get(key) + "]\n";
// }
// test +=<SUF>
return relevantRange;
}
private double calculateAverageRooms(Double[] rooms, double totalHouses) {
double actualRoomQuantity = 0;
for (int i = 0; i < 9; i++) {
actualRoomQuantity += rooms[i];
}
return actualRoomQuantity / totalHouses;
}
/**
* Checks if the percentage of elderly population in the state is the most compared to all other
* states analyzed so far.
* @param stateElderlyMap Map of states' elderly population percentages
*/
private void stateWithMostElderlyPeople(Map<Text, Double> stateElderlyMap) {
for (Text state : stateElderlyMap.keySet()) {
if (stateElderlyMap.get(state) > currentMax) {
currentMax = stateElderlyMap.get(state);
mostElderlyState.set(state);
}
}
}
/**
* Calculates 95th percentile of the given list. If the result of list * .95 divides evenly,
* that number is the 95th percentile. Otherwise, the next result is in the 95th percentile.
* @param list list to calculate 95th percentile from
* @return
*/
private String calculateNinetyFifthPercentile(List<Double> list) {
Collections.sort(list);
BigDecimal ninetyFifthPercentile = null;
double rawPercentile = list.size() * 0.95;
if (rawPercentile % 1 == 0) {
ninetyFifthPercentile = new BigDecimal(rawPercentile).setScale(0);
}
if (rawPercentile % 1 != 0) {
ninetyFifthPercentile = new BigDecimal(rawPercentile).setScale(0, BigDecimal.ROUND_UP);
}
int ninetyFifthPercentilePosition = ninetyFifthPercentile.intValueExact();
double ninetyFifthPercentileNumber = list.get(ninetyFifthPercentilePosition - 1);
String answer = Double.toString(ninetyFifthPercentileNumber);
// debug
// String test = "";
// test += ninetyFifthPercentile + ":" + ninetyFifthPercentilePosition + "\n" + list.toString() + "\n";
// test += list.size() + "\n";
// test += "***" + ninetyFifthPercentileNumber + "***";
return answer;
}
} |
134617_12 | /*
* Copyright (c) 2023, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Author: Eddie Hung, Advanced Micro Devices, Inc.
*
* This file is part of RapidWright.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xilinx.rapidwright.rwroute;
import com.xilinx.rapidwright.device.IntentCode;
import com.xilinx.rapidwright.device.Node;
import com.xilinx.rapidwright.device.Tile;
import com.xilinx.rapidwright.device.TileTypeEnum;
import com.xilinx.rapidwright.device.Wire;
import com.xilinx.rapidwright.util.Utils;
public class RouteNodeInfo {
public final RouteNodeType type;
public final short endTileXCoordinate;
public final short endTileYCoordinate;
public final short length;
private RouteNodeInfo(RouteNodeType type,
short endTileXCoordinate,
short endTileYCoordinate,
short length) {
this.type = type;
this.endTileXCoordinate = endTileXCoordinate;
this.endTileYCoordinate = endTileYCoordinate;
this.length = length;
}
public static RouteNodeInfo get(Node node) {
Wire[] wires = node.getAllWiresInNode();
Tile baseTile = node.getTile();
TileTypeEnum baseType = baseTile.getTileTypeEnum();
Tile endTile = null;
boolean pinfeedIntoLaguna = false;
for (Wire w : wires) {
Tile tile = w.getTile();
TileTypeEnum tileType = tile.getTileTypeEnum();
boolean lagunaTile = false;
if (tileType == TileTypeEnum.INT ||
(lagunaTile = Utils.isLaguna(tileType))) {
if (!lagunaTile ||
// Only consider a Laguna tile as an end tile if base tile is Laguna too
// (otherwise it's a PINFEED into a Laguna)
Utils.isLaguna(baseType)) {
boolean endTileWasNotNull = (endTile != null);
endTile = tile;
// Break if this is the second INT tile
if (endTileWasNotNull) break;
} else {
assert(!Utils.isLaguna(baseType));
pinfeedIntoLaguna = (node.getIntentCode() == IntentCode.NODE_PINFEED);
}
}
}
if (endTile == null) {
endTile = node.getTile();
}
RouteNodeType type = getType(node, endTile, pinfeedIntoLaguna);
short endTileXCoordinate = getEndTileXCoordinate(node, type, (short) endTile.getTileXCoordinate());
short endTileYCoordinate = (short) endTile.getTileYCoordinate();
short length = getLength(baseTile, type, endTileXCoordinate, endTileYCoordinate);
return new RouteNodeInfo(type, endTileXCoordinate, endTileYCoordinate, length);
}
private static short getLength(Tile baseTile, RouteNodeType type, short endTileXCoordinate, short endTileYCoordinate) {
TileTypeEnum tileType = baseTile.getTileTypeEnum();
short length = (short) Math.abs(endTileYCoordinate - baseTile.getTileYCoordinate());
if (tileType == TileTypeEnum.LAG_LAG) {
// Nodes in LAGUNA tiles must have no X distance
assert(baseTile.getTileXCoordinate() == endTileXCoordinate - 1);
} else {
length += Math.abs(endTileXCoordinate - baseTile.getTileXCoordinate());
}
switch (tileType) {
case LAG_LAG:
case LAGUNA_TILE:
if (type == RouteNodeType.SUPER_LONG_LINE) {
assert(length == RouteNodeGraph.SUPER_LONG_LINE_LENGTH_IN_TILES);
} else {
assert(length == 0);
}
break;
case INT:
if (type == RouteNodeType.LAGUNA_I) {
assert(length == 0);
}
break;
}
return length;
}
private static short getEndTileXCoordinate(Node node, RouteNodeType type, short endTileXCoordinate) {
Tile baseTile = node.getTile();
TileTypeEnum baseType = baseTile.getTileTypeEnum();
switch (baseType) {
case LAG_LAG: // UltraScale+ only
// Correct the X coordinate of all Laguna nodes since they are accessed by the INT
// tile to its right, yet the LAG tile has a tile X coordinate one less than this.
// Do not apply this correction for NODE_LAGUNA_OUTPUT nodes (which the fanin and
// fanout nodes of the SLL are marked as) unless it is a fanin (LAGUNA_I)
// (i.e. do not apply it to the fanout nodes).
// Nor apply it to VCC_WIREs since their end tiles are INT tiles.
if ((node.getIntentCode() != IntentCode.NODE_LAGUNA_OUTPUT || type == RouteNodeType.LAGUNA_I) &&
!node.isTiedToVcc()) {
assert(baseTile.getTileXCoordinate() == endTileXCoordinate);
endTileXCoordinate++;
}
break;
case LAGUNA_TILE: // UltraScale only
// In UltraScale, Laguna tiles have the same X as the base INT tile
assert(baseTile.getTileXCoordinate() == endTileXCoordinate);
break;
}
return endTileXCoordinate;
}
private static RouteNodeType getType(Node node, Tile endTile, boolean pinfeedIntoLaguna) {
// NOTE: IntentCode is device-dependent
IntentCode ic = node.getIntentCode();
switch (ic) {
case NODE_PINBOUNCE:
return RouteNodeType.PINBOUNCE;
case NODE_PINFEED:
return pinfeedIntoLaguna ? RouteNodeType.LAGUNA_I : RouteNodeType.PINFEED_I;
case NODE_LAGUNA_OUTPUT: // UltraScale+ only
assert(node.getTile().getTileTypeEnum() == TileTypeEnum.LAG_LAG);
if (node.getWireName().endsWith("_TXOUT")) {
return RouteNodeType.LAGUNA_I;
}
break;
case NODE_LAGUNA_DATA: // UltraScale+ only
assert(node.getTile().getTileTypeEnum() == TileTypeEnum.LAG_LAG);
if (node.getTile() != endTile) {
return RouteNodeType.SUPER_LONG_LINE;
}
// U-turn node at the boundary of the device
break;
case INTENT_DEFAULT:
if (node.getTile().getTileTypeEnum() == TileTypeEnum.LAGUNA_TILE) { // UltraScale only
String wireName = node.getWireName();
if (wireName.startsWith("UBUMP")) {
assert(node.getTile() != endTile);
return RouteNodeType.SUPER_LONG_LINE;
} else if (wireName.endsWith("_TXOUT")) {
// This is the inner LAGUNA_I, mark it so it gets a base cost discount
return RouteNodeType.LAGUNA_I;
}
}
break;
}
return RouteNodeType.WIRE;
}
}
| nmavuso/RapidWright | src/com/xilinx/rapidwright/rwroute/RouteNodeInfo.java | 2,158 | // NOTE: IntentCode is device-dependent | line_comment | nl | /*
* Copyright (c) 2023, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Author: Eddie Hung, Advanced Micro Devices, Inc.
*
* This file is part of RapidWright.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xilinx.rapidwright.rwroute;
import com.xilinx.rapidwright.device.IntentCode;
import com.xilinx.rapidwright.device.Node;
import com.xilinx.rapidwright.device.Tile;
import com.xilinx.rapidwright.device.TileTypeEnum;
import com.xilinx.rapidwright.device.Wire;
import com.xilinx.rapidwright.util.Utils;
public class RouteNodeInfo {
public final RouteNodeType type;
public final short endTileXCoordinate;
public final short endTileYCoordinate;
public final short length;
private RouteNodeInfo(RouteNodeType type,
short endTileXCoordinate,
short endTileYCoordinate,
short length) {
this.type = type;
this.endTileXCoordinate = endTileXCoordinate;
this.endTileYCoordinate = endTileYCoordinate;
this.length = length;
}
public static RouteNodeInfo get(Node node) {
Wire[] wires = node.getAllWiresInNode();
Tile baseTile = node.getTile();
TileTypeEnum baseType = baseTile.getTileTypeEnum();
Tile endTile = null;
boolean pinfeedIntoLaguna = false;
for (Wire w : wires) {
Tile tile = w.getTile();
TileTypeEnum tileType = tile.getTileTypeEnum();
boolean lagunaTile = false;
if (tileType == TileTypeEnum.INT ||
(lagunaTile = Utils.isLaguna(tileType))) {
if (!lagunaTile ||
// Only consider a Laguna tile as an end tile if base tile is Laguna too
// (otherwise it's a PINFEED into a Laguna)
Utils.isLaguna(baseType)) {
boolean endTileWasNotNull = (endTile != null);
endTile = tile;
// Break if this is the second INT tile
if (endTileWasNotNull) break;
} else {
assert(!Utils.isLaguna(baseType));
pinfeedIntoLaguna = (node.getIntentCode() == IntentCode.NODE_PINFEED);
}
}
}
if (endTile == null) {
endTile = node.getTile();
}
RouteNodeType type = getType(node, endTile, pinfeedIntoLaguna);
short endTileXCoordinate = getEndTileXCoordinate(node, type, (short) endTile.getTileXCoordinate());
short endTileYCoordinate = (short) endTile.getTileYCoordinate();
short length = getLength(baseTile, type, endTileXCoordinate, endTileYCoordinate);
return new RouteNodeInfo(type, endTileXCoordinate, endTileYCoordinate, length);
}
private static short getLength(Tile baseTile, RouteNodeType type, short endTileXCoordinate, short endTileYCoordinate) {
TileTypeEnum tileType = baseTile.getTileTypeEnum();
short length = (short) Math.abs(endTileYCoordinate - baseTile.getTileYCoordinate());
if (tileType == TileTypeEnum.LAG_LAG) {
// Nodes in LAGUNA tiles must have no X distance
assert(baseTile.getTileXCoordinate() == endTileXCoordinate - 1);
} else {
length += Math.abs(endTileXCoordinate - baseTile.getTileXCoordinate());
}
switch (tileType) {
case LAG_LAG:
case LAGUNA_TILE:
if (type == RouteNodeType.SUPER_LONG_LINE) {
assert(length == RouteNodeGraph.SUPER_LONG_LINE_LENGTH_IN_TILES);
} else {
assert(length == 0);
}
break;
case INT:
if (type == RouteNodeType.LAGUNA_I) {
assert(length == 0);
}
break;
}
return length;
}
private static short getEndTileXCoordinate(Node node, RouteNodeType type, short endTileXCoordinate) {
Tile baseTile = node.getTile();
TileTypeEnum baseType = baseTile.getTileTypeEnum();
switch (baseType) {
case LAG_LAG: // UltraScale+ only
// Correct the X coordinate of all Laguna nodes since they are accessed by the INT
// tile to its right, yet the LAG tile has a tile X coordinate one less than this.
// Do not apply this correction for NODE_LAGUNA_OUTPUT nodes (which the fanin and
// fanout nodes of the SLL are marked as) unless it is a fanin (LAGUNA_I)
// (i.e. do not apply it to the fanout nodes).
// Nor apply it to VCC_WIREs since their end tiles are INT tiles.
if ((node.getIntentCode() != IntentCode.NODE_LAGUNA_OUTPUT || type == RouteNodeType.LAGUNA_I) &&
!node.isTiedToVcc()) {
assert(baseTile.getTileXCoordinate() == endTileXCoordinate);
endTileXCoordinate++;
}
break;
case LAGUNA_TILE: // UltraScale only
// In UltraScale, Laguna tiles have the same X as the base INT tile
assert(baseTile.getTileXCoordinate() == endTileXCoordinate);
break;
}
return endTileXCoordinate;
}
private static RouteNodeType getType(Node node, Tile endTile, boolean pinfeedIntoLaguna) {
// NOTE: IntentCode<SUF>
IntentCode ic = node.getIntentCode();
switch (ic) {
case NODE_PINBOUNCE:
return RouteNodeType.PINBOUNCE;
case NODE_PINFEED:
return pinfeedIntoLaguna ? RouteNodeType.LAGUNA_I : RouteNodeType.PINFEED_I;
case NODE_LAGUNA_OUTPUT: // UltraScale+ only
assert(node.getTile().getTileTypeEnum() == TileTypeEnum.LAG_LAG);
if (node.getWireName().endsWith("_TXOUT")) {
return RouteNodeType.LAGUNA_I;
}
break;
case NODE_LAGUNA_DATA: // UltraScale+ only
assert(node.getTile().getTileTypeEnum() == TileTypeEnum.LAG_LAG);
if (node.getTile() != endTile) {
return RouteNodeType.SUPER_LONG_LINE;
}
// U-turn node at the boundary of the device
break;
case INTENT_DEFAULT:
if (node.getTile().getTileTypeEnum() == TileTypeEnum.LAGUNA_TILE) { // UltraScale only
String wireName = node.getWireName();
if (wireName.startsWith("UBUMP")) {
assert(node.getTile() != endTile);
return RouteNodeType.SUPER_LONG_LINE;
} else if (wireName.endsWith("_TXOUT")) {
// This is the inner LAGUNA_I, mark it so it gets a base cost discount
return RouteNodeType.LAGUNA_I;
}
}
break;
}
return RouteNodeType.WIRE;
}
}
|
28731_9 | package net.minecraft.src;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
public class GuiCreateWorld extends GuiScreen
{
private GuiScreen parentGuiScreen;
private GuiTextField textboxWorldName;
private GuiTextField textboxSeed;
private String folderName;
/** hardcore', 'creative' or 'survival */
private String gameMode;
private boolean field_73925_n;
private boolean field_73926_o;
private boolean field_73935_p;
private boolean field_73934_q;
private boolean field_73933_r;
private boolean createClicked;
/**
* True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown
*/
private boolean moreOptions;
/** The GUIButton that you click to change game modes. */
private GuiButton gameModeButton;
/**
* The GUIButton that you click to get to options like the seed when creating a world.
*/
private GuiButton moreWorldOptions;
/** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */
private GuiButton generateStructuresButton;
private GuiButton field_73938_x;
/**
* the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0
*/
private GuiButton worldTypeButton;
private GuiButton field_73936_z;
/** The first line of text describing the currently selected game mode. */
private String gameModeDescriptionLine1;
/** The second line of text describing the currently selected game mode. */
private String gameModeDescriptionLine2;
/** The current textboxSeed text */
private String seed;
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
private String localizedNewWorldText;
private int field_73916_E;
private static final String field_73917_F[] =
{
"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9"
};
public GuiCreateWorld(GuiScreen par1GuiScreen)
{
gameMode = "survival";
field_73925_n = true;
field_73926_o = false;
field_73935_p = false;
field_73934_q = false;
field_73933_r = false;
field_73916_E = 0;
parentGuiScreen = par1GuiScreen;
seed = "";
localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld");
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
textboxWorldName.updateCursorCounter();
textboxSeed.updateCursorCounter();
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
public void initGui()
{
StringTranslate stringtranslate = StringTranslate.getInstance();
Keyboard.enableRepeatEvents(true);
controlList.clear();
controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create")));
controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel")));
controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode")));
controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions")));
controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures")));
generateStructuresButton.drawButton = false;
controlList.add(field_73938_x = new GuiButton(7, width / 2 + 5, 136, 150, 20, stringtranslate.translateKey("selectWorld.bonusItems")));
field_73938_x.drawButton = false;
controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType")));
worldTypeButton.drawButton = false;
controlList.add(field_73936_z = new GuiButton(6, width / 2 - 155, 136, 150, 20, stringtranslate.translateKey("selectWorld.allowCommands")));
field_73936_z.drawButton = false;
textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20);
textboxWorldName.setFocused(true);
textboxWorldName.setText(localizedNewWorldText);
textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20);
textboxSeed.setText(seed);
makeUseableName();
func_73914_h();
}
/**
* Makes a the name for a world save folder based on your world name, replacing specific characters for _s and
* appending -s to the end until a free name is available.
*/
private void makeUseableName()
{
folderName = textboxWorldName.getText().trim();
char ac[] = ChatAllowedCharacters.allowedCharactersArray;
int i = ac.length;
for (int j = 0; j < i; j++)
{
char c = ac[j];
folderName = folderName.replace(c, '_');
}
if (MathHelper.stringNullOrLengthZero(folderName))
{
folderName = "World";
}
folderName = func_73913_a(mc.getSaveLoader(), folderName);
}
private void func_73914_h()
{
StringTranslate stringtranslate;
stringtranslate = StringTranslate.getInstance();
gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString();
gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString());
gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString());
generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString();
if (!(!field_73925_n))
{
generateStructuresButton.displayString += stringtranslate.translateKey("options.on");
}
else
{
generateStructuresButton.displayString += stringtranslate.translateKey("options.off");
}
field_73938_x.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.bonusItems")).append(" ").toString();
if (!(!field_73934_q || field_73933_r))
{
field_73938_x.displayString += stringtranslate.translateKey("options.on");
}
else
{
field_73938_x.displayString += stringtranslate.translateKey("options.off");
}
worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_73916_E].getTranslateName())).toString();
field_73936_z.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.allowCommands")).append(" ").toString();
if (!(!field_73926_o || field_73933_r))
{
field_73936_z.displayString += stringtranslate.translateKey("options.on");
}
else
{
field_73936_z.displayString += stringtranslate.translateKey("options.off");
}
}
public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str)
{
par1Str = par1Str.replaceAll("[\\./\"]", "_");
String as[] = field_73917_F;
int i = as.length;
for (int j = 0; j < i; j++)
{
String s = as[j];
if (par1Str.equalsIgnoreCase(s))
{
par1Str = (new StringBuilder()).append("_").append(par1Str).append("_").toString();
}
}
for (; par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { }
return par1Str;
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton)
{
if (!par1GuiButton.enabled)
{
return;
}
if (par1GuiButton.id == 1)
{
mc.displayGuiScreen(parentGuiScreen);
}
else if (par1GuiButton.id == 0)
{
mc.displayGuiScreen(null);
if (createClicked)
{
return;
}
createClicked = true;
long l = (new Random()).nextLong();
String s = textboxSeed.getText();
if (!MathHelper.stringNullOrLengthZero(s))
{
try
{
long l1 = Long.parseLong(s);
if (l1 != 0L)
{
l = l1;
}
}
catch (NumberFormatException numberformatexception)
{
l = s.hashCode();
}
}
EnumGameType enumgametype = EnumGameType.func_77142_a(gameMode);
WorldSettings worldsettings = new WorldSettings(l, enumgametype, field_73925_n, field_73933_r, WorldType.worldTypes[field_73916_E]);
if (field_73934_q && !field_73933_r)
{
worldsettings.func_77159_a();
}
if (field_73926_o && !field_73933_r)
{
worldsettings.func_77166_b();
}
mc.func_71371_a(folderName, textboxWorldName.getText().trim(), worldsettings);
}
else if (par1GuiButton.id == 3)
{
moreOptions = !moreOptions;
gameModeButton.drawButton = !moreOptions;
generateStructuresButton.drawButton = moreOptions;
field_73938_x.drawButton = moreOptions;
worldTypeButton.drawButton = moreOptions;
field_73936_z.drawButton = moreOptions;
if (moreOptions)
{
StringTranslate stringtranslate = StringTranslate.getInstance();
moreWorldOptions.displayString = stringtranslate.translateKey("gui.done");
}
else
{
StringTranslate stringtranslate1 = StringTranslate.getInstance();
moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions");
}
}
else if (par1GuiButton.id == 2)
{
if (gameMode.equals("survival"))
{
if (!field_73935_p)
{
field_73926_o = false;
}
field_73933_r = false;
gameMode = "hardcore";
field_73933_r = true;
field_73936_z.enabled = false;
field_73938_x.enabled = false;
func_73914_h();
}
else if (gameMode.equals("hardcore"))
{
if (!field_73935_p)
{
field_73926_o = true;
}
field_73933_r = false;
gameMode = "creative";
func_73914_h();
field_73933_r = false;
field_73936_z.enabled = true;
field_73938_x.enabled = true;
}
else
{
if (!field_73935_p)
{
field_73926_o = false;
}
gameMode = "survival";
func_73914_h();
field_73936_z.enabled = true;
field_73938_x.enabled = true;
field_73933_r = false;
}
func_73914_h();
}
else if (par1GuiButton.id == 4)
{
field_73925_n = !field_73925_n;
func_73914_h();
}
else if (par1GuiButton.id == 7)
{
field_73934_q = !field_73934_q;
func_73914_h();
}
else if (par1GuiButton.id == 5)
{
field_73916_E++;
if (field_73916_E >= WorldType.worldTypes.length)
{
field_73916_E = 0;
}
do
{
if (WorldType.worldTypes[field_73916_E] != null && WorldType.worldTypes[field_73916_E].getCanBeCreated())
{
break;
}
field_73916_E++;
if (field_73916_E >= WorldType.worldTypes.length)
{
field_73916_E = 0;
}
}
while (true);
func_73914_h();
}
else if (par1GuiButton.id == 6)
{
field_73935_p = true;
field_73926_o = !field_73926_o;
func_73914_h();
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char par1, int par2)
{
if (textboxWorldName.isFocused() && !moreOptions)
{
textboxWorldName.textboxKeyTyped(par1, par2);
localizedNewWorldText = textboxWorldName.getText();
}
else if (textboxSeed.isFocused() && moreOptions)
{
textboxSeed.textboxKeyTyped(par1, par2);
seed = textboxSeed.getText();
}
if (par1 == '\r')
{
actionPerformed((GuiButton)controlList.get(0));
}
((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0;
makeUseableName();
}
/**
* Called when the mouse is clicked.
*/
protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
if (moreOptions)
{
textboxSeed.mouseClicked(par1, par2, par3);
}
else
{
textboxWorldName.mouseClicked(par1, par2, par3);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3)
{
StringTranslate stringtranslate = StringTranslate.getInstance();
drawDefaultBackground();
drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff);
if (moreOptions)
{
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.allowCommands.info"), width / 2 - 150, 157, 0xa0a0a0);
textboxSeed.drawTextBox();
}
else
{
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0);
drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0);
textboxWorldName.drawTextBox();
drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0);
drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0);
}
super.drawScreen(par1, par2, par3);
}
}
| nmg43/mcp70-src | src/minecraft/net/minecraft/src/GuiCreateWorld.java | 4,792 | /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ | block_comment | nl | package net.minecraft.src;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
public class GuiCreateWorld extends GuiScreen
{
private GuiScreen parentGuiScreen;
private GuiTextField textboxWorldName;
private GuiTextField textboxSeed;
private String folderName;
/** hardcore', 'creative' or 'survival */
private String gameMode;
private boolean field_73925_n;
private boolean field_73926_o;
private boolean field_73935_p;
private boolean field_73934_q;
private boolean field_73933_r;
private boolean createClicked;
/**
* True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown
*/
private boolean moreOptions;
/** The GUIButton that you click to change game modes. */
private GuiButton gameModeButton;
/**
* The GUIButton that you click to get to options like the seed when creating a world.
*/
private GuiButton moreWorldOptions;
/** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */
private GuiButton generateStructuresButton;
private GuiButton field_73938_x;
/**
* the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0
*/
private GuiButton worldTypeButton;
private GuiButton field_73936_z;
/** The first line of text describing the currently selected game mode. */
private String gameModeDescriptionLine1;
/** The second line of text describing the currently selected game mode. */
private String gameModeDescriptionLine2;
/** The current textboxSeed text */
private String seed;
/** E.g. New World,<SUF>*/
private String localizedNewWorldText;
private int field_73916_E;
private static final String field_73917_F[] =
{
"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9"
};
public GuiCreateWorld(GuiScreen par1GuiScreen)
{
gameMode = "survival";
field_73925_n = true;
field_73926_o = false;
field_73935_p = false;
field_73934_q = false;
field_73933_r = false;
field_73916_E = 0;
parentGuiScreen = par1GuiScreen;
seed = "";
localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld");
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
textboxWorldName.updateCursorCounter();
textboxSeed.updateCursorCounter();
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
public void initGui()
{
StringTranslate stringtranslate = StringTranslate.getInstance();
Keyboard.enableRepeatEvents(true);
controlList.clear();
controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create")));
controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel")));
controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode")));
controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions")));
controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures")));
generateStructuresButton.drawButton = false;
controlList.add(field_73938_x = new GuiButton(7, width / 2 + 5, 136, 150, 20, stringtranslate.translateKey("selectWorld.bonusItems")));
field_73938_x.drawButton = false;
controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType")));
worldTypeButton.drawButton = false;
controlList.add(field_73936_z = new GuiButton(6, width / 2 - 155, 136, 150, 20, stringtranslate.translateKey("selectWorld.allowCommands")));
field_73936_z.drawButton = false;
textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20);
textboxWorldName.setFocused(true);
textboxWorldName.setText(localizedNewWorldText);
textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20);
textboxSeed.setText(seed);
makeUseableName();
func_73914_h();
}
/**
* Makes a the name for a world save folder based on your world name, replacing specific characters for _s and
* appending -s to the end until a free name is available.
*/
private void makeUseableName()
{
folderName = textboxWorldName.getText().trim();
char ac[] = ChatAllowedCharacters.allowedCharactersArray;
int i = ac.length;
for (int j = 0; j < i; j++)
{
char c = ac[j];
folderName = folderName.replace(c, '_');
}
if (MathHelper.stringNullOrLengthZero(folderName))
{
folderName = "World";
}
folderName = func_73913_a(mc.getSaveLoader(), folderName);
}
private void func_73914_h()
{
StringTranslate stringtranslate;
stringtranslate = StringTranslate.getInstance();
gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString();
gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString());
gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString());
generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString();
if (!(!field_73925_n))
{
generateStructuresButton.displayString += stringtranslate.translateKey("options.on");
}
else
{
generateStructuresButton.displayString += stringtranslate.translateKey("options.off");
}
field_73938_x.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.bonusItems")).append(" ").toString();
if (!(!field_73934_q || field_73933_r))
{
field_73938_x.displayString += stringtranslate.translateKey("options.on");
}
else
{
field_73938_x.displayString += stringtranslate.translateKey("options.off");
}
worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_73916_E].getTranslateName())).toString();
field_73936_z.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.allowCommands")).append(" ").toString();
if (!(!field_73926_o || field_73933_r))
{
field_73936_z.displayString += stringtranslate.translateKey("options.on");
}
else
{
field_73936_z.displayString += stringtranslate.translateKey("options.off");
}
}
public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str)
{
par1Str = par1Str.replaceAll("[\\./\"]", "_");
String as[] = field_73917_F;
int i = as.length;
for (int j = 0; j < i; j++)
{
String s = as[j];
if (par1Str.equalsIgnoreCase(s))
{
par1Str = (new StringBuilder()).append("_").append(par1Str).append("_").toString();
}
}
for (; par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { }
return par1Str;
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton)
{
if (!par1GuiButton.enabled)
{
return;
}
if (par1GuiButton.id == 1)
{
mc.displayGuiScreen(parentGuiScreen);
}
else if (par1GuiButton.id == 0)
{
mc.displayGuiScreen(null);
if (createClicked)
{
return;
}
createClicked = true;
long l = (new Random()).nextLong();
String s = textboxSeed.getText();
if (!MathHelper.stringNullOrLengthZero(s))
{
try
{
long l1 = Long.parseLong(s);
if (l1 != 0L)
{
l = l1;
}
}
catch (NumberFormatException numberformatexception)
{
l = s.hashCode();
}
}
EnumGameType enumgametype = EnumGameType.func_77142_a(gameMode);
WorldSettings worldsettings = new WorldSettings(l, enumgametype, field_73925_n, field_73933_r, WorldType.worldTypes[field_73916_E]);
if (field_73934_q && !field_73933_r)
{
worldsettings.func_77159_a();
}
if (field_73926_o && !field_73933_r)
{
worldsettings.func_77166_b();
}
mc.func_71371_a(folderName, textboxWorldName.getText().trim(), worldsettings);
}
else if (par1GuiButton.id == 3)
{
moreOptions = !moreOptions;
gameModeButton.drawButton = !moreOptions;
generateStructuresButton.drawButton = moreOptions;
field_73938_x.drawButton = moreOptions;
worldTypeButton.drawButton = moreOptions;
field_73936_z.drawButton = moreOptions;
if (moreOptions)
{
StringTranslate stringtranslate = StringTranslate.getInstance();
moreWorldOptions.displayString = stringtranslate.translateKey("gui.done");
}
else
{
StringTranslate stringtranslate1 = StringTranslate.getInstance();
moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions");
}
}
else if (par1GuiButton.id == 2)
{
if (gameMode.equals("survival"))
{
if (!field_73935_p)
{
field_73926_o = false;
}
field_73933_r = false;
gameMode = "hardcore";
field_73933_r = true;
field_73936_z.enabled = false;
field_73938_x.enabled = false;
func_73914_h();
}
else if (gameMode.equals("hardcore"))
{
if (!field_73935_p)
{
field_73926_o = true;
}
field_73933_r = false;
gameMode = "creative";
func_73914_h();
field_73933_r = false;
field_73936_z.enabled = true;
field_73938_x.enabled = true;
}
else
{
if (!field_73935_p)
{
field_73926_o = false;
}
gameMode = "survival";
func_73914_h();
field_73936_z.enabled = true;
field_73938_x.enabled = true;
field_73933_r = false;
}
func_73914_h();
}
else if (par1GuiButton.id == 4)
{
field_73925_n = !field_73925_n;
func_73914_h();
}
else if (par1GuiButton.id == 7)
{
field_73934_q = !field_73934_q;
func_73914_h();
}
else if (par1GuiButton.id == 5)
{
field_73916_E++;
if (field_73916_E >= WorldType.worldTypes.length)
{
field_73916_E = 0;
}
do
{
if (WorldType.worldTypes[field_73916_E] != null && WorldType.worldTypes[field_73916_E].getCanBeCreated())
{
break;
}
field_73916_E++;
if (field_73916_E >= WorldType.worldTypes.length)
{
field_73916_E = 0;
}
}
while (true);
func_73914_h();
}
else if (par1GuiButton.id == 6)
{
field_73935_p = true;
field_73926_o = !field_73926_o;
func_73914_h();
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char par1, int par2)
{
if (textboxWorldName.isFocused() && !moreOptions)
{
textboxWorldName.textboxKeyTyped(par1, par2);
localizedNewWorldText = textboxWorldName.getText();
}
else if (textboxSeed.isFocused() && moreOptions)
{
textboxSeed.textboxKeyTyped(par1, par2);
seed = textboxSeed.getText();
}
if (par1 == '\r')
{
actionPerformed((GuiButton)controlList.get(0));
}
((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0;
makeUseableName();
}
/**
* Called when the mouse is clicked.
*/
protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
if (moreOptions)
{
textboxSeed.mouseClicked(par1, par2, par3);
}
else
{
textboxWorldName.mouseClicked(par1, par2, par3);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3)
{
StringTranslate stringtranslate = StringTranslate.getInstance();
drawDefaultBackground();
drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff);
if (moreOptions)
{
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0);
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.allowCommands.info"), width / 2 - 150, 157, 0xa0a0a0);
textboxSeed.drawTextBox();
}
else
{
drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0);
drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0);
textboxWorldName.drawTextBox();
drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0);
drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0);
}
super.drawScreen(par1, par2, par3);
}
}
|
36183_8 | package me.noahp78.travel;
import biweekly.Biweekly;
import biweekly.ICalVersion;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import biweekly.io.chain.ChainingTextStringParser;
import biweekly.io.text.ICalWriter;
import biweekly.util.ICalDate;
import com.sun.net.httpserver.HttpServer;
import me.noahp78.travel.http.CacheServer;
import me.noahp78.travel.http.HTTPIcalServer;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalField;
import java.util.Calendar;
import java.util.Date;
import java.util.stream.Collectors;
/**
* Created by noahp on 23/jan/2017 for TravelApp
*/
public class TravelAppTest {
public static final String SERVICE = "http://webservices.ns.nl/ns-api-treinplanner?fromStation={from}&toStation={to}&dateTime={time}&Departure={dep}";
/**
* Hoeveel dagen kijken we vooruit?
*/
public static final int MAX_LOOK_AHEAD=5;
public static void main(String[] args) {
System.out.println("CurrentZone = " + ZoneId.systemDefault().toString());
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/ical", new HTTPIcalServer());
server.setExecutor(null); // creates a default executor
server.start();
}catch(Exception e){
e.printStackTrace();
}
}
public static String makeICALUK(String ROOSTER, String START_LOCATION, String END_LOCATION){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = cal.getTime();
try{
String rooster = NetUtil.sendGet(ROOSTER,true);
}catch(Exception e){
e.printStackTrace();
}
}
public static String makeICAL(String ROOSTER, String START_LOCATION, String END_LOCATION){
//Eerst lezen we het rooster in
//En maken we ons eigen "ICAL" bestand aan
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = cal.getTime();
try {
String rooster= NetUtil.sendGet(ROOSTER,true);
ChainingTextStringParser thing = Biweekly.parse(rooster);
ICalDate firstOfToday = null;
ICalDate lastOfToday = null;
ICalendar ical = new ICalendar();
int lookedahead= 0;
ical.setDescription("ReisPlanning gebaseerd op " + ROOSTER + " tussen " + START_LOCATION + " en " + END_LOCATION);
for(VEvent event : thing.first().getEvents()) {
if(event.getDateStart().getValue().getTime()< yesterday.getTime()){
continue;
}
//First error check if it isn't null
if (firstOfToday == null || lastOfToday == null) {
firstOfToday = (event.getDateStart().getValue());
lastOfToday = event.getDateEnd().getValue();
}
//check if we still are looking at today
if (event.getDateStart().getValue().getDay()== firstOfToday.getDay()) {
lastOfToday = event.getDateEnd().getValue();
//Check if this event is before the firstOfToday
if(event.getDateStart().getValue().toInstant().toEpochMilli() < firstOfToday.toInstant().toEpochMilli()){
firstOfToday = event.getDateStart().getValue();
System.out.println("Found a time where FirstOfToday was behind the current event");
}
} else {
//Heenreis
VEvent heenreis = new VEvent();
NSReis heen = plan(START_LOCATION,END_LOCATION,firstOfToday.toInstant(),"false");
heenreis.setDateStart(toDate(heen.vertrek),true);
heenreis.setDateEnd(toDate(heen.aankomst),true);
heenreis.setSummary("NS TreinReis van " + START_LOCATION + " naar " + END_LOCATION);
heenreis.setDescription("AUTOMATISCH GEPLAND DOOR JE PLANSERVICE\nDeze reis wordt gemaakt omdat je vandaag je eerst les hebt om " +firstOfToday);
ical.addEvent(heenreis);
VEvent terug = new VEvent();
NSReis terugreis = plan(END_LOCATION,START_LOCATION,lastOfToday.toInstant(),"true");
terug.setDateStart(toDate(terugreis.vertrek),true);
terug.setDateEnd(toDate(terugreis.aankomst),true);
terug.setSummary("NS TreinReis van " + END_LOCATION +" naar " + START_LOCATION);
terug.setDescription("AUTOMATISCH GEPLAND DOOR JE PLANSERVICE\nDeze reis wordt gemaakt omdat je vandaag je laatste les hebt om " +lastOfToday);
ical.addEvent(terug);
lookedahead++;
if(lookedahead > MAX_LOOK_AHEAD) {
break;
}else{
firstOfToday=event.getDateStart().getValue();
lastOfToday=event.getDateEnd().getValue();
}
}
}
File file = new File("reis.ical");
ical.addName("ReisPlanning voor rooster");
ical.setVersion(ICalVersion.V2_0);
ICalWriter writer = null;
ByteArrayOutputStream target =new ByteArrayOutputStream();
try {
writer = new ICalWriter(target, ICalVersion.V2_0);
writer.write(ical);
} finally {
if (writer != null) writer.close();
}
return target.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static Date toDate(LocalDateTime time){
Date in = new Date();
Date out = Date.from(time.atZone(ZoneId.of("Europe/Berlin")).toInstant());
return out;
}
public static NSReis plan(String from, String to, Instant instant, String dep){
String url = SERVICE.replace("{from}",from).replace("{to}",to).replace("{time}",instant.toString()).replace("{dep}",dep);
try{
String resp = sendAuthenticatedRequest(url,me.noahp78.travel.Config.NS_USER,me.noahp78.travel.Config.NS_PASS);
NSReis reis = vindtOptimaal(resp);
System.out.println("De beste reis vertrekt om " + reis.vertrek+ " en komt aan op " + reis.aankomst);
return reis;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
public static NSReis vindtOptimaal(String nsResponse) throws Exception{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream(
nsResponse.getBytes("UTF-8"));
Document doc = builder.parse(input);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
NodeList nList = doc.getElementsByTagName("ReisMogelijkheid");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE ) {
Element eElement = (Element) nNode;
String optimaal = eElement.getElementsByTagName("Optimaal").item(0).getTextContent();
if(optimaal.equalsIgnoreCase("true")){
//Vindt vertrek en aankomsttijd
String vertrek= eElement.getElementsByTagName("ActueleVertrekTijd").item(0).getTextContent();
String aankomst = eElement.getElementsByTagName("ActueleAankomstTijd").item(0).getTextContent();
System.out.println("VERTREK:" + vertrek + "\nAANKOMST:" + aankomst );
//Shitty hack todo find better way
vertrek = vertrek.replace("+0100","+01:00").replace("+0200","+02:00");
aankomst= aankomst.replace("+0100","+01:00").replace("+0200","+02:00");
LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
return new NSReis(localDate.parse(vertrek,formatter),localDate.parse(aankomst,formatter));
}
}
}
return null;
}
public static String sendAuthenticatedRequest(String url, String user, String pass)throws Exception{
if(CacheServer.haveAllowedNSCache(url)){
System.out.println("Saved NS API request because we have it cached.");
return CacheServer.getNSCachedItem(url);
}else{
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials(user, pass),
"UTF-8", false));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();
String resp = read(responseEntity.getContent());
CacheServer.saveNSRequest(url,resp);
return resp;
}
}
}
| noahp78/treinplanner | src/main/java/me/noahp78/travel/TravelAppTest.java | 2,973 | //Vindt vertrek en aankomsttijd | line_comment | nl | package me.noahp78.travel;
import biweekly.Biweekly;
import biweekly.ICalVersion;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import biweekly.io.chain.ChainingTextStringParser;
import biweekly.io.text.ICalWriter;
import biweekly.util.ICalDate;
import com.sun.net.httpserver.HttpServer;
import me.noahp78.travel.http.CacheServer;
import me.noahp78.travel.http.HTTPIcalServer;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalField;
import java.util.Calendar;
import java.util.Date;
import java.util.stream.Collectors;
/**
* Created by noahp on 23/jan/2017 for TravelApp
*/
public class TravelAppTest {
public static final String SERVICE = "http://webservices.ns.nl/ns-api-treinplanner?fromStation={from}&toStation={to}&dateTime={time}&Departure={dep}";
/**
* Hoeveel dagen kijken we vooruit?
*/
public static final int MAX_LOOK_AHEAD=5;
public static void main(String[] args) {
System.out.println("CurrentZone = " + ZoneId.systemDefault().toString());
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/ical", new HTTPIcalServer());
server.setExecutor(null); // creates a default executor
server.start();
}catch(Exception e){
e.printStackTrace();
}
}
public static String makeICALUK(String ROOSTER, String START_LOCATION, String END_LOCATION){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = cal.getTime();
try{
String rooster = NetUtil.sendGet(ROOSTER,true);
}catch(Exception e){
e.printStackTrace();
}
}
public static String makeICAL(String ROOSTER, String START_LOCATION, String END_LOCATION){
//Eerst lezen we het rooster in
//En maken we ons eigen "ICAL" bestand aan
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = cal.getTime();
try {
String rooster= NetUtil.sendGet(ROOSTER,true);
ChainingTextStringParser thing = Biweekly.parse(rooster);
ICalDate firstOfToday = null;
ICalDate lastOfToday = null;
ICalendar ical = new ICalendar();
int lookedahead= 0;
ical.setDescription("ReisPlanning gebaseerd op " + ROOSTER + " tussen " + START_LOCATION + " en " + END_LOCATION);
for(VEvent event : thing.first().getEvents()) {
if(event.getDateStart().getValue().getTime()< yesterday.getTime()){
continue;
}
//First error check if it isn't null
if (firstOfToday == null || lastOfToday == null) {
firstOfToday = (event.getDateStart().getValue());
lastOfToday = event.getDateEnd().getValue();
}
//check if we still are looking at today
if (event.getDateStart().getValue().getDay()== firstOfToday.getDay()) {
lastOfToday = event.getDateEnd().getValue();
//Check if this event is before the firstOfToday
if(event.getDateStart().getValue().toInstant().toEpochMilli() < firstOfToday.toInstant().toEpochMilli()){
firstOfToday = event.getDateStart().getValue();
System.out.println("Found a time where FirstOfToday was behind the current event");
}
} else {
//Heenreis
VEvent heenreis = new VEvent();
NSReis heen = plan(START_LOCATION,END_LOCATION,firstOfToday.toInstant(),"false");
heenreis.setDateStart(toDate(heen.vertrek),true);
heenreis.setDateEnd(toDate(heen.aankomst),true);
heenreis.setSummary("NS TreinReis van " + START_LOCATION + " naar " + END_LOCATION);
heenreis.setDescription("AUTOMATISCH GEPLAND DOOR JE PLANSERVICE\nDeze reis wordt gemaakt omdat je vandaag je eerst les hebt om " +firstOfToday);
ical.addEvent(heenreis);
VEvent terug = new VEvent();
NSReis terugreis = plan(END_LOCATION,START_LOCATION,lastOfToday.toInstant(),"true");
terug.setDateStart(toDate(terugreis.vertrek),true);
terug.setDateEnd(toDate(terugreis.aankomst),true);
terug.setSummary("NS TreinReis van " + END_LOCATION +" naar " + START_LOCATION);
terug.setDescription("AUTOMATISCH GEPLAND DOOR JE PLANSERVICE\nDeze reis wordt gemaakt omdat je vandaag je laatste les hebt om " +lastOfToday);
ical.addEvent(terug);
lookedahead++;
if(lookedahead > MAX_LOOK_AHEAD) {
break;
}else{
firstOfToday=event.getDateStart().getValue();
lastOfToday=event.getDateEnd().getValue();
}
}
}
File file = new File("reis.ical");
ical.addName("ReisPlanning voor rooster");
ical.setVersion(ICalVersion.V2_0);
ICalWriter writer = null;
ByteArrayOutputStream target =new ByteArrayOutputStream();
try {
writer = new ICalWriter(target, ICalVersion.V2_0);
writer.write(ical);
} finally {
if (writer != null) writer.close();
}
return target.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static Date toDate(LocalDateTime time){
Date in = new Date();
Date out = Date.from(time.atZone(ZoneId.of("Europe/Berlin")).toInstant());
return out;
}
public static NSReis plan(String from, String to, Instant instant, String dep){
String url = SERVICE.replace("{from}",from).replace("{to}",to).replace("{time}",instant.toString()).replace("{dep}",dep);
try{
String resp = sendAuthenticatedRequest(url,me.noahp78.travel.Config.NS_USER,me.noahp78.travel.Config.NS_PASS);
NSReis reis = vindtOptimaal(resp);
System.out.println("De beste reis vertrekt om " + reis.vertrek+ " en komt aan op " + reis.aankomst);
return reis;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
public static NSReis vindtOptimaal(String nsResponse) throws Exception{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream(
nsResponse.getBytes("UTF-8"));
Document doc = builder.parse(input);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
NodeList nList = doc.getElementsByTagName("ReisMogelijkheid");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE ) {
Element eElement = (Element) nNode;
String optimaal = eElement.getElementsByTagName("Optimaal").item(0).getTextContent();
if(optimaal.equalsIgnoreCase("true")){
//Vindt vertrek<SUF>
String vertrek= eElement.getElementsByTagName("ActueleVertrekTijd").item(0).getTextContent();
String aankomst = eElement.getElementsByTagName("ActueleAankomstTijd").item(0).getTextContent();
System.out.println("VERTREK:" + vertrek + "\nAANKOMST:" + aankomst );
//Shitty hack todo find better way
vertrek = vertrek.replace("+0100","+01:00").replace("+0200","+02:00");
aankomst= aankomst.replace("+0100","+01:00").replace("+0200","+02:00");
LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
return new NSReis(localDate.parse(vertrek,formatter),localDate.parse(aankomst,formatter));
}
}
}
return null;
}
public static String sendAuthenticatedRequest(String url, String user, String pass)throws Exception{
if(CacheServer.haveAllowedNSCache(url)){
System.out.println("Saved NS API request because we have it cached.");
return CacheServer.getNSCachedItem(url);
}else{
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials(user, pass),
"UTF-8", false));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();
String resp = read(responseEntity.getContent());
CacheServer.saveNSRequest(url,resp);
return resp;
}
}
}
|
96516_1 | package org.noear.solon.boot.websocket.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.noear.solon.boot.prop.impl.WebSocketServerProps;
import org.noear.solon.core.util.RunUtil;
import org.noear.solon.net.websocket.WebSocket;
import org.noear.solon.net.websocket.WebSocketRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
/**
* @author noear
* @since 2.3
*/
public class WsServerHandler extends SimpleChannelInboundHandler<Object> {
static final Logger log = LoggerFactory.getLogger(WsServerHandler.class);
public static final AttributeKey<String> ResourceDescriptorKey = AttributeKey.valueOf("ResourceDescriptor");
public static final AttributeKey<WebSocketServerHandshaker> HandshakerKey = AttributeKey.valueOf("Handshaker");
public static final AttributeKey<WebSocketImpl> SessionKey = AttributeKey.valueOf("Session");
static final WebSocketServerProps wsProps = WebSocketServerProps.getInstance();
private final WebSocketRouter webSocketRouter = WebSocketRouter.getInstance();
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//判断请求是HTTP请求还是WebSocket请求
if (msg instanceof FullHttpRequest) {
//处理WebSocket握手请求
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
//处理WebSocket请求
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
//先判断解码是否成功,然后判断是不是请求建立WebSocket连接
//如果HTTP解码失败,返回HTTP异常
if (!req.decoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
//生成 ResourceDescriptor
String url = "ws://" + req.headers().get(HttpHeaderNames.HOST) + req.uri();
//构造握手工厂创建握手处理类 WebSocketServerHandshaker,来构造握手响应返回给客户端
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(url, null, false);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
ctx.attr(HandshakerKey).set(handshaker);
ctx.attr(ResourceDescriptorKey).set(req.uri());
//listener.onOpen();
WebSocketImpl webSocket = new WebSocketImpl(ctx);
ctx.attr(SessionKey).set(webSocket);
webSocketRouter.getListener().onOpen(webSocket);
//设置闲置超时
if (wsProps.getIdleTimeout() > 0) {
webSocket.setIdleTimeout(wsProps.getIdleTimeout());
}
}
}
//如果接收到的消息是已经解码的WebSocketFrame消息
public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
//先对控制帧进行判断
//判断是否是关闭链路的指令
if (frame instanceof CloseWebSocketFrame) {
WebSocketServerHandshaker handshaker = ctx.attr(HandshakerKey).get();
if (handshaker != null) {
handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
}
return;
}
//判断是否是维持链路的Ping消息
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket != null) {
webSocket.onReceive();
}
webSocketRouter.getListener().onPing(webSocket);
return;
}
if (frame instanceof PongWebSocketFrame) {
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket != null) {
webSocket.onReceive();
}
webSocketRouter.getListener().onPong(webSocket);
return;
}
if (frame instanceof TextWebSocketFrame) {
//listener.onMessage();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
webSocket.onReceive();
String msgTxt = ((TextWebSocketFrame) frame).text();
webSocketRouter.getListener().onMessage(webSocket, msgTxt);
return;
}
if (frame instanceof BinaryWebSocketFrame) {
//listener.onMessage();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
webSocket.onReceive();
ByteBuffer msgBuf = frame.content().nioBuffer();
webSocketRouter.getListener().onMessage(webSocket, msgBuf);
return;
}
}
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse resp) {
if (resp.status().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);
resp.content().writeBytes(buf);
buf.release();
HttpUtil.setContentLength(resp, resp.content().readableBytes());
}
ChannelFuture f = ctx.channel().writeAndFlush(resp);
if (!HttpUtil.isKeepAlive(resp) || resp.status().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
/**
* 客户端掉线时的操作
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//listener.onClose();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket.isClosed()) {
return;
} else {
RunUtil.runAndTry(webSocket::close);
}
webSocketRouter.getListener().onClose(webSocket);
}
/**
* 发生异常时执行的操作
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//listener.onError();
try {
WebSocket webSocket = ctx.attr(SessionKey).get();
webSocketRouter.getListener().onError(webSocket, cause);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
}
RunUtil.runAndTry(ctx::close);
}
} | noear/solon | solon-projects/solon-boot/solon.boot.websocket.netty/src/main/java/org/noear/solon/boot/websocket/netty/WsServerHandler.java | 1,932 | //" + req.headers().get(HttpHeaderNames.HOST) + req.uri(); | line_comment | nl | package org.noear.solon.boot.websocket.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.noear.solon.boot.prop.impl.WebSocketServerProps;
import org.noear.solon.core.util.RunUtil;
import org.noear.solon.net.websocket.WebSocket;
import org.noear.solon.net.websocket.WebSocketRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
/**
* @author noear
* @since 2.3
*/
public class WsServerHandler extends SimpleChannelInboundHandler<Object> {
static final Logger log = LoggerFactory.getLogger(WsServerHandler.class);
public static final AttributeKey<String> ResourceDescriptorKey = AttributeKey.valueOf("ResourceDescriptor");
public static final AttributeKey<WebSocketServerHandshaker> HandshakerKey = AttributeKey.valueOf("Handshaker");
public static final AttributeKey<WebSocketImpl> SessionKey = AttributeKey.valueOf("Session");
static final WebSocketServerProps wsProps = WebSocketServerProps.getInstance();
private final WebSocketRouter webSocketRouter = WebSocketRouter.getInstance();
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//判断请求是HTTP请求还是WebSocket请求
if (msg instanceof FullHttpRequest) {
//处理WebSocket握手请求
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
//处理WebSocket请求
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
//先判断解码是否成功,然后判断是不是请求建立WebSocket连接
//如果HTTP解码失败,返回HTTP异常
if (!req.decoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
//生成 ResourceDescriptor
String url = "ws://" +<SUF>
//构造握手工厂创建握手处理类 WebSocketServerHandshaker,来构造握手响应返回给客户端
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(url, null, false);
WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
ctx.attr(HandshakerKey).set(handshaker);
ctx.attr(ResourceDescriptorKey).set(req.uri());
//listener.onOpen();
WebSocketImpl webSocket = new WebSocketImpl(ctx);
ctx.attr(SessionKey).set(webSocket);
webSocketRouter.getListener().onOpen(webSocket);
//设置闲置超时
if (wsProps.getIdleTimeout() > 0) {
webSocket.setIdleTimeout(wsProps.getIdleTimeout());
}
}
}
//如果接收到的消息是已经解码的WebSocketFrame消息
public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
//先对控制帧进行判断
//判断是否是关闭链路的指令
if (frame instanceof CloseWebSocketFrame) {
WebSocketServerHandshaker handshaker = ctx.attr(HandshakerKey).get();
if (handshaker != null) {
handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
}
return;
}
//判断是否是维持链路的Ping消息
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket != null) {
webSocket.onReceive();
}
webSocketRouter.getListener().onPing(webSocket);
return;
}
if (frame instanceof PongWebSocketFrame) {
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket != null) {
webSocket.onReceive();
}
webSocketRouter.getListener().onPong(webSocket);
return;
}
if (frame instanceof TextWebSocketFrame) {
//listener.onMessage();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
webSocket.onReceive();
String msgTxt = ((TextWebSocketFrame) frame).text();
webSocketRouter.getListener().onMessage(webSocket, msgTxt);
return;
}
if (frame instanceof BinaryWebSocketFrame) {
//listener.onMessage();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
webSocket.onReceive();
ByteBuffer msgBuf = frame.content().nioBuffer();
webSocketRouter.getListener().onMessage(webSocket, msgBuf);
return;
}
}
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse resp) {
if (resp.status().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);
resp.content().writeBytes(buf);
buf.release();
HttpUtil.setContentLength(resp, resp.content().readableBytes());
}
ChannelFuture f = ctx.channel().writeAndFlush(resp);
if (!HttpUtil.isKeepAlive(resp) || resp.status().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
/**
* 客户端掉线时的操作
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//listener.onClose();
WebSocketImpl webSocket = ctx.attr(SessionKey).get();
if (webSocket.isClosed()) {
return;
} else {
RunUtil.runAndTry(webSocket::close);
}
webSocketRouter.getListener().onClose(webSocket);
}
/**
* 发生异常时执行的操作
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//listener.onError();
try {
WebSocket webSocket = ctx.attr(SessionKey).get();
webSocketRouter.getListener().onError(webSocket, cause);
} catch (Throwable e) {
log.warn(e.getMessage(), e);
}
RunUtil.runAndTry(ctx::close);
}
} |
70282_23 |
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.TextAlignment;
public class Q3 extends MainCon {
public static Pane getpane3(){
// Create a pane and set its properties
Pane pane = new Pane();
//create main circle
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
//create first small circle
Circle sc1 = new Circle();
sc1.setCenterX(200);
sc1.setCenterY(100);
sc1.setRadius(10);
sc1.setStroke(Color.BLACK);
sc1.setFill(Color.RED);
//create second small circle
Circle sc2 = new Circle();
sc2.setCenterX(200);
sc2.setCenterY(300);
sc2.setRadius(10);
sc2.setStroke(Color.BLACK);
sc2.setFill(Color.RED);
//create third small circle
Circle sc3 = new Circle();
sc3.setCenterX(300);
sc3.setCenterY(200);
sc3.setRadius(10);
sc3.setStroke(Color.BLACK);
sc3.setFill(Color.RED);
//create lines in between circles that are marked (beginning circle)t(end circle)
Line line1t2 = new Line(200, 100, 200, 300);
Line line2t3 = new Line(200, 300, 300, 200);
Line line3t1 = new Line(300, 200, 200, 100);
//angle texts
Text angle1 = new Text(10,10,"0");
Text angle2 = new Text(10,10,"0");
Text angle3 = new Text(10,10,"0");
//add nodes to pane
pane.getChildren().addAll(circle,angle1,angle2,angle3,line1t2,line2t3,line3t1,sc1,sc2,sc3);
//
sc1.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines between points
line1t2.setStartX(x);
line1t2.setStartY(y);
line3t1.setEndX(x);
line3t1.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle1.setX(x-10);
angle1.setY(y-10);
//move circle
sc1.setCenterX(x);
sc1.setCenterY(y);
});
sc2.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines between points
line2t3.setStartX(x);
line2t3.setStartY(y);
line1t2.setEndX(x);
line1t2.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle2.setX(x-10);
angle2.setY(y-10);
//move circle
sc2.setCenterX(x);
sc2.setCenterY(y);
});
sc3.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines between points
line3t1.setStartX(x);
line3t1.setStartY(y);
line2t3.setEndX(x);
line2t3.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle3.setX(x-10);
angle3.setY(y-10);
//move circle
sc3.setCenterX(x);
sc3.setCenterY(y);
});
return pane;
}
public static void main(String[] args) {
launch(args);
}
public static double leng(Line l1){
//input is line and output is length using euclidean norm
double xd = (l1.getStartX()-l1.getEndX());
double yd = (l1.getStartY()-l1.getEndY());
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
return dnorm;
}
public static int[] angles(Line line1t2, Line line2t3, Line line3t1){
//input 3 lines, output is angle between lines in an array
int ang1 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line2t3),2)-Math.pow(leng(line3t1),2)-Math.pow(leng(line1t2),2))/(-2*leng(line3t1)*leng(line1t2)))));
int ang2 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line3t1),2)-Math.pow(leng(line2t3),2)-Math.pow(leng(line1t2),2))/(-2*leng(line2t3)*leng(line1t2)))));
int ang3 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line1t2),2)-Math.pow(leng(line3t1),2)-Math.pow(leng(line2t3),2))/(-2*leng(line2t3)*leng(line3t1)))));
return new int[] {ang1, ang2, ang3};
}
}
| nonpondo/Assignment1 | src/main/java/assignment/Q3.java | 2,337 | //move lines between points | line_comment | nl |
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.TextAlignment;
public class Q3 extends MainCon {
public static Pane getpane3(){
// Create a pane and set its properties
Pane pane = new Pane();
//create main circle
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
//create first small circle
Circle sc1 = new Circle();
sc1.setCenterX(200);
sc1.setCenterY(100);
sc1.setRadius(10);
sc1.setStroke(Color.BLACK);
sc1.setFill(Color.RED);
//create second small circle
Circle sc2 = new Circle();
sc2.setCenterX(200);
sc2.setCenterY(300);
sc2.setRadius(10);
sc2.setStroke(Color.BLACK);
sc2.setFill(Color.RED);
//create third small circle
Circle sc3 = new Circle();
sc3.setCenterX(300);
sc3.setCenterY(200);
sc3.setRadius(10);
sc3.setStroke(Color.BLACK);
sc3.setFill(Color.RED);
//create lines in between circles that are marked (beginning circle)t(end circle)
Line line1t2 = new Line(200, 100, 200, 300);
Line line2t3 = new Line(200, 300, 300, 200);
Line line3t1 = new Line(300, 200, 200, 100);
//angle texts
Text angle1 = new Text(10,10,"0");
Text angle2 = new Text(10,10,"0");
Text angle3 = new Text(10,10,"0");
//add nodes to pane
pane.getChildren().addAll(circle,angle1,angle2,angle3,line1t2,line2t3,line3t1,sc1,sc2,sc3);
//
sc1.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines between points
line1t2.setStartX(x);
line1t2.setStartY(y);
line3t1.setEndX(x);
line3t1.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle1.setX(x-10);
angle1.setY(y-10);
//move circle
sc1.setCenterX(x);
sc1.setCenterY(y);
});
sc2.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines between points
line2t3.setStartX(x);
line2t3.setStartY(y);
line1t2.setEndX(x);
line1t2.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle2.setX(x-10);
angle2.setY(y-10);
//move circle
sc2.setCenterX(x);
sc2.setCenterY(y);
});
sc3.setOnMouseDragged(e -> {
//get mouse co-ordinates relatie to origin
double xd = (e.getX()-200);
double yd = (e.getY()-200);
//get length of norm from origin to mouse co-ordinates using 2-norm
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
//calculate unit vector
double xu = xd/dnorm;
double yu = yd/dnorm;
//multiply unit vector by radius and offset to center of circle
int x = (int)(Math.floor(100*xu))+200;
int y = (int)(Math.floor(100*yu))+200;
//move lines<SUF>
line3t1.setStartX(x);
line3t1.setStartY(y);
line2t3.setEndX(x);
line2t3.setEndY(y);
//update angle nnumbers
int[] angs = angles(line1t2, line2t3, line3t1);
angle1.setText(String.valueOf(angs[0]));
angle2.setText(String.valueOf(angs[1]));
angle3.setText(String.valueOf(angs[2]));
angle3.setX(x-10);
angle3.setY(y-10);
//move circle
sc3.setCenterX(x);
sc3.setCenterY(y);
});
return pane;
}
public static void main(String[] args) {
launch(args);
}
public static double leng(Line l1){
//input is line and output is length using euclidean norm
double xd = (l1.getStartX()-l1.getEndX());
double yd = (l1.getStartY()-l1.getEndY());
double dnorm = Math.sqrt(Math.pow(xd,2)+Math.pow(yd,2));
return dnorm;
}
public static int[] angles(Line line1t2, Line line2t3, Line line3t1){
//input 3 lines, output is angle between lines in an array
int ang1 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line2t3),2)-Math.pow(leng(line3t1),2)-Math.pow(leng(line1t2),2))/(-2*leng(line3t1)*leng(line1t2)))));
int ang2 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line3t1),2)-Math.pow(leng(line2t3),2)-Math.pow(leng(line1t2),2))/(-2*leng(line2t3)*leng(line1t2)))));
int ang3 =(int)(Math.toDegrees(Math.acos((Math.pow(leng(line1t2),2)-Math.pow(leng(line3t1),2)-Math.pow(leng(line2t3),2))/(-2*leng(line2t3)*leng(line3t1)))));
return new int[] {ang1, ang2, ang3};
}
}
|
204926_1 | package edu.cmu.lti.algorithm.learning.gm;
import java.io.BufferedWriter;
import edu.cmu.lti.algorithm.container.VectorX;
import edu.cmu.lti.algorithm.container.VectorD;
import edu.cmu.lti.algorithm.container.VectorI;
import edu.cmu.lti.algorithm.container.VecVecI;
import edu.cmu.lti.algorithm.math.rand.FRand;
import edu.cmu.lti.util.file.FFile;
import edu.cmu.lti.util.html.EColor;
import edu.cmu.lti.util.system.FSystem;
/**
* this is the first draft, now it is bloated to a package
* @author nlao
*
*/
public class CRFB {
public static class Param extends edu.cmu.lti.util.run.Param{
private static final long serialVersionUID = 2008042701L; // YYYYMMDD
public Param(Class c) {
super(c);
parse();
}
public void parse(){
//m = getInt("m",5);
//eps = getDouble("eps",1e-5);
//lang = getString("lang");
//diagco=getBoolean("diagco", false);
}
}
public static enum EVType {
IN(0,EColor.azure)/*conditioned on*/
, OUT(1,EColor.lightskyblue)/*to be evaluated*/
, MID(2,EColor.rosybrown2);//hidden nodes
//really a nice place to put data!
public EColor color;
public int id;
EVType(int id, EColor color){
this.id = id;
this.color = color;
}
}
public static class Factor{
public int id;
public double w=0;
public int iV1,iV2;
//assume iV1<iV2, if iV1==-1 then it is a bias feature
public Factor(int id, int iV1, int iV2){
this.iV2= iV2;
this.iV1= iV1;
}
public String toString(){
return String.format("(%d,%d)%.1f",iV1,iV2,w);
}
public String print(){
return String.format("%d\t%d\t%.3f",iV1,iV2,w);
}
}
public static class Variable{
//public SetI mi= new SetI();
public VectorX<Factor> vf= new VectorX<Factor>(Factor.class);
//use reference to update it outside the model
//public Variable(SetI mia,SetI mid){ this.mia= mi; }
EVType type;
int id;
public Variable(int id, EVType type){
this.id = id;
//mia= new SetI();
//mid= new SetI();
this.type=type;
}
}
// variables
public VectorX<Variable> vVar= new VectorX<Variable>(Variable.class);
// factors
public VectorX<Factor> vFactor= new VectorX<Factor>(Factor.class);
// weights
//VectorD vW;
double[] x ;
// expectations//in log domain?
public VectorD vEVar=new VectorD();
public VectorD vEFa;
public VectorI viZ=new VectorI();
public VectorI viY=new VectorI();
public VectorI viH=new VectorI();
public VectorI viX=new VectorI();
public VectorI viA=new VectorI();
/*public void selectSubNet(VectorI viY, VectorI viH , VectorI viZ){
this.viH = viH;
this.viY = viY;
this.viX = viH; viX.addAll(viY);
this.viZ = viZ;
}*/
/**
* x={y,h},
* estimate p(x|z)
* @param viZ: ids of z variables
* @param viX: ids of x variables
*/
public void meanField(VectorI vi){
vEVar.extend(viA.size());
for (int iScan=0; iScan<5; ++iScan)
for (int ix : vi)
expectVar(ix);
}
private double expectVar(int id){
double e=0;
for (Factor fa: vVar.get(id).vf)
e+= expectFactor(id,fa);
//exp(e1)/(exp(e0)+exp(e1))=1/(1+exp(e0-e1))
double p=1/(1+Math.exp(-e));
vEVar.set(id, p);
return p;
}
private double expectFactor(int iVar, Factor fa){//int iF){
//= vFactor.get(iF);
if (fa.w==0) return 0.0;
double e=1;
if (fa.iV2!=iVar) e*=vEVar.get(fa.iV2);
if (fa.iV1>=0) if (fa.iV1!=iVar) e*=vEVar.get(fa.iV1);
return e*fa.w;
}
private double expectFactor(int id){
Factor fa= vFactor.get(id);
double e=vEVar.get(fa.iV2);
if (fa.iV1>=0) e*=vEVar.get(fa.iV1);
vEFa.set(id, e);
return e;
}
/**
* @param vY
* @return loss=-log(p(y|z))
*/
protected double getValue( VectorD vY){
double loss=0;
//for (int iy: viY)
for (int i=0; i<vY.size(); ++i){
if (vY.get(i)==1.0)
loss += -Math.log(vEVar.get(viY.get(i)));
else
loss += -Math.log(1-vEVar.get(viY.get(i)));
}
return 0;
}
//public void setData( VectorD vZ){ vEVar.set(viZ, vZ); }
public VectorD vX;
public VectorD vX_y;
public double loss=0;
public VectorD vG;
public Variable addVar(EVType type){
int id = vVar.size();
Variable var=new Variable(id,type);
vVar.add(var);
viA.add(id);
switch(type){
case OUT: viY.add(id);viX.add(id);break;
case MID: viH.add(id);viX.add(id);break;
case IN: viZ.add(id); break;
}
return var;
}
public String toString(){
return String.format("|vVar|=%d, |vFa|=%d"
, vVar.size(), vFactor.size());
}
public Factor addFactor(int V1, int V2){
if (V1==V2)
FSystem.dieShouldNotHappen();
if (V1>V2){ int a=V2; V2=V1;V1=a; }
Factor f=new Factor(vFactor.size(), V1,V2);
vFactor.add(f);
if (V1!=-1) vVar.get(V1).vf.add(f);
if (V2!=-1) vVar.get(V2).vf.add(f);
return f;
}
public void test(VectorD vZ){//Sample s){
vEVar.set(viZ, vZ);
//test();
meanField(viX);
vX= (VectorD) vEVar.clone();//vEVar.sub(viX);
}
//public void test(){}
//public void train(){}
public void train(VectorD vY, VectorD vZ){//Sample s){//
test(vZ);
loss = getValue(vY);
vEVar.set(viY, vY);
meanField(viH);
vX_y= (VectorD) vEVar.clone();//vEVar.sub(viX);
vG=vX_y.minus(vX);
}
/**
* vector of all variables
* @param vA
*/
public void trainA(VectorD vA){
train(vA.sub(viY), vA.sub(viZ));
}
public void testA(VectorD vA){
test(vA.sub(viZ));
}
public VecVecI sampleGibbs(int n, int nBurnIn,int nThining){
vEVar.extend(viA.size());
vEVar.setAll(0.5);
VectorI vi= this.viX;
//if (withHidden) vi.addAll(b.viA);
//else vi.addOn(b.viZ).addOn(b.viY).sortOn();
VecVecI vv=new VecVecI ();
if (nBurnIn>0)
for (int i=0;i< nBurnIn; ++i) scanGibbs(vi);
for (int i=0;i<n; ++i){
if (nBurnIn<=0)
for (int j=0;j<vEVar.size(); ++j)
vEVar.set(j,(double)FRand.drawBinary(0.5));
for (int j=0;j<nThining; ++j) scanGibbs(vi);
vv.add(vEVar.sub(vi).toVectorI());
System.out.print(".");
}
System.out.println();
return vv;
//return null;
}
protected void scanGibbs(VectorI vi){
for (int i : vi){
expectVar(i);
if (FRand.drawBoolean( vEVar.get(i)))
vEVar.set(i,1.0);
else
vEVar.set(i,0.0);
}
return;
}
public boolean save(String fn){
BufferedWriter bw = FFile.newWriter(fn);
FFile.write(bw,vVar.size()+"\n");
for ( Factor f :vFactor )
FFile.write(bw, f.print()+"\n");
FFile.flush(bw);
return true;
}
/**
* estimate p(y|x)
* @param yb: starting id of y variables
* @param ye: ending id of y variables
*/
//public void variational(int yb, int ye){ }
public static void main(String[] args) {
//TODO: test it with data from GM hw
try {
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
| noon99jaki/pra | edu/cmu/lti/algorithm/learning/gm/CRFB.java | 3,016 | //m = getInt("m",5); | line_comment | nl | package edu.cmu.lti.algorithm.learning.gm;
import java.io.BufferedWriter;
import edu.cmu.lti.algorithm.container.VectorX;
import edu.cmu.lti.algorithm.container.VectorD;
import edu.cmu.lti.algorithm.container.VectorI;
import edu.cmu.lti.algorithm.container.VecVecI;
import edu.cmu.lti.algorithm.math.rand.FRand;
import edu.cmu.lti.util.file.FFile;
import edu.cmu.lti.util.html.EColor;
import edu.cmu.lti.util.system.FSystem;
/**
* this is the first draft, now it is bloated to a package
* @author nlao
*
*/
public class CRFB {
public static class Param extends edu.cmu.lti.util.run.Param{
private static final long serialVersionUID = 2008042701L; // YYYYMMDD
public Param(Class c) {
super(c);
parse();
}
public void parse(){
//m =<SUF>
//eps = getDouble("eps",1e-5);
//lang = getString("lang");
//diagco=getBoolean("diagco", false);
}
}
public static enum EVType {
IN(0,EColor.azure)/*conditioned on*/
, OUT(1,EColor.lightskyblue)/*to be evaluated*/
, MID(2,EColor.rosybrown2);//hidden nodes
//really a nice place to put data!
public EColor color;
public int id;
EVType(int id, EColor color){
this.id = id;
this.color = color;
}
}
public static class Factor{
public int id;
public double w=0;
public int iV1,iV2;
//assume iV1<iV2, if iV1==-1 then it is a bias feature
public Factor(int id, int iV1, int iV2){
this.iV2= iV2;
this.iV1= iV1;
}
public String toString(){
return String.format("(%d,%d)%.1f",iV1,iV2,w);
}
public String print(){
return String.format("%d\t%d\t%.3f",iV1,iV2,w);
}
}
public static class Variable{
//public SetI mi= new SetI();
public VectorX<Factor> vf= new VectorX<Factor>(Factor.class);
//use reference to update it outside the model
//public Variable(SetI mia,SetI mid){ this.mia= mi; }
EVType type;
int id;
public Variable(int id, EVType type){
this.id = id;
//mia= new SetI();
//mid= new SetI();
this.type=type;
}
}
// variables
public VectorX<Variable> vVar= new VectorX<Variable>(Variable.class);
// factors
public VectorX<Factor> vFactor= new VectorX<Factor>(Factor.class);
// weights
//VectorD vW;
double[] x ;
// expectations//in log domain?
public VectorD vEVar=new VectorD();
public VectorD vEFa;
public VectorI viZ=new VectorI();
public VectorI viY=new VectorI();
public VectorI viH=new VectorI();
public VectorI viX=new VectorI();
public VectorI viA=new VectorI();
/*public void selectSubNet(VectorI viY, VectorI viH , VectorI viZ){
this.viH = viH;
this.viY = viY;
this.viX = viH; viX.addAll(viY);
this.viZ = viZ;
}*/
/**
* x={y,h},
* estimate p(x|z)
* @param viZ: ids of z variables
* @param viX: ids of x variables
*/
public void meanField(VectorI vi){
vEVar.extend(viA.size());
for (int iScan=0; iScan<5; ++iScan)
for (int ix : vi)
expectVar(ix);
}
private double expectVar(int id){
double e=0;
for (Factor fa: vVar.get(id).vf)
e+= expectFactor(id,fa);
//exp(e1)/(exp(e0)+exp(e1))=1/(1+exp(e0-e1))
double p=1/(1+Math.exp(-e));
vEVar.set(id, p);
return p;
}
private double expectFactor(int iVar, Factor fa){//int iF){
//= vFactor.get(iF);
if (fa.w==0) return 0.0;
double e=1;
if (fa.iV2!=iVar) e*=vEVar.get(fa.iV2);
if (fa.iV1>=0) if (fa.iV1!=iVar) e*=vEVar.get(fa.iV1);
return e*fa.w;
}
private double expectFactor(int id){
Factor fa= vFactor.get(id);
double e=vEVar.get(fa.iV2);
if (fa.iV1>=0) e*=vEVar.get(fa.iV1);
vEFa.set(id, e);
return e;
}
/**
* @param vY
* @return loss=-log(p(y|z))
*/
protected double getValue( VectorD vY){
double loss=0;
//for (int iy: viY)
for (int i=0; i<vY.size(); ++i){
if (vY.get(i)==1.0)
loss += -Math.log(vEVar.get(viY.get(i)));
else
loss += -Math.log(1-vEVar.get(viY.get(i)));
}
return 0;
}
//public void setData( VectorD vZ){ vEVar.set(viZ, vZ); }
public VectorD vX;
public VectorD vX_y;
public double loss=0;
public VectorD vG;
public Variable addVar(EVType type){
int id = vVar.size();
Variable var=new Variable(id,type);
vVar.add(var);
viA.add(id);
switch(type){
case OUT: viY.add(id);viX.add(id);break;
case MID: viH.add(id);viX.add(id);break;
case IN: viZ.add(id); break;
}
return var;
}
public String toString(){
return String.format("|vVar|=%d, |vFa|=%d"
, vVar.size(), vFactor.size());
}
public Factor addFactor(int V1, int V2){
if (V1==V2)
FSystem.dieShouldNotHappen();
if (V1>V2){ int a=V2; V2=V1;V1=a; }
Factor f=new Factor(vFactor.size(), V1,V2);
vFactor.add(f);
if (V1!=-1) vVar.get(V1).vf.add(f);
if (V2!=-1) vVar.get(V2).vf.add(f);
return f;
}
public void test(VectorD vZ){//Sample s){
vEVar.set(viZ, vZ);
//test();
meanField(viX);
vX= (VectorD) vEVar.clone();//vEVar.sub(viX);
}
//public void test(){}
//public void train(){}
public void train(VectorD vY, VectorD vZ){//Sample s){//
test(vZ);
loss = getValue(vY);
vEVar.set(viY, vY);
meanField(viH);
vX_y= (VectorD) vEVar.clone();//vEVar.sub(viX);
vG=vX_y.minus(vX);
}
/**
* vector of all variables
* @param vA
*/
public void trainA(VectorD vA){
train(vA.sub(viY), vA.sub(viZ));
}
public void testA(VectorD vA){
test(vA.sub(viZ));
}
public VecVecI sampleGibbs(int n, int nBurnIn,int nThining){
vEVar.extend(viA.size());
vEVar.setAll(0.5);
VectorI vi= this.viX;
//if (withHidden) vi.addAll(b.viA);
//else vi.addOn(b.viZ).addOn(b.viY).sortOn();
VecVecI vv=new VecVecI ();
if (nBurnIn>0)
for (int i=0;i< nBurnIn; ++i) scanGibbs(vi);
for (int i=0;i<n; ++i){
if (nBurnIn<=0)
for (int j=0;j<vEVar.size(); ++j)
vEVar.set(j,(double)FRand.drawBinary(0.5));
for (int j=0;j<nThining; ++j) scanGibbs(vi);
vv.add(vEVar.sub(vi).toVectorI());
System.out.print(".");
}
System.out.println();
return vv;
//return null;
}
protected void scanGibbs(VectorI vi){
for (int i : vi){
expectVar(i);
if (FRand.drawBoolean( vEVar.get(i)))
vEVar.set(i,1.0);
else
vEVar.set(i,0.0);
}
return;
}
public boolean save(String fn){
BufferedWriter bw = FFile.newWriter(fn);
FFile.write(bw,vVar.size()+"\n");
for ( Factor f :vFactor )
FFile.write(bw, f.print()+"\n");
FFile.flush(bw);
return true;
}
/**
* estimate p(y|x)
* @param yb: starting id of y variables
* @param ye: ending id of y variables
*/
//public void variational(int yb, int ye){ }
public static void main(String[] args) {
//TODO: test it with data from GM hw
try {
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
|
178676_9 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dk.dr.radio.akt;
import android.app.Activity;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.DisplayMetrics;
import java.net.URL;
import dk.dr.radio.data.Udsendelse;
import dk.dr.radio.diverse.App;
import dk.dr.radio.diverse.Log;
/**
* @author j
*/
public class Basisfragment extends Fragment {
public static final String P_KANALKODE = "kanal";
public static final String P_UDSENDELSE = "udsendelse";
public static final String P_PROGRAMSERIE = "programserie";
static final boolean LOG_LIVSCYKLUS = false;
@Override
public void onCreate(Bundle savedInstanceState) {
if (LOG_LIVSCYKLUS) Log.d("onCreate " + this);
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
if (LOG_LIVSCYKLUS) Log.d("onStart " + this);
super.onStart();
}
protected void afbrydManglerData() {
Log.d("FRAGMENT AFBRYDES " + this + " " + getArguments());
//if (!App.PRODUKTION) App.kortToast("FRAGMENT AFBRYDES " + this + " " + getArguments());
getFragmentManager().popBackStack();
}
@Override
public void onResume() {
if (LOG_LIVSCYKLUS) Log.d("onResume " + this);
super.onResume();
}
@Override
public void onPause() {
if (LOG_LIVSCYKLUS) Log.d("onPause " + this);
super.onPause();
}
@Override
public void onDestroy() {
if (LOG_LIVSCYKLUS) Log.d("onDestroy " + this);
super.onDestroy();
}
@Override
public void onAttach(Activity activity) {
if (LOG_LIVSCYKLUS) Log.d("onAttach " + this + " til " + activity);
super.onAttach(activity);
}
@Override
public void onStop() {
if (LOG_LIVSCYKLUS) Log.d("onStop " + this);
super.onStop();
}
@Override
public void onDestroyView() {
if (LOG_LIVSCYKLUS) Log.d("onDestroyView " + this);
super.onDestroyView();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
if (LOG_LIVSCYKLUS) Log.d("onActivityCreated " + this);
super.onActivityCreated(savedInstanceState);
}
/*
SKALERINGSFORHOLD
Skalering af billeder - 16/9/3
Forhold 16:9 for de store billeder
Forhold 1:1 for playlistebilleder - og de skal være 1/3-del i højden af de store billeder
*/
public static final int bredde16 = 16;
public static final int højde9 = 9;
/**
* Bredden af aktiviteten skal bruges forskellige steder til at afgøre skalering af billeder
* Der bruges generelt halv bredde ved liggende visning.
* Bemærk, værdien er *kun til læsning*, og ændrer sig ved skærmvending
*/
public static int billedeBr;
public static int billedeHø;
public static boolean halvbreddebilleder;
public static void sætBilledeDimensioner(DisplayMetrics metrics) {
halvbreddebilleder = metrics.heightPixels < metrics.widthPixels;
billedeBr = metrics.widthPixels;
if (halvbreddebilleder) billedeBr = billedeBr / 2; // Halvbreddebilleder ved liggende visning
billedeHø = billedeBr * højde9 / bredde16;
}
public static String skalérBillede(Udsendelse u) {
if (u.billedeUrl != null) return u.billedeUrl;
return u.getKanal().kanallogo_url;
}
/**
* Billedeskalering til LastFM og discogs til playlister.
* Image: "http://api.discogs.com/image/A-4970-1339439274-8053.jpeg",
* ScaledImage: "http://asset.dr.dk/discoImages/?discoserver=api.discogs.com&file=%2fimage%2fA-4970-1339439274-8053.jpeg&h=400&w=400&scaleafter=crop&quality=85",
*/
public static String skalérDiscoBilledeUrl(String url, int bredde, int højde) {
if (App.fejlsøgning) Log.d("skalérDiscoBilledeUrl url1 = " + url);
if (url == null || url.length() == 0 || "null".equals(url)) return null;
try {
URL u = new URL(url);
//String skaleretUrl = "http://asset.dr.dk/discoImages/?discoserver=" + u.getHost() + ";w=" + bredde16 + "&h=" + højde9 +
// "&file=" + URLEncoder.encode(u.getPath(), "UTF-8") + "&scaleAfter=crop&quality=85";
String skaleretUrl = "https://asset.dr.dk/discoImages/?discoserver=" + u.getHost() + "&w=" + bredde + "&h=" + højde +
"&file=" + u.getPath() + "&scaleAfter=crop&quality=85";
//Log.d("skalérDiscoBilledeUrl url2 = " + u);
//Log.d("skalérDiscoBilledeUrl url3 = " + skaleretUrl);
return skaleretUrl;
} catch (Exception e) {
Log.e("url=" + url, e);
return null;
}
}
protected static Spannable lavFedSkriftTil(String tekst, int fedTil) {
Spannable spannable = new SpannableString(tekst);
spannable.setSpan(App.skrift_gibson_fed_span, 0, fedTil, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
}
| nordfalk/EsperantoRadio | app/src/main/java/dk/dr/radio/akt/Basisfragment.java | 1,817 | //asset.dr.dk/discoImages/?discoserver=" + u.getHost() + "&w=" + bredde + "&h=" + højde + | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dk.dr.radio.akt;
import android.app.Activity;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.util.DisplayMetrics;
import java.net.URL;
import dk.dr.radio.data.Udsendelse;
import dk.dr.radio.diverse.App;
import dk.dr.radio.diverse.Log;
/**
* @author j
*/
public class Basisfragment extends Fragment {
public static final String P_KANALKODE = "kanal";
public static final String P_UDSENDELSE = "udsendelse";
public static final String P_PROGRAMSERIE = "programserie";
static final boolean LOG_LIVSCYKLUS = false;
@Override
public void onCreate(Bundle savedInstanceState) {
if (LOG_LIVSCYKLUS) Log.d("onCreate " + this);
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
if (LOG_LIVSCYKLUS) Log.d("onStart " + this);
super.onStart();
}
protected void afbrydManglerData() {
Log.d("FRAGMENT AFBRYDES " + this + " " + getArguments());
//if (!App.PRODUKTION) App.kortToast("FRAGMENT AFBRYDES " + this + " " + getArguments());
getFragmentManager().popBackStack();
}
@Override
public void onResume() {
if (LOG_LIVSCYKLUS) Log.d("onResume " + this);
super.onResume();
}
@Override
public void onPause() {
if (LOG_LIVSCYKLUS) Log.d("onPause " + this);
super.onPause();
}
@Override
public void onDestroy() {
if (LOG_LIVSCYKLUS) Log.d("onDestroy " + this);
super.onDestroy();
}
@Override
public void onAttach(Activity activity) {
if (LOG_LIVSCYKLUS) Log.d("onAttach " + this + " til " + activity);
super.onAttach(activity);
}
@Override
public void onStop() {
if (LOG_LIVSCYKLUS) Log.d("onStop " + this);
super.onStop();
}
@Override
public void onDestroyView() {
if (LOG_LIVSCYKLUS) Log.d("onDestroyView " + this);
super.onDestroyView();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
if (LOG_LIVSCYKLUS) Log.d("onActivityCreated " + this);
super.onActivityCreated(savedInstanceState);
}
/*
SKALERINGSFORHOLD
Skalering af billeder - 16/9/3
Forhold 16:9 for de store billeder
Forhold 1:1 for playlistebilleder - og de skal være 1/3-del i højden af de store billeder
*/
public static final int bredde16 = 16;
public static final int højde9 = 9;
/**
* Bredden af aktiviteten skal bruges forskellige steder til at afgøre skalering af billeder
* Der bruges generelt halv bredde ved liggende visning.
* Bemærk, værdien er *kun til læsning*, og ændrer sig ved skærmvending
*/
public static int billedeBr;
public static int billedeHø;
public static boolean halvbreddebilleder;
public static void sætBilledeDimensioner(DisplayMetrics metrics) {
halvbreddebilleder = metrics.heightPixels < metrics.widthPixels;
billedeBr = metrics.widthPixels;
if (halvbreddebilleder) billedeBr = billedeBr / 2; // Halvbreddebilleder ved liggende visning
billedeHø = billedeBr * højde9 / bredde16;
}
public static String skalérBillede(Udsendelse u) {
if (u.billedeUrl != null) return u.billedeUrl;
return u.getKanal().kanallogo_url;
}
/**
* Billedeskalering til LastFM og discogs til playlister.
* Image: "http://api.discogs.com/image/A-4970-1339439274-8053.jpeg",
* ScaledImage: "http://asset.dr.dk/discoImages/?discoserver=api.discogs.com&file=%2fimage%2fA-4970-1339439274-8053.jpeg&h=400&w=400&scaleafter=crop&quality=85",
*/
public static String skalérDiscoBilledeUrl(String url, int bredde, int højde) {
if (App.fejlsøgning) Log.d("skalérDiscoBilledeUrl url1 = " + url);
if (url == null || url.length() == 0 || "null".equals(url)) return null;
try {
URL u = new URL(url);
//String skaleretUrl = "http://asset.dr.dk/discoImages/?discoserver=" + u.getHost() + ";w=" + bredde16 + "&h=" + højde9 +
// "&file=" + URLEncoder.encode(u.getPath(), "UTF-8") + "&scaleAfter=crop&quality=85";
String skaleretUrl = "https://asset.dr.dk/discoImages/?discoserver=" +<SUF>
"&file=" + u.getPath() + "&scaleAfter=crop&quality=85";
//Log.d("skalérDiscoBilledeUrl url2 = " + u);
//Log.d("skalérDiscoBilledeUrl url3 = " + skaleretUrl);
return skaleretUrl;
} catch (Exception e) {
Log.e("url=" + url, e);
return null;
}
}
protected static Spannable lavFedSkriftTil(String tekst, int fedTil) {
Spannable spannable = new SpannableString(tekst);
spannable.setSpan(App.skrift_gibson_fed_span, 0, fedTil, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
}
|
29705_0 | package com.nortal.jroad.client.ads;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSaadrmuudatusedv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompklassifVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkomponendidVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompotsingVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSmuudatusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSnormalVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedParingType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjmuudatusedv2ParingType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjmuudatusedv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjotsingv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSprobleemidVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSteavitusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADStekstotsingVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSaadrmuudatusedv2ParingType.AadrMuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompklassifParingType.KlassifParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkomponendidParingType.KompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompotsingParingType.AadrKompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSmuudatusedParingType.MuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSnormalParingType.NormalParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedParingType.ObjMuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjotsingv2ParingType.ObjKompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSprobleemidParingType.ProbleemidParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSteavitusedParingType.TeavitusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADStekstotsingParingType.AadrTekstParam;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* <code>ads</code> (Maaameti teenused) database X-tee service.
*/
public interface AdsXTeeService {
/**
* aadresskomponentide klassifikaatori muudatuste päring <br>
* <code>ads.kompklassif.v1</code> service.
*/
ADSkompklassifVastusType kompklassifV1(KlassifParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside muudatuste päring <br>
* <code>ads.muudatused.v1</code> service.
*/
ADSmuudatusedVastusType muudatusedV1(MuudatusedParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside otsing komponentide alusel <br>
* <code>ads.kompotsing.v1</code> service.
*/
ADSkompotsingVastusType kompotsingV1(AadrKompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadressobjektide otsing <br>
* <code>ads.objotsing.v2</code> service.
*/
ADSobjotsingv2VastusType objotsingV2(ObjKompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside otsing teksti alusel <br>
* <code>ads.tekstotsing.v1</code> service.
*/
ADStekstotsingVastusType tekstotsingV1(AadrTekstParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresskomponentide kehtiva seisu päring <br>
* <code>ads.komponendid.v1</code> service.
*/
ADSkomponendidVastusType komponendidV1(KompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadressteksti normaliseerimine<br>
* <code>ads.normal.v1</code> service.
*/
ADSnormalVastusType normalV1(NormalParamCallback callback) throws XRoadServiceConsumptionException;
/**
* teavitusteenus aadresside muudatusvajaduste kohta<br>
* <code>ads.teavitused.v1</code> service.
*/
ADSteavitusedVastusType teavitusedV1(TeavitusedParamCallback callback) throws XRoadServiceConsumptionException;
/**
* adressi muudatuste päring<br>
* <code>ads.aadrmuudatused.v2</code> service.
*/
ADSaadrmuudatusedv2VastusType aadrmuudatusedV2(AadrMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* objekti aadresside muudatuste päring<br>
* <code>ads.objaadrmuudatused.v1</code> service.
*/
ADSobjaadrmuudatusedVastusType objaadrmuudatusedV1(ObjAadrMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* aadresside muudatuste päring <br>
* <code>ads.objmuudatused.v2</code> service.
*/
ADSobjmuudatusedv2VastusType objmuudatusedV2(ObjMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* teavitusteenus aadressi probleemide kohta <br>
* <code>ads.probleemid.v1</code> service.
*/
ADSprobleemidVastusType probleemidV1(ProbleemidParamCallback callback)
throws XRoadServiceConsumptionException;
interface KlassifParamCallback {
void populate(KlassifParam klassifParam);
}
interface MuudatusedParamCallback {
void populate(MuudatusedParam muudatusedParam);
}
interface AadrKompParamCallback {
void populate(AadrKompParam aadrKompParam);
}
interface ObjKompParamCallback {
void populate(ObjKompParam objKompParam);
}
interface AadrTekstParamCallback {
void populate(AadrTekstParam aadrTekstParam);
}
interface KompParamCallback {
void populate(KompParam kompParam);
}
interface NormalParamCallback {
void populate(NormalParam normalParam);
}
interface TeavitusedParamCallback {
void populate(TeavitusedParam teavitusedParam);
}
interface AadrMuudatusedParamCallback {
void populate(AadrMuudatusedParam aadrMuudatusedParam);
}
interface AarObjMuudatusedParamCallback {
void populate(ObjMuudatusedParam objMuudatusedParam);
}
interface ObjAadrMuudatusedParamCallback {
void populate(ADSobjaadrmuudatusedParingType.ObjMuudatusedParam objMuudatusedParam);
}
interface ObjMuudatusedParamCallback {
void populate(ADSobjmuudatusedv2ParingType.ObjMuudatusedParam objMuudatusedParam);
}
interface ProbleemidParamCallback {
void populate(ProbleemidParam probleemidParam);
}
}
| nortal/j-road | client-service/ads/src/main/java/com/nortal/jroad/client/ads/AdsXTeeService.java | 2,419 | /**
* <code>ads</code> (Maaameti teenused) database X-tee service.
*/ | block_comment | nl | package com.nortal.jroad.client.ads;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSaadrmuudatusedv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompklassifVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkomponendidVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompotsingVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSmuudatusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSnormalVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedParingType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjmuudatusedv2ParingType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjmuudatusedv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjotsingv2VastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSprobleemidVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSteavitusedVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADStekstotsingVastusType;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSaadrmuudatusedv2ParingType.AadrMuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompklassifParingType.KlassifParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkomponendidParingType.KompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSkompotsingParingType.AadrKompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSmuudatusedParingType.MuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSnormalParingType.NormalParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjaadrmuudatusedParingType.ObjMuudatusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSobjotsingv2ParingType.ObjKompParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSprobleemidParingType.ProbleemidParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADSteavitusedParingType.TeavitusedParam;
import com.nortal.jroad.client.ads.types.ee.maaamet.ADStekstotsingParingType.AadrTekstParam;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* <code>ads</code> (Maaameti teenused)<SUF>*/
public interface AdsXTeeService {
/**
* aadresskomponentide klassifikaatori muudatuste päring <br>
* <code>ads.kompklassif.v1</code> service.
*/
ADSkompklassifVastusType kompklassifV1(KlassifParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside muudatuste päring <br>
* <code>ads.muudatused.v1</code> service.
*/
ADSmuudatusedVastusType muudatusedV1(MuudatusedParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside otsing komponentide alusel <br>
* <code>ads.kompotsing.v1</code> service.
*/
ADSkompotsingVastusType kompotsingV1(AadrKompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadressobjektide otsing <br>
* <code>ads.objotsing.v2</code> service.
*/
ADSobjotsingv2VastusType objotsingV2(ObjKompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresside otsing teksti alusel <br>
* <code>ads.tekstotsing.v1</code> service.
*/
ADStekstotsingVastusType tekstotsingV1(AadrTekstParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadresskomponentide kehtiva seisu päring <br>
* <code>ads.komponendid.v1</code> service.
*/
ADSkomponendidVastusType komponendidV1(KompParamCallback callback) throws XRoadServiceConsumptionException;
/**
* aadressteksti normaliseerimine<br>
* <code>ads.normal.v1</code> service.
*/
ADSnormalVastusType normalV1(NormalParamCallback callback) throws XRoadServiceConsumptionException;
/**
* teavitusteenus aadresside muudatusvajaduste kohta<br>
* <code>ads.teavitused.v1</code> service.
*/
ADSteavitusedVastusType teavitusedV1(TeavitusedParamCallback callback) throws XRoadServiceConsumptionException;
/**
* adressi muudatuste päring<br>
* <code>ads.aadrmuudatused.v2</code> service.
*/
ADSaadrmuudatusedv2VastusType aadrmuudatusedV2(AadrMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* objekti aadresside muudatuste päring<br>
* <code>ads.objaadrmuudatused.v1</code> service.
*/
ADSobjaadrmuudatusedVastusType objaadrmuudatusedV1(ObjAadrMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* aadresside muudatuste päring <br>
* <code>ads.objmuudatused.v2</code> service.
*/
ADSobjmuudatusedv2VastusType objmuudatusedV2(ObjMuudatusedParamCallback callback)
throws XRoadServiceConsumptionException;
/**
* teavitusteenus aadressi probleemide kohta <br>
* <code>ads.probleemid.v1</code> service.
*/
ADSprobleemidVastusType probleemidV1(ProbleemidParamCallback callback)
throws XRoadServiceConsumptionException;
interface KlassifParamCallback {
void populate(KlassifParam klassifParam);
}
interface MuudatusedParamCallback {
void populate(MuudatusedParam muudatusedParam);
}
interface AadrKompParamCallback {
void populate(AadrKompParam aadrKompParam);
}
interface ObjKompParamCallback {
void populate(ObjKompParam objKompParam);
}
interface AadrTekstParamCallback {
void populate(AadrTekstParam aadrTekstParam);
}
interface KompParamCallback {
void populate(KompParam kompParam);
}
interface NormalParamCallback {
void populate(NormalParam normalParam);
}
interface TeavitusedParamCallback {
void populate(TeavitusedParam teavitusedParam);
}
interface AadrMuudatusedParamCallback {
void populate(AadrMuudatusedParam aadrMuudatusedParam);
}
interface AarObjMuudatusedParamCallback {
void populate(ObjMuudatusedParam objMuudatusedParam);
}
interface ObjAadrMuudatusedParamCallback {
void populate(ADSobjaadrmuudatusedParingType.ObjMuudatusedParam objMuudatusedParam);
}
interface ObjMuudatusedParamCallback {
void populate(ADSobjmuudatusedv2ParingType.ObjMuudatusedParam objMuudatusedParam);
}
interface ProbleemidParamCallback {
void populate(ProbleemidParam probleemidParam);
}
}
|
113458_8 | package universalcoins.tileentity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.common.util.Constants;
import universalcoins.UniversalCoins;
public class TileVendorBlock extends TileVendor {
String signText[] = { "", "", "", "" };
public void updateSigns() {
if (!inventory.get(itemTradeSlot).isEmpty()) {
signText[0] = sellMode ? "&" + Integer.toHexString(textColor) + "Selling"
: "&" + Integer.toHexString(textColor) + "Buying";
// add out of stock notification if not infinite and no stock found
if (!infiniteMode && sellMode && ooStockWarning) {
signText[0] = "&" + Integer.toHexString(textColor) + (I18n.translateToLocal("sign.warning.stock"));
}
// add out of coins notification if buying and no funds available
if (!sellMode && ooCoinsWarning && !infiniteMode) {
signText[0] = "&" + Integer.toHexString(textColor) + (I18n.translateToLocal("sign.warning.coins"));
}
// add inventory full notification
if (!sellMode && inventoryFullWarning) {
signText[0] = "&" + Integer.toHexString(textColor)
+ (I18n.translateToLocal("sign.warning.inventoryfull"));
}
if (inventory.get(itemTradeSlot).getCount() > 1) {
signText[1] = "&" + Integer.toHexString(textColor) + inventory.get(itemTradeSlot).getCount() + " "
+ inventory.get(itemTradeSlot).getDisplayName();
} else {
signText[1] = "&" + Integer.toHexString(textColor) + inventory.get(itemTradeSlot).getDisplayName();
}
// if (inventory.get(itemTradeSlot).isItemEnchanted()) {
// signText[2] = "&" + Integer.toHexString(textColor);
// NBTTagList tagList =
// inventory.get(itemTradeSlot).getEnchantmentTagList();
// for (int i = 0; i < tagList.tagCount(); i++) {
// NBTTagCompound enchant = ((NBTTagList)
// tagList).getCompoundTagAt(i);
// signText[2] =
// signText[2].concat(Enchantment.enchantmentsBookList[enchant.getInteger("id")]
// .getTranslatedName(enchant.getInteger("lvl")) + ", ");
// }
// } else
// signText[2] = "";
if (inventory.get(itemTradeSlot).getItem() == UniversalCoins.Items.uc_package) {
signText[2] = "&" + Integer.toHexString(textColor);
if (inventory.get(itemTradeSlot).getTagCompound() != null) {
NBTTagList tagList = inventory.get(itemTradeSlot).getTagCompound().getTagList("Inventory",
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tagList.tagCount(); i++) {
NBTTagCompound tag = (NBTTagCompound) tagList.getCompoundTagAt(i);
int itemCount = new ItemStack(tag).getCount();
String itemName = new ItemStack(tag).getDisplayName();
signText[2] += itemCount + ":" + itemName + " ";
}
}
}
signText[3] = "&" + Integer.toHexString(textColor) + "Price: " + itemPrice;
// find and update all signs
TileEntity te;
te = world.getTileEntity(new BlockPos(pos.getX() + 1, pos.getY() - 1, pos.getZ()));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX() - 1, pos.getY() - 1, pos.getZ()));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ() - 1));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ() + 1));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
}
}
}
| notabadminer/UniversalCoins | src/main/java/universalcoins/tileentity/TileVendorBlock.java | 1,654 | // .getTranslatedName(enchant.getInteger("lvl")) + ", "); | line_comment | nl | package universalcoins.tileentity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.common.util.Constants;
import universalcoins.UniversalCoins;
public class TileVendorBlock extends TileVendor {
String signText[] = { "", "", "", "" };
public void updateSigns() {
if (!inventory.get(itemTradeSlot).isEmpty()) {
signText[0] = sellMode ? "&" + Integer.toHexString(textColor) + "Selling"
: "&" + Integer.toHexString(textColor) + "Buying";
// add out of stock notification if not infinite and no stock found
if (!infiniteMode && sellMode && ooStockWarning) {
signText[0] = "&" + Integer.toHexString(textColor) + (I18n.translateToLocal("sign.warning.stock"));
}
// add out of coins notification if buying and no funds available
if (!sellMode && ooCoinsWarning && !infiniteMode) {
signText[0] = "&" + Integer.toHexString(textColor) + (I18n.translateToLocal("sign.warning.coins"));
}
// add inventory full notification
if (!sellMode && inventoryFullWarning) {
signText[0] = "&" + Integer.toHexString(textColor)
+ (I18n.translateToLocal("sign.warning.inventoryfull"));
}
if (inventory.get(itemTradeSlot).getCount() > 1) {
signText[1] = "&" + Integer.toHexString(textColor) + inventory.get(itemTradeSlot).getCount() + " "
+ inventory.get(itemTradeSlot).getDisplayName();
} else {
signText[1] = "&" + Integer.toHexString(textColor) + inventory.get(itemTradeSlot).getDisplayName();
}
// if (inventory.get(itemTradeSlot).isItemEnchanted()) {
// signText[2] = "&" + Integer.toHexString(textColor);
// NBTTagList tagList =
// inventory.get(itemTradeSlot).getEnchantmentTagList();
// for (int i = 0; i < tagList.tagCount(); i++) {
// NBTTagCompound enchant = ((NBTTagList)
// tagList).getCompoundTagAt(i);
// signText[2] =
// signText[2].concat(Enchantment.enchantmentsBookList[enchant.getInteger("id")]
// .getTranslatedName(enchant.getInteger("lvl")) +<SUF>
// }
// } else
// signText[2] = "";
if (inventory.get(itemTradeSlot).getItem() == UniversalCoins.Items.uc_package) {
signText[2] = "&" + Integer.toHexString(textColor);
if (inventory.get(itemTradeSlot).getTagCompound() != null) {
NBTTagList tagList = inventory.get(itemTradeSlot).getTagCompound().getTagList("Inventory",
Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tagList.tagCount(); i++) {
NBTTagCompound tag = (NBTTagCompound) tagList.getCompoundTagAt(i);
int itemCount = new ItemStack(tag).getCount();
String itemName = new ItemStack(tag).getDisplayName();
signText[2] += itemCount + ":" + itemName + " ";
}
}
}
signText[3] = "&" + Integer.toHexString(textColor) + "Price: " + itemPrice;
// find and update all signs
TileEntity te;
te = world.getTileEntity(new BlockPos(pos.getX() + 1, pos.getY() - 1, pos.getZ()));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX() - 1, pos.getY() - 1, pos.getZ()));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ() - 1));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
te = world.getTileEntity(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ() + 1));
if (te != null && te instanceof TileUCSign) {
TileUCSign tesign = (TileUCSign) te;
for (int i = 0; i < 4; i++) {
tesign.signText[i] = new TextComponentString(this.signText[i]);
}
tesign.updateSign();
tesign.markDirty();
}
}
}
}
|
106209_0 | package be.kdg.java.model;
import java.awt.*;
/**
* Blockshapes in verschillende vormen , gebruik van Points
* 8 verschilende vormen gevormt door X enm Y coordinaten
* Randomizen met randomEnum
* */
public enum BlockShape {
BIG_L(new Point[]{new Point(1, 1), new Point(1, 0), new Point(1, 2), new Point(2, 2)}),
LINE_HORIZONTAL(new Point[]{new Point(0, 1), new Point(1, 1), new Point(2, 1)}),
LINE_VERTICAL(new Point[]{new Point(1, 0), new Point(1, 2), new Point(1, 1)}),
REVERSED_BIG_L(new Point[]{new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(2, 2)}),
REVERSED_SMALL_L(new Point[]{new Point(0, 0), new Point(1, 0), new Point(1, 1)}),
SMALL_L(new Point[]{new Point(1, 0), new Point(1, 1), new Point(2, 1)}),
THREE_ON_THREE(new Point[]{new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1), new Point(2, 0), new Point(0, 2), new Point(2, 1), new Point(1, 2), new Point(2, 2)}),
TWO_ON_TWO(new Point[]{new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1)});
private final Point[] tiles;
BlockShape(Point[] tiles) {
this.tiles = tiles;
}
public static BlockShape randomEnum() {
return values()[(int) (Math.random() * values().length)];
}
public Point[] getTiles() {
return tiles;
}
}
| notkyllian/JavaFX_BlockGame | src/main/java/be/kdg/java/model/BlockShape.java | 536 | /**
* Blockshapes in verschillende vormen , gebruik van Points
* 8 verschilende vormen gevormt door X enm Y coordinaten
* Randomizen met randomEnum
* */ | block_comment | nl | package be.kdg.java.model;
import java.awt.*;
/**
* Blockshapes in verschillende<SUF>*/
public enum BlockShape {
BIG_L(new Point[]{new Point(1, 1), new Point(1, 0), new Point(1, 2), new Point(2, 2)}),
LINE_HORIZONTAL(new Point[]{new Point(0, 1), new Point(1, 1), new Point(2, 1)}),
LINE_VERTICAL(new Point[]{new Point(1, 0), new Point(1, 2), new Point(1, 1)}),
REVERSED_BIG_L(new Point[]{new Point(0, 1), new Point(1, 1), new Point(2, 1), new Point(2, 2)}),
REVERSED_SMALL_L(new Point[]{new Point(0, 0), new Point(1, 0), new Point(1, 1)}),
SMALL_L(new Point[]{new Point(1, 0), new Point(1, 1), new Point(2, 1)}),
THREE_ON_THREE(new Point[]{new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1), new Point(2, 0), new Point(0, 2), new Point(2, 1), new Point(1, 2), new Point(2, 2)}),
TWO_ON_TWO(new Point[]{new Point(0, 0), new Point(1, 0), new Point(0, 1), new Point(1, 1)});
private final Point[] tiles;
BlockShape(Point[] tiles) {
this.tiles = tiles;
}
public static BlockShape randomEnum() {
return values()[(int) (Math.random() * values().length)];
}
public Point[] getTiles() {
return tiles;
}
}
|
15321_0 | package nl.novi.stuivenberg.springboot.example.security.service;
import nl.novi.stuivenberg.springboot.example.security.domain.ERole;
import nl.novi.stuivenberg.springboot.example.security.domain.Role;
import nl.novi.stuivenberg.springboot.example.security.domain.User;
import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest;
import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest;
import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse;
import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse;
import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository;
import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository;
import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class AuthorizationService {
private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found.";
private UserRepository userRepository;
private PasswordEncoder encoder;
private RoleRepository roleRepository;
private AuthenticationManager authenticationManager;
private JwtUtils jwtUtils;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setEncoder(PasswordEncoder passwordEncoder) {
this.encoder = passwordEncoder;
}
@Autowired
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Autowired
public void setJwtUtils(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
*
* Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen
* worden toegevoegd en de gebruiker wordt opgeslagen in de database.
*
* @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord.
* @return een HTTP response met daarin een succesbericht.
*/
public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) {
if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
/**
* Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de
* AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons.
*
* Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid:
* 401 Unauthorized. Deze wordt gegooid door
* {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt}
*
*
* @param loginRequest De payload met username en password.
* @return een HTTP-response met daarin de JWT-token.
*/
public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
}
| novaeeken/sd-novi-authentication-backend | src/main/java/nl/novi/stuivenberg/springboot/example/security/service/AuthorizationService.java | 1,789 | /**
*
* Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen
* worden toegevoegd en de gebruiker wordt opgeslagen in de database.
*
* @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord.
* @return een HTTP response met daarin een succesbericht.
*/ | block_comment | nl | package nl.novi.stuivenberg.springboot.example.security.service;
import nl.novi.stuivenberg.springboot.example.security.domain.ERole;
import nl.novi.stuivenberg.springboot.example.security.domain.Role;
import nl.novi.stuivenberg.springboot.example.security.domain.User;
import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest;
import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest;
import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse;
import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse;
import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository;
import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository;
import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class AuthorizationService {
private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found.";
private UserRepository userRepository;
private PasswordEncoder encoder;
private RoleRepository roleRepository;
private AuthenticationManager authenticationManager;
private JwtUtils jwtUtils;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setEncoder(PasswordEncoder passwordEncoder) {
this.encoder = passwordEncoder;
}
@Autowired
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Autowired
public void setJwtUtils(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
*
* Deze methode verwerkt<SUF>*/
public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) {
if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
/**
* Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de
* AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons.
*
* Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid:
* 401 Unauthorized. Deze wordt gegooid door
* {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt}
*
*
* @param loginRequest De payload met username en password.
* @return een HTTP-response met daarin de JWT-token.
*/
public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
}
|
57106_23 | /*
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.novoda.spikes.arcore.google.rendering;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import com.google.ar.core.Camera;
import com.google.ar.core.Plane;
import com.google.ar.core.Pose;
import com.google.ar.core.TrackingState;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Renders the detected AR planes. */
public class PlaneRenderer {
private static final String TAG = PlaneRenderer.class.getSimpleName();
// Shader names.
private static final String VERTEX_SHADER_NAME = "shaders/plane.vert";
private static final String FRAGMENT_SHADER_NAME = "shaders/plane.frag";
private static final int BYTES_PER_FLOAT = Float.SIZE / 8;
private static final int BYTES_PER_SHORT = Short.SIZE / 8;
private static final int COORDS_PER_VERTEX = 3; // x, z, alpha
private static final int VERTS_PER_BOUNDARY_VERT = 2;
private static final int INDICES_PER_BOUNDARY_VERT = 3;
private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64;
private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES =
BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS;
private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES =
BYTES_PER_SHORT
* INDICES_PER_BOUNDARY_VERT
* INDICES_PER_BOUNDARY_VERT
* INITIAL_BUFFER_BOUNDARY_VERTS;
private static final float FADE_RADIUS_M = 0.25f;
private static final float DOTS_PER_METER = 10.0f;
private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3));
// Using the "signed distance field" approach to render sharp lines and circles.
// {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale}
// dotThreshold/lineThreshold: red/green intensity above which dots/lines are present
// lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0
// occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink
private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f};
private int planeProgram;
private final int[] textures = new int[1];
private int planeXZPositionAlphaAttribute;
private int planeModelUniform;
private int planeModelViewProjectionUniform;
private int textureUniform;
private int lineColorUniform;
private int dotColorUniform;
private int gridControlUniform;
private int planeUvMatrixUniform;
private FloatBuffer vertexBuffer =
ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
private ShortBuffer indexBuffer =
ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
// Temporary lists/matrices allocated here to reduce number of allocations for each frame.
private final float[] modelMatrix = new float[16];
private final float[] modelViewMatrix = new float[16];
private final float[] modelViewProjectionMatrix = new float[16];
private final float[] planeColor = new float[4];
private final float[] planeAngleUvMatrix =
new float[4]; // 2x2 rotation matrix applied to uv coords.
private final Map<Plane, Integer> planeIndexMap = new HashMap<>();
public PlaneRenderer() {}
/**
* Allocates and initializes OpenGL resources needed by the plane renderer. Must be called on the
* OpenGL thread, typically in {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}.
*
* @param context Needed to access shader source and texture PNG.
* @param gridDistanceTextureName Name of the PNG file containing the grid texture.
*/
public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException {
int vertexShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME);
int passthroughShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME);
planeProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(planeProgram, vertexShader);
GLES20.glAttachShader(planeProgram, passthroughShader);
GLES20.glLinkProgram(planeProgram);
GLES20.glUseProgram(planeProgram);
ShaderUtil.checkGLError(TAG, "Program creation");
// Read the texture.
Bitmap textureBitmap =
BitmapFactory.decodeStream(context.getAssets().open(gridDistanceTextureName));
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glTexParameteri(
GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0);
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
ShaderUtil.checkGLError(TAG, "Texture loading");
planeXZPositionAlphaAttribute = GLES20.glGetAttribLocation(planeProgram, "a_XZPositionAlpha");
planeModelUniform = GLES20.glGetUniformLocation(planeProgram, "u_Model");
planeModelViewProjectionUniform =
GLES20.glGetUniformLocation(planeProgram, "u_ModelViewProjection");
textureUniform = GLES20.glGetUniformLocation(planeProgram, "u_Texture");
lineColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_lineColor");
dotColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_dotColor");
gridControlUniform = GLES20.glGetUniformLocation(planeProgram, "u_gridControl");
planeUvMatrixUniform = GLES20.glGetUniformLocation(planeProgram, "u_PlaneUvMatrix");
ShaderUtil.checkGLError(TAG, "Program parameters");
}
/** Updates the plane model transform matrix and extents. */
private void updatePlaneParameters(
float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) {
System.arraycopy(planeMatrix, 0, modelMatrix, 0, 16);
if (boundary == null) {
vertexBuffer.limit(0);
indexBuffer.limit(0);
return;
}
// Generate a new set of vertices and a corresponding triangle strip index set so that
// the plane boundary polygon has a fading edge. This is done by making a copy of the
// boundary polygon vertices and scaling it down around center to push it inwards. Then
// the index buffer is setup accordingly.
boundary.rewind();
int boundaryVertices = boundary.limit() / 2;
int numVertices;
int numIndices;
numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT;
// drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter).
numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT;
if (vertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) {
int size = vertexBuffer.capacity();
while (size < numVertices * COORDS_PER_VERTEX) {
size *= 2;
}
vertexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
}
vertexBuffer.rewind();
vertexBuffer.limit(numVertices * COORDS_PER_VERTEX);
if (indexBuffer.capacity() < numIndices) {
int size = indexBuffer.capacity();
while (size < numIndices) {
size *= 2;
}
indexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_SHORT * size)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
}
indexBuffer.rewind();
indexBuffer.limit(numIndices);
// Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we
// generate a bunch of 0-area triangles. These don't get rendered though so it works
// out ok.
float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f);
float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f);
while (boundary.hasRemaining()) {
float x = boundary.get();
float z = boundary.get();
vertexBuffer.put(x);
vertexBuffer.put(z);
vertexBuffer.put(0.0f);
vertexBuffer.put(x * xScale);
vertexBuffer.put(z * zScale);
vertexBuffer.put(1.0f);
}
// step 1, perimeter
indexBuffer.put((short) ((boundaryVertices - 1) * 2));
for (int i = 0; i < boundaryVertices; ++i) {
indexBuffer.put((short) (i * 2));
indexBuffer.put((short) (i * 2 + 1));
}
indexBuffer.put((short) 1);
// This leaves us on the interior edge of the perimeter between the inset vertices
// for boundary verts n-1 and 0.
// step 2, interior:
for (int i = 1; i < boundaryVertices / 2; ++i) {
indexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1));
indexBuffer.put((short) (i * 2 + 1));
}
if (boundaryVertices % 2 != 0) {
indexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1));
}
}
private void draw(float[] cameraView, float[] cameraPerspective) {
// Build the ModelView and ModelViewProjection matrices
// for calculating cube position and light.
Matrix.multiplyMM(modelViewMatrix, 0, cameraView, 0, modelMatrix, 0);
Matrix.multiplyMM(modelViewProjectionMatrix, 0, cameraPerspective, 0, modelViewMatrix, 0);
// Set the position of the plane
vertexBuffer.rewind();
GLES20.glVertexAttribPointer(
planeXZPositionAlphaAttribute,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
BYTES_PER_FLOAT * COORDS_PER_VERTEX,
vertexBuffer);
// Set the Model and ModelViewProjection matrices in the shader.
GLES20.glUniformMatrix4fv(planeModelUniform, 1, false, modelMatrix, 0);
GLES20.glUniformMatrix4fv(
planeModelViewProjectionUniform, 1, false, modelViewProjectionMatrix, 0);
indexBuffer.rewind();
GLES20.glDrawElements(
GLES20.GL_TRIANGLE_STRIP, indexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, indexBuffer);
ShaderUtil.checkGLError(TAG, "Drawing plane");
}
static class SortablePlane {
final float distance;
final Plane plane;
SortablePlane(float distance, Plane plane) {
this.distance = distance;
this.plane = plane;
}
}
/**
* Draws the collection of tracked planes, with closer planes hiding more distant ones.
*
* @param allPlanes The collection of planes to draw.
* @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()}
* @param cameraPerspective The projection matrix, as returned by {@link
* Camera#getProjectionMatrix(float[], int, float, float)}
*/
public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) {
// Planes must be sorted by distance from camera so that we draw closer planes first, and
// they occlude the farther planes.
List<SortablePlane> sortedPlanes = new ArrayList<>();
float[] normal = new float[3];
float cameraX = cameraPose.tx();
float cameraY = cameraPose.ty();
float cameraZ = cameraPose.tz();
for (Plane plane : allPlanes) {
if (plane.getTrackingState() != TrackingState.TRACKING || plane.getSubsumedBy() != null) {
continue;
}
Pose center = plane.getCenterPose();
// Get transformed Y axis of plane's coordinate system.
center.getTransformedAxis(1, 1.0f, normal, 0);
// Compute dot product of plane's normal with vector from camera to plane center.
float distance =
(cameraX - center.tx()) * normal[0]
+ (cameraY - center.ty()) * normal[1]
+ (cameraZ - center.tz()) * normal[2];
if (distance < 0) { // Plane is back-facing.
continue;
}
sortedPlanes.add(new SortablePlane(distance, plane));
}
Collections.sort(
sortedPlanes,
new Comparator<SortablePlane>() {
@Override
public int compare(SortablePlane a, SortablePlane b) {
return Float.compare(a.distance, b.distance);
}
});
float[] cameraView = new float[16];
cameraPose.inverse().toMatrix(cameraView, 0);
// Planes are drawn with additive blending, masked by the alpha channel for occlusion.
// Start by clearing the alpha channel of the color buffer to 1.0.
GLES20.glClearColor(1, 1, 1, 1);
GLES20.glColorMask(false, false, false, true);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glColorMask(true, true, true, true);
// Disable depth write.
GLES20.glDepthMask(false);
// Additive blending, masked by alpha channel, clearing alpha channel.
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFuncSeparate(
GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest)
GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest)
// Set up the shader.
GLES20.glUseProgram(planeProgram);
// Attach the texture.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glUniform1i(textureUniform, 0);
// Shared fragment uniforms.
GLES20.glUniform4fv(gridControlUniform, 1, GRID_CONTROL, 0);
// Enable vertex arrays
GLES20.glEnableVertexAttribArray(planeXZPositionAlphaAttribute);
ShaderUtil.checkGLError(TAG, "Setting up to draw planes");
for (SortablePlane sortedPlane : sortedPlanes) {
Plane plane = sortedPlane.plane;
float[] planeMatrix = new float[16];
plane.getCenterPose().toMatrix(planeMatrix, 0);
updatePlaneParameters(
planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon());
// Get plane index. Keep a map to assign same indices to same planes.
Integer planeIndex = planeIndexMap.get(plane);
if (planeIndex == null) {
planeIndex = planeIndexMap.size();
planeIndexMap.put(plane, planeIndex);
}
// Set plane color. Computed deterministically from the Plane index.
int colorIndex = planeIndex % PLANE_COLORS_RGBA.length;
colorRgbaToFloat(planeColor, PLANE_COLORS_RGBA[colorIndex]);
GLES20.glUniform4fv(lineColorUniform, 1, planeColor, 0);
GLES20.glUniform4fv(dotColorUniform, 1, planeColor, 0);
// Each plane will have its own angle offset from others, to make them easier to
// distinguish. Compute a 2x2 rotation matrix from the angle.
float angleRadians = planeIndex * 0.144f;
float uScale = DOTS_PER_METER;
float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE;
planeAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale;
planeAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale;
planeAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale;
planeAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale;
GLES20.glUniformMatrix2fv(planeUvMatrixUniform, 1, false, planeAngleUvMatrix, 0);
draw(cameraView, cameraPerspective);
}
// Clean up the state we set
GLES20.glDisableVertexAttribArray(planeXZPositionAlphaAttribute);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDepthMask(true);
ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes");
}
private static void colorRgbaToFloat(float[] planeColor, int colorRgba) {
planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f;
planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f;
planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f;
planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f;
}
private static final int[] PLANE_COLORS_RGBA = {
0xFFFFFFFF,
0xF44336FF,
0xE91E63FF,
0x9C27B0FF,
0x673AB7FF,
0x3F51B5FF,
0x2196F3FF,
0x03A9F4FF,
0x00BCD4FF,
0x009688FF,
0x4CAF50FF,
0x8BC34AFF,
0xCDDC39FF,
0xFFEB3BFF,
0xFFC107FF,
0xFF9800FF,
};
}
| novoda/spikes | ARCoreAdvanced/app/src/main/java/com/novoda/spikes/arcore/google/rendering/PlaneRenderer.java | 5,745 | // step 2, interior: | line_comment | nl | /*
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.novoda.spikes.arcore.google.rendering;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import com.google.ar.core.Camera;
import com.google.ar.core.Plane;
import com.google.ar.core.Pose;
import com.google.ar.core.TrackingState;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Renders the detected AR planes. */
public class PlaneRenderer {
private static final String TAG = PlaneRenderer.class.getSimpleName();
// Shader names.
private static final String VERTEX_SHADER_NAME = "shaders/plane.vert";
private static final String FRAGMENT_SHADER_NAME = "shaders/plane.frag";
private static final int BYTES_PER_FLOAT = Float.SIZE / 8;
private static final int BYTES_PER_SHORT = Short.SIZE / 8;
private static final int COORDS_PER_VERTEX = 3; // x, z, alpha
private static final int VERTS_PER_BOUNDARY_VERT = 2;
private static final int INDICES_PER_BOUNDARY_VERT = 3;
private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64;
private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES =
BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS;
private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES =
BYTES_PER_SHORT
* INDICES_PER_BOUNDARY_VERT
* INDICES_PER_BOUNDARY_VERT
* INITIAL_BUFFER_BOUNDARY_VERTS;
private static final float FADE_RADIUS_M = 0.25f;
private static final float DOTS_PER_METER = 10.0f;
private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3));
// Using the "signed distance field" approach to render sharp lines and circles.
// {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale}
// dotThreshold/lineThreshold: red/green intensity above which dots/lines are present
// lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0
// occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink
private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f};
private int planeProgram;
private final int[] textures = new int[1];
private int planeXZPositionAlphaAttribute;
private int planeModelUniform;
private int planeModelViewProjectionUniform;
private int textureUniform;
private int lineColorUniform;
private int dotColorUniform;
private int gridControlUniform;
private int planeUvMatrixUniform;
private FloatBuffer vertexBuffer =
ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
private ShortBuffer indexBuffer =
ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
// Temporary lists/matrices allocated here to reduce number of allocations for each frame.
private final float[] modelMatrix = new float[16];
private final float[] modelViewMatrix = new float[16];
private final float[] modelViewProjectionMatrix = new float[16];
private final float[] planeColor = new float[4];
private final float[] planeAngleUvMatrix =
new float[4]; // 2x2 rotation matrix applied to uv coords.
private final Map<Plane, Integer> planeIndexMap = new HashMap<>();
public PlaneRenderer() {}
/**
* Allocates and initializes OpenGL resources needed by the plane renderer. Must be called on the
* OpenGL thread, typically in {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}.
*
* @param context Needed to access shader source and texture PNG.
* @param gridDistanceTextureName Name of the PNG file containing the grid texture.
*/
public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException {
int vertexShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME);
int passthroughShader =
ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME);
planeProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(planeProgram, vertexShader);
GLES20.glAttachShader(planeProgram, passthroughShader);
GLES20.glLinkProgram(planeProgram);
GLES20.glUseProgram(planeProgram);
ShaderUtil.checkGLError(TAG, "Program creation");
// Read the texture.
Bitmap textureBitmap =
BitmapFactory.decodeStream(context.getAssets().open(gridDistanceTextureName));
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glTexParameteri(
GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0);
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
ShaderUtil.checkGLError(TAG, "Texture loading");
planeXZPositionAlphaAttribute = GLES20.glGetAttribLocation(planeProgram, "a_XZPositionAlpha");
planeModelUniform = GLES20.glGetUniformLocation(planeProgram, "u_Model");
planeModelViewProjectionUniform =
GLES20.glGetUniformLocation(planeProgram, "u_ModelViewProjection");
textureUniform = GLES20.glGetUniformLocation(planeProgram, "u_Texture");
lineColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_lineColor");
dotColorUniform = GLES20.glGetUniformLocation(planeProgram, "u_dotColor");
gridControlUniform = GLES20.glGetUniformLocation(planeProgram, "u_gridControl");
planeUvMatrixUniform = GLES20.glGetUniformLocation(planeProgram, "u_PlaneUvMatrix");
ShaderUtil.checkGLError(TAG, "Program parameters");
}
/** Updates the plane model transform matrix and extents. */
private void updatePlaneParameters(
float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) {
System.arraycopy(planeMatrix, 0, modelMatrix, 0, 16);
if (boundary == null) {
vertexBuffer.limit(0);
indexBuffer.limit(0);
return;
}
// Generate a new set of vertices and a corresponding triangle strip index set so that
// the plane boundary polygon has a fading edge. This is done by making a copy of the
// boundary polygon vertices and scaling it down around center to push it inwards. Then
// the index buffer is setup accordingly.
boundary.rewind();
int boundaryVertices = boundary.limit() / 2;
int numVertices;
int numIndices;
numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT;
// drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter).
numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT;
if (vertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) {
int size = vertexBuffer.capacity();
while (size < numVertices * COORDS_PER_VERTEX) {
size *= 2;
}
vertexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
}
vertexBuffer.rewind();
vertexBuffer.limit(numVertices * COORDS_PER_VERTEX);
if (indexBuffer.capacity() < numIndices) {
int size = indexBuffer.capacity();
while (size < numIndices) {
size *= 2;
}
indexBuffer =
ByteBuffer.allocateDirect(BYTES_PER_SHORT * size)
.order(ByteOrder.nativeOrder())
.asShortBuffer();
}
indexBuffer.rewind();
indexBuffer.limit(numIndices);
// Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we
// generate a bunch of 0-area triangles. These don't get rendered though so it works
// out ok.
float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f);
float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f);
while (boundary.hasRemaining()) {
float x = boundary.get();
float z = boundary.get();
vertexBuffer.put(x);
vertexBuffer.put(z);
vertexBuffer.put(0.0f);
vertexBuffer.put(x * xScale);
vertexBuffer.put(z * zScale);
vertexBuffer.put(1.0f);
}
// step 1, perimeter
indexBuffer.put((short) ((boundaryVertices - 1) * 2));
for (int i = 0; i < boundaryVertices; ++i) {
indexBuffer.put((short) (i * 2));
indexBuffer.put((short) (i * 2 + 1));
}
indexBuffer.put((short) 1);
// This leaves us on the interior edge of the perimeter between the inset vertices
// for boundary verts n-1 and 0.
// step 2,<SUF>
for (int i = 1; i < boundaryVertices / 2; ++i) {
indexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1));
indexBuffer.put((short) (i * 2 + 1));
}
if (boundaryVertices % 2 != 0) {
indexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1));
}
}
private void draw(float[] cameraView, float[] cameraPerspective) {
// Build the ModelView and ModelViewProjection matrices
// for calculating cube position and light.
Matrix.multiplyMM(modelViewMatrix, 0, cameraView, 0, modelMatrix, 0);
Matrix.multiplyMM(modelViewProjectionMatrix, 0, cameraPerspective, 0, modelViewMatrix, 0);
// Set the position of the plane
vertexBuffer.rewind();
GLES20.glVertexAttribPointer(
planeXZPositionAlphaAttribute,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
BYTES_PER_FLOAT * COORDS_PER_VERTEX,
vertexBuffer);
// Set the Model and ModelViewProjection matrices in the shader.
GLES20.glUniformMatrix4fv(planeModelUniform, 1, false, modelMatrix, 0);
GLES20.glUniformMatrix4fv(
planeModelViewProjectionUniform, 1, false, modelViewProjectionMatrix, 0);
indexBuffer.rewind();
GLES20.glDrawElements(
GLES20.GL_TRIANGLE_STRIP, indexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, indexBuffer);
ShaderUtil.checkGLError(TAG, "Drawing plane");
}
static class SortablePlane {
final float distance;
final Plane plane;
SortablePlane(float distance, Plane plane) {
this.distance = distance;
this.plane = plane;
}
}
/**
* Draws the collection of tracked planes, with closer planes hiding more distant ones.
*
* @param allPlanes The collection of planes to draw.
* @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()}
* @param cameraPerspective The projection matrix, as returned by {@link
* Camera#getProjectionMatrix(float[], int, float, float)}
*/
public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) {
// Planes must be sorted by distance from camera so that we draw closer planes first, and
// they occlude the farther planes.
List<SortablePlane> sortedPlanes = new ArrayList<>();
float[] normal = new float[3];
float cameraX = cameraPose.tx();
float cameraY = cameraPose.ty();
float cameraZ = cameraPose.tz();
for (Plane plane : allPlanes) {
if (plane.getTrackingState() != TrackingState.TRACKING || plane.getSubsumedBy() != null) {
continue;
}
Pose center = plane.getCenterPose();
// Get transformed Y axis of plane's coordinate system.
center.getTransformedAxis(1, 1.0f, normal, 0);
// Compute dot product of plane's normal with vector from camera to plane center.
float distance =
(cameraX - center.tx()) * normal[0]
+ (cameraY - center.ty()) * normal[1]
+ (cameraZ - center.tz()) * normal[2];
if (distance < 0) { // Plane is back-facing.
continue;
}
sortedPlanes.add(new SortablePlane(distance, plane));
}
Collections.sort(
sortedPlanes,
new Comparator<SortablePlane>() {
@Override
public int compare(SortablePlane a, SortablePlane b) {
return Float.compare(a.distance, b.distance);
}
});
float[] cameraView = new float[16];
cameraPose.inverse().toMatrix(cameraView, 0);
// Planes are drawn with additive blending, masked by the alpha channel for occlusion.
// Start by clearing the alpha channel of the color buffer to 1.0.
GLES20.glClearColor(1, 1, 1, 1);
GLES20.glColorMask(false, false, false, true);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glColorMask(true, true, true, true);
// Disable depth write.
GLES20.glDepthMask(false);
// Additive blending, masked by alpha channel, clearing alpha channel.
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFuncSeparate(
GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest)
GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest)
// Set up the shader.
GLES20.glUseProgram(planeProgram);
// Attach the texture.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glUniform1i(textureUniform, 0);
// Shared fragment uniforms.
GLES20.glUniform4fv(gridControlUniform, 1, GRID_CONTROL, 0);
// Enable vertex arrays
GLES20.glEnableVertexAttribArray(planeXZPositionAlphaAttribute);
ShaderUtil.checkGLError(TAG, "Setting up to draw planes");
for (SortablePlane sortedPlane : sortedPlanes) {
Plane plane = sortedPlane.plane;
float[] planeMatrix = new float[16];
plane.getCenterPose().toMatrix(planeMatrix, 0);
updatePlaneParameters(
planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon());
// Get plane index. Keep a map to assign same indices to same planes.
Integer planeIndex = planeIndexMap.get(plane);
if (planeIndex == null) {
planeIndex = planeIndexMap.size();
planeIndexMap.put(plane, planeIndex);
}
// Set plane color. Computed deterministically from the Plane index.
int colorIndex = planeIndex % PLANE_COLORS_RGBA.length;
colorRgbaToFloat(planeColor, PLANE_COLORS_RGBA[colorIndex]);
GLES20.glUniform4fv(lineColorUniform, 1, planeColor, 0);
GLES20.glUniform4fv(dotColorUniform, 1, planeColor, 0);
// Each plane will have its own angle offset from others, to make them easier to
// distinguish. Compute a 2x2 rotation matrix from the angle.
float angleRadians = planeIndex * 0.144f;
float uScale = DOTS_PER_METER;
float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE;
planeAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale;
planeAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale;
planeAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale;
planeAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale;
GLES20.glUniformMatrix2fv(planeUvMatrixUniform, 1, false, planeAngleUvMatrix, 0);
draw(cameraView, cameraPerspective);
}
// Clean up the state we set
GLES20.glDisableVertexAttribArray(planeXZPositionAlphaAttribute);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDepthMask(true);
ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes");
}
private static void colorRgbaToFloat(float[] planeColor, int colorRgba) {
planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f;
planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f;
planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f;
planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f;
}
private static final int[] PLANE_COLORS_RGBA = {
0xFFFFFFFF,
0xF44336FF,
0xE91E63FF,
0x9C27B0FF,
0x673AB7FF,
0x3F51B5FF,
0x2196F3FF,
0x03A9F4FF,
0x00BCD4FF,
0x009688FF,
0x4CAF50FF,
0x8BC34AFF,
0xCDDC39FF,
0xFFEB3BFF,
0xFFC107FF,
0xFF9800FF,
};
}
|
88072_31 | package tx;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class GameOfLife {
//max value for x/y so when the Dataset should have 50*50 pixels this number should be 50
private int MAX;
private HashMap<String, Boolean> CURRENT_GENERATION;
//constructor
public GameOfLife(int max) {
//max ist die höhe und breite. 50 wäre also ein Raster von 50*50 Quadraten (die die coordinaten 0-49 auf beiden achsen haben, weil arrays usw ja bei 0 beginnen)
this.MAX = max;
//das startset wird generiert und als CURRENT_GENERATION gesetzt.
this.CURRENT_GENERATION = this.generate_startset();
}
public void next_generation() {
//so hier soll jetzt die jeweils nächste Generation "heranwachsen"
/* Jetzt der [AUFBAU]
* Also erstmal wo sich die Felder (Quadrate) befinden:
* [MM] X , Y = das momentane Feld!
* [ML] X-1, Y = das Feld davor
* [OL] X-1, Y-1 = das Feld schräg oben links
* [OM] X , Y-1 = das Feld darüber
* [OR] X+1, Y-1 = das Feld schräg oben rechts
* [MR] X+1, Y = das Feld danach
* [UR] X+1, Y+1 = das Feld schräg unten rechts
* [UM] X , Y+1 = das Feld darunter
* [UL] X-1, Y+1 = das Feld schräg unten links
*
* ([OL] steht z.B. für Oben-Links, [ML] für Mitte Links usw.)
*
* [Achtung] Endlos implementation, die Regeln gelten auf einem endlosen feld (thoeretisch), wir haben uns aber
* für eine bestimte Größe (50*50) entschieden. Das Problem ist jetzt:
*
* -> Was ist mit dem nachbarfeld rechts (X+1, Y), wenn X bereits auf Feld 50 ist? Welchen wert hat dieses Feld?
* => Lösung, wir nehemen das erste Feld also X=0 als Nachbarn, so geht das auch auf der Y achse.
* Damit stellen wir in gewisser weise eine unendlichkeit sicher weil alles was auf der Rechten seite über den rand hinaus geht,
* kommt auf der linken seite wieder herein, also der Nachbar vom 50. Feld (X Koordinate 49) ist demnach das Feld mit dem 1. Feld (X Koordinate 0).
* Und weil sich das auch auf die Y achse bezieht hat jedes Feld 8 Nachbarn, weil alles was am Rand steht seine nachbarn auf der entgegengesetzten seite
* findet.
*
* Was ein Gehirnf*ck meine fresse.
*
*
* Jetzt die [REGELN]
*
* [1] Ein Feld ist in seiner nächsten Generation ausgefüllt, wenn es in seiner jetztigen generation
* AUSGEFÜLLT war und 2-3 ausgefüllte nachbarfelder hat. <ÜBERLEBT>
*
* [2] Ein Feld ist in seiner nächsten Generation ausgefült, wenn es in seiner jetztigen generation
* NICHT AUSGEFÜLLT war, und genau 3 ausgefüllte nachbarfelder hat. <GEBOREN>
* -> Bedeutet bei der [1] Regel müssen wir blos schauen ob es momentan ausgefüllt ist und ob es 2 Nachbarn hat,
* weil mit 3 nachbarn wird ja automatisch ein neues geboren, somit wäre ein zusätzliche if abfrage doppelt gemoppelt.
*
* [3] Ein Feld ist in seiner nächsten Generation NICHT AUSGEFÜLLT, wenn es in seiner jetzigen generation nur 1 oder mehr als 3
* also 4+ ausgefüllte nachbarn hat. <TOT/Gar nicht erst geboren>
*
*
* Also auf an die Implementation:
* */
//wir definieren erstmal eine neue Next-Generation Map in die wir nach und nach die Nächste generation speichern.
var NEXT_GENERATION = new HashMap<String, Boolean>();
//Jetzt wieder alle Koordinaten durchgehen und alle deren Nachbarfelder überprüfen ob sie momentan ausgefüllt sind.
for(int y = 0; y < this.MAX; y++) {
for(int x = 0; x < this.MAX; x++) {
//Nachbarfeld counter, wird immer um 1 erhöht wenn ein Nachbarfeld ausgefüllt ist.
var counter = 0;
//[MM] momentanes Feld um das es gerade geht
var MOMENTAN_AUSGEFULLT = cord(x,y);
//counter += 1 wenn entsprechnede coordinate true zurückgibt also ausgefüllt ist
counter += (this.cord(x-1,y) == true) ? 1 : 0; //[ML]
counter += (this.cord(x-1,y-1) == true) ? 1 : 0; //[OL]
counter += (this.cord(x,y-1) == true) ? 1 : 0; //[OM]
counter += (this.cord(x+1,y-1) == true) ? 1 : 0; //[OR]
counter += (this.cord(x+1,y) == true) ? 1 : 0; //[MR]
counter += (this.cord(x+1,y+1) == true) ? 1 : 0; //[UR]
counter += (this.cord(x,y+1) == true) ? 1 : 0; //[UM]
counter += (this.cord(x-1,y+1) == true) ? 1 : 0; //[UL]
//jetzt noch die logik für die [REGELN]
//[1] Regel -> Wenn sie in dieser Generation ausgefüllt war, überlebt sie mit nur 2 nachbarn auch in der nächsten generation
if(MOMENTAN_AUSGEFULLT == true && counter == 2) {
NEXT_GENERATION.put(x+":"+y, true); //überlebt
}
//[2] Regel -> wenn sie mindestens 3 Nachbarn hat, ist sie in der nächsten generation ausgefüllt egal ob sie in dieser generation ausgefüllt war oder nicht
else if(counter == 3) {
NEXT_GENERATION.put(x+":"+y, true); //wird geboren
}
//[3] Regel -> in jedem anderen fall stirbt sie oder wird gar nicht erst geboren (ausgefüllt)
else {
NEXT_GENERATION.put(x+":"+y, false); //stirbt
}
//nicht vergessen counter wieder auf 0 zu setzen, weil wir ja in der For schleife jede coordinate einzeln durchlaufen und jedes mal alle ihre 8 nachbarn zählen
counter = 0;
}
}
//Zum Schluss setzen wir die Momentane Generation zur nächsten generation,
//also ist die Momentane Generation jetzt die Nächste Generation, und mit pane_from_current()
//kann man jetzt die neue Pane bekommen und in der Main.java dann mit setBottom() updaten/setzen.
this.CURRENT_GENERATION = NEXT_GENERATION;
}
//Gibt true zurück wenn die gegebene koordinate ausgefüllt ist, sonst false.
public Boolean cord(int x, int y) {
//[Logik] wenn x oder y über seine breite hinausgeht oder kleiner als index 0, wird das jeweils erste oder letzte element zugewiesen:
// => also Nachbar Rechts vom Feld X 50 (Koordinate X 49) ist das erste element (Koordinate X 0) und so weiter
if(x == this.MAX) {
x = 0;
}
if(y == this.MAX) {
y = 0;
}
if(x == -1) {
x = this.MAX-1;
}
if(y == -1) {
y = this.MAX-1;
}
//und dann einfach true oder false zurückgeben ob der jeweilige nachbar eben ausgefüllt ist oder nicht.
return this.CURRENT_GENERATION.get(x+":"+y);
}
//generiert eine Pane inklusive aller kleinen Ausgefüllten und nicht ausgefüllten Quadarte - aus der this.CURRENT_GENERATION hashmap
public Pane pane_from_current() {
var sub_pane = new Pane();
for(int y = 0; y < this.MAX; y++) {
for(int x = 0; x < this.MAX; x++) {
//neues Quadrat erzeugen
var r = new Rectangle(10,10);
//warum hier *11? -> Weil tatsächlich dadurch zwischen den Quadraten am ende immer 1 px abstand zum nächsten ist.
r.setX(x*11);
r.setY(y*11);
//optional zur verschönerung abgerundete Ecken:
r.setArcHeight(6);
r.setArcWidth(6);
//wenn das entsprechende Feld True ist, heißt es es ist ausgefüllt
if(this.CURRENT_GENERATION.get(x+":"+y) == true) {
r.setFill(Color.BLUEVIOLET);
}else{
r.setFill(Color.WHITE);
}
sub_pane.getChildren().add(r);
}
}
return sub_pane;
}
//das STARTSET ist der Ausgangszustand, also quasi die Formation mit der wir starten, also wenn das Programm ausgeführt wird, sind die in dem Array "alive" angegebenen
//elemente die koordinaten "x:y" die ausgefüllt sind.
public HashMap<String, Boolean> generate_startset() {
String[] alive = {
"10:10", "11:10", "9:11", "12:11", "10:12",
"12:12", "11:13", "20:20", "21:20", "22:20",
"22:21", "21:22", "30:30", "31:30", "29:31",
"30:31", "30:32", "40:40", "41:40", "42:40",
"43:40", "44:40", "45:40", "41:41", "42:41",
"43:41", "44:41", "45:41", "41:42", "43:42",
"44:42", "45:42", "41:43", "42:43", "43:43",
"44:43", "45:43", "5:5", "6:5", "6:6", "5:6",
"5:7","5:4", "15:15", "16:15", "17:15", "18:15",
"14:16", "18:16", "18:17", "14:18", "17:18","17:19"
};
//das eben angelegte Array in eine Liste umwandeln um es einfacher zu handlen
List<String> alive_list = Arrays.asList(alive);
//hashmap inistialisieren die als Key "x:y" und als value einen boolean nimmt. true = ausgefüllt, false = nicht ausgefüllt
var startset = new HashMap<String, Boolean>();
//erstmal alle coordinaten erzeugen
for (int y = 0; y < this.MAX; y++) {
//und noch die x coordinaten
for(int x = 0; x < this.MAX; x++) {
//element
if(alive_list.contains((x+":"+y)))
{
//die coordinate befindet sich im array also ist sie ausgefüllt
startset.put(x+":"+y, true);
} else {
//die coordinate ist nicht im array also ist sie nicht ausgefüllt
startset.put(x+":"+y, false);
}
}
}
return startset;
}
}
| noxomix/prakt-was-ich-nicht-machen-muss | mit_dokumentation/GameOfLife.java | 3,351 | //erstmal alle coordinaten erzeugen | line_comment | nl | package tx;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class GameOfLife {
//max value for x/y so when the Dataset should have 50*50 pixels this number should be 50
private int MAX;
private HashMap<String, Boolean> CURRENT_GENERATION;
//constructor
public GameOfLife(int max) {
//max ist die höhe und breite. 50 wäre also ein Raster von 50*50 Quadraten (die die coordinaten 0-49 auf beiden achsen haben, weil arrays usw ja bei 0 beginnen)
this.MAX = max;
//das startset wird generiert und als CURRENT_GENERATION gesetzt.
this.CURRENT_GENERATION = this.generate_startset();
}
public void next_generation() {
//so hier soll jetzt die jeweils nächste Generation "heranwachsen"
/* Jetzt der [AUFBAU]
* Also erstmal wo sich die Felder (Quadrate) befinden:
* [MM] X , Y = das momentane Feld!
* [ML] X-1, Y = das Feld davor
* [OL] X-1, Y-1 = das Feld schräg oben links
* [OM] X , Y-1 = das Feld darüber
* [OR] X+1, Y-1 = das Feld schräg oben rechts
* [MR] X+1, Y = das Feld danach
* [UR] X+1, Y+1 = das Feld schräg unten rechts
* [UM] X , Y+1 = das Feld darunter
* [UL] X-1, Y+1 = das Feld schräg unten links
*
* ([OL] steht z.B. für Oben-Links, [ML] für Mitte Links usw.)
*
* [Achtung] Endlos implementation, die Regeln gelten auf einem endlosen feld (thoeretisch), wir haben uns aber
* für eine bestimte Größe (50*50) entschieden. Das Problem ist jetzt:
*
* -> Was ist mit dem nachbarfeld rechts (X+1, Y), wenn X bereits auf Feld 50 ist? Welchen wert hat dieses Feld?
* => Lösung, wir nehemen das erste Feld also X=0 als Nachbarn, so geht das auch auf der Y achse.
* Damit stellen wir in gewisser weise eine unendlichkeit sicher weil alles was auf der Rechten seite über den rand hinaus geht,
* kommt auf der linken seite wieder herein, also der Nachbar vom 50. Feld (X Koordinate 49) ist demnach das Feld mit dem 1. Feld (X Koordinate 0).
* Und weil sich das auch auf die Y achse bezieht hat jedes Feld 8 Nachbarn, weil alles was am Rand steht seine nachbarn auf der entgegengesetzten seite
* findet.
*
* Was ein Gehirnf*ck meine fresse.
*
*
* Jetzt die [REGELN]
*
* [1] Ein Feld ist in seiner nächsten Generation ausgefüllt, wenn es in seiner jetztigen generation
* AUSGEFÜLLT war und 2-3 ausgefüllte nachbarfelder hat. <ÜBERLEBT>
*
* [2] Ein Feld ist in seiner nächsten Generation ausgefült, wenn es in seiner jetztigen generation
* NICHT AUSGEFÜLLT war, und genau 3 ausgefüllte nachbarfelder hat. <GEBOREN>
* -> Bedeutet bei der [1] Regel müssen wir blos schauen ob es momentan ausgefüllt ist und ob es 2 Nachbarn hat,
* weil mit 3 nachbarn wird ja automatisch ein neues geboren, somit wäre ein zusätzliche if abfrage doppelt gemoppelt.
*
* [3] Ein Feld ist in seiner nächsten Generation NICHT AUSGEFÜLLT, wenn es in seiner jetzigen generation nur 1 oder mehr als 3
* also 4+ ausgefüllte nachbarn hat. <TOT/Gar nicht erst geboren>
*
*
* Also auf an die Implementation:
* */
//wir definieren erstmal eine neue Next-Generation Map in die wir nach und nach die Nächste generation speichern.
var NEXT_GENERATION = new HashMap<String, Boolean>();
//Jetzt wieder alle Koordinaten durchgehen und alle deren Nachbarfelder überprüfen ob sie momentan ausgefüllt sind.
for(int y = 0; y < this.MAX; y++) {
for(int x = 0; x < this.MAX; x++) {
//Nachbarfeld counter, wird immer um 1 erhöht wenn ein Nachbarfeld ausgefüllt ist.
var counter = 0;
//[MM] momentanes Feld um das es gerade geht
var MOMENTAN_AUSGEFULLT = cord(x,y);
//counter += 1 wenn entsprechnede coordinate true zurückgibt also ausgefüllt ist
counter += (this.cord(x-1,y) == true) ? 1 : 0; //[ML]
counter += (this.cord(x-1,y-1) == true) ? 1 : 0; //[OL]
counter += (this.cord(x,y-1) == true) ? 1 : 0; //[OM]
counter += (this.cord(x+1,y-1) == true) ? 1 : 0; //[OR]
counter += (this.cord(x+1,y) == true) ? 1 : 0; //[MR]
counter += (this.cord(x+1,y+1) == true) ? 1 : 0; //[UR]
counter += (this.cord(x,y+1) == true) ? 1 : 0; //[UM]
counter += (this.cord(x-1,y+1) == true) ? 1 : 0; //[UL]
//jetzt noch die logik für die [REGELN]
//[1] Regel -> Wenn sie in dieser Generation ausgefüllt war, überlebt sie mit nur 2 nachbarn auch in der nächsten generation
if(MOMENTAN_AUSGEFULLT == true && counter == 2) {
NEXT_GENERATION.put(x+":"+y, true); //überlebt
}
//[2] Regel -> wenn sie mindestens 3 Nachbarn hat, ist sie in der nächsten generation ausgefüllt egal ob sie in dieser generation ausgefüllt war oder nicht
else if(counter == 3) {
NEXT_GENERATION.put(x+":"+y, true); //wird geboren
}
//[3] Regel -> in jedem anderen fall stirbt sie oder wird gar nicht erst geboren (ausgefüllt)
else {
NEXT_GENERATION.put(x+":"+y, false); //stirbt
}
//nicht vergessen counter wieder auf 0 zu setzen, weil wir ja in der For schleife jede coordinate einzeln durchlaufen und jedes mal alle ihre 8 nachbarn zählen
counter = 0;
}
}
//Zum Schluss setzen wir die Momentane Generation zur nächsten generation,
//also ist die Momentane Generation jetzt die Nächste Generation, und mit pane_from_current()
//kann man jetzt die neue Pane bekommen und in der Main.java dann mit setBottom() updaten/setzen.
this.CURRENT_GENERATION = NEXT_GENERATION;
}
//Gibt true zurück wenn die gegebene koordinate ausgefüllt ist, sonst false.
public Boolean cord(int x, int y) {
//[Logik] wenn x oder y über seine breite hinausgeht oder kleiner als index 0, wird das jeweils erste oder letzte element zugewiesen:
// => also Nachbar Rechts vom Feld X 50 (Koordinate X 49) ist das erste element (Koordinate X 0) und so weiter
if(x == this.MAX) {
x = 0;
}
if(y == this.MAX) {
y = 0;
}
if(x == -1) {
x = this.MAX-1;
}
if(y == -1) {
y = this.MAX-1;
}
//und dann einfach true oder false zurückgeben ob der jeweilige nachbar eben ausgefüllt ist oder nicht.
return this.CURRENT_GENERATION.get(x+":"+y);
}
//generiert eine Pane inklusive aller kleinen Ausgefüllten und nicht ausgefüllten Quadarte - aus der this.CURRENT_GENERATION hashmap
public Pane pane_from_current() {
var sub_pane = new Pane();
for(int y = 0; y < this.MAX; y++) {
for(int x = 0; x < this.MAX; x++) {
//neues Quadrat erzeugen
var r = new Rectangle(10,10);
//warum hier *11? -> Weil tatsächlich dadurch zwischen den Quadraten am ende immer 1 px abstand zum nächsten ist.
r.setX(x*11);
r.setY(y*11);
//optional zur verschönerung abgerundete Ecken:
r.setArcHeight(6);
r.setArcWidth(6);
//wenn das entsprechende Feld True ist, heißt es es ist ausgefüllt
if(this.CURRENT_GENERATION.get(x+":"+y) == true) {
r.setFill(Color.BLUEVIOLET);
}else{
r.setFill(Color.WHITE);
}
sub_pane.getChildren().add(r);
}
}
return sub_pane;
}
//das STARTSET ist der Ausgangszustand, also quasi die Formation mit der wir starten, also wenn das Programm ausgeführt wird, sind die in dem Array "alive" angegebenen
//elemente die koordinaten "x:y" die ausgefüllt sind.
public HashMap<String, Boolean> generate_startset() {
String[] alive = {
"10:10", "11:10", "9:11", "12:11", "10:12",
"12:12", "11:13", "20:20", "21:20", "22:20",
"22:21", "21:22", "30:30", "31:30", "29:31",
"30:31", "30:32", "40:40", "41:40", "42:40",
"43:40", "44:40", "45:40", "41:41", "42:41",
"43:41", "44:41", "45:41", "41:42", "43:42",
"44:42", "45:42", "41:43", "42:43", "43:43",
"44:43", "45:43", "5:5", "6:5", "6:6", "5:6",
"5:7","5:4", "15:15", "16:15", "17:15", "18:15",
"14:16", "18:16", "18:17", "14:18", "17:18","17:19"
};
//das eben angelegte Array in eine Liste umwandeln um es einfacher zu handlen
List<String> alive_list = Arrays.asList(alive);
//hashmap inistialisieren die als Key "x:y" und als value einen boolean nimmt. true = ausgefüllt, false = nicht ausgefüllt
var startset = new HashMap<String, Boolean>();
//erstmal alle<SUF>
for (int y = 0; y < this.MAX; y++) {
//und noch die x coordinaten
for(int x = 0; x < this.MAX; x++) {
//element
if(alive_list.contains((x+":"+y)))
{
//die coordinate befindet sich im array also ist sie ausgefüllt
startset.put(x+":"+y, true);
} else {
//die coordinate ist nicht im array also ist sie nicht ausgefüllt
startset.put(x+":"+y, false);
}
}
}
return startset;
}
}
|
188962_31 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Ecosystem {
public class Organism {
public String name; //name of organism (either specified or auto-generated)
public int level;
public String type; //type of organism (plant, animal, etc.)
public String lifestyle; //what types of organisms it eats (for animals)
public ArrayList<String> preyList; //all the organisms it eats
//each value in here is a trophic link, as the links are being designed
//as predator ---> prey links (instead of double counting them or using both prey and predator links)
public Organism(String name, int level, String type, String eating, ArrayList<String> preyList) {
this.name = name;
this.level = level;
this.type = type;
this.lifestyle = eating;
this.preyList = preyList;
}
public Organism(String name) {
this.name = name;
this.preyList = new ArrayList<String>();
}
public void assignLevel() { //assigns trophic level to organism
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
if (random <= 5) this.level = 4; //5% chance
else if (random <= 20) this.level = 3; //15% chance (20 - 15)
else if (random <= 50) this.level = 2; //30% chance
else this.level = 1; //50% chance
}
public void assignType() { //assigns type of organism to organism
//"plant", "animal"
if (this.level == 1) this.type = "plant";
else if (this.level > 1 && this.level <= 4) this.type = "animal";
else System.out.print("assignType: Organism is not in a trophic level");
}
public void assignLifestyle() { //assigns what the organism eats
//"none", "carnivore", "herbivore", "omnivore"
if (this.level == 1) {
this.lifestyle = "none"; //basal species, so no prey
}
else if (this.level == 2) {
this.lifestyle = "herbivore"; //get food from plants primarily
}
else if (this.level == 3) { //get food from plants or animals
int random = (int)(Math.random()*100 + 1);
if (random <= 40) this.lifestyle = "omnivore"; //40% chance
else this.lifestyle = "carnivore"; //60% chance
}
else if (this.level == 4) { //mostly get food from animals (but can also get food from plants)
int random = (int)(Math.random()*100 + 1);
if (random <= 10) this.lifestyle = "omnivore"; //10% chance
else this.lifestyle = "carnivore"; //90% chance
}
}
public String preyString() { //preyList will be sorted by commas
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.preyList.size(); i++) {
if (i == this.preyList.size() - 1) sb.append(preyList.get(i));
else sb.append(preyList.get(i)+ ",");
}
return sb.toString();
}
public String toString() {
return this.name + " " + this.type + " " + this.lifestyle + " " + this.preyString();
}
}
public class DataPoint { //to hold data points in a better manner
public int trophicLinks;
public int speciesNum;
public double connectance;
public DataPoint(int trophicLinks, int speciesNum, double connectance) {
this.trophicLinks = trophicLinks;
this.speciesNum = speciesNum;
this.connectance = connectance;
}
public String toString() {
return "Links: " + this.trophicLinks + " Species: " + this.speciesNum + " Connectance: " + this.connectance;
}
}
//final int[] foodChance = {0, 20, 40, 55, 65, 75, 80, 85, 90}; //(original) low chance
//final int[] foodChance = {0, 10, 20, 35, 45, 50, 55, 60, 60}; //(original) high chance
//final int[] foodChance = {0, 25, 45, 65, 75, 80, 85, 90, 90}; //low chance
//final int[] foodChance = {0, 30, 55, 70, 80, 85, 90, 95, 95}; //lower chance
final int[] foodChance = {0, 50, 65, 75, 85, 90, 90, 95, 95}; // absoluteLow chance
//final int[] foodChance = {0, 15, 35, 45, 55, 65, 70, 75, 75}; //medium chance
//final int[] foodChance = {0, 5, 20, 30, 40, 45, 50, 55, 60}; //high chance //inverse chances of getting another food source (
//makes it so the more food sources an organism has, the less likely it is to get another
ArrayList<ArrayList<Organism>> trophicLevels; //each index is ArrayList for that trophic level
ArrayList<DataPoint> data; //to hold all the data points for plotting (either in this or another file)
ArrayList<String> carnivoreNames;
ArrayList<String> herbivoreNames;
ArrayList<String> omnivoreNames;
ArrayList<String> plantNames;
public Ecosystem () {
trophicLevels = new ArrayList<ArrayList<Organism>>();
data = new ArrayList<DataPoint>();
for (int i = 0; i < 4; i++) { //adding each trophic level
trophicLevels.add(new ArrayList<Organism>()); //IN ORDER (index 0 is trophic level 1)
}
}
public ArrayList<Integer> getRandomIndex(ArrayList<Organism> trophic){
ArrayList<Integer> indexes = new ArrayList<Integer>();
while (indexes.size() != trophic.size()) {
int random = (int)(Math.random()*trophic.size());
if (indexes.contains(random) == false) indexes.add(random);
}
for (int i = 0; i < indexes.size(); i++) {
System.out.println(indexes.get(i));
}
return indexes;
}
public void assignPredators(Organism o) { //assign all predators for given organism
if (o.level == 4) return; //no predators for apex predator (4th level)
else if (o.level > 0 && o.level < 4) { //between 1 and 3
int predatorLevel = o.level; // level above it (where the predators would be) (level is 1 more than index so it equals index + 1)
ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(predatorLevel)); //gets indexes according to size but in random order
for (int i = 0; i < randomIndex.size(); i++) {
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
int sizePrey = trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.size();
int chance = 0; //chance of becoming a predator for the given organism
if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance
else chance = foodChance[sizePrey]; //appropriate chance
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("carnivore")) {
if (o.type.equals("animal")) {
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if carnivore eating animal that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name);
}
}
}
}
else if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("herbivore")) {
if (o.type.equals("plant")) {
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if herbivore eating plant that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name);
}
}
}
}
else if (trophicLevels.get(predatorLevel).get(i).lifestyle.equals("omnivore")) {
if (trophicLevels.get(predatorLevel).get(i).preyList.contains(o.name) == false) { //if omnivore eating something that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(i).preyList.add(o.name);
}
}
}
}
}
}
public void assignPrey(Organism o) { //assign all the prey for given organism
if (o.level == 1) return; //no prey for basal species (1st level)
else if (o.level > 1 && o.level <= 4) { //between 2 and 4
int preyLevel = o.level - 2; // level below it (where the prey would be) (since level = index + 1, level below is index - 2)
ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(preyLevel)); //gets indexes according to size but in random order
for (int i = 0; i < randomIndex.size(); i++) {
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
int sizePrey = o.preyList.size();
int chance = 0; //chance of the given organism getting more prey
if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance
else chance = foodChance[sizePrey]; //appropriate chance
if (o.lifestyle.equals("carnivore")) {
if (trophicLevels.get(preyLevel).get(i).type.equals("animal")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if carnivore eating animal that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
else if (o.lifestyle.equals("herbivore")) {
if (trophicLevels.get(preyLevel).get(i).type.equals("plant")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if herbivore eating plant that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
else if (o.lifestyle.equals("omnivore")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if omnivore eating something that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
}
}
public void initializeNames() throws FileNotFoundException { //for adding names into the name arrays using files of words/names
carnivoreNames = new ArrayList<String>();
herbivoreNames = new ArrayList<String>();
omnivoreNames = new ArrayList<String>();
plantNames = new ArrayList<String>();
Scanner fileContents = new Scanner(new File("names/randomCarnivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
carnivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomHerbivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
herbivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomOmnivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
omnivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomPlant.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
plantNames.add(contents);
}
fileContents.close();
}
public String randomName(ArrayList<String> nameList) { //corresponding ArrayList gets a name chosen and removed
int random = (int)(Math.random()*nameList.size()); //between 0 and size of list (not including the actual size tho)
String name = nameList.get(random);
nameList.remove(random); //so repeat names can't show up
return name;
}
public void addOrganism(String name, int level, String type, String lifestyle, ArrayList<String> preyList) { //in case any of it is already initialized
Organism o = new Organism(name); //so organism functions can be used
if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements)
o.assignLevel();
o.assignType();
o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
assignPrey(o);
assignPredators(o);
}
//if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details)
if (type.isEmpty()) o.assignType();
if (lifestyle.isEmpty()) o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
if (preyList.isEmpty()) assignPrey(o);
assignPredators(o);
trophicLevels.get(o.level - 1).add(o);
return;
}
public void addBeforeAssign(String name, int level, String type, String lifestyle) { //adding function where predator and prey are assigned later
Organism o = new Organism(name); //so organism functions can be used
if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements)
o.assignLevel();
o.assignType();
o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
}
else o.level = level;
//if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details)
if (type.isEmpty()) o.assignType();
else o.type = type;
if (lifestyle.isEmpty()) o.assignLifestyle();
else o.lifestyle = lifestyle;
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
else o.name = name;
trophicLevels.get(o.level - 1).add(o);
return;
}
public boolean removeOrganism(String name) { //removes a given organism (searches by name for it)
int level = 0; //trophic level of organism
for (int i = 0; i < trophicLevels.size(); i++) {
for (int j = 0; j < trophicLevels.get(i).size(); j++) {
if (trophicLevels.get(i).get(j).name.equals(name)) {
level = i + 1;
trophicLevels.get(i).remove(j); //removes organism at given index
if (level != 4) { //not apex predator
for (int k = 0; k < trophicLevels.get(level).size(); k++) {
if (trophicLevels.get(level).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators
trophicLevels.get(level).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it)
}
}
}
return true;
}
}
}
return false;
}
public boolean removeOrganism(String name, int level) { //removes a given organism (searches by name for it but uses level to make it faster)
int levelUpdated = level - 1;
for (int j = 0; j < trophicLevels.get(levelUpdated).size(); j++) {
if (trophicLevels.get(levelUpdated).get(j).name.equals(name)) {
trophicLevels.get(levelUpdated).remove(j); //removes organism at given index
if (level != 4) { //not apex predator
for (int k = 0; k < trophicLevels.get(levelUpdated).size(); k++) {
if (trophicLevels.get(levelUpdated).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators
trophicLevels.get(levelUpdated).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it)
}
}
}
return true;
}
}
return false;
}
public int getTrophicLinks() {
int trophicLinks = 0;
for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level
for (int j = 0; j < trophicLevels.get(i).size(); j++) { //each organism in trophic level
trophicLinks += trophicLevels.get(i).get(j).preyList.size(); //size of preyList (each being a link)
}
}
return trophicLinks;
}
public int getSpeciesNumber() {
int species = 0;
for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level
species += trophicLevels.get(i).size(); //size of each trophic level (# of organisms in it)
}
return species;
}
public float getConnectance(int trophicLinks, int speciesNumber) {
float links = (float) trophicLinks;
float species = (float) speciesNumber;
return (links / ((species * (species - 1)) / 2));
}
public DataPoint getData(int links, int species, double connectance) {
return new DataPoint(links, species, connectance);
}
public void addData(DataPoint dataPoint) { //may not need function but good to have just in case
data.add(dataPoint);
}
public void saveEcosystem(String name) throws FileNotFoundException {
File file = new File("ecostorage/" + name + "Eco.txt"); //make name same as ecosystem name for simplicity
PrintWriter logger = new PrintWriter(file);
for (int i = 3; i >= 0; i--) {
int level = i + 1;
logger.println("Trophic Level " + level + ": " + trophicLevels.get(i).size() + " Organisms");
ArrayList<Organism> currentLevel = trophicLevels.get(i);
for (int j = 0; j < currentLevel.size(); j++) {
logger.println(currentLevel.get(j).toString());
}
logger.println();
}
logger.close();
}
public void saveData(String name) throws FileNotFoundException {
File file = new File("datastorage/" + name + "Data.txt"); //make name same as ecosystem name for simplicity
PrintWriter logger = new PrintWriter(file);
for (int i = 0; i < data.size(); i++) {
logger.println(data.get(i).toString());
}
logger.close();
}
/*public void testFunc() { //for testing features of subclasses
Organism tests = new Organism("tests");
for (int i = 0; i < 10000; i++) {
int chance = tests.assignLevel();
if (chance == 0) {
break;
}
}
}*/
public static void main(String[] args) throws FileNotFoundException {
for (int k = 0; k < 20; k++) {
Ecosystem test = new Ecosystem();
test.initializeNames();
ArrayList<String> a = new ArrayList<String>(); //so addOrganism works
//initial species
test.addBeforeAssign("a", 4, "animal", "carnivore");
test.addBeforeAssign("g", 3, "animal", "omnivore");
test.addBeforeAssign("p", 2, "animal", "herbivore");
test.addBeforeAssign("z", 1, "plant", "none");
for (int i = 0; i < 6; i++) {
test.addBeforeAssign("", 0, "", ""); //default values so it randomizes them all
}
//assign predator and prey for them all
for (int i = 0; i < test.trophicLevels.size(); i++) {
for (int j = 0; j < test.trophicLevels.get(i).size(); j++) {
test.assignPrey(test.trophicLevels.get(i).get(j));
}
}
//initial data point
int links = test.getTrophicLinks();
int species = test.getSpeciesNumber();
double connectance = test.getConnectance(links, species);
DataPoint data = test.getData(links, species, connectance);
test.addData(data);
//test.saveEcosystem("test1");
//test.saveData("test1");
//adding extra species
for (int i = 0; i < 25; i++) {
test.addOrganism("", 0, "", "", a); //default values so it randomizes them all
links = test.getTrophicLinks();
species = test.getSpeciesNumber();
connectance = test.getConnectance(links, species);
data = test.getData(links, species, connectance);
test.addData(data);
}
//saving work
String name = "rem" + k; //CHANGE name here for new data set
test.saveEcosystem(name);
test.saveData(name);
//test.saveEcosystem("test");
}
}
}
| npal312/ecosystem-simulator | EN-250/src/Ecosystem.java | 6,973 | //between 1 and 3 | line_comment | nl | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Ecosystem {
public class Organism {
public String name; //name of organism (either specified or auto-generated)
public int level;
public String type; //type of organism (plant, animal, etc.)
public String lifestyle; //what types of organisms it eats (for animals)
public ArrayList<String> preyList; //all the organisms it eats
//each value in here is a trophic link, as the links are being designed
//as predator ---> prey links (instead of double counting them or using both prey and predator links)
public Organism(String name, int level, String type, String eating, ArrayList<String> preyList) {
this.name = name;
this.level = level;
this.type = type;
this.lifestyle = eating;
this.preyList = preyList;
}
public Organism(String name) {
this.name = name;
this.preyList = new ArrayList<String>();
}
public void assignLevel() { //assigns trophic level to organism
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
if (random <= 5) this.level = 4; //5% chance
else if (random <= 20) this.level = 3; //15% chance (20 - 15)
else if (random <= 50) this.level = 2; //30% chance
else this.level = 1; //50% chance
}
public void assignType() { //assigns type of organism to organism
//"plant", "animal"
if (this.level == 1) this.type = "plant";
else if (this.level > 1 && this.level <= 4) this.type = "animal";
else System.out.print("assignType: Organism is not in a trophic level");
}
public void assignLifestyle() { //assigns what the organism eats
//"none", "carnivore", "herbivore", "omnivore"
if (this.level == 1) {
this.lifestyle = "none"; //basal species, so no prey
}
else if (this.level == 2) {
this.lifestyle = "herbivore"; //get food from plants primarily
}
else if (this.level == 3) { //get food from plants or animals
int random = (int)(Math.random()*100 + 1);
if (random <= 40) this.lifestyle = "omnivore"; //40% chance
else this.lifestyle = "carnivore"; //60% chance
}
else if (this.level == 4) { //mostly get food from animals (but can also get food from plants)
int random = (int)(Math.random()*100 + 1);
if (random <= 10) this.lifestyle = "omnivore"; //10% chance
else this.lifestyle = "carnivore"; //90% chance
}
}
public String preyString() { //preyList will be sorted by commas
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.preyList.size(); i++) {
if (i == this.preyList.size() - 1) sb.append(preyList.get(i));
else sb.append(preyList.get(i)+ ",");
}
return sb.toString();
}
public String toString() {
return this.name + " " + this.type + " " + this.lifestyle + " " + this.preyString();
}
}
public class DataPoint { //to hold data points in a better manner
public int trophicLinks;
public int speciesNum;
public double connectance;
public DataPoint(int trophicLinks, int speciesNum, double connectance) {
this.trophicLinks = trophicLinks;
this.speciesNum = speciesNum;
this.connectance = connectance;
}
public String toString() {
return "Links: " + this.trophicLinks + " Species: " + this.speciesNum + " Connectance: " + this.connectance;
}
}
//final int[] foodChance = {0, 20, 40, 55, 65, 75, 80, 85, 90}; //(original) low chance
//final int[] foodChance = {0, 10, 20, 35, 45, 50, 55, 60, 60}; //(original) high chance
//final int[] foodChance = {0, 25, 45, 65, 75, 80, 85, 90, 90}; //low chance
//final int[] foodChance = {0, 30, 55, 70, 80, 85, 90, 95, 95}; //lower chance
final int[] foodChance = {0, 50, 65, 75, 85, 90, 90, 95, 95}; // absoluteLow chance
//final int[] foodChance = {0, 15, 35, 45, 55, 65, 70, 75, 75}; //medium chance
//final int[] foodChance = {0, 5, 20, 30, 40, 45, 50, 55, 60}; //high chance //inverse chances of getting another food source (
//makes it so the more food sources an organism has, the less likely it is to get another
ArrayList<ArrayList<Organism>> trophicLevels; //each index is ArrayList for that trophic level
ArrayList<DataPoint> data; //to hold all the data points for plotting (either in this or another file)
ArrayList<String> carnivoreNames;
ArrayList<String> herbivoreNames;
ArrayList<String> omnivoreNames;
ArrayList<String> plantNames;
public Ecosystem () {
trophicLevels = new ArrayList<ArrayList<Organism>>();
data = new ArrayList<DataPoint>();
for (int i = 0; i < 4; i++) { //adding each trophic level
trophicLevels.add(new ArrayList<Organism>()); //IN ORDER (index 0 is trophic level 1)
}
}
public ArrayList<Integer> getRandomIndex(ArrayList<Organism> trophic){
ArrayList<Integer> indexes = new ArrayList<Integer>();
while (indexes.size() != trophic.size()) {
int random = (int)(Math.random()*trophic.size());
if (indexes.contains(random) == false) indexes.add(random);
}
for (int i = 0; i < indexes.size(); i++) {
System.out.println(indexes.get(i));
}
return indexes;
}
public void assignPredators(Organism o) { //assign all predators for given organism
if (o.level == 4) return; //no predators for apex predator (4th level)
else if (o.level > 0 && o.level < 4) { //between 1<SUF>
int predatorLevel = o.level; // level above it (where the predators would be) (level is 1 more than index so it equals index + 1)
ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(predatorLevel)); //gets indexes according to size but in random order
for (int i = 0; i < randomIndex.size(); i++) {
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
int sizePrey = trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.size();
int chance = 0; //chance of becoming a predator for the given organism
if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance
else chance = foodChance[sizePrey]; //appropriate chance
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("carnivore")) {
if (o.type.equals("animal")) {
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if carnivore eating animal that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name);
}
}
}
}
else if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("herbivore")) {
if (o.type.equals("plant")) {
if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if herbivore eating plant that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name);
}
}
}
}
else if (trophicLevels.get(predatorLevel).get(i).lifestyle.equals("omnivore")) {
if (trophicLevels.get(predatorLevel).get(i).preyList.contains(o.name) == false) { //if omnivore eating something that it doesn't already eat
if (random <= 100 - chance) {
trophicLevels.get(predatorLevel).get(i).preyList.add(o.name);
}
}
}
}
}
}
public void assignPrey(Organism o) { //assign all the prey for given organism
if (o.level == 1) return; //no prey for basal species (1st level)
else if (o.level > 1 && o.level <= 4) { //between 2 and 4
int preyLevel = o.level - 2; // level below it (where the prey would be) (since level = index + 1, level below is index - 2)
ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(preyLevel)); //gets indexes according to size but in random order
for (int i = 0; i < randomIndex.size(); i++) {
int random = (int)(Math.random()*100 + 1); //number between 1 and 100
int sizePrey = o.preyList.size();
int chance = 0; //chance of the given organism getting more prey
if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance
else chance = foodChance[sizePrey]; //appropriate chance
if (o.lifestyle.equals("carnivore")) {
if (trophicLevels.get(preyLevel).get(i).type.equals("animal")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if carnivore eating animal that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
else if (o.lifestyle.equals("herbivore")) {
if (trophicLevels.get(preyLevel).get(i).type.equals("plant")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if herbivore eating plant that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
else if (o.lifestyle.equals("omnivore")) {
if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if omnivore eating something that it doesn't already eat
if (random <= 100 - chance) {
o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name);
}
}
}
}
}
}
public void initializeNames() throws FileNotFoundException { //for adding names into the name arrays using files of words/names
carnivoreNames = new ArrayList<String>();
herbivoreNames = new ArrayList<String>();
omnivoreNames = new ArrayList<String>();
plantNames = new ArrayList<String>();
Scanner fileContents = new Scanner(new File("names/randomCarnivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
carnivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomHerbivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
herbivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomOmnivore.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
omnivoreNames.add(contents);
}
fileContents.close();
fileContents = new Scanner(new File("names/randomPlant.txt"));
while (fileContents.hasNext()) {
String contents = fileContents.nextLine();
plantNames.add(contents);
}
fileContents.close();
}
public String randomName(ArrayList<String> nameList) { //corresponding ArrayList gets a name chosen and removed
int random = (int)(Math.random()*nameList.size()); //between 0 and size of list (not including the actual size tho)
String name = nameList.get(random);
nameList.remove(random); //so repeat names can't show up
return name;
}
public void addOrganism(String name, int level, String type, String lifestyle, ArrayList<String> preyList) { //in case any of it is already initialized
Organism o = new Organism(name); //so organism functions can be used
if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements)
o.assignLevel();
o.assignType();
o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
assignPrey(o);
assignPredators(o);
}
//if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details)
if (type.isEmpty()) o.assignType();
if (lifestyle.isEmpty()) o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
if (preyList.isEmpty()) assignPrey(o);
assignPredators(o);
trophicLevels.get(o.level - 1).add(o);
return;
}
public void addBeforeAssign(String name, int level, String type, String lifestyle) { //adding function where predator and prey are assigned later
Organism o = new Organism(name); //so organism functions can be used
if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements)
o.assignLevel();
o.assignType();
o.assignLifestyle();
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
}
else o.level = level;
//if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details)
if (type.isEmpty()) o.assignType();
else o.type = type;
if (lifestyle.isEmpty()) o.assignLifestyle();
else o.lifestyle = lifestyle;
if (name.isEmpty() == true) {
if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames);
else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames);
else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames);
else if (o.type.equals("plant")) o.name = randomName(plantNames);
}
else o.name = name;
trophicLevels.get(o.level - 1).add(o);
return;
}
public boolean removeOrganism(String name) { //removes a given organism (searches by name for it)
int level = 0; //trophic level of organism
for (int i = 0; i < trophicLevels.size(); i++) {
for (int j = 0; j < trophicLevels.get(i).size(); j++) {
if (trophicLevels.get(i).get(j).name.equals(name)) {
level = i + 1;
trophicLevels.get(i).remove(j); //removes organism at given index
if (level != 4) { //not apex predator
for (int k = 0; k < trophicLevels.get(level).size(); k++) {
if (trophicLevels.get(level).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators
trophicLevels.get(level).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it)
}
}
}
return true;
}
}
}
return false;
}
public boolean removeOrganism(String name, int level) { //removes a given organism (searches by name for it but uses level to make it faster)
int levelUpdated = level - 1;
for (int j = 0; j < trophicLevels.get(levelUpdated).size(); j++) {
if (trophicLevels.get(levelUpdated).get(j).name.equals(name)) {
trophicLevels.get(levelUpdated).remove(j); //removes organism at given index
if (level != 4) { //not apex predator
for (int k = 0; k < trophicLevels.get(levelUpdated).size(); k++) {
if (trophicLevels.get(levelUpdated).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators
trophicLevels.get(levelUpdated).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it)
}
}
}
return true;
}
}
return false;
}
public int getTrophicLinks() {
int trophicLinks = 0;
for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level
for (int j = 0; j < trophicLevels.get(i).size(); j++) { //each organism in trophic level
trophicLinks += trophicLevels.get(i).get(j).preyList.size(); //size of preyList (each being a link)
}
}
return trophicLinks;
}
public int getSpeciesNumber() {
int species = 0;
for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level
species += trophicLevels.get(i).size(); //size of each trophic level (# of organisms in it)
}
return species;
}
public float getConnectance(int trophicLinks, int speciesNumber) {
float links = (float) trophicLinks;
float species = (float) speciesNumber;
return (links / ((species * (species - 1)) / 2));
}
public DataPoint getData(int links, int species, double connectance) {
return new DataPoint(links, species, connectance);
}
public void addData(DataPoint dataPoint) { //may not need function but good to have just in case
data.add(dataPoint);
}
public void saveEcosystem(String name) throws FileNotFoundException {
File file = new File("ecostorage/" + name + "Eco.txt"); //make name same as ecosystem name for simplicity
PrintWriter logger = new PrintWriter(file);
for (int i = 3; i >= 0; i--) {
int level = i + 1;
logger.println("Trophic Level " + level + ": " + trophicLevels.get(i).size() + " Organisms");
ArrayList<Organism> currentLevel = trophicLevels.get(i);
for (int j = 0; j < currentLevel.size(); j++) {
logger.println(currentLevel.get(j).toString());
}
logger.println();
}
logger.close();
}
public void saveData(String name) throws FileNotFoundException {
File file = new File("datastorage/" + name + "Data.txt"); //make name same as ecosystem name for simplicity
PrintWriter logger = new PrintWriter(file);
for (int i = 0; i < data.size(); i++) {
logger.println(data.get(i).toString());
}
logger.close();
}
/*public void testFunc() { //for testing features of subclasses
Organism tests = new Organism("tests");
for (int i = 0; i < 10000; i++) {
int chance = tests.assignLevel();
if (chance == 0) {
break;
}
}
}*/
public static void main(String[] args) throws FileNotFoundException {
for (int k = 0; k < 20; k++) {
Ecosystem test = new Ecosystem();
test.initializeNames();
ArrayList<String> a = new ArrayList<String>(); //so addOrganism works
//initial species
test.addBeforeAssign("a", 4, "animal", "carnivore");
test.addBeforeAssign("g", 3, "animal", "omnivore");
test.addBeforeAssign("p", 2, "animal", "herbivore");
test.addBeforeAssign("z", 1, "plant", "none");
for (int i = 0; i < 6; i++) {
test.addBeforeAssign("", 0, "", ""); //default values so it randomizes them all
}
//assign predator and prey for them all
for (int i = 0; i < test.trophicLevels.size(); i++) {
for (int j = 0; j < test.trophicLevels.get(i).size(); j++) {
test.assignPrey(test.trophicLevels.get(i).get(j));
}
}
//initial data point
int links = test.getTrophicLinks();
int species = test.getSpeciesNumber();
double connectance = test.getConnectance(links, species);
DataPoint data = test.getData(links, species, connectance);
test.addData(data);
//test.saveEcosystem("test1");
//test.saveData("test1");
//adding extra species
for (int i = 0; i < 25; i++) {
test.addOrganism("", 0, "", "", a); //default values so it randomizes them all
links = test.getTrophicLinks();
species = test.getSpeciesNumber();
connectance = test.getConnectance(links, species);
data = test.getData(links, species, connectance);
test.addData(data);
}
//saving work
String name = "rem" + k; //CHANGE name here for new data set
test.saveEcosystem(name);
test.saveData(name);
//test.saveEcosystem("test");
}
}
}
|
205188_1 | package nl.vpro.api.client.pages;
import lombok.extern.log4j.Log4j2;
import java.time.Instant;
import jakarta.xml.bind.JAXB;
import org.junit.jupiter.api.*;
import nl.vpro.domain.classification.ClassificationService;
import nl.vpro.domain.page.PageIdMatch;
import nl.vpro.domain.page.update.*;
import nl.vpro.rs.pages.update.PageUpdateRestService;
import nl.vpro.util.Env;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Disabled("This required running server at publish-test")
@Log4j2
public class PageUpdateApiClientITest {
private static PageUpdateApiClient clients;
@BeforeAll
public static void setUp() {
clients = PageUpdateApiClient.configured(Env.TEST).build();
}
@Test
public void testSave() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdateRestService client2 = clients.getPageUpdateRestService();
assertThat(client).isSameAs(client2);
PageUpdate instance = PageUpdateBuilder.article("http://www.meeuw.org/test/1234")
.title("my title " + Instant.now())
.broadcasters("VPRO").build();
SaveResult saveResult = client.save(instance, null);
log.info("{}", saveResult);
}
@Test
public void testSaveTopStory() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdate page = PageUpdateBuilder.article("http://www.meeuw.org/test/topstory")
.title("supergoed, dit! (" + Instant.now() + ")")
.paragraphs(ParagraphUpdate.of("paragraaf1", "bla bla, blie blie"), ParagraphUpdate.of("alinea 2", "bloe bloe"))
.broadcasters("VPRO")
.build();
JAXB.marshal(page, System.out);
SaveResult result = client.save(page, null);
log.info("{}", result);
}
@Test
public void testSaveWithTopStory() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdate page = PageUpdateBuilder.article("http://www.meeuw.org/test/page_with_topstory")
.broadcasters("VPRO")
.lastModified(Instant.now())
.title("Page with topstory (" + Instant.now() + ")")
.links(LinkUpdate.topStory("http://www.meeuw.org/test/topstory", "heel goed artikel"))
.build();
SaveResult result = client.save(page, null);
log.info("{}", result);
}
@Test
public void testDelete() {
final PageUpdateRestService client = clients.getPageUpdateRestService();
final DeleteResult deleteResult = client.delete("http://www.meeuw.org/test/1234", false, 1, true, PageIdMatch.URL);
log.info("{}", deleteResult);
}
@Test
public void testDeleteMultiple() {
PageUpdateRestService client = clients.getPageUpdateRestService();
DeleteResult result = client.delete("http://www.meeuw.org/", true, 100, true, PageIdMatch.URL);
log.info("{}", result);
}
@Test
public void testGetClassificationService() {
ClassificationService classificationService = clients.getClassificationService();
assertEquals("Jeugd", classificationService.getTerm("3.0.1.1").getName());
classificationService = clients.getClassificationService();
assertEquals("Film", classificationService.getTerm("3.0.1.2").getName());
}
}
| npo-poms/api-clients | pages-backend-api-client/src/test/java/nl/vpro/api/client/pages/PageUpdateApiClientITest.java | 1,020 | //www.meeuw.org/test/1234", false, 1, true, PageIdMatch.URL); | line_comment | nl | package nl.vpro.api.client.pages;
import lombok.extern.log4j.Log4j2;
import java.time.Instant;
import jakarta.xml.bind.JAXB;
import org.junit.jupiter.api.*;
import nl.vpro.domain.classification.ClassificationService;
import nl.vpro.domain.page.PageIdMatch;
import nl.vpro.domain.page.update.*;
import nl.vpro.rs.pages.update.PageUpdateRestService;
import nl.vpro.util.Env;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Disabled("This required running server at publish-test")
@Log4j2
public class PageUpdateApiClientITest {
private static PageUpdateApiClient clients;
@BeforeAll
public static void setUp() {
clients = PageUpdateApiClient.configured(Env.TEST).build();
}
@Test
public void testSave() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdateRestService client2 = clients.getPageUpdateRestService();
assertThat(client).isSameAs(client2);
PageUpdate instance = PageUpdateBuilder.article("http://www.meeuw.org/test/1234")
.title("my title " + Instant.now())
.broadcasters("VPRO").build();
SaveResult saveResult = client.save(instance, null);
log.info("{}", saveResult);
}
@Test
public void testSaveTopStory() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdate page = PageUpdateBuilder.article("http://www.meeuw.org/test/topstory")
.title("supergoed, dit! (" + Instant.now() + ")")
.paragraphs(ParagraphUpdate.of("paragraaf1", "bla bla, blie blie"), ParagraphUpdate.of("alinea 2", "bloe bloe"))
.broadcasters("VPRO")
.build();
JAXB.marshal(page, System.out);
SaveResult result = client.save(page, null);
log.info("{}", result);
}
@Test
public void testSaveWithTopStory() {
PageUpdateRestService client = clients.getPageUpdateRestService();
PageUpdate page = PageUpdateBuilder.article("http://www.meeuw.org/test/page_with_topstory")
.broadcasters("VPRO")
.lastModified(Instant.now())
.title("Page with topstory (" + Instant.now() + ")")
.links(LinkUpdate.topStory("http://www.meeuw.org/test/topstory", "heel goed artikel"))
.build();
SaveResult result = client.save(page, null);
log.info("{}", result);
}
@Test
public void testDelete() {
final PageUpdateRestService client = clients.getPageUpdateRestService();
final DeleteResult deleteResult = client.delete("http://www.meeuw.org/test/1234", false,<SUF>
log.info("{}", deleteResult);
}
@Test
public void testDeleteMultiple() {
PageUpdateRestService client = clients.getPageUpdateRestService();
DeleteResult result = client.delete("http://www.meeuw.org/", true, 100, true, PageIdMatch.URL);
log.info("{}", result);
}
@Test
public void testGetClassificationService() {
ClassificationService classificationService = clients.getClassificationService();
assertEquals("Jeugd", classificationService.getTerm("3.0.1.1").getName());
classificationService = clients.getClassificationService();
assertEquals("Film", classificationService.getTerm("3.0.1.2").getName());
}
}
|
27403_1 | package nl.vpro.domain.page.update;
import java.lang.reflect.Array;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import nl.vpro.domain.classification.Term;
import nl.vpro.domain.image.ImageType;
import nl.vpro.domain.media.Schedule;
import nl.vpro.domain.page.*;
import nl.vpro.domain.user.Broadcaster;
/**
* @author Michiel Meeuwissen
* @since 2.0
*/
public class PageUpdateBuilder {
protected final PageUpdate page;
public static PageUpdateBuilder page() {
return new PageUpdateBuilder(new PageUpdate());
}
public static PageUpdateBuilder page(@NonNull PageType type, @NonNull String url) {
return new PageUpdateBuilder(new PageUpdate(type, url));
}
public static PageUpdateBuilder article(String url) {
return page(PageType.ARTICLE, url);
}
public static PageUpdateBuilder page(Page page) {
return PageUpdate.builder(page.getType(), page.getUrl())
.creationDate(page.getCreationDate())
.lastModified(page.getLastModified())
.lastPublished(page.getLastPublished())
.publishStart(page.getPublishStartInstant())
.alternativeUrls(toArray(page.getAlternativeUrls()))
.broadcasters(toArray(page.getBroadcasters(), String.class, Broadcaster::getId))
.crids(toArray(page.getCrids()))
.embeds(toArray(page.getEmbeds(), EmbedUpdate.class, EmbedUpdate::of))
.genres(toArray(page.getGenres(), String.class, Genre::getTermId))
.images(toArray(page.getImages(), ImageUpdate.class, ImageUpdate::of))
.keywords(toArray(page.getKeywords()))
.links(toArray(page.getLinks(), LinkUpdate.class, LinkUpdate::of))
.paragraphs(toArray(page.getParagraphs(), ParagraphUpdate.class, ParagraphUpdate::of))
.portal(PortalUpdate.of(page.getPortal()))
.relations(toArray(page.getRelations(), RelationUpdate.class, RelationUpdate::of))
.statRefs(toArray(page.getStatRefs()))
.subtitle(page.getSubtitle())
.summary(page.getSummary())
.title(page.getTitle())
.tags(page.getTags())
;
}
@SuppressWarnings("unchecked")
private static <T, UT> UT[] toArray(Collection<T> collection, Class<UT> clazz, Function<T, UT> mapper) {
if (collection == null || collection.isEmpty()) {
return (UT[]) Array.newInstance(clazz, 0);
} else {
return collection.stream().filter(Objects::nonNull).map(mapper).toArray(i -> (UT[]) Array.newInstance(clazz, i));
}
}
private static String[] toArray(Collection<String> collection) {
if (collection == null || collection.isEmpty()) {
return new String[0];
} else {
return collection.toArray(new String[0]);
}
}
private PageUpdateBuilder(PageUpdate page) {
this.page = page;
}
public PageUpdateBuilder broadcasters(String... broadcasters) {
return broadcasters(Arrays.asList(broadcasters));
}
public PageUpdateBuilder portal(PortalUpdate portal) {
page.setPortal(portal);
return this;
}
public PageUpdateBuilder title(String title) {
page.setTitle(title);
return this;
}
public PageUpdateBuilder subtitle(String subtitle) {
page.setSubtitle(subtitle);
return this;
}
public PageUpdateBuilder keywords(String... keywords) {
return keywords(Arrays.asList(keywords));
}
public PageUpdateBuilder keywords(List<String> keywords) {
page.setKeywords(keywords);
return this;
}
public PageUpdateBuilder genres(String... genres) {
return genres(Arrays.asList(genres));
}
public PageUpdateBuilder genres(List<String> genres) {
page.setGenres(genres);
return this;
}
public PageUpdateBuilder genres(Term... genres) {
return genreTerms(Arrays.asList(genres));
}
public PageUpdateBuilder genreTerms(List<Term> genres) {
page.setGenres(genres.stream().map(Term::getTermId).collect(Collectors.toList()));
return this;
}
public PageUpdateBuilder paragraphs(ParagraphUpdate... paragraphs) {
return paragraphs(Arrays.asList(paragraphs));
}
public PageUpdateBuilder paragraphs(List<ParagraphUpdate> paragraphs) {
page.setParagraphs(paragraphs);
return this;
}
public PageUpdateBuilder summary(String summary) {
page.setSummary(summary);
return this;
}
public PageUpdateBuilder tags(String... tags) {
return tags(Arrays.asList(tags));
}
public PageUpdateBuilder tags(List<String> tags) {
page.setTags(tags);
return this;
}
public PageUpdateBuilder broadcasters(List<String> broadcasters) {
page.setBroadcasters(broadcasters);
return this;
}
public PageUpdateBuilder links(LinkUpdate... links) {
return links(Arrays.asList(links));
}
public PageUpdateBuilder links(List<LinkUpdate> links) {
page.setLinks(links);
return this;
}
public PageUpdateBuilder embeds(EmbedUpdate... embeds) {
page.setEmbeds(Arrays.asList(embeds));
return this;
}
public PageUpdateBuilder images(ImageUpdate... images) {
page.setImages(Arrays.asList(images));
return this;
}
public PageUpdateBuilder relations(RelationUpdate... relations) {
page.setRelations(Arrays.asList(relations));
return this;
}
public PageUpdateBuilder crids(String... crids) {
page.setCrids(Arrays.asList(crids));
return this;
}
public PageUpdateBuilder alternativeUrls(String... urls) {
page.setAlternativeUrls(Arrays.asList(urls));
return this;
}
public PageUpdateBuilder statRefs(String... statRefs) {
page.setStatRefs(Arrays.asList(statRefs));
return this;
}
public PageUpdateBuilder publishStart(Date date) {
page.setPublishStart(fromDate(date));
return this;
}
public PageUpdateBuilder publishStart(Instant date) {
page.setPublishStart(date);
return this;
}
public PageUpdateBuilder publishStart(LocalDateTime date) {
return publishStart(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder lastPublished(Instant date) {
page.setLastPublished(date);
return this;
}
public PageUpdateBuilder lastPublished(LocalDateTime date) {
return lastPublished(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder creationDate(Instant date) {
page.setCreationDate(date);
return this;
}
public PageUpdateBuilder creationDate(LocalDateTime date) {
return creationDate(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder lastModified(Instant date) {
page.setLastModified(date);
return this;
}
public PageUpdateBuilder lastModified(LocalDateTime date) {
return lastModified(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder withNow() {
Instant now = Instant.now();
return creationDate(now)
.lastModified(now);
}
public PageUpdateBuilder workflow(PageWorkflow workflow) {
page.setWorkflow(workflow);
return this;
}
public PageUpdateBuilder deleted() {
return workflow(PageWorkflow.DELETED);
}
public PageUpdateBuilder deleted(boolean deleted) {
return workflow(deleted ? PageWorkflow.DELETED : PageWorkflow.PUBLISHED);
}
Instant fromDate(Date date) {
return date == null ? null : date.toInstant();
}
public PageUpdateBuilder example() {
return
title("Groot brein in klein dier")
.subtitle("De naakte molrat heeft ‘m")
.summary("Een klein, harig beestje met het gewicht van een paperclip was mogelijk de directe voorouder van alle hedendaagse zoogdieren, waaronder de mens. Levend in de schaduw van de dinosaurussen kroop het diertje 195 miljoen jaar geleden tussen de planten door, op zoek naar insecten die het met zijn vlijmscherpe tandjes vermaalde. Het is de oudste zoogdierachtige die tot nu toe is gevonden.")
.paragraphs(new ParagraphUpdate("Voorouders", "Onderzoekers vonden de directe voorouder van ...", null))
.portal(
PortalUpdate.builder()
.id("WETENSCHAP24")
.url("http://npowetenschap.nl")
.section(
Section.builder().displayName("quantummechanica").path("/quantum").build()
).build())
.images(new ImageUpdate(ImageType.ICON, null, null, new ImageLocation("http://www.wetenschap24.nl/.imaging/stk/wetenschap/vtk-imagegallery-normal/media/wetenschap/noorderlicht/artikelen/2001/May/3663525/original/3663525.jpeg")))
.tags("molrat", "brein", "naakt", "jura")
.keywords("wetenschap", "hoezo", "biologie")
.broadcasters("VPRO", "KRO")
.links(LinkUpdate.topStory("http://www.vpro.nl/heelgoed.html", "kijk hier!"))
.embeds(new EmbedUpdate("POMS_VPRO_203778", "Noorderlicht"))
.genres("3.0.1.1")
.crids("crid://example/1")
.creationDate(LocalDateTime.of(2017, 2, 1, 7, 52))
.lastModified(LocalDateTime.of(2017, 2, 1, 8, 52))
.lastPublished(LocalDateTime.of(2017, 2, 1, 9, 52))
.publishStart(LocalDateTime.of(2017, 2, 1, 9, 52))
.statRefs("http://comscore/1")
.alternativeUrls(build().getUrl() + "?alternative")
;
}
public PageUpdate build() {
if (page.getWorkflow() == null) {
page.setWorkflow(PageWorkflow.PUBLISHED);
}
return page;
}
}
| npo-poms/poms-shared | pages-domain/src/main/java/nl/vpro/domain/page/update/PageUpdateBuilder.java | 3,015 | //www.vpro.nl/heelgoed.html", "kijk hier!")) | line_comment | nl | package nl.vpro.domain.page.update;
import java.lang.reflect.Array;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import nl.vpro.domain.classification.Term;
import nl.vpro.domain.image.ImageType;
import nl.vpro.domain.media.Schedule;
import nl.vpro.domain.page.*;
import nl.vpro.domain.user.Broadcaster;
/**
* @author Michiel Meeuwissen
* @since 2.0
*/
public class PageUpdateBuilder {
protected final PageUpdate page;
public static PageUpdateBuilder page() {
return new PageUpdateBuilder(new PageUpdate());
}
public static PageUpdateBuilder page(@NonNull PageType type, @NonNull String url) {
return new PageUpdateBuilder(new PageUpdate(type, url));
}
public static PageUpdateBuilder article(String url) {
return page(PageType.ARTICLE, url);
}
public static PageUpdateBuilder page(Page page) {
return PageUpdate.builder(page.getType(), page.getUrl())
.creationDate(page.getCreationDate())
.lastModified(page.getLastModified())
.lastPublished(page.getLastPublished())
.publishStart(page.getPublishStartInstant())
.alternativeUrls(toArray(page.getAlternativeUrls()))
.broadcasters(toArray(page.getBroadcasters(), String.class, Broadcaster::getId))
.crids(toArray(page.getCrids()))
.embeds(toArray(page.getEmbeds(), EmbedUpdate.class, EmbedUpdate::of))
.genres(toArray(page.getGenres(), String.class, Genre::getTermId))
.images(toArray(page.getImages(), ImageUpdate.class, ImageUpdate::of))
.keywords(toArray(page.getKeywords()))
.links(toArray(page.getLinks(), LinkUpdate.class, LinkUpdate::of))
.paragraphs(toArray(page.getParagraphs(), ParagraphUpdate.class, ParagraphUpdate::of))
.portal(PortalUpdate.of(page.getPortal()))
.relations(toArray(page.getRelations(), RelationUpdate.class, RelationUpdate::of))
.statRefs(toArray(page.getStatRefs()))
.subtitle(page.getSubtitle())
.summary(page.getSummary())
.title(page.getTitle())
.tags(page.getTags())
;
}
@SuppressWarnings("unchecked")
private static <T, UT> UT[] toArray(Collection<T> collection, Class<UT> clazz, Function<T, UT> mapper) {
if (collection == null || collection.isEmpty()) {
return (UT[]) Array.newInstance(clazz, 0);
} else {
return collection.stream().filter(Objects::nonNull).map(mapper).toArray(i -> (UT[]) Array.newInstance(clazz, i));
}
}
private static String[] toArray(Collection<String> collection) {
if (collection == null || collection.isEmpty()) {
return new String[0];
} else {
return collection.toArray(new String[0]);
}
}
private PageUpdateBuilder(PageUpdate page) {
this.page = page;
}
public PageUpdateBuilder broadcasters(String... broadcasters) {
return broadcasters(Arrays.asList(broadcasters));
}
public PageUpdateBuilder portal(PortalUpdate portal) {
page.setPortal(portal);
return this;
}
public PageUpdateBuilder title(String title) {
page.setTitle(title);
return this;
}
public PageUpdateBuilder subtitle(String subtitle) {
page.setSubtitle(subtitle);
return this;
}
public PageUpdateBuilder keywords(String... keywords) {
return keywords(Arrays.asList(keywords));
}
public PageUpdateBuilder keywords(List<String> keywords) {
page.setKeywords(keywords);
return this;
}
public PageUpdateBuilder genres(String... genres) {
return genres(Arrays.asList(genres));
}
public PageUpdateBuilder genres(List<String> genres) {
page.setGenres(genres);
return this;
}
public PageUpdateBuilder genres(Term... genres) {
return genreTerms(Arrays.asList(genres));
}
public PageUpdateBuilder genreTerms(List<Term> genres) {
page.setGenres(genres.stream().map(Term::getTermId).collect(Collectors.toList()));
return this;
}
public PageUpdateBuilder paragraphs(ParagraphUpdate... paragraphs) {
return paragraphs(Arrays.asList(paragraphs));
}
public PageUpdateBuilder paragraphs(List<ParagraphUpdate> paragraphs) {
page.setParagraphs(paragraphs);
return this;
}
public PageUpdateBuilder summary(String summary) {
page.setSummary(summary);
return this;
}
public PageUpdateBuilder tags(String... tags) {
return tags(Arrays.asList(tags));
}
public PageUpdateBuilder tags(List<String> tags) {
page.setTags(tags);
return this;
}
public PageUpdateBuilder broadcasters(List<String> broadcasters) {
page.setBroadcasters(broadcasters);
return this;
}
public PageUpdateBuilder links(LinkUpdate... links) {
return links(Arrays.asList(links));
}
public PageUpdateBuilder links(List<LinkUpdate> links) {
page.setLinks(links);
return this;
}
public PageUpdateBuilder embeds(EmbedUpdate... embeds) {
page.setEmbeds(Arrays.asList(embeds));
return this;
}
public PageUpdateBuilder images(ImageUpdate... images) {
page.setImages(Arrays.asList(images));
return this;
}
public PageUpdateBuilder relations(RelationUpdate... relations) {
page.setRelations(Arrays.asList(relations));
return this;
}
public PageUpdateBuilder crids(String... crids) {
page.setCrids(Arrays.asList(crids));
return this;
}
public PageUpdateBuilder alternativeUrls(String... urls) {
page.setAlternativeUrls(Arrays.asList(urls));
return this;
}
public PageUpdateBuilder statRefs(String... statRefs) {
page.setStatRefs(Arrays.asList(statRefs));
return this;
}
public PageUpdateBuilder publishStart(Date date) {
page.setPublishStart(fromDate(date));
return this;
}
public PageUpdateBuilder publishStart(Instant date) {
page.setPublishStart(date);
return this;
}
public PageUpdateBuilder publishStart(LocalDateTime date) {
return publishStart(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder lastPublished(Instant date) {
page.setLastPublished(date);
return this;
}
public PageUpdateBuilder lastPublished(LocalDateTime date) {
return lastPublished(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder creationDate(Instant date) {
page.setCreationDate(date);
return this;
}
public PageUpdateBuilder creationDate(LocalDateTime date) {
return creationDate(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder lastModified(Instant date) {
page.setLastModified(date);
return this;
}
public PageUpdateBuilder lastModified(LocalDateTime date) {
return lastModified(date.atZone(Schedule.ZONE_ID).toInstant());
}
public PageUpdateBuilder withNow() {
Instant now = Instant.now();
return creationDate(now)
.lastModified(now);
}
public PageUpdateBuilder workflow(PageWorkflow workflow) {
page.setWorkflow(workflow);
return this;
}
public PageUpdateBuilder deleted() {
return workflow(PageWorkflow.DELETED);
}
public PageUpdateBuilder deleted(boolean deleted) {
return workflow(deleted ? PageWorkflow.DELETED : PageWorkflow.PUBLISHED);
}
Instant fromDate(Date date) {
return date == null ? null : date.toInstant();
}
public PageUpdateBuilder example() {
return
title("Groot brein in klein dier")
.subtitle("De naakte molrat heeft ‘m")
.summary("Een klein, harig beestje met het gewicht van een paperclip was mogelijk de directe voorouder van alle hedendaagse zoogdieren, waaronder de mens. Levend in de schaduw van de dinosaurussen kroop het diertje 195 miljoen jaar geleden tussen de planten door, op zoek naar insecten die het met zijn vlijmscherpe tandjes vermaalde. Het is de oudste zoogdierachtige die tot nu toe is gevonden.")
.paragraphs(new ParagraphUpdate("Voorouders", "Onderzoekers vonden de directe voorouder van ...", null))
.portal(
PortalUpdate.builder()
.id("WETENSCHAP24")
.url("http://npowetenschap.nl")
.section(
Section.builder().displayName("quantummechanica").path("/quantum").build()
).build())
.images(new ImageUpdate(ImageType.ICON, null, null, new ImageLocation("http://www.wetenschap24.nl/.imaging/stk/wetenschap/vtk-imagegallery-normal/media/wetenschap/noorderlicht/artikelen/2001/May/3663525/original/3663525.jpeg")))
.tags("molrat", "brein", "naakt", "jura")
.keywords("wetenschap", "hoezo", "biologie")
.broadcasters("VPRO", "KRO")
.links(LinkUpdate.topStory("http://www.vpro.nl/heelgoed.html", "kijk<SUF>
.embeds(new EmbedUpdate("POMS_VPRO_203778", "Noorderlicht"))
.genres("3.0.1.1")
.crids("crid://example/1")
.creationDate(LocalDateTime.of(2017, 2, 1, 7, 52))
.lastModified(LocalDateTime.of(2017, 2, 1, 8, 52))
.lastPublished(LocalDateTime.of(2017, 2, 1, 9, 52))
.publishStart(LocalDateTime.of(2017, 2, 1, 9, 52))
.statRefs("http://comscore/1")
.alternativeUrls(build().getUrl() + "?alternative")
;
}
public PageUpdate build() {
if (page.getWorkflow() == null) {
page.setWorkflow(PageWorkflow.PUBLISHED);
}
return page;
}
}
|
164149_2 | /* Copyright 2008 - The Cytoscape Consortium (www.cytoscape.org)
*
* The Cytoscape Consortium is:
* - Institute for Systems Biology
* - University of California San Diego
* - Memorial Sloan-Kettering Cancer Center
* - Institut Pasteur
* - Agilent Technologies
*
* Authors: B. Arman Aksoy, Thomas Kelder, Emek Demir
*
* This file is part of PaxtoolsPlugin.
*
* PaxtoolsPlugin 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.
*
* PaxtoolsPlugin 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 Lesser General Public License
* along with this project. If not, see <http://www.gnu.org/licenses/>.
*/
package org.biyoenformatik.cytoscape;
import cytoscape.data.readers.GraphReader;
import cytoscape.data.CyAttributes;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.util.CyNetworkNaming;
import cytoscape.CyNetwork;
import cytoscape.CyNode;
import cytoscape.CyEdge;
import cytoscape.Cytoscape;
import cytoscape.visual.VisualStyle;
import cytoscape.visual.VisualMappingManager;
import cytoscape.view.CyNetworkView;
import org.biopax.paxtools.model.Model;
import org.biopax.paxtools.model.level2.*;
import org.biopax.paxtools.io.jena.JenaIOHandler;
import org.biyoenformatik.cytoscape.util.BioPAXUtil;
import org.mskcc.biopax_plugin.util.cytoscape.CytoscapeWrapper;
import org.mskcc.biopax_plugin.util.cytoscape.NetworkListener;
import org.mskcc.biopax_plugin.util.cytoscape.LayoutUtil;
import org.mskcc.biopax_plugin.style.BioPaxVisualStyleUtil;
import org.mskcc.biopax_plugin.view.BioPaxContainer;
import org.mskcc.biopax_plugin.mapping.MapBioPaxToCytoscape;
import org.mskcc.biopax_plugin.mapping.MapNodeAttributes;
import java.io.*;
import giny.view.GraphView;
public class PaxtoolsReader implements GraphReader {
private Model biopaxModel = null;
private String fileName = null;
private CyLayoutAlgorithm layoutAlgorithm;
private int[] nodeIndices, edgeIndices;
public PaxtoolsReader(String fileName) {
this.fileName = fileName;
this.layoutAlgorithm = new LayoutUtil();
}
public PaxtoolsReader(Model biopaxModel) {
this.biopaxModel = biopaxModel;
this.layoutAlgorithm = new LayoutUtil();
}
public void read() throws IOException {
if( biopaxModel == null ) {
FileInputStream ioStream = new FileInputStream(fileName);
biopaxModel = new JenaIOHandler().convertFromOWL(ioStream);
}
BioPAXUtil.CytoscapeGraphElements csGraphEls
= BioPAXUtil.bioPAXtoCytoscapeGraph(biopaxModel);
nodeIndices = new int[csGraphEls.nodes.size()];
edgeIndices = new int[csGraphEls.edges.size()];
int count = 0;
for(CyNode node: csGraphEls.nodes)
nodeIndices[count++] = node.getRootGraphIndex();
count = 0;
for(CyEdge edge: csGraphEls.edges)
edgeIndices[count++] = edge.getRootGraphIndex();
}
public void layout(GraphView view) {
getLayoutAlgorithm().doLayout((CyNetworkView) view);
}
public CyLayoutAlgorithm getLayoutAlgorithm() {
return layoutAlgorithm;
}
public int[] getNodeIndicesArray() {
return nodeIndices;
}
public int[] getEdgeIndicesArray() {
return edgeIndices;
}
public void doPostProcessing(CyNetwork cyNetwork) {
/**
* Sets a network attribute which indicates this network
* is a biopax network
*/
CyAttributes networkAttributes = Cytoscape.getNetworkAttributes();
// get cyNetwork id
String networkID = cyNetwork.getIdentifier();
// set biopax network attribute
networkAttributes.setAttribute(networkID, MapBioPaxToCytoscape.BIOPAX_NETWORK, Boolean.TRUE);
// Repair Canonical Name
MapBioPaxToCytoscape.repairCanonicalName(cyNetwork);
// repair network name
if (getNetworkName().equals("")) {
MapBioPaxToCytoscape.repairNetworkName(cyNetwork);
}
// Set default Quick Find Index
networkAttributes.setAttribute(cyNetwork.getIdentifier(), "quickfind.default_index",
MapNodeAttributes.BIOPAX_SHORT_NAME);
// Keep the model map
BioPAXUtil.setNetworkModel(cyNetwork, biopaxModel);
// set url to pathway commons -
// used for pathway commons context menus
String urlToBioPAXWebServices = System.getProperty("biopax.web_services_url");
if (urlToBioPAXWebServices != null && urlToBioPAXWebServices.length() > 0) {
networkAttributes.setAttribute(cyNetwork.getIdentifier(),
"biopax.web_services_url",
urlToBioPAXWebServices);
System.setProperty("biopax.web_services_url", "");
}
// set data source attribute
// used for pathway commons context menus
String dataSources = System.getProperty("biopax.data_sources");
if (dataSources != null && dataSources.length() > 0) {
networkAttributes.setAttribute(cyNetwork.getIdentifier(),
"biopax.data_sources",
dataSources);
System.setProperty("biopax.data_sources", "");
}
// Set-up the BioPax Visual Style
final VisualStyle bioPaxVisualStyle = BioPaxVisualStyleUtil.getBioPaxVisualStyle();
final VisualMappingManager manager = Cytoscape.getVisualMappingManager();
final CyNetworkView view = Cytoscape.getNetworkView(cyNetwork.getIdentifier());
view.setVisualStyle(bioPaxVisualStyle.getName());
manager.setVisualStyle(bioPaxVisualStyle);
view.applyVizmapper(bioPaxVisualStyle);
// Set up BP UI
CytoscapeWrapper.initBioPaxPlugInUI();
BioPaxContainer bpContainer = BioPaxContainer.getInstance();
bpContainer.showLegend();
NetworkListener networkListener = bpContainer.getNetworkListener();
networkListener.registerNetwork(cyNetwork);
}
public String getNetworkName() {
String backupName = "Unknown", networkName = null;
for(pathway aPathway: biopaxModel.getObjects(pathway.class)) {
String aName = BioPAXUtil.getNameSmart(aPathway);
if( aName != null && aName.length() != 0 )
backupName = aName; // back-up name
else
continue;
if( aPathway.isPATHWAY_COMPONENTSof().isEmpty() )
networkName = backupName;
}
return (networkName == null ? backupName : networkName);
}
}
| nrnb/gsoc2008arman | PaxtoolsPlugin/src/org/biyoenformatik/cytoscape/PaxtoolsReader.java | 2,111 | // get cyNetwork id | line_comment | nl | /* Copyright 2008 - The Cytoscape Consortium (www.cytoscape.org)
*
* The Cytoscape Consortium is:
* - Institute for Systems Biology
* - University of California San Diego
* - Memorial Sloan-Kettering Cancer Center
* - Institut Pasteur
* - Agilent Technologies
*
* Authors: B. Arman Aksoy, Thomas Kelder, Emek Demir
*
* This file is part of PaxtoolsPlugin.
*
* PaxtoolsPlugin 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.
*
* PaxtoolsPlugin 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 Lesser General Public License
* along with this project. If not, see <http://www.gnu.org/licenses/>.
*/
package org.biyoenformatik.cytoscape;
import cytoscape.data.readers.GraphReader;
import cytoscape.data.CyAttributes;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.util.CyNetworkNaming;
import cytoscape.CyNetwork;
import cytoscape.CyNode;
import cytoscape.CyEdge;
import cytoscape.Cytoscape;
import cytoscape.visual.VisualStyle;
import cytoscape.visual.VisualMappingManager;
import cytoscape.view.CyNetworkView;
import org.biopax.paxtools.model.Model;
import org.biopax.paxtools.model.level2.*;
import org.biopax.paxtools.io.jena.JenaIOHandler;
import org.biyoenformatik.cytoscape.util.BioPAXUtil;
import org.mskcc.biopax_plugin.util.cytoscape.CytoscapeWrapper;
import org.mskcc.biopax_plugin.util.cytoscape.NetworkListener;
import org.mskcc.biopax_plugin.util.cytoscape.LayoutUtil;
import org.mskcc.biopax_plugin.style.BioPaxVisualStyleUtil;
import org.mskcc.biopax_plugin.view.BioPaxContainer;
import org.mskcc.biopax_plugin.mapping.MapBioPaxToCytoscape;
import org.mskcc.biopax_plugin.mapping.MapNodeAttributes;
import java.io.*;
import giny.view.GraphView;
public class PaxtoolsReader implements GraphReader {
private Model biopaxModel = null;
private String fileName = null;
private CyLayoutAlgorithm layoutAlgorithm;
private int[] nodeIndices, edgeIndices;
public PaxtoolsReader(String fileName) {
this.fileName = fileName;
this.layoutAlgorithm = new LayoutUtil();
}
public PaxtoolsReader(Model biopaxModel) {
this.biopaxModel = biopaxModel;
this.layoutAlgorithm = new LayoutUtil();
}
public void read() throws IOException {
if( biopaxModel == null ) {
FileInputStream ioStream = new FileInputStream(fileName);
biopaxModel = new JenaIOHandler().convertFromOWL(ioStream);
}
BioPAXUtil.CytoscapeGraphElements csGraphEls
= BioPAXUtil.bioPAXtoCytoscapeGraph(biopaxModel);
nodeIndices = new int[csGraphEls.nodes.size()];
edgeIndices = new int[csGraphEls.edges.size()];
int count = 0;
for(CyNode node: csGraphEls.nodes)
nodeIndices[count++] = node.getRootGraphIndex();
count = 0;
for(CyEdge edge: csGraphEls.edges)
edgeIndices[count++] = edge.getRootGraphIndex();
}
public void layout(GraphView view) {
getLayoutAlgorithm().doLayout((CyNetworkView) view);
}
public CyLayoutAlgorithm getLayoutAlgorithm() {
return layoutAlgorithm;
}
public int[] getNodeIndicesArray() {
return nodeIndices;
}
public int[] getEdgeIndicesArray() {
return edgeIndices;
}
public void doPostProcessing(CyNetwork cyNetwork) {
/**
* Sets a network attribute which indicates this network
* is a biopax network
*/
CyAttributes networkAttributes = Cytoscape.getNetworkAttributes();
// get cyNetwork<SUF>
String networkID = cyNetwork.getIdentifier();
// set biopax network attribute
networkAttributes.setAttribute(networkID, MapBioPaxToCytoscape.BIOPAX_NETWORK, Boolean.TRUE);
// Repair Canonical Name
MapBioPaxToCytoscape.repairCanonicalName(cyNetwork);
// repair network name
if (getNetworkName().equals("")) {
MapBioPaxToCytoscape.repairNetworkName(cyNetwork);
}
// Set default Quick Find Index
networkAttributes.setAttribute(cyNetwork.getIdentifier(), "quickfind.default_index",
MapNodeAttributes.BIOPAX_SHORT_NAME);
// Keep the model map
BioPAXUtil.setNetworkModel(cyNetwork, biopaxModel);
// set url to pathway commons -
// used for pathway commons context menus
String urlToBioPAXWebServices = System.getProperty("biopax.web_services_url");
if (urlToBioPAXWebServices != null && urlToBioPAXWebServices.length() > 0) {
networkAttributes.setAttribute(cyNetwork.getIdentifier(),
"biopax.web_services_url",
urlToBioPAXWebServices);
System.setProperty("biopax.web_services_url", "");
}
// set data source attribute
// used for pathway commons context menus
String dataSources = System.getProperty("biopax.data_sources");
if (dataSources != null && dataSources.length() > 0) {
networkAttributes.setAttribute(cyNetwork.getIdentifier(),
"biopax.data_sources",
dataSources);
System.setProperty("biopax.data_sources", "");
}
// Set-up the BioPax Visual Style
final VisualStyle bioPaxVisualStyle = BioPaxVisualStyleUtil.getBioPaxVisualStyle();
final VisualMappingManager manager = Cytoscape.getVisualMappingManager();
final CyNetworkView view = Cytoscape.getNetworkView(cyNetwork.getIdentifier());
view.setVisualStyle(bioPaxVisualStyle.getName());
manager.setVisualStyle(bioPaxVisualStyle);
view.applyVizmapper(bioPaxVisualStyle);
// Set up BP UI
CytoscapeWrapper.initBioPaxPlugInUI();
BioPaxContainer bpContainer = BioPaxContainer.getInstance();
bpContainer.showLegend();
NetworkListener networkListener = bpContainer.getNetworkListener();
networkListener.registerNetwork(cyNetwork);
}
public String getNetworkName() {
String backupName = "Unknown", networkName = null;
for(pathway aPathway: biopaxModel.getObjects(pathway.class)) {
String aName = BioPAXUtil.getNameSmart(aPathway);
if( aName != null && aName.length() != 0 )
backupName = aName; // back-up name
else
continue;
if( aPathway.isPATHWAY_COMPONENTSof().isEmpty() )
networkName = backupName;
}
return (networkName == null ? backupName : networkName);
}
}
|
183080_3 | /*
* (c) COPYRIGHT 1999 World Wide Web Consortium
* (Massachusetts Institute of Technology, Institut National de Recherche
* en Informatique et en Automatique, Keio University).
* All Rights Reserved. http://www.w3.org/Consortium/Legal/
*
* $Id$
*/
package org.w3c.css.util;
import org.w3c.css.css.StyleSheet;
import org.w3c.css.parser.Frame;
import org.w3c.www.http.HttpAcceptCharset;
import org.w3c.www.http.HttpAcceptCharsetList;
import org.w3c.www.http.HttpFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Philippe Le Hegaret
* @version $Revision$
*/
public class ApplContext {
// the charset of the first source (url/uploaded/text)
public static Charset defaultCharset;
public static Charset utf8Charset;
static {
try {
defaultCharset = Charset.forName("iso-8859-1");
utf8Charset = Charset.forName("utf-8");
} catch (Exception ex) {
// we are in deep trouble here
defaultCharset = null;
utf8Charset = null;
}
}
private class BomEncoding {
Charset uriCharset = null;
boolean fromBom = false;
private BomEncoding(Charset c, boolean fb) {
uriCharset = c;
fromBom = fb;
}
private BomEncoding(Charset c) {
this(c, false);
}
private BomEncoding() {
}
}
// charset definition of traversed URLs
private HashMap<URL, BomEncoding> uricharsets = null;
// namespace definitions
private HashMap<URL, HashMap<String, String>> namespaces = null;
// default prefix
public static String defaultPrefix = "*defaultprefix*";
public static String noPrefix = "*noprefix*";
private ArrayList<URL> linkedmedia = new ArrayList<URL>();
String credential = null;
String lang;
Messages msgs;
Frame frame;
StyleSheet styleSheet = null;
CssVersion version = CssVersion.getDefault();
CssProfile profile = CssProfile.NONE;
String input;
Class cssselectorstyle;
int origin = -1;
String medium;
private String link;
int warningLevel = 0;
boolean treatVendorExtensionsAsWarnings = false;
boolean treatCssHacksAsWarnings = false;
boolean suggestPropertyName = true;
private String propertyKey = null;
public boolean followlinks() {
return followlinks;
}
public void setFollowlinks(boolean followlinks) {
this.followlinks = followlinks;
}
boolean followlinks = true;
FakeFile fakefile = null;
String faketext = null;
Charset faketextcharset = null;
URL fakeurl = null;
URL referrer = null;
/**
* Creates a new ApplContext
*/
public ApplContext(String lang) {
this.lang = lang;
msgs = new Messages(lang);
}
public int getWarningLevel() {
return warningLevel;
}
public void setWarningLevel(int warningLevel) {
this.warningLevel = warningLevel;
}
public ArrayList<URL> getLinkedURIs() {
return linkedmedia;
}
public void addLinkedURI(URL url) {
if (url != null) {
linkedmedia.add(url);
}
}
// as ugly as everything else
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setFrame(Frame frame) {
this.frame = frame;
frame.ac = this;
}
public Frame getFrame() {
return frame;
}
public void setStyleSheet(StyleSheet styleSheet) {
this.styleSheet = styleSheet;
}
public StyleSheet getStyleSheet() {
return styleSheet;
}
public Class getCssSelectorsStyle() {
return cssselectorstyle;
}
public void setCssSelectorsStyle(Class s) {
cssselectorstyle = s;
}
public Messages getMsg() {
return msgs;
}
public String getContentType() {
return (msgs != null) ? msgs.getString("content-type") : null;
}
public String getContentLanguage() {
return (msgs != null) ? msgs.getString("content-language") : null;
}
/**
* Searches the properties list for a content-encoding one. If it does not
* exist, searches for output-encoding-name. If it still does not exists,
* the method returns the default utf-8 value
*
* @return the output encoding of this ApplContext
*/
public String getContentEncoding() {
// return (msgs != null) ? msgs.getString("content-encoding") : null;
String res = null;
if (msgs != null) {
res = msgs.getString("content-encoding");
if (res == null) {
res = msgs.getString("output-encoding-name");
}
if (res != null) {
// if an encoding has been found, return it
return res;
}
}
// default encoding
return Utf8Properties.ENCODING;
}
public String getLang() {
return lang;
}
public void setCssVersion(String cssversion) {
version = CssVersion.resolve(this, cssversion);
propertyKey = null;
}
public void setCssVersion(CssVersion version) {
this.version = version;
propertyKey = null;
}
public String getCssVersionString() {
return version.toString();
}
public CssVersion getCssVersion() {
return version;
}
public void setProfile(String profile) {
this.profile = CssProfile.resolve(this, profile);
propertyKey = null;
}
/**
* get the String used to fetch the relevant property file
*/
public String getPropertyKey() {
if (propertyKey != null) {
return propertyKey;
}
if (profile == CssProfile.SVG && version == CssVersion.CSS3) {
propertyKey = version.toString() + profile.toString();
return propertyKey;
}
if (profile != CssProfile.EMPTY && profile != CssProfile.NONE) {
propertyKey = profile.toString();
} else {
propertyKey = version.toString();
}
return propertyKey;
}
public CssProfile getCssProfile() {
return profile;
}
public String getProfileString() {
return profile.toString();
}
public void setCssVersionAndProfile(String spec) {
// for things like SVG, version will be set to the default one
// CSS21 in that case, as defined in CssVersion
// and profile will be resolved to svg.
//
// if the version resolve then profile will default to NONE
// TODO should we check profile first and if SVG or MOBILE
// set specific version of CSS (like CSS2 and not CSS21 for MOBILE) ?
if ((spec == null) || spec.isEmpty()) {
version = CssVersion.getDefault();
profile = CssProfile.SVG;
} else {
String low = spec.toLowerCase();
version = CssVersion.resolve(this, low);
profile = CssProfile.resolve(this, low);
// some special cases...
// http://www.atsc.org/cms/index.php/standards/published-standards/71-atsc-a100-standard
if (profile.equals(CssProfile.ATSCTV)) {
version = CssVersion.CSS2;
}
}
}
public void setOrigin(int origin) {
this.origin = origin;
}
public int getOrigin() {
return origin;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getMedium() {
return medium;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getLink() {
return link;
}
public void setLink(String queryString) {
this.link = queryString;
}
public boolean getTreatVendorExtensionsAsWarnings() {
return treatVendorExtensionsAsWarnings;
}
/**
* Change the behaviour of error reporting for vendor extensions.
*
* @param treatVendorExtensionsAsWarnings
*
*/
public void setTreatVendorExtensionsAsWarnings(
boolean treatVendorExtensionsAsWarnings) {
this.treatVendorExtensionsAsWarnings = treatVendorExtensionsAsWarnings;
}
public boolean getTreatCssHacksAsWarnings() {
return treatCssHacksAsWarnings;
}
/**
* Change the behaviour of error reporting for CSS Hacks.
*
* @param treatCssHacksAsWarnings
*/
public void setTreatCssHacksAsWarnings(boolean treatCssHacksAsWarnings) {
this.treatCssHacksAsWarnings = treatCssHacksAsWarnings;
}
public boolean getSuggestPropertyName() {
return suggestPropertyName;
}
public void setSuggestPropertyName(boolean b) {
suggestPropertyName = b;
}
/**
* Sets the content encoding to the first charset that appears in
* <i>acceptCharset</i>. If the charset is not supported, the content
* encoding will be utf-8
*
* @param acceptCharset a String representing the Accept-Charset request parameter
*/
public void setContentEncoding(String acceptCharset) {
if (acceptCharset != null) {
// uses some Jigsaw classes to parse the Accept-Charset
// these classes need to load a lot of stuff, so it may be quite
// long the first time
HttpAcceptCharsetList charsetList;
HttpAcceptCharset[] charsets;
charsetList = HttpFactory.parseAcceptCharsetList(acceptCharset);
charsets = (HttpAcceptCharset[]) charsetList.getValue();
String encoding = null;
double quality = 0.0;
String biasedcharset = getMsg().getString("output-encoding-name");
for (int i = 0; i < charsets.length && quality < 1.0; i++) {
HttpAcceptCharset charset = charsets[i];
String currentCharset = charset.getCharset();
// checks that the charset is supported by Java
if (isCharsetSupported(currentCharset)) {
double currentQuality = charset.getQuality();
// we prefer utf-8
// FIXME (the bias value and the biased charset
// should be dependant on the language)
if ((biasedcharset != null) &&
!biasedcharset.equalsIgnoreCase(currentCharset)) {
currentQuality *= 0.5;
}
if (currentQuality > quality) {
quality = currentQuality;
encoding = charset.getCharset();
}
}
}
if (encoding != null) {
getMsg().properties.setProperty("content-encoding", encoding);
} else {
// no valid charset
getMsg().properties.remove("content-encoding");
}
} else {
// no Accept-Charset given
getMsg().properties.remove("content-encoding");
}
}
private boolean isCharsetSupported(String charset) {
if ("*".equals(charset)) {
return true;
}
try {
return Charset.isSupported(charset);
} catch (Exception e) {
return false;
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, String charset, boolean from_bom) {
if (uricharsets == null) {
uricharsets = new HashMap<>();
}
Charset c = null;
try {
c = Charset.forName(charset);
} catch (IllegalCharsetNameException icex) {
// FIXME add a warning in the CSS
} catch (UnsupportedCharsetException ucex) {
// FIXME inform about lack of support
}
if (c != null) {
uricharsets.put(url, new BomEncoding(c, from_bom));
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, Charset charset) {
if (uricharsets == null) {
uricharsets = new HashMap<URL, BomEncoding>();
}
uricharsets.put(url, new BomEncoding(charset));
}
public boolean isCharsetFromBOM(URL url) {
BomEncoding b;
if (uricharsets == null) {
return false;
}
b = uricharsets.get(url);
if (b != null) {
return b.fromBom;
}
return false;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public String getCharsetForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b != null) {
return b.uriCharset.toString();
}
return null;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public Charset getCharsetObjForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b == null) {
return null;
}
return b.uriCharset;
}
/**
* store content of uploaded file
*/
public void setFakeFile(FakeFile fakefile) {
this.fakefile = fakefile;
}
/**
* store content of entered text
*/
public void setFakeText(String faketext, Charset faketextcharset) {
this.faketext = faketext;
this.faketextcharset = faketextcharset;
}
public InputStream getFakeInputStream(URL source)
throws IOException {
InputStream is = null;
Charset c = null;
if (fakefile != null) {
is = fakefile.getInputStream();
}
if (faketext != null) {
is = new ByteArrayInputStream(faketext.getBytes(faketextcharset));
c = faketextcharset;
}
if (is == null) {
return null;
}
if (c == null) {
c = getCharsetObjForURL(source);
}
if (c == null) {
UnicodeInputStream uis = new UnicodeInputStream(is);
String guessedCharset = uis.getEncodingFromStream();
if (guessedCharset != null) {
setCharsetForURL(source, guessedCharset, true);
}
return uis;
} else {
if (utf8Charset.compareTo(c) == 0) {
return new UnicodeInputStream(is);
}
}
return is;
}
public boolean isInputFake() {
return ((faketext != null) || (fakefile != null));
}
public void setFakeURL(String fakeurl) {
try {
this.fakeurl = new URL(fakeurl);
} catch (Exception ex) {
}
}
public URL getFakeURL() {
return fakeurl;
}
/**
* support for namespaces
*/
public void setNamespace(URL url, String prefix, String nsname) {
if (namespaces == null) {
namespaces = new HashMap<URL, HashMap<String, String>>();
}
// reformat the prefix if null.
String realPrefix = ((prefix != null) && !prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
nsdefs = new HashMap<String, String>();
nsdefs.put(realPrefix, nsname);
namespaces.put(url, nsdefs);
} else {
// do we need to check if we have a redefinition ?
nsdefs.put(realPrefix, nsname);
}
}
// true if a namespace is defined in the document (CSS fragment)
// defined by the URL, with prefix "prefix"
public boolean isNamespaceDefined(URL url, String prefix) {
if (prefix == null) { // no prefix, always match
return true;
}
if (prefix.equals("*")) { // any ns, always true
return true;
}
String realPrefix = (!prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
return false;
}
return nsdefs.containsKey(realPrefix);
}
/**
* Set the current referrer for possible linked style sheets
*
* @param referrer the referring URL
*/
public void setReferrer(URL referrer) {
this.referrer = referrer;
}
/**
* get the referrer URL (or null if not relevant)
*
* @return an URL
*/
public URL getReferrer() {
return referrer;
}
}
| nschonni/css-validator | org/w3c/css/util/ApplContext.java | 4,884 | // we are in deep trouble here | line_comment | nl | /*
* (c) COPYRIGHT 1999 World Wide Web Consortium
* (Massachusetts Institute of Technology, Institut National de Recherche
* en Informatique et en Automatique, Keio University).
* All Rights Reserved. http://www.w3.org/Consortium/Legal/
*
* $Id$
*/
package org.w3c.css.util;
import org.w3c.css.css.StyleSheet;
import org.w3c.css.parser.Frame;
import org.w3c.www.http.HttpAcceptCharset;
import org.w3c.www.http.HttpAcceptCharsetList;
import org.w3c.www.http.HttpFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Philippe Le Hegaret
* @version $Revision$
*/
public class ApplContext {
// the charset of the first source (url/uploaded/text)
public static Charset defaultCharset;
public static Charset utf8Charset;
static {
try {
defaultCharset = Charset.forName("iso-8859-1");
utf8Charset = Charset.forName("utf-8");
} catch (Exception ex) {
// we are<SUF>
defaultCharset = null;
utf8Charset = null;
}
}
private class BomEncoding {
Charset uriCharset = null;
boolean fromBom = false;
private BomEncoding(Charset c, boolean fb) {
uriCharset = c;
fromBom = fb;
}
private BomEncoding(Charset c) {
this(c, false);
}
private BomEncoding() {
}
}
// charset definition of traversed URLs
private HashMap<URL, BomEncoding> uricharsets = null;
// namespace definitions
private HashMap<URL, HashMap<String, String>> namespaces = null;
// default prefix
public static String defaultPrefix = "*defaultprefix*";
public static String noPrefix = "*noprefix*";
private ArrayList<URL> linkedmedia = new ArrayList<URL>();
String credential = null;
String lang;
Messages msgs;
Frame frame;
StyleSheet styleSheet = null;
CssVersion version = CssVersion.getDefault();
CssProfile profile = CssProfile.NONE;
String input;
Class cssselectorstyle;
int origin = -1;
String medium;
private String link;
int warningLevel = 0;
boolean treatVendorExtensionsAsWarnings = false;
boolean treatCssHacksAsWarnings = false;
boolean suggestPropertyName = true;
private String propertyKey = null;
public boolean followlinks() {
return followlinks;
}
public void setFollowlinks(boolean followlinks) {
this.followlinks = followlinks;
}
boolean followlinks = true;
FakeFile fakefile = null;
String faketext = null;
Charset faketextcharset = null;
URL fakeurl = null;
URL referrer = null;
/**
* Creates a new ApplContext
*/
public ApplContext(String lang) {
this.lang = lang;
msgs = new Messages(lang);
}
public int getWarningLevel() {
return warningLevel;
}
public void setWarningLevel(int warningLevel) {
this.warningLevel = warningLevel;
}
public ArrayList<URL> getLinkedURIs() {
return linkedmedia;
}
public void addLinkedURI(URL url) {
if (url != null) {
linkedmedia.add(url);
}
}
// as ugly as everything else
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setFrame(Frame frame) {
this.frame = frame;
frame.ac = this;
}
public Frame getFrame() {
return frame;
}
public void setStyleSheet(StyleSheet styleSheet) {
this.styleSheet = styleSheet;
}
public StyleSheet getStyleSheet() {
return styleSheet;
}
public Class getCssSelectorsStyle() {
return cssselectorstyle;
}
public void setCssSelectorsStyle(Class s) {
cssselectorstyle = s;
}
public Messages getMsg() {
return msgs;
}
public String getContentType() {
return (msgs != null) ? msgs.getString("content-type") : null;
}
public String getContentLanguage() {
return (msgs != null) ? msgs.getString("content-language") : null;
}
/**
* Searches the properties list for a content-encoding one. If it does not
* exist, searches for output-encoding-name. If it still does not exists,
* the method returns the default utf-8 value
*
* @return the output encoding of this ApplContext
*/
public String getContentEncoding() {
// return (msgs != null) ? msgs.getString("content-encoding") : null;
String res = null;
if (msgs != null) {
res = msgs.getString("content-encoding");
if (res == null) {
res = msgs.getString("output-encoding-name");
}
if (res != null) {
// if an encoding has been found, return it
return res;
}
}
// default encoding
return Utf8Properties.ENCODING;
}
public String getLang() {
return lang;
}
public void setCssVersion(String cssversion) {
version = CssVersion.resolve(this, cssversion);
propertyKey = null;
}
public void setCssVersion(CssVersion version) {
this.version = version;
propertyKey = null;
}
public String getCssVersionString() {
return version.toString();
}
public CssVersion getCssVersion() {
return version;
}
public void setProfile(String profile) {
this.profile = CssProfile.resolve(this, profile);
propertyKey = null;
}
/**
* get the String used to fetch the relevant property file
*/
public String getPropertyKey() {
if (propertyKey != null) {
return propertyKey;
}
if (profile == CssProfile.SVG && version == CssVersion.CSS3) {
propertyKey = version.toString() + profile.toString();
return propertyKey;
}
if (profile != CssProfile.EMPTY && profile != CssProfile.NONE) {
propertyKey = profile.toString();
} else {
propertyKey = version.toString();
}
return propertyKey;
}
public CssProfile getCssProfile() {
return profile;
}
public String getProfileString() {
return profile.toString();
}
public void setCssVersionAndProfile(String spec) {
// for things like SVG, version will be set to the default one
// CSS21 in that case, as defined in CssVersion
// and profile will be resolved to svg.
//
// if the version resolve then profile will default to NONE
// TODO should we check profile first and if SVG or MOBILE
// set specific version of CSS (like CSS2 and not CSS21 for MOBILE) ?
if ((spec == null) || spec.isEmpty()) {
version = CssVersion.getDefault();
profile = CssProfile.SVG;
} else {
String low = spec.toLowerCase();
version = CssVersion.resolve(this, low);
profile = CssProfile.resolve(this, low);
// some special cases...
// http://www.atsc.org/cms/index.php/standards/published-standards/71-atsc-a100-standard
if (profile.equals(CssProfile.ATSCTV)) {
version = CssVersion.CSS2;
}
}
}
public void setOrigin(int origin) {
this.origin = origin;
}
public int getOrigin() {
return origin;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getMedium() {
return medium;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getLink() {
return link;
}
public void setLink(String queryString) {
this.link = queryString;
}
public boolean getTreatVendorExtensionsAsWarnings() {
return treatVendorExtensionsAsWarnings;
}
/**
* Change the behaviour of error reporting for vendor extensions.
*
* @param treatVendorExtensionsAsWarnings
*
*/
public void setTreatVendorExtensionsAsWarnings(
boolean treatVendorExtensionsAsWarnings) {
this.treatVendorExtensionsAsWarnings = treatVendorExtensionsAsWarnings;
}
public boolean getTreatCssHacksAsWarnings() {
return treatCssHacksAsWarnings;
}
/**
* Change the behaviour of error reporting for CSS Hacks.
*
* @param treatCssHacksAsWarnings
*/
public void setTreatCssHacksAsWarnings(boolean treatCssHacksAsWarnings) {
this.treatCssHacksAsWarnings = treatCssHacksAsWarnings;
}
public boolean getSuggestPropertyName() {
return suggestPropertyName;
}
public void setSuggestPropertyName(boolean b) {
suggestPropertyName = b;
}
/**
* Sets the content encoding to the first charset that appears in
* <i>acceptCharset</i>. If the charset is not supported, the content
* encoding will be utf-8
*
* @param acceptCharset a String representing the Accept-Charset request parameter
*/
public void setContentEncoding(String acceptCharset) {
if (acceptCharset != null) {
// uses some Jigsaw classes to parse the Accept-Charset
// these classes need to load a lot of stuff, so it may be quite
// long the first time
HttpAcceptCharsetList charsetList;
HttpAcceptCharset[] charsets;
charsetList = HttpFactory.parseAcceptCharsetList(acceptCharset);
charsets = (HttpAcceptCharset[]) charsetList.getValue();
String encoding = null;
double quality = 0.0;
String biasedcharset = getMsg().getString("output-encoding-name");
for (int i = 0; i < charsets.length && quality < 1.0; i++) {
HttpAcceptCharset charset = charsets[i];
String currentCharset = charset.getCharset();
// checks that the charset is supported by Java
if (isCharsetSupported(currentCharset)) {
double currentQuality = charset.getQuality();
// we prefer utf-8
// FIXME (the bias value and the biased charset
// should be dependant on the language)
if ((biasedcharset != null) &&
!biasedcharset.equalsIgnoreCase(currentCharset)) {
currentQuality *= 0.5;
}
if (currentQuality > quality) {
quality = currentQuality;
encoding = charset.getCharset();
}
}
}
if (encoding != null) {
getMsg().properties.setProperty("content-encoding", encoding);
} else {
// no valid charset
getMsg().properties.remove("content-encoding");
}
} else {
// no Accept-Charset given
getMsg().properties.remove("content-encoding");
}
}
private boolean isCharsetSupported(String charset) {
if ("*".equals(charset)) {
return true;
}
try {
return Charset.isSupported(charset);
} catch (Exception e) {
return false;
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, String charset, boolean from_bom) {
if (uricharsets == null) {
uricharsets = new HashMap<>();
}
Charset c = null;
try {
c = Charset.forName(charset);
} catch (IllegalCharsetNameException icex) {
// FIXME add a warning in the CSS
} catch (UnsupportedCharsetException ucex) {
// FIXME inform about lack of support
}
if (c != null) {
uricharsets.put(url, new BomEncoding(c, from_bom));
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, Charset charset) {
if (uricharsets == null) {
uricharsets = new HashMap<URL, BomEncoding>();
}
uricharsets.put(url, new BomEncoding(charset));
}
public boolean isCharsetFromBOM(URL url) {
BomEncoding b;
if (uricharsets == null) {
return false;
}
b = uricharsets.get(url);
if (b != null) {
return b.fromBom;
}
return false;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public String getCharsetForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b != null) {
return b.uriCharset.toString();
}
return null;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public Charset getCharsetObjForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b == null) {
return null;
}
return b.uriCharset;
}
/**
* store content of uploaded file
*/
public void setFakeFile(FakeFile fakefile) {
this.fakefile = fakefile;
}
/**
* store content of entered text
*/
public void setFakeText(String faketext, Charset faketextcharset) {
this.faketext = faketext;
this.faketextcharset = faketextcharset;
}
public InputStream getFakeInputStream(URL source)
throws IOException {
InputStream is = null;
Charset c = null;
if (fakefile != null) {
is = fakefile.getInputStream();
}
if (faketext != null) {
is = new ByteArrayInputStream(faketext.getBytes(faketextcharset));
c = faketextcharset;
}
if (is == null) {
return null;
}
if (c == null) {
c = getCharsetObjForURL(source);
}
if (c == null) {
UnicodeInputStream uis = new UnicodeInputStream(is);
String guessedCharset = uis.getEncodingFromStream();
if (guessedCharset != null) {
setCharsetForURL(source, guessedCharset, true);
}
return uis;
} else {
if (utf8Charset.compareTo(c) == 0) {
return new UnicodeInputStream(is);
}
}
return is;
}
public boolean isInputFake() {
return ((faketext != null) || (fakefile != null));
}
public void setFakeURL(String fakeurl) {
try {
this.fakeurl = new URL(fakeurl);
} catch (Exception ex) {
}
}
public URL getFakeURL() {
return fakeurl;
}
/**
* support for namespaces
*/
public void setNamespace(URL url, String prefix, String nsname) {
if (namespaces == null) {
namespaces = new HashMap<URL, HashMap<String, String>>();
}
// reformat the prefix if null.
String realPrefix = ((prefix != null) && !prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
nsdefs = new HashMap<String, String>();
nsdefs.put(realPrefix, nsname);
namespaces.put(url, nsdefs);
} else {
// do we need to check if we have a redefinition ?
nsdefs.put(realPrefix, nsname);
}
}
// true if a namespace is defined in the document (CSS fragment)
// defined by the URL, with prefix "prefix"
public boolean isNamespaceDefined(URL url, String prefix) {
if (prefix == null) { // no prefix, always match
return true;
}
if (prefix.equals("*")) { // any ns, always true
return true;
}
String realPrefix = (!prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
return false;
}
return nsdefs.containsKey(realPrefix);
}
/**
* Set the current referrer for possible linked style sheets
*
* @param referrer the referring URL
*/
public void setReferrer(URL referrer) {
this.referrer = referrer;
}
/**
* get the referrer URL (or null if not relevant)
*
* @return an URL
*/
public URL getReferrer() {
return referrer;
}
}
|
183293_45 | package Syndrill.Controller;
import Syndrill.Logic.Logic;
import Syndrill.Model.*;
import Syndrill.Model.Exceptions.GleicheKnoten;
import Syndrill.Model.Exceptions.KanteNichtGefunden;
import Syndrill.View.MainWindow;
import javax.imageio.ImageIO;
import javax.naming.NamingException;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;
/**
* Klasse des Application-Controllers
*/
public class Controller {
private Logic logic;
private MainWindow mainWindow;
/**
* Controller Konstruktor
* @param logic Logic
*/
public Controller(Logic logic){
this.logic = logic;
}
/**
* Methode zum Kreieren des Hauptfensters
* @throws IOException
*/
private void createMainApplication() throws IOException {
mainWindow = new MainWindow(this);
mainWindow.setVisible(true);
}
/**
* Methode zum Angeizegen der Nachricht
* @param nachricht
* @param titel
* @param nachrichtTyp
*/
private void showMessage(String nachricht, String titel, int nachrichtTyp){
JOptionPane.showMessageDialog(mainWindow, nachricht, titel,
nachrichtTyp);
}
/**
* Methode zum Starten der Application
* @throws IOException
*/
public void startApplication() throws IOException {
createMainApplication();
}
/**
* Methode zum Schließen der Application
*/
public void applicationExit() {
System.exit(0);
}
/**
* Methode ruft Relayout-Methode des View
*/
private void refreshGraph(){
mainWindow.refreshUI();
}
/**
* Methode gibt aktuelle Sphärenpanel zurück
* @return JPanel
*/
private JPanel getSpherePanel(){
return mainWindow.getSpherePanel();
}
/**
* Methode zum Exportieren des Graphen als PDF
* @param panel JPanel zuexportierende Panel
* @param glassPane zuexportierende GlassPane
* @param fileName Dateiname für Speicherung
*/
public void saveToPDF(JPanel panel, Component glassPane, String fileName) {
File imgFile = new File("glassPane.png");
BufferedImage img = new BufferedImage(glassPane.getWidth(), glassPane.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
glassPane.paint(g);
g.dispose();
try{
ImageIO.write(img, "png", imgFile);
}catch(IOException e){
e.printStackTrace();
}
PdfDocument pdf = null;
try {
pdf = new PdfDocument(new PdfWriter(fileName));
pdf.addNewPage();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfPage page = pdf.getFirstPage();
int rotate = page.getRotation();
if(rotate == 0){
page.setRotation(90);
}
BufferedImage jImg = new BufferedImage(panel.getWidth(),
panel.getHeight(),
BufferedImage.TYPE_INT_ARGB);
panel.paint(jImg.createGraphics());
com.itextpdf.layout.element.Image itextImg = null;
try {
itextImg = new com.itextpdf.layout.element.Image(
ImageDataFactory.create(jImg, null));
} catch (IOException e) {
e.printStackTrace();
}
ImageData imageData = null;
try {
imageData = ImageDataFactory.create("glassPane.png");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Document document = new Document(pdf);
itextImg.setRotationAngle(Math.toRadians(90));
itextImg.setFixedPosition(0,0);
itextImg.scaleToFit(page.getPageSize().getHeight(), page.getPageSize().getWidth());
document.add(itextImg);
com.itextpdf.layout.element.Image pdfImg = new com.itextpdf.layout.element.Image(imageData);
pdfImg.setRotationAngle(Math.toRadians(90));
// Y Koordinaten Anpassung
// - 17 mac
// - 30 win
String OS = System.getProperty("os.name", "generic").toLowerCase();
int left = -17;
if(OS.split(" ").length > 1){
if( OS.split(" ")[0].equals("windows")){
left = -15;
}
}
pdfImg.setFixedPosition(left,0);
pdfImg.scaleToFit(page.getPageSize().getHeight(), page.getPageSize().getWidth());
document.add(pdfImg);
document.close();
}
/**
* Methode liefert das Pfad der ausgewählten Ordner sowie Dateinamen mit Addition des Formates zurück
* @param format String
* @return String
*/
public String chooseDirectory(String format){
File fileToSave = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Graph speichern unter...");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showSaveDialog(mainWindow);
if (result == JFileChooser.APPROVE_OPTION) {
fileToSave = fileChooser.getSelectedFile();
}
return fileToSave.getAbsolutePath()+"."+format;
}
/**
* Methode liefert das Pfad der zuladender Graphdatei zurück
* @return String
*/
public String chooseFile() {
File fileToSave = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Graphdatei auswählen");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(mainWindow);
if (result == JFileChooser.APPROVE_OPTION) {
fileToSave = fileChooser.getSelectedFile();
}
return fileToSave.getAbsolutePath();
}
/**
* Methode zum Anliegen eines neuen Graphes
*/
public void createNewGraph() {
allKanten = new LinkedList<>();
logic.createNewGraph();
getSpherePanel().removeAll();
refreshGraph();
}
/**
* Methode zum Speichern des gesamten Graphes unter einer Datei
* @param filePath String
*/
public void saveGraph(String filePath) {
try {
logic.saveGraph(filePath);
showMessage("Graph wurde erfolgreich abgespeichert", "Aktion erfolgreich", JOptionPane.PLAIN_MESSAGE);
} catch (IOException e) {
showMessage(e.getMessage(),"Graphspeicherung fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Setzen des aktuellen Sphärenkomponentes
* @param sphereKomponent JPanel
*/
public void setCurrentSphereKomponent(JPanel sphereKomponent){
logic.setCurrentSphaereKomponent(sphereKomponent);
}
/**
* Methode gibt den aktuellen Sphärenkomponent zurück
* @return JPanel
*/
public JPanel getCurrentSphereKomponent(){
return logic.getCurrentSphaereKomponent();
}
/**
* Methode setzt die aktuelle Sphäre
* @param sphaere Sphaere
*/
public void setCurrentSphere(Sphaere sphaere) {
try{
logic.setCurrentSphere(sphaere);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht gefunden", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen der aktuellen Sphäre
*/
public void deleteCurrentSphere() {
deleteSphere(logic.getCurrentSphere());
}
/**
* Methode zeigt ein Dialog zum Erstellen der Sphäre
*/
public void createSphere(){
if(mainWindow == null){
throw new NullPointerException("MainApplication ist null");
}
mainWindow.displayCreateSphereDialog();
}
/**
* Methode zum Erstellen der Sphäre und dessen UI-Komponente
* @param sphereName String
* @param farbe Color
*/
public void createSphere(String sphereName, Color farbe){
try {
Sphaere sp = logic.createSphere(sphereName, farbe);
logic.checkNames(sp);
JPanel spKomponent = createSphereKomponent(sp);
displaySphereKomponent(spKomponent);
logic.addSphere(sp);
logic.addSphereKomponent(sp,spKomponent);
repaintKanten();
JOptionPane.showMessageDialog(mainWindow, "Sphäre wurde erfolgreich hinzugefügt", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht erstellt", JOptionPane.ERROR_MESSAGE);
}catch (IllegalArgumentException | NamingException e) {
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht erstellt", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Bearbeiten der Sphäre
* @param sphaere Sphaere
* @param farbe Color
*/
public void editSphere(Sphaere sphaere, Color farbe){
try{
logic.editSphere(sphaere, farbe);
sphaere.getSphaereKomponent().setBackground(farbe);
refreshGraph();
JOptionPane.showMessageDialog(mainWindow, "Sphäre wurde erfolgreich bearbeitet", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen der Sphäre
* @param sphaere Sphaere
*/
private void deleteSphere(Sphaere sphaere){
try{
logic.deleteSphere(sphaere);
deleteSphereRelations(sphaere);
deleteSphereKomponent();
refreshGraph();
}catch (NoSuchElementException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht gelöscht", JOptionPane.ERROR_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, "Keine zugehörige Sphärekomponente wurde gefunden", "Sphäre wurde nicht gelöscht", JOptionPane.ERROR_MESSAGE);
}
}
private void deleteSphereRelations(Sphaere sphaere) {
for(Knoten k : sphaere.getKnotenList()){
logic.deleteKantenOfKnoten(k);
deleteRelationen(k);
}
}
/**
* Methode gibt einen erstellten Sphärenkomponent zurück
* @param sphaere Sphaere
* @return JPanel
*/
public JPanel createSphereKomponent(Sphaere sphaere){
if(sphaere == null){
throw new NullPointerException("Sphäre ist null");
}
return mainWindow.createSphereKomponent(sphaere);
}
/**
* Methode zum Anzeigen der Sphärenkomponente
* @param sphaerenKomponent JPanel
*/
public void displaySphereKomponent(JPanel sphaerenKomponent){
if(sphaerenKomponent == null){
throw new NullPointerException("Sphärenkomponent ist null");
}
mainWindow.displaySphereKomponent(sphaerenKomponent);
}
/**
* Methode zum Löschen des aktuellen Sphärenkomponentes
*/
private void deleteSphereKomponent() {
JPanel spherePanel = getSpherePanel();
JPanel sphereKomponent = logic.getCurrentSphaereKomponent();
spherePanel.remove(sphereKomponent);
}
/**
* Methode zeigt ein Dialog zum Erstellen des Knoten
*/
public void createKnoten(){
if(mainWindow != null){
mainWindow.displayCreateKnotenDialog();
}
}
/**
* Methode zum Erstellen des Knoten anhand der zwei Parameter
* @param bezeichnung String
* @param farbe Color
*/
public void createKnoten(String bezeichnung, Color farbe) {
try{
Knoten knoten = logic.createKnoten(bezeichnung, farbe);
JPanel knotenKomponent = createKnotenKomponent(knoten);
displayKnotenKomponent(knotenKomponent);
Sphaere currentSp = logic.getCurrentSphere();
knoten.setKnotenKomponent(knotenKomponent);
logic.addKnoten(currentSp,knoten);
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich erstellt", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten konnte nicht erstellt werden", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Bearbeiten des Knotens
* @param knoten Knoten
* @param farbeNeu Color
*/
public void editKnoten(Knoten knoten, Color farbeNeu) {
try{
logic.editKnoten(knoten, farbeNeu);
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich bearbeitet", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen des Knotens
* @param knoten Knoten
*/
public void deleteKnoten(Knoten knoten){
try{
if(logic.deleteKnoten(knoten)){
deleteRelationen(knoten);
deleteKnotenKomponent(knoten);
mainWindow.refreshUI();
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich gelöscht", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde nicht gelöscht", "Fehler", JOptionPane.INFORMATION_MESSAGE);
}
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode löscht alle Kanten-Relationen eines Knoten
* @param knoten Knoten
*/
private void deleteRelationen(Knoten knoten) {
for(Kante k : knoten.getKantenList()){
logic.getAlleKantenKomponente().deleteLines(k.getRelation().getStartPoint(), k.getRelation().getEndPoint());
}
logic.getAlleKantenKomponente().refresh();
}
/**
* Methode liefert ein Knotenkomponent zum Knoten zurück
* @param knoten Knoten
* @return JPanel
*/
private JPanel createKnotenKomponent(Knoten knoten){
return mainWindow.createKnotenKomponent(knoten);
}
/**
* Methode zum Anzeigen des Knotenkomponentes
* @param knotenKomponent JPanel
*/
private void displayKnotenKomponent(JPanel knotenKomponent) {
mainWindow.displayKnotenKomponent(knotenKomponent);
}
/**
* Methode zum Löschen des Knotenkomponentes
* @param knoten Knoten
*/
private void deleteKnotenKomponent(Knoten knoten){
int index = 0;
for(Component c : getCurrentSphereKomponent().getComponents()){
if(c.equals(knoten.getKnotenKomponent())){
break;
}
index += 1;
}
getCurrentSphereKomponent().remove(index);
}
/**
* Methode zum Repaint aller existierender Kanten
*/
private void repaintKanten() {
logic.getAlleKantenKomponente().refresh();
}
/**
* Hilfsmethode zum Erstellen der Kante
* @param kantenArt Kantenart
*/
public void newKante(KantenArt kantenArt){
setNewKantenArt(kantenArt);
enableKantenZeichnung();
}
/**
* Hilfsmethode zum Anlegen der Kante
* @param kantenArt KantenArt
*/
private void setNewKantenArt(KantenArt kantenArt){
logic.setCurrentKantenArt(kantenArt);
}
/**
* Hilfsmethode, die erlaubt, eine Kante zwischen zwei Knoten zu zeichnen
*/
private void enableKantenZeichnung(){
logic.setKantenZeichnung(true);
}
/**
* Hilfsmethode gibt den Status der Kantenzeichnung zurück
* @return boolean
*/
public boolean getKantenZeichnung() {
return logic.getKantenZeichnung();
}
/**
* Methode zum Erstellen der Kante anhand der zwei ausgewählten bzw. angeclickten UI-Knotenkomponente
* @param knoten Knoten
*/
public void setKantenKnoten(Knoten knoten) {
try {
boolean kanteReadyToBeDrawn = logic.setKantenKnoten(knoten);
if(kanteReadyToBeDrawn && !logic.getCurrentKantenArt().equals(KantenArt.UNBEKANNT)){
Color farbe = mainWindow.displaySetColorKanteDialog();
Kante newKante = logic.createKante(farbe);
logic.addKanteToSelectedKnoten(newKante);
logic.createKantenKomponent(newKante);
}else if(kanteReadyToBeDrawn && logic.getCurrentKantenArt().equals(KantenArt.UNBEKANNT)){
logic.deleteKante();
loadAllKantenKomponente();
}
logic.getAlleKantenKomponente().refresh();
updateGlassPlane();
} catch (KanteNichtGefunden | GleicheKnoten e){
showMessage(e.getMessage(),"Aktion fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zur Neuzeichnung der Kanten
*/
private void updateGlassPlane() {
if(!logic.getAlleKantenKomponente().empty()){
loadAllKantenKomponente();
if(!mainWindow.getGlassPane().isVisible()){
mainWindow.getGlassPane().setVisible(true);
}
}
}
private void loadAllKantenKomponente() {
mainWindow.setGlassPane(logic.getAlleKantenKomponente());
}
/**
* Hilfsliste zur Elimination von gleichen Kanten
*/
private java.util.List<Kante> allKanten = new LinkedList<>();
/**
* Methode zum Laden des Graphen aus einer Datei
* @param filePath String
*/
public void loadGraph(String filePath){
createNewGraph();
try {
logic.loadGraph(filePath);
Graph g = logic.getCurrentGraph();
for(Sphaere s : g.getSphaerenList()){
loadSphaere(s);
}
loadAllKanten();
refreshGraph();
updateGlassPlane();
logic.deleteRelationLink();
} catch (IOException e) {
showMessage(e.getMessage(),"Graphladen fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Hilfsmethode zum Laden der Sphären des zuladenden Graphes
* @param sphaere Sphaere
*/
private void loadSphaere(Sphaere sphaere) {
JPanel sphaereKomponent = createSphereKomponent(sphaere);
displaySphereKomponent(sphaereKomponent);
for(Knoten k : sphaere.getKnotenList()){
loadKnoten(k, sphaereKomponent);
}
}
/**
* Hilfsmethode zum Laden der Knoten des zuladenden Graphes
* @param knoten Knoten
* @param sphaereKomponent JPanel
*/
private void loadKnoten(Knoten knoten, JPanel sphaereKomponent) {
JPanel knotenKomponent = createKnotenKomponent(knoten);
sphaereKomponent.add(knotenKomponent);
knotenKomponent.setLocation(knoten.getInternalPosition());
knotenKomponent.setSize(knoten.getGroesse());
knotenKomponent.setVisible(true);
knotenKomponent.validate();
knotenKomponent.repaint();
knoten.setKnotenKomponent(knotenKomponent);
for(Kante kante : knoten.getKantenList()){
allKanten.add(kante);
}
}
/**
* Hilfsmethode zum Laden aller Kanten
*/
private void loadAllKanten() {
java.util.List<Kante> kantenToLoad = allKanten.stream().distinct().collect(Collectors.toList());
for(Kante kante : kantenToLoad){
loadKante(kante);
}
}
/**
* Hilfsmethode zum Laden einzelner Kante
* @param kante
*/
private void loadKante(Kante kante) {
logic.createKantenKomponent(kante);
}
// Für Tests
public void setMainWindow(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
}
| nshevo/syndrom_concept | main/java/Syndrill/Controller/Controller.java | 6,537 | /**
* Hilfsmethode zum Laden der Knoten des zuladenden Graphes
* @param knoten Knoten
* @param sphaereKomponent JPanel
*/ | block_comment | nl | package Syndrill.Controller;
import Syndrill.Logic.Logic;
import Syndrill.Model.*;
import Syndrill.Model.Exceptions.GleicheKnoten;
import Syndrill.Model.Exceptions.KanteNichtGefunden;
import Syndrill.View.MainWindow;
import javax.imageio.ImageIO;
import javax.naming.NamingException;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;
/**
* Klasse des Application-Controllers
*/
public class Controller {
private Logic logic;
private MainWindow mainWindow;
/**
* Controller Konstruktor
* @param logic Logic
*/
public Controller(Logic logic){
this.logic = logic;
}
/**
* Methode zum Kreieren des Hauptfensters
* @throws IOException
*/
private void createMainApplication() throws IOException {
mainWindow = new MainWindow(this);
mainWindow.setVisible(true);
}
/**
* Methode zum Angeizegen der Nachricht
* @param nachricht
* @param titel
* @param nachrichtTyp
*/
private void showMessage(String nachricht, String titel, int nachrichtTyp){
JOptionPane.showMessageDialog(mainWindow, nachricht, titel,
nachrichtTyp);
}
/**
* Methode zum Starten der Application
* @throws IOException
*/
public void startApplication() throws IOException {
createMainApplication();
}
/**
* Methode zum Schließen der Application
*/
public void applicationExit() {
System.exit(0);
}
/**
* Methode ruft Relayout-Methode des View
*/
private void refreshGraph(){
mainWindow.refreshUI();
}
/**
* Methode gibt aktuelle Sphärenpanel zurück
* @return JPanel
*/
private JPanel getSpherePanel(){
return mainWindow.getSpherePanel();
}
/**
* Methode zum Exportieren des Graphen als PDF
* @param panel JPanel zuexportierende Panel
* @param glassPane zuexportierende GlassPane
* @param fileName Dateiname für Speicherung
*/
public void saveToPDF(JPanel panel, Component glassPane, String fileName) {
File imgFile = new File("glassPane.png");
BufferedImage img = new BufferedImage(glassPane.getWidth(), glassPane.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
glassPane.paint(g);
g.dispose();
try{
ImageIO.write(img, "png", imgFile);
}catch(IOException e){
e.printStackTrace();
}
PdfDocument pdf = null;
try {
pdf = new PdfDocument(new PdfWriter(fileName));
pdf.addNewPage();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfPage page = pdf.getFirstPage();
int rotate = page.getRotation();
if(rotate == 0){
page.setRotation(90);
}
BufferedImage jImg = new BufferedImage(panel.getWidth(),
panel.getHeight(),
BufferedImage.TYPE_INT_ARGB);
panel.paint(jImg.createGraphics());
com.itextpdf.layout.element.Image itextImg = null;
try {
itextImg = new com.itextpdf.layout.element.Image(
ImageDataFactory.create(jImg, null));
} catch (IOException e) {
e.printStackTrace();
}
ImageData imageData = null;
try {
imageData = ImageDataFactory.create("glassPane.png");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Document document = new Document(pdf);
itextImg.setRotationAngle(Math.toRadians(90));
itextImg.setFixedPosition(0,0);
itextImg.scaleToFit(page.getPageSize().getHeight(), page.getPageSize().getWidth());
document.add(itextImg);
com.itextpdf.layout.element.Image pdfImg = new com.itextpdf.layout.element.Image(imageData);
pdfImg.setRotationAngle(Math.toRadians(90));
// Y Koordinaten Anpassung
// - 17 mac
// - 30 win
String OS = System.getProperty("os.name", "generic").toLowerCase();
int left = -17;
if(OS.split(" ").length > 1){
if( OS.split(" ")[0].equals("windows")){
left = -15;
}
}
pdfImg.setFixedPosition(left,0);
pdfImg.scaleToFit(page.getPageSize().getHeight(), page.getPageSize().getWidth());
document.add(pdfImg);
document.close();
}
/**
* Methode liefert das Pfad der ausgewählten Ordner sowie Dateinamen mit Addition des Formates zurück
* @param format String
* @return String
*/
public String chooseDirectory(String format){
File fileToSave = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Graph speichern unter...");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showSaveDialog(mainWindow);
if (result == JFileChooser.APPROVE_OPTION) {
fileToSave = fileChooser.getSelectedFile();
}
return fileToSave.getAbsolutePath()+"."+format;
}
/**
* Methode liefert das Pfad der zuladender Graphdatei zurück
* @return String
*/
public String chooseFile() {
File fileToSave = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Graphdatei auswählen");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(mainWindow);
if (result == JFileChooser.APPROVE_OPTION) {
fileToSave = fileChooser.getSelectedFile();
}
return fileToSave.getAbsolutePath();
}
/**
* Methode zum Anliegen eines neuen Graphes
*/
public void createNewGraph() {
allKanten = new LinkedList<>();
logic.createNewGraph();
getSpherePanel().removeAll();
refreshGraph();
}
/**
* Methode zum Speichern des gesamten Graphes unter einer Datei
* @param filePath String
*/
public void saveGraph(String filePath) {
try {
logic.saveGraph(filePath);
showMessage("Graph wurde erfolgreich abgespeichert", "Aktion erfolgreich", JOptionPane.PLAIN_MESSAGE);
} catch (IOException e) {
showMessage(e.getMessage(),"Graphspeicherung fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Setzen des aktuellen Sphärenkomponentes
* @param sphereKomponent JPanel
*/
public void setCurrentSphereKomponent(JPanel sphereKomponent){
logic.setCurrentSphaereKomponent(sphereKomponent);
}
/**
* Methode gibt den aktuellen Sphärenkomponent zurück
* @return JPanel
*/
public JPanel getCurrentSphereKomponent(){
return logic.getCurrentSphaereKomponent();
}
/**
* Methode setzt die aktuelle Sphäre
* @param sphaere Sphaere
*/
public void setCurrentSphere(Sphaere sphaere) {
try{
logic.setCurrentSphere(sphaere);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht gefunden", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen der aktuellen Sphäre
*/
public void deleteCurrentSphere() {
deleteSphere(logic.getCurrentSphere());
}
/**
* Methode zeigt ein Dialog zum Erstellen der Sphäre
*/
public void createSphere(){
if(mainWindow == null){
throw new NullPointerException("MainApplication ist null");
}
mainWindow.displayCreateSphereDialog();
}
/**
* Methode zum Erstellen der Sphäre und dessen UI-Komponente
* @param sphereName String
* @param farbe Color
*/
public void createSphere(String sphereName, Color farbe){
try {
Sphaere sp = logic.createSphere(sphereName, farbe);
logic.checkNames(sp);
JPanel spKomponent = createSphereKomponent(sp);
displaySphereKomponent(spKomponent);
logic.addSphere(sp);
logic.addSphereKomponent(sp,spKomponent);
repaintKanten();
JOptionPane.showMessageDialog(mainWindow, "Sphäre wurde erfolgreich hinzugefügt", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht erstellt", JOptionPane.ERROR_MESSAGE);
}catch (IllegalArgumentException | NamingException e) {
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht erstellt", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Bearbeiten der Sphäre
* @param sphaere Sphaere
* @param farbe Color
*/
public void editSphere(Sphaere sphaere, Color farbe){
try{
logic.editSphere(sphaere, farbe);
sphaere.getSphaereKomponent().setBackground(farbe);
refreshGraph();
JOptionPane.showMessageDialog(mainWindow, "Sphäre wurde erfolgreich bearbeitet", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen der Sphäre
* @param sphaere Sphaere
*/
private void deleteSphere(Sphaere sphaere){
try{
logic.deleteSphere(sphaere);
deleteSphereRelations(sphaere);
deleteSphereKomponent();
refreshGraph();
}catch (NoSuchElementException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Sphäre wurde nicht gelöscht", JOptionPane.ERROR_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, "Keine zugehörige Sphärekomponente wurde gefunden", "Sphäre wurde nicht gelöscht", JOptionPane.ERROR_MESSAGE);
}
}
private void deleteSphereRelations(Sphaere sphaere) {
for(Knoten k : sphaere.getKnotenList()){
logic.deleteKantenOfKnoten(k);
deleteRelationen(k);
}
}
/**
* Methode gibt einen erstellten Sphärenkomponent zurück
* @param sphaere Sphaere
* @return JPanel
*/
public JPanel createSphereKomponent(Sphaere sphaere){
if(sphaere == null){
throw new NullPointerException("Sphäre ist null");
}
return mainWindow.createSphereKomponent(sphaere);
}
/**
* Methode zum Anzeigen der Sphärenkomponente
* @param sphaerenKomponent JPanel
*/
public void displaySphereKomponent(JPanel sphaerenKomponent){
if(sphaerenKomponent == null){
throw new NullPointerException("Sphärenkomponent ist null");
}
mainWindow.displaySphereKomponent(sphaerenKomponent);
}
/**
* Methode zum Löschen des aktuellen Sphärenkomponentes
*/
private void deleteSphereKomponent() {
JPanel spherePanel = getSpherePanel();
JPanel sphereKomponent = logic.getCurrentSphaereKomponent();
spherePanel.remove(sphereKomponent);
}
/**
* Methode zeigt ein Dialog zum Erstellen des Knoten
*/
public void createKnoten(){
if(mainWindow != null){
mainWindow.displayCreateKnotenDialog();
}
}
/**
* Methode zum Erstellen des Knoten anhand der zwei Parameter
* @param bezeichnung String
* @param farbe Color
*/
public void createKnoten(String bezeichnung, Color farbe) {
try{
Knoten knoten = logic.createKnoten(bezeichnung, farbe);
JPanel knotenKomponent = createKnotenKomponent(knoten);
displayKnotenKomponent(knotenKomponent);
Sphaere currentSp = logic.getCurrentSphere();
knoten.setKnotenKomponent(knotenKomponent);
logic.addKnoten(currentSp,knoten);
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich erstellt", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten konnte nicht erstellt werden", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Bearbeiten des Knotens
* @param knoten Knoten
* @param farbeNeu Color
*/
public void editKnoten(Knoten knoten, Color farbeNeu) {
try{
logic.editKnoten(knoten, farbeNeu);
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich bearbeitet", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zum Löschen des Knotens
* @param knoten Knoten
*/
public void deleteKnoten(Knoten knoten){
try{
if(logic.deleteKnoten(knoten)){
deleteRelationen(knoten);
deleteKnotenKomponent(knoten);
mainWindow.refreshUI();
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde erfolgreich gelöscht", "Aktion erfolgreich", JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(mainWindow, "Knoten wurde nicht gelöscht", "Fehler", JOptionPane.INFORMATION_MESSAGE);
}
}catch (NullPointerException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}catch (RuntimeException e){
JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Knoten wurde nicht bearbeitet", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode löscht alle Kanten-Relationen eines Knoten
* @param knoten Knoten
*/
private void deleteRelationen(Knoten knoten) {
for(Kante k : knoten.getKantenList()){
logic.getAlleKantenKomponente().deleteLines(k.getRelation().getStartPoint(), k.getRelation().getEndPoint());
}
logic.getAlleKantenKomponente().refresh();
}
/**
* Methode liefert ein Knotenkomponent zum Knoten zurück
* @param knoten Knoten
* @return JPanel
*/
private JPanel createKnotenKomponent(Knoten knoten){
return mainWindow.createKnotenKomponent(knoten);
}
/**
* Methode zum Anzeigen des Knotenkomponentes
* @param knotenKomponent JPanel
*/
private void displayKnotenKomponent(JPanel knotenKomponent) {
mainWindow.displayKnotenKomponent(knotenKomponent);
}
/**
* Methode zum Löschen des Knotenkomponentes
* @param knoten Knoten
*/
private void deleteKnotenKomponent(Knoten knoten){
int index = 0;
for(Component c : getCurrentSphereKomponent().getComponents()){
if(c.equals(knoten.getKnotenKomponent())){
break;
}
index += 1;
}
getCurrentSphereKomponent().remove(index);
}
/**
* Methode zum Repaint aller existierender Kanten
*/
private void repaintKanten() {
logic.getAlleKantenKomponente().refresh();
}
/**
* Hilfsmethode zum Erstellen der Kante
* @param kantenArt Kantenart
*/
public void newKante(KantenArt kantenArt){
setNewKantenArt(kantenArt);
enableKantenZeichnung();
}
/**
* Hilfsmethode zum Anlegen der Kante
* @param kantenArt KantenArt
*/
private void setNewKantenArt(KantenArt kantenArt){
logic.setCurrentKantenArt(kantenArt);
}
/**
* Hilfsmethode, die erlaubt, eine Kante zwischen zwei Knoten zu zeichnen
*/
private void enableKantenZeichnung(){
logic.setKantenZeichnung(true);
}
/**
* Hilfsmethode gibt den Status der Kantenzeichnung zurück
* @return boolean
*/
public boolean getKantenZeichnung() {
return logic.getKantenZeichnung();
}
/**
* Methode zum Erstellen der Kante anhand der zwei ausgewählten bzw. angeclickten UI-Knotenkomponente
* @param knoten Knoten
*/
public void setKantenKnoten(Knoten knoten) {
try {
boolean kanteReadyToBeDrawn = logic.setKantenKnoten(knoten);
if(kanteReadyToBeDrawn && !logic.getCurrentKantenArt().equals(KantenArt.UNBEKANNT)){
Color farbe = mainWindow.displaySetColorKanteDialog();
Kante newKante = logic.createKante(farbe);
logic.addKanteToSelectedKnoten(newKante);
logic.createKantenKomponent(newKante);
}else if(kanteReadyToBeDrawn && logic.getCurrentKantenArt().equals(KantenArt.UNBEKANNT)){
logic.deleteKante();
loadAllKantenKomponente();
}
logic.getAlleKantenKomponente().refresh();
updateGlassPlane();
} catch (KanteNichtGefunden | GleicheKnoten e){
showMessage(e.getMessage(),"Aktion fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Methode zur Neuzeichnung der Kanten
*/
private void updateGlassPlane() {
if(!logic.getAlleKantenKomponente().empty()){
loadAllKantenKomponente();
if(!mainWindow.getGlassPane().isVisible()){
mainWindow.getGlassPane().setVisible(true);
}
}
}
private void loadAllKantenKomponente() {
mainWindow.setGlassPane(logic.getAlleKantenKomponente());
}
/**
* Hilfsliste zur Elimination von gleichen Kanten
*/
private java.util.List<Kante> allKanten = new LinkedList<>();
/**
* Methode zum Laden des Graphen aus einer Datei
* @param filePath String
*/
public void loadGraph(String filePath){
createNewGraph();
try {
logic.loadGraph(filePath);
Graph g = logic.getCurrentGraph();
for(Sphaere s : g.getSphaerenList()){
loadSphaere(s);
}
loadAllKanten();
refreshGraph();
updateGlassPlane();
logic.deleteRelationLink();
} catch (IOException e) {
showMessage(e.getMessage(),"Graphladen fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Hilfsmethode zum Laden der Sphären des zuladenden Graphes
* @param sphaere Sphaere
*/
private void loadSphaere(Sphaere sphaere) {
JPanel sphaereKomponent = createSphereKomponent(sphaere);
displaySphereKomponent(sphaereKomponent);
for(Knoten k : sphaere.getKnotenList()){
loadKnoten(k, sphaereKomponent);
}
}
/**
* Hilfsmethode zum Laden<SUF>*/
private void loadKnoten(Knoten knoten, JPanel sphaereKomponent) {
JPanel knotenKomponent = createKnotenKomponent(knoten);
sphaereKomponent.add(knotenKomponent);
knotenKomponent.setLocation(knoten.getInternalPosition());
knotenKomponent.setSize(knoten.getGroesse());
knotenKomponent.setVisible(true);
knotenKomponent.validate();
knotenKomponent.repaint();
knoten.setKnotenKomponent(knotenKomponent);
for(Kante kante : knoten.getKantenList()){
allKanten.add(kante);
}
}
/**
* Hilfsmethode zum Laden aller Kanten
*/
private void loadAllKanten() {
java.util.List<Kante> kantenToLoad = allKanten.stream().distinct().collect(Collectors.toList());
for(Kante kante : kantenToLoad){
loadKante(kante);
}
}
/**
* Hilfsmethode zum Laden einzelner Kante
* @param kante
*/
private void loadKante(Kante kante) {
logic.createKantenKomponent(kante);
}
// Für Tests
public void setMainWindow(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
}
|
83536_3 | package io.github.nthduc.springboot.springboot_rest_api.repositories;
import io.github.nthduc.springboot.springboot_rest_api.models.HelloWorldBean;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale );
//return "Hello World V2";
//1:
//2:
// - Example: `en` - English (Good Morning)
// - Example: `nl` - Dutch (Goedemorgen)
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
} | nthduc/spring-master | springboot-rest-api/src/main/java/io/github/nthduc/springboot/springboot_rest_api/repositories/HelloWorldController.java | 522 | // - Example: `nl` - Dutch (Goedemorgen) | line_comment | nl | package io.github.nthduc.springboot.springboot_rest_api.repositories;
import io.github.nthduc.springboot.springboot_rest_api.models.HelloWorldBean;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale );
//return "Hello World V2";
//1:
//2:
// - Example: `en` - English (Good Morning)
// - Example:<SUF>
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
} |
26575_1 | /*
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted.image;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.graalvm.compiler.core.common.NumUtil;
import org.graalvm.compiler.serviceprovider.BufferUtil;
import org.graalvm.nativeimage.c.function.CFunctionPointer;
import org.graalvm.nativeimage.c.function.RelocatedPointer;
import com.oracle.objectfile.ObjectFile;
import com.oracle.svm.hosted.meta.MethodPointer;
import jdk.vm.ci.meta.ResolvedJavaMethod;
public final class RelocatableBuffer {
public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) {
return new RelocatableBuffer(name, size, byteOrder);
}
/*
* Map methods.
*/
public RelocatableBuffer.Info getInfo(final int key) {
return getMap().get(key);
}
// The only place is is used is to add the ObjectHeader bits to a DynamicHub,
// which is otherwise just a reference to a class.
// In the future, this could be used for any offset from a relocated object reference.
public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addRelocation(int key, ObjectFile.RelocationKind relocationKind, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(relocationKind, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public int mapSize() {
return getMap().size();
}
// TODO: Replace with a visitor pattern rather than exposing the entrySet.
public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() {
return getMap().entrySet();
}
/** Raw map access. */
private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) {
return getMap().put(key, value);
}
/** Raw map access. */
protected Map<Integer, RelocatableBuffer.Info> getMap() {
return map;
}
/*
* ByteBuffer methods.
*/
public byte getByte(final int index) {
return getBuffer().get(index);
}
public RelocatableBuffer putByte(final byte value) {
getBuffer().put(value);
return this;
}
public RelocatableBuffer putByte(final int index, final byte value) {
getBuffer().put(index, value);
return this;
}
public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) {
getBuffer().put(source, offset, length);
return this;
}
public RelocatableBuffer putInt(final int index, final int value) {
getBuffer().putInt(index, value);
return this;
}
public int getPosition() {
return getBuffer().position();
}
public RelocatableBuffer setPosition(final int newPosition) {
BufferUtil.asBaseBuffer(getBuffer()).position(newPosition);
return this;
}
// TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer.
protected byte[] getBytes() {
return getBuffer().array();
}
// TODO: This should become a private method.
protected ByteBuffer getBuffer() {
return buffer;
}
/*
* Info factory.
*/
private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
return new Info(kind, relocationSize, explicitAddend, targetObject);
}
/*
* Debugging.
*/
public String getName() {
return name;
}
protected static String targetObjectClassification(final Object targetObject) {
final StringBuilder result = new StringBuilder();
if (targetObject == null) {
result.append("null");
} else {
if (targetObject instanceof CFunctionPointer) {
result.append("pointer to function");
if (targetObject instanceof MethodPointer) {
final MethodPointer mp = (MethodPointer) targetObject;
final ResolvedJavaMethod hm = mp.getMethod();
result.append(" name: ");
result.append(hm.getName());
}
} else {
result.append("pointer to data");
}
}
return result.toString();
}
/** Constructor. */
private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) {
this.name = name;
this.size = size;
final int intSize = NumUtil.safeToInt(size);
this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder);
this.map = new TreeMap<>();
}
// Immutable fields.
/** For debugging. */
protected final String name;
/** The size of the ByteBuffer. */
protected final long size;
/** The ByteBuffer itself. */
protected final ByteBuffer buffer;
/** The map itself. */
private final TreeMap<Integer, RelocatableBuffer.Info> map;
// Constants.
static final long serialVersionUID = 0;
static final int WORD_SIZE = 8; // HACK: hard-code for now
// Note: A non-static inner class.
// Note: To keep the RelocatableBuffer from getting separated from this Info.
public class Info {
/*
* Access methods.
*/
public int getRelocationSize() {
return relocationSize;
}
public ObjectFile.RelocationKind getRelocationKind() {
return relocationKind;
}
public boolean hasExplicitAddend() {
return (explicitAddend != null);
}
// May return null.
public Long getExplicitAddend() {
return explicitAddend;
}
public Object getTargetObject() {
return targetObject;
}
// Protected constructor called only from RelocatableBuffer.infoFactory method.
protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
this.relocationKind = kind;
this.relocationSize = relocationSize;
this.explicitAddend = explicitAddend;
this.targetObject = targetObject;
}
// Immutable state.
private final int relocationSize;
private final ObjectFile.RelocationKind relocationKind;
private final Long explicitAddend;
/**
* The referenced object on the heap. If this is an instance of a {@link RelocatedPointer},
* than the relocation is not treated as a data relocation but has a special meaning, e.g. a
* code (text section) or constants (rodata section) relocation.
*/
private final Object targetObject;
@Override
public String toString() {
return "RelocatableBuffer.Info(targetObject=" + targetObject + " relocationSize=" + relocationSize + " relocationKind=" + relocationKind + " explicitAddend=" + explicitAddend + ")";
}
}
}
| nurkiewicz/graal | substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/image/RelocatableBuffer.java | 2,468 | /*
* Map methods.
*/ | block_comment | nl | /*
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted.image;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.graalvm.compiler.core.common.NumUtil;
import org.graalvm.compiler.serviceprovider.BufferUtil;
import org.graalvm.nativeimage.c.function.CFunctionPointer;
import org.graalvm.nativeimage.c.function.RelocatedPointer;
import com.oracle.objectfile.ObjectFile;
import com.oracle.svm.hosted.meta.MethodPointer;
import jdk.vm.ci.meta.ResolvedJavaMethod;
public final class RelocatableBuffer {
public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) {
return new RelocatableBuffer(name, size, byteOrder);
}
/*
* Map methods.
<SUF>*/
public RelocatableBuffer.Info getInfo(final int key) {
return getMap().get(key);
}
// The only place is is used is to add the ObjectHeader bits to a DynamicHub,
// which is otherwise just a reference to a class.
// In the future, this could be used for any offset from a relocated object reference.
public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public RelocatableBuffer.Info addRelocation(int key, ObjectFile.RelocationKind relocationKind, int relocationSize, Long explicitAddend, Object targetObject) {
final RelocatableBuffer.Info info = infoFactory(relocationKind, relocationSize, explicitAddend, targetObject);
final RelocatableBuffer.Info result = putInfo(key, info);
return result;
}
public int mapSize() {
return getMap().size();
}
// TODO: Replace with a visitor pattern rather than exposing the entrySet.
public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() {
return getMap().entrySet();
}
/** Raw map access. */
private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) {
return getMap().put(key, value);
}
/** Raw map access. */
protected Map<Integer, RelocatableBuffer.Info> getMap() {
return map;
}
/*
* ByteBuffer methods.
*/
public byte getByte(final int index) {
return getBuffer().get(index);
}
public RelocatableBuffer putByte(final byte value) {
getBuffer().put(value);
return this;
}
public RelocatableBuffer putByte(final int index, final byte value) {
getBuffer().put(index, value);
return this;
}
public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) {
getBuffer().put(source, offset, length);
return this;
}
public RelocatableBuffer putInt(final int index, final int value) {
getBuffer().putInt(index, value);
return this;
}
public int getPosition() {
return getBuffer().position();
}
public RelocatableBuffer setPosition(final int newPosition) {
BufferUtil.asBaseBuffer(getBuffer()).position(newPosition);
return this;
}
// TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer.
protected byte[] getBytes() {
return getBuffer().array();
}
// TODO: This should become a private method.
protected ByteBuffer getBuffer() {
return buffer;
}
/*
* Info factory.
*/
private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
return new Info(kind, relocationSize, explicitAddend, targetObject);
}
/*
* Debugging.
*/
public String getName() {
return name;
}
protected static String targetObjectClassification(final Object targetObject) {
final StringBuilder result = new StringBuilder();
if (targetObject == null) {
result.append("null");
} else {
if (targetObject instanceof CFunctionPointer) {
result.append("pointer to function");
if (targetObject instanceof MethodPointer) {
final MethodPointer mp = (MethodPointer) targetObject;
final ResolvedJavaMethod hm = mp.getMethod();
result.append(" name: ");
result.append(hm.getName());
}
} else {
result.append("pointer to data");
}
}
return result.toString();
}
/** Constructor. */
private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) {
this.name = name;
this.size = size;
final int intSize = NumUtil.safeToInt(size);
this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder);
this.map = new TreeMap<>();
}
// Immutable fields.
/** For debugging. */
protected final String name;
/** The size of the ByteBuffer. */
protected final long size;
/** The ByteBuffer itself. */
protected final ByteBuffer buffer;
/** The map itself. */
private final TreeMap<Integer, RelocatableBuffer.Info> map;
// Constants.
static final long serialVersionUID = 0;
static final int WORD_SIZE = 8; // HACK: hard-code for now
// Note: A non-static inner class.
// Note: To keep the RelocatableBuffer from getting separated from this Info.
public class Info {
/*
* Access methods.
*/
public int getRelocationSize() {
return relocationSize;
}
public ObjectFile.RelocationKind getRelocationKind() {
return relocationKind;
}
public boolean hasExplicitAddend() {
return (explicitAddend != null);
}
// May return null.
public Long getExplicitAddend() {
return explicitAddend;
}
public Object getTargetObject() {
return targetObject;
}
// Protected constructor called only from RelocatableBuffer.infoFactory method.
protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) {
this.relocationKind = kind;
this.relocationSize = relocationSize;
this.explicitAddend = explicitAddend;
this.targetObject = targetObject;
}
// Immutable state.
private final int relocationSize;
private final ObjectFile.RelocationKind relocationKind;
private final Long explicitAddend;
/**
* The referenced object on the heap. If this is an instance of a {@link RelocatedPointer},
* than the relocation is not treated as a data relocation but has a special meaning, e.g. a
* code (text section) or constants (rodata section) relocation.
*/
private final Object targetObject;
@Override
public String toString() {
return "RelocatableBuffer.Info(targetObject=" + targetObject + " relocationSize=" + relocationSize + " relocationKind=" + relocationKind + " explicitAddend=" + explicitAddend + ")";
}
}
}
|
92849_24 | package com.nutiteq.advancedmap.activity;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ZoomControls;
import com.nutiteq.MapView;
import com.nutiteq.advancedmap.R;
import com.nutiteq.components.Components;
import com.nutiteq.components.MapPos;
import com.nutiteq.components.Options;
import com.nutiteq.log.Log;
import com.nutiteq.projections.EPSG3857;
import com.nutiteq.rasterdatasources.HTTPRasterDataSource;
import com.nutiteq.rasterdatasources.RasterDataSource;
import com.nutiteq.rasterlayers.RasterLayer;
import com.nutiteq.style.ModelStyle;
import com.nutiteq.style.StyleSet;
import com.nutiteq.utils.UnscaledBitmapLoader;
import com.nutiteq.vectorlayers.NMLModelOnlineLayer;
/**
* Demonstrates NMLModelOnlineLayer - online 3D model layer which loads data from Nutiteq NML online API.
*
* The demo server has data of few cities: Tallinn, Barcelona, San Francisco. This content is from Google 3D Warehouse
*
* Loaded data is partly cached locally with special cache.
*
* @author jaak
*
*/
public class Online3DMapActivity extends Activity {
private static final String DATASET = "http://kaart.nutiteq.ee/nml/nmlserver3.php?data=chicago"; // default dataset
private MapView mapView;
private StyleSet<ModelStyle> modelStyleSet;
private NMLModelOnlineLayer modelLayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// enable logging for troubleshooting - optional
Log.enableAll();
Log.setTag("online3d");
// 1. Get the MapView from the Layout xml - mandatory
mapView = (MapView) findViewById(R.id.mapView);
// Optional, but very useful: restore map state during device rotation,
// it is saved in onRetainNonConfigurationInstance() below
Components retainObject = (Components) getLastNonConfigurationInstance();
if (retainObject != null) {
// just restore configuration, skip other initializations
mapView.setComponents(retainObject);
return;
} else {
// 2. create and set MapView components - mandatory
Components components = new Components();
// set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D
mapView.setComponents(components);
}
// 3. Define map layer for basemap - mandatory.
RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");
RasterLayer mapLayer = new RasterLayer(dataSource, 2);
mapView.getLayers().setBaseLayer(mapLayer);
// define style for 3D to define minimum zoom = 14
ModelStyle modelStyle = ModelStyle.builder().build();
modelStyleSet = new StyleSet<ModelStyle>(null);
modelStyleSet.setZoomStyle(14, modelStyle);
// Tallinn
//mapView.setFocusPoint(new MapPos(2753845.7830863246f, 8275045.674995658f));
// San Francisco
//mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));
// getMapView().setFocusPoint(new MapPos(-1.3625947E7f, 4550716.0f));
// Chicago
getMapView().setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-87.6219, 41.8769), 1000);
// Rotterdam
//mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(4.480727f, 51.921098f));
mapView.setZoom(17.0f);
// set initial layer
online3DLayer(DATASET);
// rotation - 0 = north-up
//mapView.setMapRotation(-96.140175f);
// tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
//mapView.setTilt(30.0f);
// Activate some mapview options to make it smoother - optional
mapView.getOptions().setPreloading(false);
mapView.getOptions().setSeamlessHorizontalPan(true);
mapView.getOptions().setTileFading(false);
mapView.getOptions().setKineticPanning(true);
mapView.getOptions().setDoubleClickZoomIn(true);
mapView.getOptions().setDualClickZoomOut(true);
// set sky bitmap - optional, default - white
mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setSkyOffset(4.86f);
mapView.getOptions().setSkyBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.sky_small));
// Map background, visible if no map tiles loaded - optional, default - white
mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setBackgroundPlaneBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.background_plane));
mapView.getOptions().setClearColor(Color.WHITE);
// configure texture caching - optional, suggested
mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024);
mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);
// define online map persistent caching - optional, suggested. Default - no caching
mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
// set persistent raster cache limit to 100MB
mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);
// 4. zoom buttons using Android widgets - optional
// get the zoomcontrols that was defined in main.xml
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
// set zoomcontrols listeners to enable zooming
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
public void onClick(final View v) {
mapView.zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
public void onClick(final View v) {
mapView.zoomOut();
}
});
}
@Override
protected void onStart() {
mapView.startMapping();
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
Log.debug("x " + getMapView().getFocusPoint().x);
Log.debug("y " + getMapView().getFocusPoint().y);
Log.debug("tilt " + getMapView().getTilt());
Log.debug("rotation " + getMapView().getMapRotation());
Log.debug("zoom " + getMapView().getZoom());
mapView.stopMapping();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.online3d, menu);
return true;
}
@Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
item.setChecked(true);
switch (item.getItemId()) {
// map types
case R.id.menu3d_seattle:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=seattle");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-122.3336f, 47.6014f), 1000);
break;
case R.id.menu3d_la:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=los_angeles");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-118.24270, 34.05368), 1000);
break;
case R.id.menu3d_chicago:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=chicago");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-87.6219, 41.8769), 1000);
break;
}
return false;
}
// Switch online 3D Model layer with given URL
private void online3DLayer(String dataset) {
if(modelLayer != null)
mapView.getLayers().removeLayer(modelLayer);
modelLayer = new NMLModelOnlineLayer(new EPSG3857(),
dataset, modelStyleSet);
modelLayer.setMemoryLimit(40*1024*1024);
modelLayer.setPersistentCacheSize(60*1024*1024);
modelLayer.setPersistentCachePath(this.getDatabasePath("nmlcache_"+dataset.substring(dataset.lastIndexOf("="))).getPath());
modelLayer.setLODResolutionFactor(0.3f);
mapView.getLayers().addLayer(modelLayer);
}
public MapView getMapView() {
return mapView;
}
}
| nutiteq/hellomap3d | AdvancedMap3D/src/main/java/com/nutiteq/advancedmap/activity/Online3DMapActivity.java | 2,640 | // set zoomcontrols listeners to enable zooming | line_comment | nl | package com.nutiteq.advancedmap.activity;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ZoomControls;
import com.nutiteq.MapView;
import com.nutiteq.advancedmap.R;
import com.nutiteq.components.Components;
import com.nutiteq.components.MapPos;
import com.nutiteq.components.Options;
import com.nutiteq.log.Log;
import com.nutiteq.projections.EPSG3857;
import com.nutiteq.rasterdatasources.HTTPRasterDataSource;
import com.nutiteq.rasterdatasources.RasterDataSource;
import com.nutiteq.rasterlayers.RasterLayer;
import com.nutiteq.style.ModelStyle;
import com.nutiteq.style.StyleSet;
import com.nutiteq.utils.UnscaledBitmapLoader;
import com.nutiteq.vectorlayers.NMLModelOnlineLayer;
/**
* Demonstrates NMLModelOnlineLayer - online 3D model layer which loads data from Nutiteq NML online API.
*
* The demo server has data of few cities: Tallinn, Barcelona, San Francisco. This content is from Google 3D Warehouse
*
* Loaded data is partly cached locally with special cache.
*
* @author jaak
*
*/
public class Online3DMapActivity extends Activity {
private static final String DATASET = "http://kaart.nutiteq.ee/nml/nmlserver3.php?data=chicago"; // default dataset
private MapView mapView;
private StyleSet<ModelStyle> modelStyleSet;
private NMLModelOnlineLayer modelLayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// enable logging for troubleshooting - optional
Log.enableAll();
Log.setTag("online3d");
// 1. Get the MapView from the Layout xml - mandatory
mapView = (MapView) findViewById(R.id.mapView);
// Optional, but very useful: restore map state during device rotation,
// it is saved in onRetainNonConfigurationInstance() below
Components retainObject = (Components) getLastNonConfigurationInstance();
if (retainObject != null) {
// just restore configuration, skip other initializations
mapView.setComponents(retainObject);
return;
} else {
// 2. create and set MapView components - mandatory
Components components = new Components();
// set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D
mapView.setComponents(components);
}
// 3. Define map layer for basemap - mandatory.
RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");
RasterLayer mapLayer = new RasterLayer(dataSource, 2);
mapView.getLayers().setBaseLayer(mapLayer);
// define style for 3D to define minimum zoom = 14
ModelStyle modelStyle = ModelStyle.builder().build();
modelStyleSet = new StyleSet<ModelStyle>(null);
modelStyleSet.setZoomStyle(14, modelStyle);
// Tallinn
//mapView.setFocusPoint(new MapPos(2753845.7830863246f, 8275045.674995658f));
// San Francisco
//mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));
// getMapView().setFocusPoint(new MapPos(-1.3625947E7f, 4550716.0f));
// Chicago
getMapView().setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-87.6219, 41.8769), 1000);
// Rotterdam
//mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(4.480727f, 51.921098f));
mapView.setZoom(17.0f);
// set initial layer
online3DLayer(DATASET);
// rotation - 0 = north-up
//mapView.setMapRotation(-96.140175f);
// tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
//mapView.setTilt(30.0f);
// Activate some mapview options to make it smoother - optional
mapView.getOptions().setPreloading(false);
mapView.getOptions().setSeamlessHorizontalPan(true);
mapView.getOptions().setTileFading(false);
mapView.getOptions().setKineticPanning(true);
mapView.getOptions().setDoubleClickZoomIn(true);
mapView.getOptions().setDualClickZoomOut(true);
// set sky bitmap - optional, default - white
mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setSkyOffset(4.86f);
mapView.getOptions().setSkyBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.sky_small));
// Map background, visible if no map tiles loaded - optional, default - white
mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setBackgroundPlaneBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.background_plane));
mapView.getOptions().setClearColor(Color.WHITE);
// configure texture caching - optional, suggested
mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024);
mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);
// define online map persistent caching - optional, suggested. Default - no caching
mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
// set persistent raster cache limit to 100MB
mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);
// 4. zoom buttons using Android widgets - optional
// get the zoomcontrols that was defined in main.xml
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
// set zoomcontrols<SUF>
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
public void onClick(final View v) {
mapView.zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
public void onClick(final View v) {
mapView.zoomOut();
}
});
}
@Override
protected void onStart() {
mapView.startMapping();
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
Log.debug("x " + getMapView().getFocusPoint().x);
Log.debug("y " + getMapView().getFocusPoint().y);
Log.debug("tilt " + getMapView().getTilt());
Log.debug("rotation " + getMapView().getMapRotation());
Log.debug("zoom " + getMapView().getZoom());
mapView.stopMapping();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.online3d, menu);
return true;
}
@Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
item.setChecked(true);
switch (item.getItemId()) {
// map types
case R.id.menu3d_seattle:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=seattle");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-122.3336f, 47.6014f), 1000);
break;
case R.id.menu3d_la:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=los_angeles");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-118.24270, 34.05368), 1000);
break;
case R.id.menu3d_chicago:
online3DLayer("http://kaart.nutiteq.ee/nml/nmlserver3.php?data=chicago");
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(-87.6219, 41.8769), 1000);
break;
}
return false;
}
// Switch online 3D Model layer with given URL
private void online3DLayer(String dataset) {
if(modelLayer != null)
mapView.getLayers().removeLayer(modelLayer);
modelLayer = new NMLModelOnlineLayer(new EPSG3857(),
dataset, modelStyleSet);
modelLayer.setMemoryLimit(40*1024*1024);
modelLayer.setPersistentCacheSize(60*1024*1024);
modelLayer.setPersistentCachePath(this.getDatabasePath("nmlcache_"+dataset.substring(dataset.lastIndexOf("="))).getPath());
modelLayer.setLODResolutionFactor(0.3f);
mapView.getLayers().addLayer(modelLayer);
}
public MapView getMapView() {
return mapView;
}
}
|
140104_8 | package org.nutz.lang;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
* 秒表
*
* @author zozoh([email protected])
*/
public class Stopwatch {
private boolean nano;
private long from;
private long to;
private List<StopTag> tags;
private StopTag lastTag;
/**
* 秒表开始计时,计时时间的最小单位是毫秒
*
* @return 开始计时的秒表对象
*/
public static Stopwatch begin() {
Stopwatch sw = new Stopwatch();
sw.start();
return sw;
}
/**
* 秒表开始计时,计时时间的最小单位是毫微秒
*
* @return 开始计时的秒表对象
*/
public static Stopwatch beginNano() {
Stopwatch sw = new Stopwatch();
sw.nano = true;
sw.start();
return sw;
}
/**
* 创建一个秒表对象,该对象的计时时间的最小单位是毫秒
*
* @return 秒表对象
*/
public static Stopwatch create() {
return new Stopwatch();
}
/**
* 创建一个秒表对象,该对象的计时时间的最小单位是毫微秒
*
* @return 秒表对象
*/
public static Stopwatch createNano() {
Stopwatch sw = new Stopwatch();
sw.nano = true;
return sw;
}
public static Stopwatch run(Runnable atom) {
Stopwatch sw = begin();
atom.run();
sw.stop();
return sw;
}
public static Stopwatch runNano(Runnable atom) {
Stopwatch sw = beginNano();
atom.run();
sw.stop();
return sw;
}
/**
* 开始计时,并返回开始计时的时间,该时间最小单位由创建秒表时确定
*
* @return 开始计时的时间
*/
public long start() {
from = currentTime();
to = from;
return from;
}
private long currentTime() {
return nano ? System.nanoTime() : System.currentTimeMillis();
}
/**
* 记录停止时间,该时间最小单位由创建秒表时确定
*
* @return 自身以便链式赋值
*/
public long stop() {
to = currentTime();
return to;
}
/**
* @return 计时结果(ms)
*/
public long getDuration() {
return to - from;
}
/**
* @see #getDuration()
*/
public long du() {
return to - from;
}
/**
* 开始计时的时间,该时间最小单位由创建秒表时确定
*
* @return 开始计时的时间
*/
public long getStartTime() {
return from;
}
/**
* 停止计时的时间,该时间最小单位由创建秒表时确定
*
* @return 停止计时的时间
*/
public long getEndTime() {
return to;
}
/**
* 返回格式为 <code>Total: [计时时间][计时时间单位] : [计时开始时间]=>[计时结束时间]</code> 的字符串
*
* @return 格式为 <code>Total: [计时时间][计时时间单位] : [计时开始时间]=>[计时结束时间]</code> 的字符串
*/
@Override
public String toString() {
String prefix = String.format("Total: %d%s : [%s]=>[%s]",
this.getDuration(),
(nano ? "ns" : "ms"),
Times.sDTms2(new Date(from)),
Times.sDTms2(new Date(to)));
if (tags == null)
return prefix;
StringBuilder sb = new StringBuilder(prefix).append("\r\n");
for (int i = 0; i < tags.size(); i++) {
StopTag tag = tags.get(i);
sb.append(String.format(" -> %5s: %dms",
tag.name == null ? "TAG" + i : tag.name,
tag.du()));
if (i < tags.size() - 1)
sb.append("\r\n");
}
return sb.toString();
}
public StopTag tag(String name) {
if (tags == null)
tags = new LinkedList<Stopwatch.StopTag>();
lastTag = new StopTag(name, System.currentTimeMillis(), lastTag);
tags.add(lastTag);
return lastTag;
}
public StopTag tagf(String fmt, Object... args) {
return tag(String.format(fmt, args));
}
public class StopTag {
public String name;
public long tm;
public StopTag pre;
public StopTag() {}
public StopTag(String name, long tm, StopTag pre) {
super();
this.name = name;
this.tm = tm;
this.pre = pre;
}
public long du() {
if (pre == null)
return tm - from;
return tm - pre.tm;
}
}
}
| nutzam/nutz | src/org/nutz/lang/Stopwatch.java | 1,486 | /**
* @see #getDuration()
*/ | block_comment | nl | package org.nutz.lang;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
* 秒表
*
* @author zozoh([email protected])
*/
public class Stopwatch {
private boolean nano;
private long from;
private long to;
private List<StopTag> tags;
private StopTag lastTag;
/**
* 秒表开始计时,计时时间的最小单位是毫秒
*
* @return 开始计时的秒表对象
*/
public static Stopwatch begin() {
Stopwatch sw = new Stopwatch();
sw.start();
return sw;
}
/**
* 秒表开始计时,计时时间的最小单位是毫微秒
*
* @return 开始计时的秒表对象
*/
public static Stopwatch beginNano() {
Stopwatch sw = new Stopwatch();
sw.nano = true;
sw.start();
return sw;
}
/**
* 创建一个秒表对象,该对象的计时时间的最小单位是毫秒
*
* @return 秒表对象
*/
public static Stopwatch create() {
return new Stopwatch();
}
/**
* 创建一个秒表对象,该对象的计时时间的最小单位是毫微秒
*
* @return 秒表对象
*/
public static Stopwatch createNano() {
Stopwatch sw = new Stopwatch();
sw.nano = true;
return sw;
}
public static Stopwatch run(Runnable atom) {
Stopwatch sw = begin();
atom.run();
sw.stop();
return sw;
}
public static Stopwatch runNano(Runnable atom) {
Stopwatch sw = beginNano();
atom.run();
sw.stop();
return sw;
}
/**
* 开始计时,并返回开始计时的时间,该时间最小单位由创建秒表时确定
*
* @return 开始计时的时间
*/
public long start() {
from = currentTime();
to = from;
return from;
}
private long currentTime() {
return nano ? System.nanoTime() : System.currentTimeMillis();
}
/**
* 记录停止时间,该时间最小单位由创建秒表时确定
*
* @return 自身以便链式赋值
*/
public long stop() {
to = currentTime();
return to;
}
/**
* @return 计时结果(ms)
*/
public long getDuration() {
return to - from;
}
/**
* @see #getDuration()
<SUF>*/
public long du() {
return to - from;
}
/**
* 开始计时的时间,该时间最小单位由创建秒表时确定
*
* @return 开始计时的时间
*/
public long getStartTime() {
return from;
}
/**
* 停止计时的时间,该时间最小单位由创建秒表时确定
*
* @return 停止计时的时间
*/
public long getEndTime() {
return to;
}
/**
* 返回格式为 <code>Total: [计时时间][计时时间单位] : [计时开始时间]=>[计时结束时间]</code> 的字符串
*
* @return 格式为 <code>Total: [计时时间][计时时间单位] : [计时开始时间]=>[计时结束时间]</code> 的字符串
*/
@Override
public String toString() {
String prefix = String.format("Total: %d%s : [%s]=>[%s]",
this.getDuration(),
(nano ? "ns" : "ms"),
Times.sDTms2(new Date(from)),
Times.sDTms2(new Date(to)));
if (tags == null)
return prefix;
StringBuilder sb = new StringBuilder(prefix).append("\r\n");
for (int i = 0; i < tags.size(); i++) {
StopTag tag = tags.get(i);
sb.append(String.format(" -> %5s: %dms",
tag.name == null ? "TAG" + i : tag.name,
tag.du()));
if (i < tags.size() - 1)
sb.append("\r\n");
}
return sb.toString();
}
public StopTag tag(String name) {
if (tags == null)
tags = new LinkedList<Stopwatch.StopTag>();
lastTag = new StopTag(name, System.currentTimeMillis(), lastTag);
tags.add(lastTag);
return lastTag;
}
public StopTag tagf(String fmt, Object... args) {
return tag(String.format(fmt, args));
}
public class StopTag {
public String name;
public long tm;
public StopTag pre;
public StopTag() {}
public StopTag(String name, long tm, StopTag pre) {
super();
this.name = name;
this.tm = tm;
this.pre = pre;
}
public long du() {
if (pre == null)
return tm - from;
return tm - pre.tm;
}
}
}
|
151932_5 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.client.impl.cldr;
import com.google.gwt.core.client.JavaScriptObject;
// DO NOT EDIT - GENERATED FROM CLDR DATA:
// cldrVersion=25
// date=$Date: 2014-03-01 06:57:43 +0100 (Sat, 01 Mar 2014) $
// number=$Revision: 9852 $
// type=root
/**
* Localized names for the "fy" locale.
*/
public class LocalizedNamesImpl_fy extends LocalizedNamesImpl {
@Override
public String[] loadSortedRegionCodes() {
return new String[] {
"AF",
"AX",
"AL",
"DZ",
"VI",
"AS",
"AD",
"AO",
"AI",
"AQ",
"AG",
"AR",
"AM",
"AW",
"AC",
"AU",
"AZ",
"BS",
"BH",
"BD",
"BB",
"BE",
"BZ",
"BJ",
"BM",
"BT",
"BO",
"BA",
"BW",
"BV",
"BR",
"IO",
"VG",
"BN",
"BG",
"BF",
"BI",
"KH",
"CA",
"KY",
"EA",
"CL",
"CP",
"KM",
"CG",
"CD",
"CK",
"CR",
"CW",
"DK",
"DG",
"DJ",
"DO",
"DM",
"to",
"DE",
"AT",
"TL",
"EC",
"EG",
"SV",
"GQ",
"ER",
"EE",
"ET",
"EU",
"FO",
"FK",
"US",
"FJ",
"PH",
"FI",
"FR",
"TF",
"GF",
"PF",
"GA",
"GM",
"GE",
"GH",
"GI",
"GD",
"GL",
"GR",
"GP",
"GU",
"GT",
"GG",
"GN",
"GW",
"GY",
"HT",
"HM",
"HN",
"HU",
"HK",
"IE",
"IN",
"IQ",
"IR",
"IM",
"IL",
"IT",
"CI",
"JM",
"JP",
"YE",
"JE",
"JO",
"CV",
"CM",
"IC",
"BQ",
"KZ",
"KE",
"KG",
"KI",
"KW",
"CC",
"CO",
"XK",
"HR",
"CX",
"CU",
"LA",
"LS",
"LV",
"LB",
"LR",
"LY",
"LI",
"LT",
"LU",
"UM",
"MA",
"MO",
"MK",
"MG",
"MW",
"MV",
"MY",
"ML",
"MT",
"mo",
"MH",
"MQ",
"MR",
"MU",
"YT",
"MX",
"FM",
"MD",
"MC",
"MN",
"ME",
"MS",
"MZ",
"MM",
"NA",
"NR",
"NL",
"AN",
"NP",
"NI",
"NE",
"NG",
"NC",
"NZ",
"NU",
"KP",
"MP",
"NO",
"NF",
"UG",
"UA",
"QO",
"UZ",
"OM",
"PK",
"PW",
"PS",
"PA",
"PG",
"PY",
"PE",
"PN",
"PL",
"PT",
"PR",
"QA",
"RE",
"RO",
"RU",
"RW",
"BL",
"KN",
"LC",
"MF",
"PM",
"VC",
"SB",
"WS",
"SM",
"SA",
"ST",
"SN",
"RS",
"SC",
"SL",
"CN",
"SG",
"SH",
"SX",
"CF",
"SI",
"SK",
"SD",
"SO",
"ES",
"SJ",
"LK",
"sn",
"GS",
"KR",
"SS",
"SR",
"SZ",
"CH",
"CY",
"SY",
"TJ",
"TW",
"TZ",
"TH",
"TG",
"TK",
"TO",
"TT",
"TA",
"TD",
"CZ",
"TN",
"TR",
"TM",
"TC",
"TV",
"UY",
"VU",
"VA",
"VE",
"AE",
"GB",
"VN",
"WF",
"EH",
"BY",
"ID",
"IS",
"ZA",
"ZM",
"ZW",
"SE",
};
}
@Override
protected void loadNameMapJava() {
super.loadNameMapJava();
namesMap.put("001", "Wrâld");
namesMap.put("002", "Afrika");
namesMap.put("003", "Noard-Amerika");
namesMap.put("005", "Sûd-Amerika");
namesMap.put("009", "Oceanië");
namesMap.put("011", "West-Afrika");
namesMap.put("013", "Midden-Amerika");
namesMap.put("014", "East-Afrika");
namesMap.put("015", "Noard-Afrika");
namesMap.put("017", "Sintraal-Afrika");
namesMap.put("018", "Sûdelijk Afrika");
namesMap.put("019", "Amerika");
namesMap.put("021", "Noardlik Amerika");
namesMap.put("029", "Karibysk gebiet");
namesMap.put("030", "East-Azië");
namesMap.put("034", "Sûd-Azië");
namesMap.put("035", "Sûdoost-Azië");
namesMap.put("039", "Sûd-Europa");
namesMap.put("053", "Australazië");
namesMap.put("054", "Melanesië");
namesMap.put("057", "Micronesyske regio");
namesMap.put("061", "Polynesië");
namesMap.put("142", "Azië");
namesMap.put("143", "Sintraal-Azië");
namesMap.put("145", "West-Azië");
namesMap.put("150", "Europa");
namesMap.put("151", "East-Europa");
namesMap.put("154", "Noard-Europa");
namesMap.put("155", "West-Europa");
namesMap.put("419", "Latynsk-Amearika");
namesMap.put("AC", "Ascension");
namesMap.put("AE", "Verenigde Arabyske Emiraten");
namesMap.put("AG", "Antigua en Barbuda");
namesMap.put("AL", "Albanië");
namesMap.put("AM", "Armenië");
namesMap.put("AN", "Nederlânske Antillen");
namesMap.put("AR", "Argentinië");
namesMap.put("AS", "Amerikaansk Samoa");
namesMap.put("AT", "Eastenryk");
namesMap.put("AU", "Australië");
namesMap.put("AX", "Ålân");
namesMap.put("AZ", "Azerbeidzjan");
namesMap.put("BA", "Bosnië en Herzegovina");
namesMap.put("BE", "België");
namesMap.put("BG", "Bulgarije");
namesMap.put("BH", "Bahrein");
namesMap.put("BQ", "Karibysk Nederlân");
namesMap.put("BR", "Brazilië");
namesMap.put("BS", "Bahama’s");
namesMap.put("BV", "Bouveteilân");
namesMap.put("BY", "Wit-Ruslân");
namesMap.put("CC", "Kokosilanen");
namesMap.put("CD", "Congo-Kinshasa");
namesMap.put("CF", "Sintraal-Afrikaanske Republyk");
namesMap.put("CG", "Congo-Brazzaville");
namesMap.put("CH", "Switserlân");
namesMap.put("CI", "Ivoorkust");
namesMap.put("CK", "Cookeilannen");
namesMap.put("CL", "Chili");
namesMap.put("CM", "Kameroen");
namesMap.put("CN", "Sina");
namesMap.put("CO", "Kolombia");
namesMap.put("CP", "Clipperton");
namesMap.put("CU", "Kuba");
namesMap.put("CV", "Kaapverdië");
namesMap.put("CX", "Krysteilan");
namesMap.put("CY", "Syprus");
namesMap.put("CZ", "Tsjechje");
namesMap.put("DE", "Dútslân");
namesMap.put("DK", "Denemarken");
namesMap.put("DM", "Dominika");
namesMap.put("DZ", "Algerije");
namesMap.put("EA", "Ceuta en Melilla");
namesMap.put("EE", "Estlân");
namesMap.put("EG", "Egypte");
namesMap.put("EH", "Westelijke Sahara");
namesMap.put("ES", "Spanje");
namesMap.put("ET", "Ethiopië");
namesMap.put("EU", "Europeeske Unie");
namesMap.put("FI", "Finlân");
namesMap.put("FK", "Falklâneilannen");
namesMap.put("FM", "Micronesië");
namesMap.put("FO", "Faeröer");
namesMap.put("FR", "Frankrijk");
namesMap.put("GB", "Verenigd Koninkrijk");
namesMap.put("GE", "Georgië");
namesMap.put("GF", "Frans-Guyana");
namesMap.put("GL", "Grienlân");
namesMap.put("GN", "Guinee");
namesMap.put("GQ", "Equatoriaal-Guinea");
namesMap.put("GR", "Grikelân");
namesMap.put("GS", "Sûd-Georgia en Sûdlike Sandwicheilannen");
namesMap.put("GW", "Guinee-Bissau");
namesMap.put("HK", "Hongkong SAR van Sina");
namesMap.put("HM", "Heard- en McDonaldeilannen");
namesMap.put("HR", "Kroatië");
namesMap.put("HT", "Haïti");
namesMap.put("HU", "Hongarije");
namesMap.put("IC", "Kanaryske Eilânnen");
namesMap.put("ID", "Yndonesië");
namesMap.put("IE", "Ierlân");
namesMap.put("IL", "Israël");
namesMap.put("IO", "Britse Gebieden yn de Indyske Oseaan");
namesMap.put("IQ", "Irak");
namesMap.put("IS", "Yslân");
namesMap.put("IT", "Italië");
namesMap.put("JO", "Jordanië");
namesMap.put("KE", "Kenia");
namesMap.put("KG", "Kirgizië");
namesMap.put("KH", "Cambodja");
namesMap.put("KM", "Comoren");
namesMap.put("KN", "Saint Kitts en Nevis");
namesMap.put("KP", "Noard-Korea");
namesMap.put("KR", "Sûd-Korea");
namesMap.put("KW", "Koeweit");
namesMap.put("KY", "Caymaneilannen");
namesMap.put("KZ", "Kazachstan");
namesMap.put("LB", "Libanon");
namesMap.put("LT", "Litouwen");
namesMap.put("LU", "Luxemburg");
namesMap.put("LV", "Letlân");
namesMap.put("LY", "Libië");
namesMap.put("MD", "Moldavië");
namesMap.put("MF", "Saint-Martin");
namesMap.put("MG", "Madeiaskar");
namesMap.put("MH", "Marshalleilannen");
namesMap.put("MK", "Macedonië");
namesMap.put("MM", "Myanmar (Birma)");
namesMap.put("MN", "Mongolië");
namesMap.put("MO", "Macao SAR van Sina");
namesMap.put("MP", "Noardlike Marianeneilannen");
namesMap.put("MR", "Mauritanië");
namesMap.put("MV", "Maldiven");
namesMap.put("MY", "Maleisië");
namesMap.put("NA", "Namibië");
namesMap.put("NC", "Nij-Caledonië");
namesMap.put("NF", "Norfolkeilân");
namesMap.put("NL", "Nederlân");
namesMap.put("NO", "Noarwegen");
namesMap.put("NZ", "Nij-Seelân");
namesMap.put("PF", "Frans-Polynesië");
namesMap.put("PG", "Papoea-Nij-Guinea");
namesMap.put("PH", "Filipijnen");
namesMap.put("PL", "Polen");
namesMap.put("PM", "Saint-Pierre en Miquelon");
namesMap.put("PN", "Pitcairneilannen");
namesMap.put("PS", "Palestynske gebieten");
namesMap.put("QO", "Oerig Oceanië");
namesMap.put("RO", "Roemenië");
namesMap.put("RS", "Servië");
namesMap.put("RU", "Ruslân");
namesMap.put("SA", "Saoedi-Arabië");
namesMap.put("SB", "Salomonseilannen");
namesMap.put("SC", "Seychellen");
namesMap.put("SD", "Soedan");
namesMap.put("SE", "Zweden");
namesMap.put("SH", "Sint-Helena");
namesMap.put("SI", "Slovenië");
namesMap.put("SJ", "Spitsbergen en Jan Mayen");
namesMap.put("SK", "Slowakije");
namesMap.put("SO", "Somalië");
namesMap.put("SS", "Sûd-Soedan");
namesMap.put("ST", "Sao Tomé en Principe");
namesMap.put("SX", "Sint-Maarten");
namesMap.put("SY", "Syrië");
namesMap.put("SZ", "Swazilân");
namesMap.put("TC", "Turks- en Caicoseilannen");
namesMap.put("TD", "Tsjaad");
namesMap.put("TF", "Franse Gebieden in de zuidelijke Indyske Oseaan");
namesMap.put("TH", "Thailân");
namesMap.put("TJ", "Tadzjikistan");
namesMap.put("TL", "East-Timor");
namesMap.put("TN", "Tunesië");
namesMap.put("TR", "Turkije");
namesMap.put("TT", "Trinidad en Tobago");
namesMap.put("UA", "Oekraïne");
namesMap.put("UG", "Oeganda");
namesMap.put("UM", "Lyts ôflizzen eilannen fan de Ferienigde Staten");
namesMap.put("US", "Ferienigde Staten");
namesMap.put("UZ", "Oezbekistan");
namesMap.put("VA", "Vaticaanstêd");
namesMap.put("VC", "Saint Vincent en de Grenadines");
namesMap.put("VG", "Britse Maagdeneilannen");
namesMap.put("VI", "Amerikaanske Maagdeneilannen");
namesMap.put("WF", "Wallis en Futuna");
namesMap.put("YE", "Jemen");
namesMap.put("ZZ", "Unbekend gebiet");
namesMap.put("mo", "Marokko");
namesMap.put("sn", "Sûd-Afrika");
namesMap.put("to", "Dominikaanske Republyk");
}
@Override
protected JavaScriptObject loadNameMapNative() {
return overrideMap(super.loadNameMapNative(), loadMyNameMap());
}
private native JavaScriptObject loadMyNameMap() /*-{
return {
"001": "Wrâld",
"002": "Afrika",
"003": "Noard-Amerika",
"005": "Sûd-Amerika",
"009": "Oceanië",
"011": "West-Afrika",
"013": "Midden-Amerika",
"014": "East-Afrika",
"015": "Noard-Afrika",
"017": "Sintraal-Afrika",
"018": "Sûdelijk Afrika",
"019": "Amerika",
"021": "Noardlik Amerika",
"029": "Karibysk gebiet",
"030": "East-Azië",
"034": "Sûd-Azië",
"035": "Sûdoost-Azië",
"039": "Sûd-Europa",
"053": "Australazië",
"054": "Melanesië",
"057": "Micronesyske regio",
"061": "Polynesië",
"142": "Azië",
"143": "Sintraal-Azië",
"145": "West-Azië",
"150": "Europa",
"151": "East-Europa",
"154": "Noard-Europa",
"155": "West-Europa",
"419": "Latynsk-Amearika",
"AC": "Ascension",
"AE": "Verenigde Arabyske Emiraten",
"AG": "Antigua en Barbuda",
"AL": "Albanië",
"AM": "Armenië",
"AN": "Nederlânske Antillen",
"AR": "Argentinië",
"AS": "Amerikaansk Samoa",
"AT": "Eastenryk",
"AU": "Australië",
"AX": "Ålân",
"AZ": "Azerbeidzjan",
"BA": "Bosnië en Herzegovina",
"BE": "België",
"BG": "Bulgarije",
"BH": "Bahrein",
"BQ": "Karibysk Nederlân",
"BR": "Brazilië",
"BS": "Bahama’s",
"BV": "Bouveteilân",
"BY": "Wit-Ruslân",
"CC": "Kokosilanen",
"CD": "Congo-Kinshasa",
"CF": "Sintraal-Afrikaanske Republyk",
"CG": "Congo-Brazzaville",
"CH": "Switserlân",
"CI": "Ivoorkust",
"CK": "Cookeilannen",
"CL": "Chili",
"CM": "Kameroen",
"CN": "Sina",
"CO": "Kolombia",
"CP": "Clipperton",
"CU": "Kuba",
"CV": "Kaapverdië",
"CX": "Krysteilan",
"CY": "Syprus",
"CZ": "Tsjechje",
"DE": "Dútslân",
"DK": "Denemarken",
"DM": "Dominika",
"DZ": "Algerije",
"EA": "Ceuta en Melilla",
"EE": "Estlân",
"EG": "Egypte",
"EH": "Westelijke Sahara",
"ES": "Spanje",
"ET": "Ethiopië",
"EU": "Europeeske Unie",
"FI": "Finlân",
"FK": "Falklâneilannen",
"FM": "Micronesië",
"FO": "Faeröer",
"FR": "Frankrijk",
"GB": "Verenigd Koninkrijk",
"GE": "Georgië",
"GF": "Frans-Guyana",
"GL": "Grienlân",
"GN": "Guinee",
"GQ": "Equatoriaal-Guinea",
"GR": "Grikelân",
"GS": "Sûd-Georgia en Sûdlike Sandwicheilannen",
"GW": "Guinee-Bissau",
"HK": "Hongkong SAR van Sina",
"HM": "Heard- en McDonaldeilannen",
"HR": "Kroatië",
"HT": "Haïti",
"HU": "Hongarije",
"IC": "Kanaryske Eilânnen",
"ID": "Yndonesië",
"IE": "Ierlân",
"IL": "Israël",
"IO": "Britse Gebieden yn de Indyske Oseaan",
"IQ": "Irak",
"IS": "Yslân",
"IT": "Italië",
"JO": "Jordanië",
"KE": "Kenia",
"KG": "Kirgizië",
"KH": "Cambodja",
"KM": "Comoren",
"KN": "Saint Kitts en Nevis",
"KP": "Noard-Korea",
"KR": "Sûd-Korea",
"KW": "Koeweit",
"KY": "Caymaneilannen",
"KZ": "Kazachstan",
"LB": "Libanon",
"LT": "Litouwen",
"LU": "Luxemburg",
"LV": "Letlân",
"LY": "Libië",
"MD": "Moldavië",
"MF": "Saint-Martin",
"MG": "Madeiaskar",
"MH": "Marshalleilannen",
"MK": "Macedonië",
"MM": "Myanmar (Birma)",
"MN": "Mongolië",
"MO": "Macao SAR van Sina",
"MP": "Noardlike Marianeneilannen",
"MR": "Mauritanië",
"MV": "Maldiven",
"MY": "Maleisië",
"NA": "Namibië",
"NC": "Nij-Caledonië",
"NF": "Norfolkeilân",
"NL": "Nederlân",
"NO": "Noarwegen",
"NZ": "Nij-Seelân",
"PF": "Frans-Polynesië",
"PG": "Papoea-Nij-Guinea",
"PH": "Filipijnen",
"PL": "Polen",
"PM": "Saint-Pierre en Miquelon",
"PN": "Pitcairneilannen",
"PS": "Palestynske gebieten",
"QO": "Oerig Oceanië",
"RO": "Roemenië",
"RS": "Servië",
"RU": "Ruslân",
"SA": "Saoedi-Arabië",
"SB": "Salomonseilannen",
"SC": "Seychellen",
"SD": "Soedan",
"SE": "Zweden",
"SH": "Sint-Helena",
"SI": "Slovenië",
"SJ": "Spitsbergen en Jan Mayen",
"SK": "Slowakije",
"SO": "Somalië",
"SS": "Sûd-Soedan",
"ST": "Sao Tomé en Principe",
"SX": "Sint-Maarten",
"SY": "Syrië",
"SZ": "Swazilân",
"TC": "Turks- en Caicoseilannen",
"TD": "Tsjaad",
"TF": "Franse Gebieden in de zuidelijke Indyske Oseaan",
"TH": "Thailân",
"TJ": "Tadzjikistan",
"TL": "East-Timor",
"TN": "Tunesië",
"TR": "Turkije",
"TT": "Trinidad en Tobago",
"UA": "Oekraïne",
"UG": "Oeganda",
"UM": "Lyts ôflizzen eilannen fan de Ferienigde Staten",
"US": "Ferienigde Staten",
"UZ": "Oezbekistan",
"VA": "Vaticaanstêd",
"VC": "Saint Vincent en de Grenadines",
"VG": "Britse Maagdeneilannen",
"VI": "Amerikaanske Maagdeneilannen",
"WF": "Wallis en Futuna",
"YE": "Jemen",
"ZZ": "Unbekend gebiet",
"mo": "Marokko",
"sn": "Sûd-Afrika",
"to": "Dominikaanske Republyk"
};
}-*/;
}
| nuxeo/gwt | user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_fy.java | 7,275 | /*-{
return {
"001": "Wrâld",
"002": "Afrika",
"003": "Noard-Amerika",
"005": "Sûd-Amerika",
"009": "Oceanië",
"011": "West-Afrika",
"013": "Midden-Amerika",
"014": "East-Afrika",
"015": "Noard-Afrika",
"017": "Sintraal-Afrika",
"018": "Sûdelijk Afrika",
"019": "Amerika",
"021": "Noardlik Amerika",
"029": "Karibysk gebiet",
"030": "East-Azië",
"034": "Sûd-Azië",
"035": "Sûdoost-Azië",
"039": "Sûd-Europa",
"053": "Australazië",
"054": "Melanesië",
"057": "Micronesyske regio",
"061": "Polynesië",
"142": "Azië",
"143": "Sintraal-Azië",
"145": "West-Azië",
"150": "Europa",
"151": "East-Europa",
"154": "Noard-Europa",
"155": "West-Europa",
"419": "Latynsk-Amearika",
"AC": "Ascension",
"AE": "Verenigde Arabyske Emiraten",
"AG": "Antigua en Barbuda",
"AL": "Albanië",
"AM": "Armenië",
"AN": "Nederlânske Antillen",
"AR": "Argentinië",
"AS": "Amerikaansk Samoa",
"AT": "Eastenryk",
"AU": "Australië",
"AX": "Ålân",
"AZ": "Azerbeidzjan",
"BA": "Bosnië en Herzegovina",
"BE": "België",
"BG": "Bulgarije",
"BH": "Bahrein",
"BQ": "Karibysk Nederlân",
"BR": "Brazilië",
"BS": "Bahama’s",
"BV": "Bouveteilân",
"BY": "Wit-Ruslân",
"CC": "Kokosilanen",
"CD": "Congo-Kinshasa",
"CF": "Sintraal-Afrikaanske Republyk",
"CG": "Congo-Brazzaville",
"CH": "Switserlân",
"CI": "Ivoorkust",
"CK": "Cookeilannen",
"CL": "Chili",
"CM": "Kameroen",
"CN": "Sina",
"CO": "Kolombia",
"CP": "Clipperton",
"CU": "Kuba",
"CV": "Kaapverdië",
"CX": "Krysteilan",
"CY": "Syprus",
"CZ": "Tsjechje",
"DE": "Dútslân",
"DK": "Denemarken",
"DM": "Dominika",
"DZ": "Algerije",
"EA": "Ceuta en Melilla",
"EE": "Estlân",
"EG": "Egypte",
"EH": "Westelijke Sahara",
"ES": "Spanje",
"ET": "Ethiopië",
"EU": "Europeeske Unie",
"FI": "Finlân",
"FK": "Falklâneilannen",
"FM": "Micronesië",
"FO": "Faeröer",
"FR": "Frankrijk",
"GB": "Verenigd Koninkrijk",
"GE": "Georgië",
"GF": "Frans-Guyana",
"GL": "Grienlân",
"GN": "Guinee",
"GQ": "Equatoriaal-Guinea",
"GR": "Grikelân",
"GS": "Sûd-Georgia en Sûdlike Sandwicheilannen",
"GW": "Guinee-Bissau",
"HK": "Hongkong SAR van Sina",
"HM": "Heard- en McDonaldeilannen",
"HR": "Kroatië",
"HT": "Haïti",
"HU": "Hongarije",
"IC": "Kanaryske Eilânnen",
"ID": "Yndonesië",
"IE": "Ierlân",
"IL": "Israël",
"IO": "Britse Gebieden yn de Indyske Oseaan",
"IQ": "Irak",
"IS": "Yslân",
"IT": "Italië",
"JO": "Jordanië",
"KE": "Kenia",
"KG": "Kirgizië",
"KH": "Cambodja",
"KM": "Comoren",
"KN": "Saint Kitts en Nevis",
"KP": "Noard-Korea",
"KR": "Sûd-Korea",
"KW": "Koeweit",
"KY": "Caymaneilannen",
"KZ": "Kazachstan",
"LB": "Libanon",
"LT": "Litouwen",
"LU": "Luxemburg",
"LV": "Letlân",
"LY": "Libië",
"MD": "Moldavië",
"MF": "Saint-Martin",
"MG": "Madeiaskar",
"MH": "Marshalleilannen",
"MK": "Macedonië",
"MM": "Myanmar (Birma)",
"MN": "Mongolië",
"MO": "Macao SAR van Sina",
"MP": "Noardlike Marianeneilannen",
"MR": "Mauritanië",
"MV": "Maldiven",
"MY": "Maleisië",
"NA": "Namibië",
"NC": "Nij-Caledonië",
"NF": "Norfolkeilân",
"NL": "Nederlân",
"NO": "Noarwegen",
"NZ": "Nij-Seelân",
"PF": "Frans-Polynesië",
"PG": "Papoea-Nij-Guinea",
"PH": "Filipijnen",
"PL": "Polen",
"PM": "Saint-Pierre en Miquelon",
"PN": "Pitcairneilannen",
"PS": "Palestynske gebieten",
"QO": "Oerig Oceanië",
"RO": "Roemenië",
"RS": "Servië",
"RU": "Ruslân",
"SA": "Saoedi-Arabië",
"SB": "Salomonseilannen",
"SC": "Seychellen",
"SD": "Soedan",
"SE": "Zweden",
"SH": "Sint-Helena",
"SI": "Slovenië",
"SJ": "Spitsbergen en Jan Mayen",
"SK": "Slowakije",
"SO": "Somalië",
"SS": "Sûd-Soedan",
"ST": "Sao Tomé en Principe",
"SX": "Sint-Maarten",
"SY": "Syrië",
"SZ": "Swazilân",
"TC": "Turks- en Caicoseilannen",
"TD": "Tsjaad",
"TF": "Franse Gebieden in de zuidelijke Indyske Oseaan",
"TH": "Thailân",
"TJ": "Tadzjikistan",
"TL": "East-Timor",
"TN": "Tunesië",
"TR": "Turkije",
"TT": "Trinidad en Tobago",
"UA": "Oekraïne",
"UG": "Oeganda",
"UM": "Lyts ôflizzen eilannen fan de Ferienigde Staten",
"US": "Ferienigde Staten",
"UZ": "Oezbekistan",
"VA": "Vaticaanstêd",
"VC": "Saint Vincent en de Grenadines",
"VG": "Britse Maagdeneilannen",
"VI": "Amerikaanske Maagdeneilannen",
"WF": "Wallis en Futuna",
"YE": "Jemen",
"ZZ": "Unbekend gebiet",
"mo": "Marokko",
"sn": "Sûd-Afrika",
"to": "Dominikaanske Republyk"
};
}-*/ | block_comment | nl | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.client.impl.cldr;
import com.google.gwt.core.client.JavaScriptObject;
// DO NOT EDIT - GENERATED FROM CLDR DATA:
// cldrVersion=25
// date=$Date: 2014-03-01 06:57:43 +0100 (Sat, 01 Mar 2014) $
// number=$Revision: 9852 $
// type=root
/**
* Localized names for the "fy" locale.
*/
public class LocalizedNamesImpl_fy extends LocalizedNamesImpl {
@Override
public String[] loadSortedRegionCodes() {
return new String[] {
"AF",
"AX",
"AL",
"DZ",
"VI",
"AS",
"AD",
"AO",
"AI",
"AQ",
"AG",
"AR",
"AM",
"AW",
"AC",
"AU",
"AZ",
"BS",
"BH",
"BD",
"BB",
"BE",
"BZ",
"BJ",
"BM",
"BT",
"BO",
"BA",
"BW",
"BV",
"BR",
"IO",
"VG",
"BN",
"BG",
"BF",
"BI",
"KH",
"CA",
"KY",
"EA",
"CL",
"CP",
"KM",
"CG",
"CD",
"CK",
"CR",
"CW",
"DK",
"DG",
"DJ",
"DO",
"DM",
"to",
"DE",
"AT",
"TL",
"EC",
"EG",
"SV",
"GQ",
"ER",
"EE",
"ET",
"EU",
"FO",
"FK",
"US",
"FJ",
"PH",
"FI",
"FR",
"TF",
"GF",
"PF",
"GA",
"GM",
"GE",
"GH",
"GI",
"GD",
"GL",
"GR",
"GP",
"GU",
"GT",
"GG",
"GN",
"GW",
"GY",
"HT",
"HM",
"HN",
"HU",
"HK",
"IE",
"IN",
"IQ",
"IR",
"IM",
"IL",
"IT",
"CI",
"JM",
"JP",
"YE",
"JE",
"JO",
"CV",
"CM",
"IC",
"BQ",
"KZ",
"KE",
"KG",
"KI",
"KW",
"CC",
"CO",
"XK",
"HR",
"CX",
"CU",
"LA",
"LS",
"LV",
"LB",
"LR",
"LY",
"LI",
"LT",
"LU",
"UM",
"MA",
"MO",
"MK",
"MG",
"MW",
"MV",
"MY",
"ML",
"MT",
"mo",
"MH",
"MQ",
"MR",
"MU",
"YT",
"MX",
"FM",
"MD",
"MC",
"MN",
"ME",
"MS",
"MZ",
"MM",
"NA",
"NR",
"NL",
"AN",
"NP",
"NI",
"NE",
"NG",
"NC",
"NZ",
"NU",
"KP",
"MP",
"NO",
"NF",
"UG",
"UA",
"QO",
"UZ",
"OM",
"PK",
"PW",
"PS",
"PA",
"PG",
"PY",
"PE",
"PN",
"PL",
"PT",
"PR",
"QA",
"RE",
"RO",
"RU",
"RW",
"BL",
"KN",
"LC",
"MF",
"PM",
"VC",
"SB",
"WS",
"SM",
"SA",
"ST",
"SN",
"RS",
"SC",
"SL",
"CN",
"SG",
"SH",
"SX",
"CF",
"SI",
"SK",
"SD",
"SO",
"ES",
"SJ",
"LK",
"sn",
"GS",
"KR",
"SS",
"SR",
"SZ",
"CH",
"CY",
"SY",
"TJ",
"TW",
"TZ",
"TH",
"TG",
"TK",
"TO",
"TT",
"TA",
"TD",
"CZ",
"TN",
"TR",
"TM",
"TC",
"TV",
"UY",
"VU",
"VA",
"VE",
"AE",
"GB",
"VN",
"WF",
"EH",
"BY",
"ID",
"IS",
"ZA",
"ZM",
"ZW",
"SE",
};
}
@Override
protected void loadNameMapJava() {
super.loadNameMapJava();
namesMap.put("001", "Wrâld");
namesMap.put("002", "Afrika");
namesMap.put("003", "Noard-Amerika");
namesMap.put("005", "Sûd-Amerika");
namesMap.put("009", "Oceanië");
namesMap.put("011", "West-Afrika");
namesMap.put("013", "Midden-Amerika");
namesMap.put("014", "East-Afrika");
namesMap.put("015", "Noard-Afrika");
namesMap.put("017", "Sintraal-Afrika");
namesMap.put("018", "Sûdelijk Afrika");
namesMap.put("019", "Amerika");
namesMap.put("021", "Noardlik Amerika");
namesMap.put("029", "Karibysk gebiet");
namesMap.put("030", "East-Azië");
namesMap.put("034", "Sûd-Azië");
namesMap.put("035", "Sûdoost-Azië");
namesMap.put("039", "Sûd-Europa");
namesMap.put("053", "Australazië");
namesMap.put("054", "Melanesië");
namesMap.put("057", "Micronesyske regio");
namesMap.put("061", "Polynesië");
namesMap.put("142", "Azië");
namesMap.put("143", "Sintraal-Azië");
namesMap.put("145", "West-Azië");
namesMap.put("150", "Europa");
namesMap.put("151", "East-Europa");
namesMap.put("154", "Noard-Europa");
namesMap.put("155", "West-Europa");
namesMap.put("419", "Latynsk-Amearika");
namesMap.put("AC", "Ascension");
namesMap.put("AE", "Verenigde Arabyske Emiraten");
namesMap.put("AG", "Antigua en Barbuda");
namesMap.put("AL", "Albanië");
namesMap.put("AM", "Armenië");
namesMap.put("AN", "Nederlânske Antillen");
namesMap.put("AR", "Argentinië");
namesMap.put("AS", "Amerikaansk Samoa");
namesMap.put("AT", "Eastenryk");
namesMap.put("AU", "Australië");
namesMap.put("AX", "Ålân");
namesMap.put("AZ", "Azerbeidzjan");
namesMap.put("BA", "Bosnië en Herzegovina");
namesMap.put("BE", "België");
namesMap.put("BG", "Bulgarije");
namesMap.put("BH", "Bahrein");
namesMap.put("BQ", "Karibysk Nederlân");
namesMap.put("BR", "Brazilië");
namesMap.put("BS", "Bahama’s");
namesMap.put("BV", "Bouveteilân");
namesMap.put("BY", "Wit-Ruslân");
namesMap.put("CC", "Kokosilanen");
namesMap.put("CD", "Congo-Kinshasa");
namesMap.put("CF", "Sintraal-Afrikaanske Republyk");
namesMap.put("CG", "Congo-Brazzaville");
namesMap.put("CH", "Switserlân");
namesMap.put("CI", "Ivoorkust");
namesMap.put("CK", "Cookeilannen");
namesMap.put("CL", "Chili");
namesMap.put("CM", "Kameroen");
namesMap.put("CN", "Sina");
namesMap.put("CO", "Kolombia");
namesMap.put("CP", "Clipperton");
namesMap.put("CU", "Kuba");
namesMap.put("CV", "Kaapverdië");
namesMap.put("CX", "Krysteilan");
namesMap.put("CY", "Syprus");
namesMap.put("CZ", "Tsjechje");
namesMap.put("DE", "Dútslân");
namesMap.put("DK", "Denemarken");
namesMap.put("DM", "Dominika");
namesMap.put("DZ", "Algerije");
namesMap.put("EA", "Ceuta en Melilla");
namesMap.put("EE", "Estlân");
namesMap.put("EG", "Egypte");
namesMap.put("EH", "Westelijke Sahara");
namesMap.put("ES", "Spanje");
namesMap.put("ET", "Ethiopië");
namesMap.put("EU", "Europeeske Unie");
namesMap.put("FI", "Finlân");
namesMap.put("FK", "Falklâneilannen");
namesMap.put("FM", "Micronesië");
namesMap.put("FO", "Faeröer");
namesMap.put("FR", "Frankrijk");
namesMap.put("GB", "Verenigd Koninkrijk");
namesMap.put("GE", "Georgië");
namesMap.put("GF", "Frans-Guyana");
namesMap.put("GL", "Grienlân");
namesMap.put("GN", "Guinee");
namesMap.put("GQ", "Equatoriaal-Guinea");
namesMap.put("GR", "Grikelân");
namesMap.put("GS", "Sûd-Georgia en Sûdlike Sandwicheilannen");
namesMap.put("GW", "Guinee-Bissau");
namesMap.put("HK", "Hongkong SAR van Sina");
namesMap.put("HM", "Heard- en McDonaldeilannen");
namesMap.put("HR", "Kroatië");
namesMap.put("HT", "Haïti");
namesMap.put("HU", "Hongarije");
namesMap.put("IC", "Kanaryske Eilânnen");
namesMap.put("ID", "Yndonesië");
namesMap.put("IE", "Ierlân");
namesMap.put("IL", "Israël");
namesMap.put("IO", "Britse Gebieden yn de Indyske Oseaan");
namesMap.put("IQ", "Irak");
namesMap.put("IS", "Yslân");
namesMap.put("IT", "Italië");
namesMap.put("JO", "Jordanië");
namesMap.put("KE", "Kenia");
namesMap.put("KG", "Kirgizië");
namesMap.put("KH", "Cambodja");
namesMap.put("KM", "Comoren");
namesMap.put("KN", "Saint Kitts en Nevis");
namesMap.put("KP", "Noard-Korea");
namesMap.put("KR", "Sûd-Korea");
namesMap.put("KW", "Koeweit");
namesMap.put("KY", "Caymaneilannen");
namesMap.put("KZ", "Kazachstan");
namesMap.put("LB", "Libanon");
namesMap.put("LT", "Litouwen");
namesMap.put("LU", "Luxemburg");
namesMap.put("LV", "Letlân");
namesMap.put("LY", "Libië");
namesMap.put("MD", "Moldavië");
namesMap.put("MF", "Saint-Martin");
namesMap.put("MG", "Madeiaskar");
namesMap.put("MH", "Marshalleilannen");
namesMap.put("MK", "Macedonië");
namesMap.put("MM", "Myanmar (Birma)");
namesMap.put("MN", "Mongolië");
namesMap.put("MO", "Macao SAR van Sina");
namesMap.put("MP", "Noardlike Marianeneilannen");
namesMap.put("MR", "Mauritanië");
namesMap.put("MV", "Maldiven");
namesMap.put("MY", "Maleisië");
namesMap.put("NA", "Namibië");
namesMap.put("NC", "Nij-Caledonië");
namesMap.put("NF", "Norfolkeilân");
namesMap.put("NL", "Nederlân");
namesMap.put("NO", "Noarwegen");
namesMap.put("NZ", "Nij-Seelân");
namesMap.put("PF", "Frans-Polynesië");
namesMap.put("PG", "Papoea-Nij-Guinea");
namesMap.put("PH", "Filipijnen");
namesMap.put("PL", "Polen");
namesMap.put("PM", "Saint-Pierre en Miquelon");
namesMap.put("PN", "Pitcairneilannen");
namesMap.put("PS", "Palestynske gebieten");
namesMap.put("QO", "Oerig Oceanië");
namesMap.put("RO", "Roemenië");
namesMap.put("RS", "Servië");
namesMap.put("RU", "Ruslân");
namesMap.put("SA", "Saoedi-Arabië");
namesMap.put("SB", "Salomonseilannen");
namesMap.put("SC", "Seychellen");
namesMap.put("SD", "Soedan");
namesMap.put("SE", "Zweden");
namesMap.put("SH", "Sint-Helena");
namesMap.put("SI", "Slovenië");
namesMap.put("SJ", "Spitsbergen en Jan Mayen");
namesMap.put("SK", "Slowakije");
namesMap.put("SO", "Somalië");
namesMap.put("SS", "Sûd-Soedan");
namesMap.put("ST", "Sao Tomé en Principe");
namesMap.put("SX", "Sint-Maarten");
namesMap.put("SY", "Syrië");
namesMap.put("SZ", "Swazilân");
namesMap.put("TC", "Turks- en Caicoseilannen");
namesMap.put("TD", "Tsjaad");
namesMap.put("TF", "Franse Gebieden in de zuidelijke Indyske Oseaan");
namesMap.put("TH", "Thailân");
namesMap.put("TJ", "Tadzjikistan");
namesMap.put("TL", "East-Timor");
namesMap.put("TN", "Tunesië");
namesMap.put("TR", "Turkije");
namesMap.put("TT", "Trinidad en Tobago");
namesMap.put("UA", "Oekraïne");
namesMap.put("UG", "Oeganda");
namesMap.put("UM", "Lyts ôflizzen eilannen fan de Ferienigde Staten");
namesMap.put("US", "Ferienigde Staten");
namesMap.put("UZ", "Oezbekistan");
namesMap.put("VA", "Vaticaanstêd");
namesMap.put("VC", "Saint Vincent en de Grenadines");
namesMap.put("VG", "Britse Maagdeneilannen");
namesMap.put("VI", "Amerikaanske Maagdeneilannen");
namesMap.put("WF", "Wallis en Futuna");
namesMap.put("YE", "Jemen");
namesMap.put("ZZ", "Unbekend gebiet");
namesMap.put("mo", "Marokko");
namesMap.put("sn", "Sûd-Afrika");
namesMap.put("to", "Dominikaanske Republyk");
}
@Override
protected JavaScriptObject loadNameMapNative() {
return overrideMap(super.loadNameMapNative(), loadMyNameMap());
}
private native JavaScriptObject loadMyNameMap() /*-{
<SUF>*/;
}
|
29294_2 | /**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.richfaces.renderkit;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.ajax4jsf.javascript.JSEncoder;
import org.ajax4jsf.renderkit.HeaderResourcesRendererBase;
import org.ajax4jsf.renderkit.RendererUtils;
import org.richfaces.component.UIEffect;
import org.richfaces.json.JSONTokener;
/**
* @author Nick Belaevski
* mailto:[email protected]
* created 09.08.2007
*
*/
public class EffectRendererBase extends HeaderResourcesRendererBase {
/* (non-Javadoc)
* @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
*/
protected Class getComponentClass() {
return UIEffect.class;
}
private static final Pattern VARIABLE_PATTERN = Pattern.compile("^\\s*[_,A-Z,a-z]\\w*(?:\\.[_,A-Z,a-z]\\w*)*\\s*$");
public String convertElementParameter(Object parameter) {
if (parameter==null)
return "''";
String s = parameter.toString();
if (VARIABLE_PATTERN.matcher(s).matches()) {
return "typeof "+s+" == \"object\" ? "+s+" : $('"+s+"')";
} else {
return "'"+s+"'";
}
}
public String convertParameters(FacesContext context, UIEffect effect) throws IOException {
String params = effect.getParams();
if (params == null) {
return null;
}
StringBuffer buffer = new StringBuffer("{" + params + "}");
try {
replace(context, effect, buffer);
return buffer.toString();
} catch (Exception e) {
IOException exception = new IOException(e.getMessage());
exception.initCause(e);
throw exception;
}
}
private static void replace(FacesContext context, UIComponent effect, StringBuffer s) throws Exception {
JSONTokener x = new JSONTokener(s.toString());
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
int idx;
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
idx = x.getMyIndex();
//System.out.println(s.substring(x.getMyIndex()));
key = x.nextValue().toString();
}
/*
* The key is followed by ':'. We will also tolerate '=' or '=>'.
*/
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
if ("id".equals(key)) {
Object value = x.nextValue();
UIComponent component = RendererUtils.getInstance().findComponentFor(effect, value.toString());
if (component != null) {
value = component.getClientId(context);
}
s.replace(idx, x.getMyIndex(), "'id': '" + value + "'");
return ;
} else {
x.nextValue();
}
/*
* Pairs are separated by ','. We will also tolerate ';'.
*/
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
public String escapeJavaScript(Object s) {
if (s != null) {
JSEncoder encoder = new JSEncoder();
StringBuffer result = new StringBuffer();
String string = s.toString();
int length = string.length();
for (int i = 0; i < length; i++) {
result.append(encoder.encode(string.charAt(i)));
}
return result.toString();
} else {
return null;
}
}
}
| nuxeo/richfaces-3.3 | ui/effect/src/main/java/org/richfaces/renderkit/EffectRendererBase.java | 1,545 | /* (non-Javadoc)
* @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
*/ | block_comment | nl | /**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.richfaces.renderkit;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.ajax4jsf.javascript.JSEncoder;
import org.ajax4jsf.renderkit.HeaderResourcesRendererBase;
import org.ajax4jsf.renderkit.RendererUtils;
import org.richfaces.component.UIEffect;
import org.richfaces.json.JSONTokener;
/**
* @author Nick Belaevski
* mailto:[email protected]
* created 09.08.2007
*
*/
public class EffectRendererBase extends HeaderResourcesRendererBase {
/* (non-Javadoc)
<SUF>*/
protected Class getComponentClass() {
return UIEffect.class;
}
private static final Pattern VARIABLE_PATTERN = Pattern.compile("^\\s*[_,A-Z,a-z]\\w*(?:\\.[_,A-Z,a-z]\\w*)*\\s*$");
public String convertElementParameter(Object parameter) {
if (parameter==null)
return "''";
String s = parameter.toString();
if (VARIABLE_PATTERN.matcher(s).matches()) {
return "typeof "+s+" == \"object\" ? "+s+" : $('"+s+"')";
} else {
return "'"+s+"'";
}
}
public String convertParameters(FacesContext context, UIEffect effect) throws IOException {
String params = effect.getParams();
if (params == null) {
return null;
}
StringBuffer buffer = new StringBuffer("{" + params + "}");
try {
replace(context, effect, buffer);
return buffer.toString();
} catch (Exception e) {
IOException exception = new IOException(e.getMessage());
exception.initCause(e);
throw exception;
}
}
private static void replace(FacesContext context, UIComponent effect, StringBuffer s) throws Exception {
JSONTokener x = new JSONTokener(s.toString());
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
int idx;
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
idx = x.getMyIndex();
//System.out.println(s.substring(x.getMyIndex()));
key = x.nextValue().toString();
}
/*
* The key is followed by ':'. We will also tolerate '=' or '=>'.
*/
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
if ("id".equals(key)) {
Object value = x.nextValue();
UIComponent component = RendererUtils.getInstance().findComponentFor(effect, value.toString());
if (component != null) {
value = component.getClientId(context);
}
s.replace(idx, x.getMyIndex(), "'id': '" + value + "'");
return ;
} else {
x.nextValue();
}
/*
* Pairs are separated by ','. We will also tolerate ';'.
*/
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
public String escapeJavaScript(Object s) {
if (s != null) {
JSEncoder encoder = new JSEncoder();
StringBuffer result = new StringBuffer();
String string = s.toString();
int length = string.length();
for (int i = 0; i < length; i++) {
result.append(encoder.encode(string.charAt(i)));
}
return result.toString();
} else {
return null;
}
}
}
|
185927_6 | // Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.gesturenav;
import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.widget.ListView;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.Restriction;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.gesturenav.NavigationSheetMediator.ItemProperties;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.profiles.ProfileManager;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabbed_mode.TabbedRootUiCoordinator;
import org.chromium.chrome.browser.ui.RootUiCoordinator;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.R;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetController;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.NavigationEntry;
import org.chromium.content_public.browser.NavigationHistory;
import org.chromium.content_public.browser.test.mock.MockNavigationController;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.ui.modelutil.MVCListAdapter.ListItem;
import org.chromium.ui.test.util.UiRestriction;
import org.chromium.url.GURL;
import java.util.concurrent.ExecutionException;
/** Tests for the gesture navigation sheet. */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class NavigationSheetTest {
@Rule
public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
private static final int INVALID_NAVIGATION_INDEX = -1;
private static final int NAVIGATION_INDEX_1 = 1;
private static final int NAVIGATION_INDEX_2 = 5;
private static final int NAVIGATION_INDEX_3 = 9;
private static final int FULL_HISTORY_ENTRY_INDEX = 13;
private BottomSheetController mBottomSheetController;
@Before
public void setUp() throws Exception {
mActivityTestRule.startMainActivityOnBlankPage();
mBottomSheetController =
mActivityTestRule
.getActivity()
.getRootUiCoordinatorForTesting()
.getBottomSheetController();
}
private static class TestNavigationEntry extends NavigationEntry {
public TestNavigationEntry(
int index,
GURL url,
GURL virtualUrl,
GURL originalUrl,
String title,
Bitmap favicon,
int transition,
long timestamp) {
super(
index,
url,
virtualUrl,
originalUrl,
title,
favicon,
transition,
timestamp,
/* isInitialEntry= */ false);
}
}
private static class TestNavigationController extends MockNavigationController {
private final NavigationHistory mHistory;
private int mNavigatedIndex = INVALID_NAVIGATION_INDEX;
public TestNavigationController() {
mHistory = new NavigationHistory();
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_1,
new GURL("about:blank"),
GURL.emptyGURL(),
GURL.emptyGURL(),
"About Blank",
null,
0,
0));
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_2,
new GURL(UrlUtils.encodeHtmlDataUri("<html>1</html>")),
GURL.emptyGURL(),
GURL.emptyGURL(),
null,
null,
0,
0));
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_3,
new GURL(UrlConstants.NTP_URL),
GURL.emptyGURL(),
GURL.emptyGURL(),
null,
null,
0,
0));
}
@Override
public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) {
return mHistory;
}
@Override
public void goToNavigationIndex(int index) {
mNavigatedIndex = index;
}
}
private class TestSheetDelegate implements NavigationSheet.Delegate {
private static final int MAXIMUM_HISTORY_ITEMS = 8;
private final NavigationController mNavigationController;
public TestSheetDelegate(NavigationController controller) {
mNavigationController = controller;
}
@Override
public NavigationHistory getHistory(boolean forward, boolean isOffTheRecord) {
NavigationHistory history =
mNavigationController.getDirectedNavigationHistory(
forward, MAXIMUM_HISTORY_ITEMS);
if (!isOffTheRecord) {
history.addEntry(
new NavigationEntry(
FULL_HISTORY_ENTRY_INDEX,
new GURL(UrlConstants.HISTORY_URL),
GURL.emptyGURL(),
GURL.emptyGURL(),
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history),
null,
0,
0,
/* isInitialEntry= */ false));
}
return history;
}
@Override
public void navigateToIndex(int index) {
mNavigationController.goToNavigationIndex(index);
}
}
private NavigationSheet getNavigationSheet() {
RootUiCoordinator coordinator =
mActivityTestRule.getActivity().getRootUiCoordinatorForTesting();
return ((TabbedRootUiCoordinator) coordinator).getNavigationSheetForTesting();
}
@Test
@MediumTest
public void testFaviconFetching() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
Criteria.checkThat(
i + "th element",
item.model.get(ItemProperties.ICON),
Matchers.notNullValue());
}
});
}
@Test
@SmallTest
public void testItemSelection() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(() -> listview.getChildCount() >= 2);
Assert.assertEquals(INVALID_NAVIGATION_INDEX, controller.mNavigatedIndex);
ThreadUtils.runOnUiThreadBlocking(() -> listview.getChildAt(1).callOnClick());
CriteriaHelper.pollUiThread(sheet::isHidden);
CriteriaHelper.pollUiThread(
() -> {
Criteria.checkThat(controller.mNavigatedIndex, Matchers.is(NAVIGATION_INDEX_2));
});
}
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackTriggering() {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting);
// Wait for the long press timeout to trigger and show the navigation popup.
CriteriaHelper.pollUiThread(() -> getNavigationSheet() != null);
}
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackAfterActivityDestroy() {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
// Simulate the Activity destruction after a runnable to display navigation
// sheet gets delay-posted.
activity.getRootUiCoordinatorForTesting().destroyActivityForTesting();
});
// Test should finish without crash.
}
@Test
@SmallTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackTriggering_Cancellation() throws ExecutionException {
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting);
TestThreadUtils.runOnUiThreadBlocking(
() -> {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
activity.onKeyUp(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(() -> !activity.hasPendingNavigationRunnableForTesting());
// Ensure no navigation popup is showing.
Assert.assertNull(TestThreadUtils.runOnUiThreadBlocking(this::getNavigationSheet));
}
@Test
@MediumTest
public void testFieldsForOffTheRecordProfile() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, true);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
boolean doesNewIncognitoTabItemPresent = false;
boolean doesShowFullHistoryItemPresent = false;
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
String label = item.model.get(ItemProperties.LABEL);
String incognitoNtpText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.menu_new_incognito_tab);
String fullHistoryText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history);
if (label.equals(incognitoNtpText)) {
doesNewIncognitoTabItemPresent = true;
} else if (label.equals(fullHistoryText)) {
doesShowFullHistoryItemPresent = true;
}
}
Assert.assertTrue(doesNewIncognitoTabItemPresent);
Assert.assertFalse(doesShowFullHistoryItemPresent);
});
}
@Test
@MediumTest
public void testFieldsForRegularProfile() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
boolean doesNewTabItemPresent = false;
boolean doesShowFullHisotryItemPresent = false;
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
String label = item.model.get(ItemProperties.LABEL);
String regularNtpText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.menu_new_tab);
String fullHistoryText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history);
if (label.equals(regularNtpText)) {
doesNewTabItemPresent = true;
} else if (label.equals(fullHistoryText)) {
doesShowFullHisotryItemPresent = true;
}
}
Assert.assertTrue(doesNewTabItemPresent);
Assert.assertTrue(doesShowFullHisotryItemPresent);
});
}
private NavigationSheet showPopup(NavigationController controller, boolean isOffTheRecord)
throws ExecutionException {
return TestThreadUtils.runOnUiThreadBlocking(
() -> {
Tab tab = mActivityTestRule.getActivity().getActivityTabProvider().get();
Profile profile = ProfileManager.getLastUsedRegularProfile();
if (isOffTheRecord) {
profile = profile.getPrimaryOTRProfile(true);
}
NavigationSheet navigationSheet =
NavigationSheet.create(
tab.getContentView(),
mActivityTestRule.getActivity(),
() -> mBottomSheetController,
profile);
navigationSheet.setDelegate(new TestSheetDelegate(controller));
navigationSheet.startAndExpand(false, false);
return navigationSheet;
});
}
}
| nwjs/chromium.src | chrome/android/javatests/src/org/chromium/chrome/browser/gesturenav/NavigationSheetTest.java | 4,214 | // sheet gets delay-posted. | line_comment | nl | // Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.gesturenav;
import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.widget.ListView;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.Restriction;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.gesturenav.NavigationSheetMediator.ItemProperties;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.profiles.ProfileManager;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabbed_mode.TabbedRootUiCoordinator;
import org.chromium.chrome.browser.ui.RootUiCoordinator;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.R;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetController;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.NavigationEntry;
import org.chromium.content_public.browser.NavigationHistory;
import org.chromium.content_public.browser.test.mock.MockNavigationController;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.ui.modelutil.MVCListAdapter.ListItem;
import org.chromium.ui.test.util.UiRestriction;
import org.chromium.url.GURL;
import java.util.concurrent.ExecutionException;
/** Tests for the gesture navigation sheet. */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class NavigationSheetTest {
@Rule
public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
private static final int INVALID_NAVIGATION_INDEX = -1;
private static final int NAVIGATION_INDEX_1 = 1;
private static final int NAVIGATION_INDEX_2 = 5;
private static final int NAVIGATION_INDEX_3 = 9;
private static final int FULL_HISTORY_ENTRY_INDEX = 13;
private BottomSheetController mBottomSheetController;
@Before
public void setUp() throws Exception {
mActivityTestRule.startMainActivityOnBlankPage();
mBottomSheetController =
mActivityTestRule
.getActivity()
.getRootUiCoordinatorForTesting()
.getBottomSheetController();
}
private static class TestNavigationEntry extends NavigationEntry {
public TestNavigationEntry(
int index,
GURL url,
GURL virtualUrl,
GURL originalUrl,
String title,
Bitmap favicon,
int transition,
long timestamp) {
super(
index,
url,
virtualUrl,
originalUrl,
title,
favicon,
transition,
timestamp,
/* isInitialEntry= */ false);
}
}
private static class TestNavigationController extends MockNavigationController {
private final NavigationHistory mHistory;
private int mNavigatedIndex = INVALID_NAVIGATION_INDEX;
public TestNavigationController() {
mHistory = new NavigationHistory();
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_1,
new GURL("about:blank"),
GURL.emptyGURL(),
GURL.emptyGURL(),
"About Blank",
null,
0,
0));
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_2,
new GURL(UrlUtils.encodeHtmlDataUri("<html>1</html>")),
GURL.emptyGURL(),
GURL.emptyGURL(),
null,
null,
0,
0));
mHistory.addEntry(
new TestNavigationEntry(
NAVIGATION_INDEX_3,
new GURL(UrlConstants.NTP_URL),
GURL.emptyGURL(),
GURL.emptyGURL(),
null,
null,
0,
0));
}
@Override
public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) {
return mHistory;
}
@Override
public void goToNavigationIndex(int index) {
mNavigatedIndex = index;
}
}
private class TestSheetDelegate implements NavigationSheet.Delegate {
private static final int MAXIMUM_HISTORY_ITEMS = 8;
private final NavigationController mNavigationController;
public TestSheetDelegate(NavigationController controller) {
mNavigationController = controller;
}
@Override
public NavigationHistory getHistory(boolean forward, boolean isOffTheRecord) {
NavigationHistory history =
mNavigationController.getDirectedNavigationHistory(
forward, MAXIMUM_HISTORY_ITEMS);
if (!isOffTheRecord) {
history.addEntry(
new NavigationEntry(
FULL_HISTORY_ENTRY_INDEX,
new GURL(UrlConstants.HISTORY_URL),
GURL.emptyGURL(),
GURL.emptyGURL(),
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history),
null,
0,
0,
/* isInitialEntry= */ false));
}
return history;
}
@Override
public void navigateToIndex(int index) {
mNavigationController.goToNavigationIndex(index);
}
}
private NavigationSheet getNavigationSheet() {
RootUiCoordinator coordinator =
mActivityTestRule.getActivity().getRootUiCoordinatorForTesting();
return ((TabbedRootUiCoordinator) coordinator).getNavigationSheetForTesting();
}
@Test
@MediumTest
public void testFaviconFetching() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
Criteria.checkThat(
i + "th element",
item.model.get(ItemProperties.ICON),
Matchers.notNullValue());
}
});
}
@Test
@SmallTest
public void testItemSelection() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(() -> listview.getChildCount() >= 2);
Assert.assertEquals(INVALID_NAVIGATION_INDEX, controller.mNavigatedIndex);
ThreadUtils.runOnUiThreadBlocking(() -> listview.getChildAt(1).callOnClick());
CriteriaHelper.pollUiThread(sheet::isHidden);
CriteriaHelper.pollUiThread(
() -> {
Criteria.checkThat(controller.mNavigatedIndex, Matchers.is(NAVIGATION_INDEX_2));
});
}
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackTriggering() {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting);
// Wait for the long press timeout to trigger and show the navigation popup.
CriteriaHelper.pollUiThread(() -> getNavigationSheet() != null);
}
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackAfterActivityDestroy() {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
// Simulate the Activity destruction after a runnable to display navigation
// sheet gets<SUF>
activity.getRootUiCoordinatorForTesting().destroyActivityForTesting();
});
// Test should finish without crash.
}
@Test
@SmallTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE)
public void testLongPressBackTriggering_Cancellation() throws ExecutionException {
ChromeTabbedActivity activity = mActivityTestRule.getActivity();
TestThreadUtils.runOnUiThreadBlocking(
() -> {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
activity.onKeyDown(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting);
TestThreadUtils.runOnUiThreadBlocking(
() -> {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
activity.onKeyUp(KeyEvent.KEYCODE_BACK, event);
});
CriteriaHelper.pollUiThread(() -> !activity.hasPendingNavigationRunnableForTesting());
// Ensure no navigation popup is showing.
Assert.assertNull(TestThreadUtils.runOnUiThreadBlocking(this::getNavigationSheet));
}
@Test
@MediumTest
public void testFieldsForOffTheRecordProfile() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, true);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
boolean doesNewIncognitoTabItemPresent = false;
boolean doesShowFullHistoryItemPresent = false;
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
String label = item.model.get(ItemProperties.LABEL);
String incognitoNtpText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.menu_new_incognito_tab);
String fullHistoryText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history);
if (label.equals(incognitoNtpText)) {
doesNewIncognitoTabItemPresent = true;
} else if (label.equals(fullHistoryText)) {
doesShowFullHistoryItemPresent = true;
}
}
Assert.assertTrue(doesNewIncognitoTabItemPresent);
Assert.assertFalse(doesShowFullHistoryItemPresent);
});
}
@Test
@MediumTest
public void testFieldsForRegularProfile() throws ExecutionException {
TestNavigationController controller = new TestNavigationController();
NavigationSheetCoordinator sheet =
(NavigationSheetCoordinator) showPopup(controller, false);
ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries);
CriteriaHelper.pollUiThread(
() -> {
boolean doesNewTabItemPresent = false;
boolean doesShowFullHisotryItemPresent = false;
for (int i = 0; i < controller.mHistory.getEntryCount(); i++) {
ListItem item = (ListItem) listview.getAdapter().getItem(i);
String label = item.model.get(ItemProperties.LABEL);
String regularNtpText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.menu_new_tab);
String fullHistoryText =
mActivityTestRule
.getActivity()
.getResources()
.getString(R.string.show_full_history);
if (label.equals(regularNtpText)) {
doesNewTabItemPresent = true;
} else if (label.equals(fullHistoryText)) {
doesShowFullHisotryItemPresent = true;
}
}
Assert.assertTrue(doesNewTabItemPresent);
Assert.assertTrue(doesShowFullHisotryItemPresent);
});
}
private NavigationSheet showPopup(NavigationController controller, boolean isOffTheRecord)
throws ExecutionException {
return TestThreadUtils.runOnUiThreadBlocking(
() -> {
Tab tab = mActivityTestRule.getActivity().getActivityTabProvider().get();
Profile profile = ProfileManager.getLastUsedRegularProfile();
if (isOffTheRecord) {
profile = profile.getPrimaryOTRProfile(true);
}
NavigationSheet navigationSheet =
NavigationSheet.create(
tab.getContentView(),
mActivityTestRule.getActivity(),
() -> mBottomSheetController,
profile);
navigationSheet.setDelegate(new TestSheetDelegate(controller));
navigationSheet.startAndExpand(false, false);
return navigationSheet;
});
}
}
|
178740_6 | package gate.lingpipe;
import gate.ProcessingResource;
import gate.Resource;
import gate.creole.*;
import gate.util.*;
import gate.*;
import java.util.*;
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory;
import com.aliasi.tokenizer.Tokenizer;
/**
* LingPipe Tokenizer PR.
*
* @author Ekaterina Stambolieva + SB
*
*/
public class TokenizerPR extends AbstractLanguageAnalyser implements
ProcessingResource {
private static final long serialVersionUID = -6429885471274279223L;
/**
* Name of the output annotation set
*/
private String outputASName;
/**
* tokeniser factory used for tokenizing text
*/
private com.aliasi.tokenizer.TokenizerFactory tf;
/** Initialise this resource, and return it. */
public Resource init() throws ResourceInstantiationException {
// construct tokenizer
tf = IndoEuropeanTokenizerFactory.INSTANCE;
return this;
}
public void reInit() throws ResourceInstantiationException {
init();
}
/**
* execute method. Makes LingPipe API calls to tokenize the document.
* It uses the document's string and passes it over to the LingPipe to
* tokenize. It also generates space tokens as well.
*/
public void execute() throws ExecutionException {
if(document == null) {
throw new ExecutionException("There is no loaded document");
}
super.fireProgressChanged(0);
long startOffset = 0, endOffset = 0;
AnnotationSet as = null;
if(outputASName == null || outputASName.trim().length() == 0)
as = document.getAnnotations();
else as = document.getAnnotations(outputASName);
String docContent = document.getContent().toString();
List<String> tokenList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
// -----
// rendes tokenizálás: kikapcs
// Tokenizer tokenizer = tf.tokenizer(docContent.toCharArray(), 0, docContent
// .length());
// tokenizer.tokenize(tokenList, whiteList);
// na itt van a rendes tokenizálás helyett egy
// "dummy", ami adott karakter mentén vág
String separator = " "; // regex! :)
String[] words = docContent.split( separator ); // "tokenizálás" :)
whiteList.add( "" ); // 1 db szeparátor a legelejére -- így jó lett...
// sztem a LingPipe-os alábbi ciklus hülyesége miatt kell
for ( int i = 0; i < words.length; i++ ) {
tokenList.add( words[i] );
if ( i < words.length - 1 ) { // jó ez: separator 1-gyel kevesebb van :)
whiteList.add( separator ); // ez gáz, XXX XXX XXX
// mert nem tuti, hogy ua-t teszi vissza, mint ami ott volt!
// pl. ha 2 db separator karakter van egymás után / a végén XXX
}
}
// * ha az elején szepa -> betesz egy üres tokent az elejére
// * 2 szepa egymás mellett -> néha betesz üres tokent, néha nem...
// dummy tokenizer vége
// -----
for(int i = 0; i < whiteList.size(); i++) {
try {
startOffset = endOffset;
endOffset = startOffset + whiteList.get(i).length();
if((endOffset - startOffset) != 0) {
FeatureMap fmSpaces = Factory.newFeatureMap();
fmSpaces.put("length", "" + (endOffset - startOffset));
as.add(new Long(startOffset), new Long(endOffset), "SpaceToken",
fmSpaces);
}
if(i < tokenList.size()) {
startOffset = endOffset;
endOffset = startOffset + tokenList.get(i).length();
FeatureMap fmTokens = Factory.newFeatureMap();
fmTokens.put("length", "" + (endOffset - startOffset));
as.add(new Long(startOffset), new Long(endOffset), "Token", fmTokens);
}
}
catch(InvalidOffsetException e) {
throw new ExecutionException(e);
}
}
}
/**
* gets name of the output annotation set
* @return
*/
public String getOutputASName() {
return outputASName;
}
/**
* sets name of the output annotaiton set
* @param outputAS
*/
public void setOutputASName(String outputAS) {
this.outputASName = outputAS;
}
}
| nytud/hunlp-GATE | attic/TokenizerPR.java | 1,288 | // Tokenizer tokenizer = tf.tokenizer(docContent.toCharArray(), 0, docContent | line_comment | nl | package gate.lingpipe;
import gate.ProcessingResource;
import gate.Resource;
import gate.creole.*;
import gate.util.*;
import gate.*;
import java.util.*;
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory;
import com.aliasi.tokenizer.Tokenizer;
/**
* LingPipe Tokenizer PR.
*
* @author Ekaterina Stambolieva + SB
*
*/
public class TokenizerPR extends AbstractLanguageAnalyser implements
ProcessingResource {
private static final long serialVersionUID = -6429885471274279223L;
/**
* Name of the output annotation set
*/
private String outputASName;
/**
* tokeniser factory used for tokenizing text
*/
private com.aliasi.tokenizer.TokenizerFactory tf;
/** Initialise this resource, and return it. */
public Resource init() throws ResourceInstantiationException {
// construct tokenizer
tf = IndoEuropeanTokenizerFactory.INSTANCE;
return this;
}
public void reInit() throws ResourceInstantiationException {
init();
}
/**
* execute method. Makes LingPipe API calls to tokenize the document.
* It uses the document's string and passes it over to the LingPipe to
* tokenize. It also generates space tokens as well.
*/
public void execute() throws ExecutionException {
if(document == null) {
throw new ExecutionException("There is no loaded document");
}
super.fireProgressChanged(0);
long startOffset = 0, endOffset = 0;
AnnotationSet as = null;
if(outputASName == null || outputASName.trim().length() == 0)
as = document.getAnnotations();
else as = document.getAnnotations(outputASName);
String docContent = document.getContent().toString();
List<String> tokenList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
// -----
// rendes tokenizálás: kikapcs
// Tokenizer tokenizer<SUF>
// .length());
// tokenizer.tokenize(tokenList, whiteList);
// na itt van a rendes tokenizálás helyett egy
// "dummy", ami adott karakter mentén vág
String separator = " "; // regex! :)
String[] words = docContent.split( separator ); // "tokenizálás" :)
whiteList.add( "" ); // 1 db szeparátor a legelejére -- így jó lett...
// sztem a LingPipe-os alábbi ciklus hülyesége miatt kell
for ( int i = 0; i < words.length; i++ ) {
tokenList.add( words[i] );
if ( i < words.length - 1 ) { // jó ez: separator 1-gyel kevesebb van :)
whiteList.add( separator ); // ez gáz, XXX XXX XXX
// mert nem tuti, hogy ua-t teszi vissza, mint ami ott volt!
// pl. ha 2 db separator karakter van egymás után / a végén XXX
}
}
// * ha az elején szepa -> betesz egy üres tokent az elejére
// * 2 szepa egymás mellett -> néha betesz üres tokent, néha nem...
// dummy tokenizer vége
// -----
for(int i = 0; i < whiteList.size(); i++) {
try {
startOffset = endOffset;
endOffset = startOffset + whiteList.get(i).length();
if((endOffset - startOffset) != 0) {
FeatureMap fmSpaces = Factory.newFeatureMap();
fmSpaces.put("length", "" + (endOffset - startOffset));
as.add(new Long(startOffset), new Long(endOffset), "SpaceToken",
fmSpaces);
}
if(i < tokenList.size()) {
startOffset = endOffset;
endOffset = startOffset + tokenList.get(i).length();
FeatureMap fmTokens = Factory.newFeatureMap();
fmTokens.put("length", "" + (endOffset - startOffset));
as.add(new Long(startOffset), new Long(endOffset), "Token", fmTokens);
}
}
catch(InvalidOffsetException e) {
throw new ExecutionException(e);
}
}
}
/**
* gets name of the output annotation set
* @return
*/
public String getOutputASName() {
return outputASName;
}
/**
* sets name of the output annotaiton set
* @param outputAS
*/
public void setOutputASName(String outputAS) {
this.outputASName = outputAS;
}
}
|
40704_29 | //
// Copyright 2004-2023 New Zealand Institute of Language, Brain and Behaviour,
// University of Canterbury
// Written by Robert Fromont - [email protected]
//
// This file is part of nzilbb.ag.
//
// nzilbb.ag 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.
//
// nzilbb.ag 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 nzilbb.ag; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package nzilbb.formatter.praat;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.IOException;
/**
* {@link IntervalTier} time interval.
* @author Robert Fromont
*/
public class Interval implements ITextEntity {
// Attributes:
private double dXmin = 0.0;
/** Sets start time
* @param xmin The start time in seconds.
*/
public void setXmin(double xmin) { dXmin = xmin; }
/** Gets start time
* @return The start time in seconds.
*/
public double getXmin() { return dXmin; }
private double dXmax = 0.0;
/** Sets end time
* @param xmax The end time in seconds.
*/
public void setXmax(double xmax) { dXmax = xmax; }
/** Gets end time
* @return The end time in seconds.
*/
public double getXmax() { return dXmax; }
private String sText = "";
/** Sets label
* @param text The label.
*/
public void setText(String text) { sText = text; }
/** Gets label
* @return The label.
*/
public String getText() { if (sText == null) return ""; else return sText; }
/**
* Constructor
*/
public Interval() {
} // end of constructor
/**
* Constructor
* @param text The label for the interval.
* @param xMin The start time in seconds.
* @param xMax The end time in seconds.
*/
public Interval(String text, double xMin, double xMax) {
setText(text);
setXmin(xMin);
setXmax(xMax);
} // end of constructor
/**
* Copy constructor
* @param other The interval to copy.
*/
public Interval(Interval other) {
setText(other.getText());
setXmin(other.getXmin());
setXmax(other.getXmax());
} // end of constructor
/**
* Returns the halway point between Xmin and Xmax
* @return Xmin + ( (Xmax-Xmin) / 2 )
*/
public double getMidPoint() {
return getXmin() + ( (getXmax()-getXmin()) / 2.0 );
} // end of getMidPoint()
// ITextEntity methods
/**
* Text-file representation of the object.
*/
public void writeText(Writer writer) throws java.io.IOException {
writer.write(
"\n xmin = " + TextGrid.OffsetFormat.format(Math.min(getXmin(),getXmax())) + " " +
"\n xmax = " + TextGrid.OffsetFormat.format(Math.max(getXmin(),getXmax())) + " " +
"\n text = \"" + getText().replace("\"", "\"\"") + "\" ");
}
/**
* Deserializes the interval.
* @param reader The reader to read from.
* @throws IOException If an IO error occurs.
*/
public void readText(BufferedReader reader) throws IOException {
setXmin(Double.parseDouble(TextGrid.readValue("xmin", reader)));
setXmax(Double.parseDouble(TextGrid.readValue("xmax", reader)));
setText(TextGrid.readValue("text", reader));
}
/**
* String representation of the object
*/
public String toString() {
return "xmin = " + getXmin() +
", xmax = " + getXmax() +
", text = \"" + getText().replace("\"", "\"\"")
+ "\"";
}
} // end of class Interval
| nzilbb/ag | formatter/praat/src/main/java/nzilbb/formatter/praat/Interval.java | 1,362 | // end of getMidPoint()
| line_comment | nl | //
// Copyright 2004-2023 New Zealand Institute of Language, Brain and Behaviour,
// University of Canterbury
// Written by Robert Fromont - [email protected]
//
// This file is part of nzilbb.ag.
//
// nzilbb.ag 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.
//
// nzilbb.ag 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 nzilbb.ag; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package nzilbb.formatter.praat;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.IOException;
/**
* {@link IntervalTier} time interval.
* @author Robert Fromont
*/
public class Interval implements ITextEntity {
// Attributes:
private double dXmin = 0.0;
/** Sets start time
* @param xmin The start time in seconds.
*/
public void setXmin(double xmin) { dXmin = xmin; }
/** Gets start time
* @return The start time in seconds.
*/
public double getXmin() { return dXmin; }
private double dXmax = 0.0;
/** Sets end time
* @param xmax The end time in seconds.
*/
public void setXmax(double xmax) { dXmax = xmax; }
/** Gets end time
* @return The end time in seconds.
*/
public double getXmax() { return dXmax; }
private String sText = "";
/** Sets label
* @param text The label.
*/
public void setText(String text) { sText = text; }
/** Gets label
* @return The label.
*/
public String getText() { if (sText == null) return ""; else return sText; }
/**
* Constructor
*/
public Interval() {
} // end of constructor
/**
* Constructor
* @param text The label for the interval.
* @param xMin The start time in seconds.
* @param xMax The end time in seconds.
*/
public Interval(String text, double xMin, double xMax) {
setText(text);
setXmin(xMin);
setXmax(xMax);
} // end of constructor
/**
* Copy constructor
* @param other The interval to copy.
*/
public Interval(Interval other) {
setText(other.getText());
setXmin(other.getXmin());
setXmax(other.getXmax());
} // end of constructor
/**
* Returns the halway point between Xmin and Xmax
* @return Xmin + ( (Xmax-Xmin) / 2 )
*/
public double getMidPoint() {
return getXmin() + ( (getXmax()-getXmin()) / 2.0 );
} // end of<SUF>
// ITextEntity methods
/**
* Text-file representation of the object.
*/
public void writeText(Writer writer) throws java.io.IOException {
writer.write(
"\n xmin = " + TextGrid.OffsetFormat.format(Math.min(getXmin(),getXmax())) + " " +
"\n xmax = " + TextGrid.OffsetFormat.format(Math.max(getXmin(),getXmax())) + " " +
"\n text = \"" + getText().replace("\"", "\"\"") + "\" ");
}
/**
* Deserializes the interval.
* @param reader The reader to read from.
* @throws IOException If an IO error occurs.
*/
public void readText(BufferedReader reader) throws IOException {
setXmin(Double.parseDouble(TextGrid.readValue("xmin", reader)));
setXmax(Double.parseDouble(TextGrid.readValue("xmax", reader)));
setText(TextGrid.readValue("text", reader));
}
/**
* String representation of the object
*/
public String toString() {
return "xmin = " + getXmin() +
", xmax = " + getXmax() +
", text = \"" + getText().replace("\"", "\"\"")
+ "\"";
}
} // end of class Interval
|
177856_49 | /*
This software was produced for the U. S. Government
under Contract No. W15P7T-11-C-F600, and is
subject to the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation
Clause 252.227-7014 (JUN 1995)
Copyright 2013 The MITRE Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.opensextant.solrtexttagger;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionLengthAttribute;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IntsRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builds phrases from {@link Token}s in {@link TokenStream}. This works by
* evaluating {@link PositionIncrementAttribute} as well as the
* {@link OffsetAttribute}. <p>
* Using the {@link PositionLengthAttribute} would be much easier but some
* Lucene {@link Analyzer}s don't yet properly support it as of Lucene 4.5.
*
* <h3>Performance considerations:</h3>
*
* {@link TokenStream}s that do <i>not</i> define any alternate tokens (i.e.
* no token has <code>posInc == 0</code>) will be processed by calling
* {@link #add(int, int, int)} once for the first token. For all
* remaining tokens {@link #append(int, int, int)} will be called. This code
* path does execute fast. Processing such TokenStreams will only create a
* single instance of {@link Phrase}. <p>
* For {@link TokenStream}s that do define alternate tokens, more processing
* is needed. For each branch (defined by the start offset of a token with a
* position increment of zero) start positions of existing {@link Phrase}s need
* to be checked. All existing {@link Phrase}s that use this position need to
* be copied and on the copy the current term need to be set.
*
* <h3>Limitations</h3>
*
* This class can not support multi token matchings of {@link SynonymFilter}.
* Those are entries in the synonyms file where a left hand value with
* <code>n</code> tokens is mapped to a right hand value with more then
* <code>n</code> tokens (e.g. <code>'DNS => Domain Name Service'</code> or
* also <code>'DNS, Domain Name Service'</code>). Users are encouraged to
* reverse all such mappings so that the synonym with the more tokens is on
* the left hand side (e.g. <code>'Domain Name Service => DNS'</code>). <p>
* If the PhraseBuilder encounters such cases the
* {@link #addTerm(int, int, int, int, int)} will throw an
* {@link UnsupportedTokenException} and ERROR level logging providing similar
* information will be printed to the log.<p>
* For more information on this issue please look at the <i>Limitation<i>
* section of the Blog
* <a href="http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html">
* Lucene's TokenStreams are actually graphs!</a> by Michael McCandless.
*
* <hr>
* <b>TODO:</b> This could also directly take the {@link TokenStream} as input
* and also implement the logic of iterating over the tokens. Currently this is
* still done in the {@link TaggerFstCorpus}#analyze(..) method.
* <hr>
*
* @author Rupert Westenthaler
*/
class PhraseBuilder {
private final Logger log = LoggerFactory.getLogger(PhraseBuilder.class);
/**
* List with the phrases. This list is sorted by {@link Phrase#pStart}
*/
protected final List<Phrase> phrases;
/**
* Used to memorize the start offset of the first token(s) reported by the
* TokenStream
*/
private int startOffset = -1;
/**
* Internally used by {@link #branch(int, int, int)} and
* {@link #append(int, int, int)} to temporarily store {@link Phrase}. <p>
* Those methods use this field to avoid creating new {@link List}
* instances on each call.<p>
* Users of this field are expected to call {@link List#clear()} before
* usage.
*/
private List<Phrase> tempPhrases;
/**
* Creates a new PhraseBuilder instance with the initial capacity.
* Note that this instance should be reused by calling {@link #reset()}.
*
* @see #reset()
*/
public PhraseBuilder(int initialPathCapacity) {
phrases = new ArrayList<Phrase>(initialPathCapacity);
tempPhrases = new ArrayList<Phrase>(initialPathCapacity);
}
/**
* Adds the term to the phrase
*
* @param termId the integer termId representing the term.
* @param start the start offset for the term
* @param end the end offset of the term
* @param posInc the position increment of the term
* @param posLen the position length of the term (currently not used)
* @throws UnsupportedTokenException if the parsed term can not be processed
*/
public void addTerm(int termId, int start, int end, int posInc, int posLen) {
if (posInc > 0) { //new token position
if (phrases.isEmpty()) { // the first token
startOffset = start; //set the start offset
create(termId, start, end); //create a new Phrase
} else { //tokens with posInc > 0 need to be appended to existing phrases
if (!append(termId, start, end)) {
//this means that we do have multiple tokens for the same span (start
//and end offset).
log.error("Unable to append term[offset: [{},{}], posInc: {}, posLen {}] "
+ "to any phrase.", new Object[]{start, end, posInc, posLen});
log.error("This is caused by Terms with posInc > 0 but same "
+ "offsets already used by an other token. Please change the "
+ "configuration of your Analyzer chain.");
log.error("This can be cuased e.g. by:");
log.error(" > the SynonymFilter with configured multiple word mappings "
+ "(e.g. 'DNS => Domain Name Service'). In such cases it can be "
+ "solved by using the reverse mappings ('Domain Name Service => DNS')");
log.error(" > Using the WordDelimiterFilter to generate tokens that are "
+ "afterwards processed by the SynonymFilter.");
log.error(" > Applying the WordDelimiterFilter to tokens where the term. "
+ "length != endOffset - startOffset. In such cases the "
+ "WordDelimiterFilter does correct offset. This can e.g. be cuased "
+ "by the HyphenatedWordsFilter or the EnglishPossessiveFilter. "
+ "Generally it is recommended to use the WordDelimiterFilter "
+ "directly after the Tokenizer.");
log.error("For more information see also limitations section of "
+ "http://blog.mikemccandless.com/2012/04/"
+ "lucenes-tokenstreams-are-actually.html");
throw new UnsupportedTokenException("Encountered Term with "
+ "posInc > 0 but similar offset as existing one (see ERROR "
+ "level loggings for details and help!");
} //else successfully appended
}
} else { //tokens with posInc == 0 are alternatives to existing tokens
if (start == startOffset) { //if alternative starts at the beginning
create(termId, start, end); //simply create a new phrase
} else { //we need to create branches for existing phrases
branch(termId, start, end);
}
}
}
/**
* Creates a new phrase and adds the parsed term and registers it to
* {@link #phrases}. This method expects that
* <code>start == {@link #startOffset}</code>
*
* @return the created phrase
*/
private Phrase create(int termId, int start, int end) {
assert startOffset <= start;
if (!phrases.isEmpty()) {
//do not create multiple phrases for the same termId
int size = phrases.size();
for (int i = 0; i < size; i++) {
Phrase phrase = phrases.get(i);
if (phrase.length() == 1 && phrase.getTerm(0) == termId) {
return phrase;
}
}
}
Phrase phrase = new Phrase(8);
phrases.add(phrase);
phrase.pStart = start;
phrase.add(termId, start, end);
return phrase;
}
/**
* This appends a Token to existing phrases. It is expected to be called if the
* <code>{@link PositionIncrementAttribute#getPositionIncrement() posInc} > 0 </code>
* for the parsed term.<p>
* <b>NOTEs:</b> <ul>
* <li> This method can not guarantee that the parsed term is
* appended to any of the phrases. There are cases in that it is not possible
* to reconstruct phrases based on posInc, start and end offset of terms
* (e.g. for some {@link SynonymFilter} mappings). This method is able to
* detect such situations and will refuse to append according tokens. Callers
* can detect this by <code>false</code> being returned.<p>
* <li> This method is able to deal with multiple tokens using the same
* start/end offset as long as there are not multiple possible paths. This
* means e.g. that synonyms like 'Domain Name Service => DNS' will be
* correctly handled. However using analyzers generating such token streams
* are still problematic as they may result in unintended behaviour during
* search. See the 'Domain Name Service => DNS' example in the limitation
* section of <a href="http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html">
* Lucene's TokenStreams are actually graphs!</a> by Michael McCandless for
* details why this is the case.<br>
* </ul>
*
* @param termId the termId representing the term
* @param start the start index of the term
* @param end the end index of the term
* @return if the term was appended to any of the phrases.
*/
private boolean append(int termId, int start, int end) {
int addPos = -1; //stores the char offset of the phrase end where we append
int branchPos = -1;
tempPhrases.clear(); //need to clear before usage
for (int i = phrases.size() - 1; i >= 0; i--) {
Phrase phrase = phrases.get(i);
int phraseEnd = phrase.pEnd;
if (phraseEnd <= start) {
phrase.add(termId, start, end);
addPos = phraseEnd;
} else if (addPos >= 0) { //to avoid unnecessary iterations
//Tokens can only be appended to phrases ending in a single position.
//While multiple phrases might use this position, we can stop iterating
//as soon as phrases no longer have the same pEnd value after the
//parsed token was appended (addPos >= 0)
break;
} else if (phraseEnd == end) {
//save phrases with same end pos as the parsed term for further
//processing (see below)
tempPhrases.add(phrase);
} //else uninteresting token
//maybe we need to call branch later on ...
// ... so also calculate the possible branch position
int startPos = phrase.getPos(phrase.length() - 1);
if (startPos > branchPos && startPos <= start) {
branchPos = startPos;
}
}
if (addPos < 0) { //not added
//Two possible reasons:
//(1) there was an alternate token where this should have been appended
//but it was removed by a TokenFilter (e.g. "Mr. A.St." could get split
// to "Mr", "A.St.", "A", "St" and the StopFilterFactory would remove "A".
//So we might see a token "ST" with a posInc=1 with no token to
//append to as "Mr" is already taken by "A.St.".
//In this case what we need to do is to find the branchPos for the
//removed "A" token and append "ST" directly to that.
//(2) multiple tokens with posInc > 0 for tokens with the same
//span (start/end offset). This is typically the case if a single token
//in the text is split up to several. Those cases can only be correctly
//handled if all matching phrases have the same termId as otherwise
//we can not reconstruct the correct phrases.
//First test for case (2)
boolean isSameSpan = false; //used to check for (2)
if (!tempPhrases.isEmpty()) {
int tempSize = tempPhrases.size();
int addPhraseNum = -1;
long tId = Long.MIN_VALUE; //keep default outside of int range
boolean foundMultiple = false;
for (int i = 0; !foundMultiple && i < tempSize; i++) {
Phrase phrase = tempPhrases.get(i);
//check if the last token of this phrase has the same span
int index = phrase.length() - 1;
if (phrase.getPos(index) == start) { //check if start also matches
isSameSpan = true; //there is a token with the same span
//but first check for multiple phrases with different termIds
int id = phrase.getTerm(index);
if (tId == Long.MIN_VALUE) { //store the phraseId
tId = id;
} else if (id != tId) {
//encountered multiple phrases with different termIds
// ... stop here (error handling is done by calling method
foundMultiple = true;
} //else multiple phrases with same termId
//do not append immediately (because we should not change the state
//in case we will find multiple phrases with different termIds
addPhraseNum++;
if (addPhraseNum != i) { //write validated back to tempPhrases
tempPhrases.set(addPhraseNum, phrase);
} //else the current element is this one
} //only end matches -> not the same start/end offset -> ignore
}
if (!foundMultiple && addPhraseNum >= 0) {
addPos = end; //just to set addPos > 0
//now finally append to phrases with same span
for (int i = 0; i <= addPhraseNum; i++) {
tempPhrases.get(i).add(termId, start, end);
}
}
} //no span with the same end offset ... can only be case (1)
//handle case (1)
if (!isSameSpan) {
//NOTE that branchPos might not be available if the removed token
//was at the beginning of the text. So use the start offset of the
//parsed token if branchPos < 0
return branch(termId, branchPos < 0 ? start : branchPos, end);
}
}
return addPos >= 0;
}
/**
* Creates branch(es) for an alternate term at the parsed start/end char
* offsets. Also inserts created {@link Phrase}s to {@link #phrases} keeping
* elements in {@link #phrases} sorted by {@link Phrase#pStart}. No return
* value as the state will be stored in the {@link #phrases} collection.<p>
* Note this method is only called for {@link TokenStream}s with alternate
* tokens (<code>{@link PositionIncrementAttribute#getPositionIncrement() posInc}
* == 0</code>). So this rather complex operation will only be executed for
* labels that do result in such tokens.
*
* @param termId the termId to add right after the branch
* @param start the start of the term. Also the position of the branch
* @param end the end of the term
* @return <code>true</code> if the termId was successfully processed.
* Otherwise <code>false</code>
*/
private boolean branch(int termId, int start, int end) {
int size = phrases.size();
tempPhrases.clear(); //need to clear before using
boolean create = true; //if not a branch create a new phrase
//we need to create a branch for all phrases starting before the parsed term
int i = 0;
for (; i < size; i++) {
Phrase phrase = phrases.get(i);
if (phrase.pStart < start) {
if (phrase.hasPos(start)) {
create = false; // this is a branch
Phrase branch = phrase.clone();
branch.pStart = start;
if (branch.set(termId, start, end)) {
tempPhrases.add(branch);
} //else no need to branch, because the parsed termId equals
//the previous one.
} //else the phrase starts earlier, but does not have a term that ends
//at the start position of the current one (it skips this position
//with a term of a posLen > 1). So we do not need to create a branch.
} else if (phrase.pStart > start) {
//stop here, because it is the position in phrases where we need to
//start inserting the creates branches.
break;
}
}
if (create) {
return create(termId, start, end) != null;
} else { //insert branches into phrases
int bSize = tempPhrases.size();
if (bSize > 0) { //insert branch(es) in sorted phrases list
int numSwap = size - i;
for (int j = 0; j < bSize; j++, i++) {
if (i < size) {
//swap the 'j' element of branches with the 'i' of #phrases
tempPhrases.set(j, phrases.set(i, tempPhrases.get(j)));
} else {
phrases.add(tempPhrases.get(j));
}
}
for (; i < size; i++) { //add remaining elements in phrases as we need to
tempPhrases.add(phrases.get(i)); //append them to have a sorted list
}
//finally add Phrases swapped to branches to the end of #phrases
for (int j = 0; j < numSwap; j++) {
phrases.add(tempPhrases.get(j));
}
//now #phrases is again sorted by Phrase#pStart
} //else no branch created (branch would have same termId as existing one)
return true;
}
}
/**
* Getter for the {@link IntsRef}s of the phrases build from terms parsed to
* the {@link #addTerm(int, int, int, int, int)} method.
*
* @return An array containing the created phrases. Each phrase is represented
* by a {@link IntsRef}s of its termIds.
*/
public IntsRef[] getPhrases() {
int size = phrases.size();
IntsRef[] refs = new IntsRef[phrases.size()];
for (int i = 0; i < size; i++) {
refs[i] = phrases.get(i).getPath();
}
return refs;
}
/**
* Resets this {@link PhraseBuilder} instance to its initial state.
* This allows to reuse the same instance to build phrases for multiple
* {@link TokenStream}s.
*/
public void reset() {
phrases.clear();
startOffset = -1;
}
/**
* Private class used to build up a single phrase. An {@link IntsRef} is used
* to build up the phrase. Words are represented by the integer termId.
*
* @author Rupert Westenthaler
*/
static class Phrase implements Cloneable {
/**
* The path
*/
private final IntsRef path;
/**
* stores the start offsets of terms contained in this phrase. NOTE that
* this array only contains as many valid values as the number of
* termIds in {@link #path}.
*/
private int[] pos;
/**
* the current end offset of the phrase.
*/
protected int pEnd;
/**
* The index at that this phrase was created. This is the char offset where
* the first term of this phrase is different as of other phrases. This
* information is required to know when one needs to create alternate
* phrases for alternate tokens.
*/
protected int pStart;
/**
* Creates a new (empty) path with the given capacity
*/
Phrase(int initialCapacity) {
this(new IntsRef(initialCapacity), new int[initialCapacity], -1);
}
/**
* Internally used by {@link #clone()} to construct a new Phrase with
* data copied from the cloned instance.
*
* @param path
* @param pos
* @param pEnd
* @see #clone()
*/
private Phrase(IntsRef path, int[] pos, int pEnd) {
this.path = path;
this.pos = pos;
this.pEnd = pEnd;
this.pStart = -1;
}
/**
* Adds a term to the {@link IntsRef} representing the path
*
* @param termId the termId to add
* @param tEnd the end position of the term
*/
void add(int termId, int start, int end) {
// assert start >= pEnd; //the added term MUST be at the end of the Phrase
path.grow(++path.length); //add an element to the path
path.ints[path.length - 1] = termId;
if (pos.length < path.length) { //increase pos array size
pos = ArrayUtil.grow(pos);
}
pos[path.length - 1] = start;
pEnd = end;
}
/**
* Sets the term at the according position of the phrase. Also removes
* all follow up elements from the phrase
*
* @param termId the term represented by the termId
* @param start the start offset of the term. Will be used to determine the
* correct position within the phrase
* @param end the end offset of the term.
*/
boolean set(int termId, int start, int end) {
assert start < pEnd;
//backward lookup as we expect to replace the last element most of the time
for (int idx = path.length - 1; idx >= 0; idx--) {
if (pos[idx] <= start) { //found the index
int oldTermId = path.ints[idx];
if (oldTermId != termId) {
path.ints[idx] = termId;
path.length = idx + 1;
pEnd = end; //update the end
return true;
} else {
return false;
}
}
}
//save guard
throw new IllegalStateException("Should be unreachable. Please report as "
+ "a bug!");
}
int length() {
return path.length;
}
/**
* Checks if a term in this phrase has the given start position
*
* @param pos the position to check
* @return <code>true</code> if such a term exists. Otherwise <code>false</code>
*/
boolean hasPos(int pos) {
//search backwards in pos array as we expect this method will ask about
//the last term in the phrase. Only in rare cases about an earlier.
for (int idx = path.length - 1; idx >= 0; idx--) {
int value = this.pos[idx];
if (value == pos) {
return true;
}
if (value < pos) {
return false;
}
}
return false;
}
/**
* Returns the start offset of the term at the parsed index within the
* phrase.
*
* @param index the index
* @return
*/
int getPos(int index) {
return pos[index];
}
/**
* Gets the termId of a term in the phrase
*
* @param index the index of the element
* @return the termId
*/
int getTerm(int index) {
return path.ints[index];
}
/**
* The {@link IntsRef} representing this path
*
* @return
*/
public IntsRef getPath() {
return path;
}
/**
* The end position of this path
*
* @return
*/
public int getEnd() {
return pEnd;
}
/**
* A "deep" clone AKA copy. Uses same array size over-allocation.
*/
@Override
public Phrase clone() {
//Could use IntsRef.deepClone() but lets use same over-capacity
int[] pathClone = new int[path.ints.length]; //use same capacity
System.arraycopy(path.ints, 0, pathClone, 0, path.length); //copy data
//also clone the positions of the path
int[] posClone = new int[pos.length];//use same capacity
System.arraycopy(pos, 0, posClone, 0, path.length); //only path.length items
return new Phrase(new IntsRef(pathClone, 0, path.length), posClone, pEnd);
}
}
} | o19s/SolrTextTagger | src/main/java/org/opensextant/solrtexttagger/PhraseBuilder.java | 7,003 | //keep default outside of int range | line_comment | nl | /*
This software was produced for the U. S. Government
under Contract No. W15P7T-11-C-F600, and is
subject to the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation
Clause 252.227-7014 (JUN 1995)
Copyright 2013 The MITRE Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.opensextant.solrtexttagger;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionLengthAttribute;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IntsRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builds phrases from {@link Token}s in {@link TokenStream}. This works by
* evaluating {@link PositionIncrementAttribute} as well as the
* {@link OffsetAttribute}. <p>
* Using the {@link PositionLengthAttribute} would be much easier but some
* Lucene {@link Analyzer}s don't yet properly support it as of Lucene 4.5.
*
* <h3>Performance considerations:</h3>
*
* {@link TokenStream}s that do <i>not</i> define any alternate tokens (i.e.
* no token has <code>posInc == 0</code>) will be processed by calling
* {@link #add(int, int, int)} once for the first token. For all
* remaining tokens {@link #append(int, int, int)} will be called. This code
* path does execute fast. Processing such TokenStreams will only create a
* single instance of {@link Phrase}. <p>
* For {@link TokenStream}s that do define alternate tokens, more processing
* is needed. For each branch (defined by the start offset of a token with a
* position increment of zero) start positions of existing {@link Phrase}s need
* to be checked. All existing {@link Phrase}s that use this position need to
* be copied and on the copy the current term need to be set.
*
* <h3>Limitations</h3>
*
* This class can not support multi token matchings of {@link SynonymFilter}.
* Those are entries in the synonyms file where a left hand value with
* <code>n</code> tokens is mapped to a right hand value with more then
* <code>n</code> tokens (e.g. <code>'DNS => Domain Name Service'</code> or
* also <code>'DNS, Domain Name Service'</code>). Users are encouraged to
* reverse all such mappings so that the synonym with the more tokens is on
* the left hand side (e.g. <code>'Domain Name Service => DNS'</code>). <p>
* If the PhraseBuilder encounters such cases the
* {@link #addTerm(int, int, int, int, int)} will throw an
* {@link UnsupportedTokenException} and ERROR level logging providing similar
* information will be printed to the log.<p>
* For more information on this issue please look at the <i>Limitation<i>
* section of the Blog
* <a href="http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html">
* Lucene's TokenStreams are actually graphs!</a> by Michael McCandless.
*
* <hr>
* <b>TODO:</b> This could also directly take the {@link TokenStream} as input
* and also implement the logic of iterating over the tokens. Currently this is
* still done in the {@link TaggerFstCorpus}#analyze(..) method.
* <hr>
*
* @author Rupert Westenthaler
*/
class PhraseBuilder {
private final Logger log = LoggerFactory.getLogger(PhraseBuilder.class);
/**
* List with the phrases. This list is sorted by {@link Phrase#pStart}
*/
protected final List<Phrase> phrases;
/**
* Used to memorize the start offset of the first token(s) reported by the
* TokenStream
*/
private int startOffset = -1;
/**
* Internally used by {@link #branch(int, int, int)} and
* {@link #append(int, int, int)} to temporarily store {@link Phrase}. <p>
* Those methods use this field to avoid creating new {@link List}
* instances on each call.<p>
* Users of this field are expected to call {@link List#clear()} before
* usage.
*/
private List<Phrase> tempPhrases;
/**
* Creates a new PhraseBuilder instance with the initial capacity.
* Note that this instance should be reused by calling {@link #reset()}.
*
* @see #reset()
*/
public PhraseBuilder(int initialPathCapacity) {
phrases = new ArrayList<Phrase>(initialPathCapacity);
tempPhrases = new ArrayList<Phrase>(initialPathCapacity);
}
/**
* Adds the term to the phrase
*
* @param termId the integer termId representing the term.
* @param start the start offset for the term
* @param end the end offset of the term
* @param posInc the position increment of the term
* @param posLen the position length of the term (currently not used)
* @throws UnsupportedTokenException if the parsed term can not be processed
*/
public void addTerm(int termId, int start, int end, int posInc, int posLen) {
if (posInc > 0) { //new token position
if (phrases.isEmpty()) { // the first token
startOffset = start; //set the start offset
create(termId, start, end); //create a new Phrase
} else { //tokens with posInc > 0 need to be appended to existing phrases
if (!append(termId, start, end)) {
//this means that we do have multiple tokens for the same span (start
//and end offset).
log.error("Unable to append term[offset: [{},{}], posInc: {}, posLen {}] "
+ "to any phrase.", new Object[]{start, end, posInc, posLen});
log.error("This is caused by Terms with posInc > 0 but same "
+ "offsets already used by an other token. Please change the "
+ "configuration of your Analyzer chain.");
log.error("This can be cuased e.g. by:");
log.error(" > the SynonymFilter with configured multiple word mappings "
+ "(e.g. 'DNS => Domain Name Service'). In such cases it can be "
+ "solved by using the reverse mappings ('Domain Name Service => DNS')");
log.error(" > Using the WordDelimiterFilter to generate tokens that are "
+ "afterwards processed by the SynonymFilter.");
log.error(" > Applying the WordDelimiterFilter to tokens where the term. "
+ "length != endOffset - startOffset. In such cases the "
+ "WordDelimiterFilter does correct offset. This can e.g. be cuased "
+ "by the HyphenatedWordsFilter or the EnglishPossessiveFilter. "
+ "Generally it is recommended to use the WordDelimiterFilter "
+ "directly after the Tokenizer.");
log.error("For more information see also limitations section of "
+ "http://blog.mikemccandless.com/2012/04/"
+ "lucenes-tokenstreams-are-actually.html");
throw new UnsupportedTokenException("Encountered Term with "
+ "posInc > 0 but similar offset as existing one (see ERROR "
+ "level loggings for details and help!");
} //else successfully appended
}
} else { //tokens with posInc == 0 are alternatives to existing tokens
if (start == startOffset) { //if alternative starts at the beginning
create(termId, start, end); //simply create a new phrase
} else { //we need to create branches for existing phrases
branch(termId, start, end);
}
}
}
/**
* Creates a new phrase and adds the parsed term and registers it to
* {@link #phrases}. This method expects that
* <code>start == {@link #startOffset}</code>
*
* @return the created phrase
*/
private Phrase create(int termId, int start, int end) {
assert startOffset <= start;
if (!phrases.isEmpty()) {
//do not create multiple phrases for the same termId
int size = phrases.size();
for (int i = 0; i < size; i++) {
Phrase phrase = phrases.get(i);
if (phrase.length() == 1 && phrase.getTerm(0) == termId) {
return phrase;
}
}
}
Phrase phrase = new Phrase(8);
phrases.add(phrase);
phrase.pStart = start;
phrase.add(termId, start, end);
return phrase;
}
/**
* This appends a Token to existing phrases. It is expected to be called if the
* <code>{@link PositionIncrementAttribute#getPositionIncrement() posInc} > 0 </code>
* for the parsed term.<p>
* <b>NOTEs:</b> <ul>
* <li> This method can not guarantee that the parsed term is
* appended to any of the phrases. There are cases in that it is not possible
* to reconstruct phrases based on posInc, start and end offset of terms
* (e.g. for some {@link SynonymFilter} mappings). This method is able to
* detect such situations and will refuse to append according tokens. Callers
* can detect this by <code>false</code> being returned.<p>
* <li> This method is able to deal with multiple tokens using the same
* start/end offset as long as there are not multiple possible paths. This
* means e.g. that synonyms like 'Domain Name Service => DNS' will be
* correctly handled. However using analyzers generating such token streams
* are still problematic as they may result in unintended behaviour during
* search. See the 'Domain Name Service => DNS' example in the limitation
* section of <a href="http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html">
* Lucene's TokenStreams are actually graphs!</a> by Michael McCandless for
* details why this is the case.<br>
* </ul>
*
* @param termId the termId representing the term
* @param start the start index of the term
* @param end the end index of the term
* @return if the term was appended to any of the phrases.
*/
private boolean append(int termId, int start, int end) {
int addPos = -1; //stores the char offset of the phrase end where we append
int branchPos = -1;
tempPhrases.clear(); //need to clear before usage
for (int i = phrases.size() - 1; i >= 0; i--) {
Phrase phrase = phrases.get(i);
int phraseEnd = phrase.pEnd;
if (phraseEnd <= start) {
phrase.add(termId, start, end);
addPos = phraseEnd;
} else if (addPos >= 0) { //to avoid unnecessary iterations
//Tokens can only be appended to phrases ending in a single position.
//While multiple phrases might use this position, we can stop iterating
//as soon as phrases no longer have the same pEnd value after the
//parsed token was appended (addPos >= 0)
break;
} else if (phraseEnd == end) {
//save phrases with same end pos as the parsed term for further
//processing (see below)
tempPhrases.add(phrase);
} //else uninteresting token
//maybe we need to call branch later on ...
// ... so also calculate the possible branch position
int startPos = phrase.getPos(phrase.length() - 1);
if (startPos > branchPos && startPos <= start) {
branchPos = startPos;
}
}
if (addPos < 0) { //not added
//Two possible reasons:
//(1) there was an alternate token where this should have been appended
//but it was removed by a TokenFilter (e.g. "Mr. A.St." could get split
// to "Mr", "A.St.", "A", "St" and the StopFilterFactory would remove "A".
//So we might see a token "ST" with a posInc=1 with no token to
//append to as "Mr" is already taken by "A.St.".
//In this case what we need to do is to find the branchPos for the
//removed "A" token and append "ST" directly to that.
//(2) multiple tokens with posInc > 0 for tokens with the same
//span (start/end offset). This is typically the case if a single token
//in the text is split up to several. Those cases can only be correctly
//handled if all matching phrases have the same termId as otherwise
//we can not reconstruct the correct phrases.
//First test for case (2)
boolean isSameSpan = false; //used to check for (2)
if (!tempPhrases.isEmpty()) {
int tempSize = tempPhrases.size();
int addPhraseNum = -1;
long tId = Long.MIN_VALUE; //keep default<SUF>
boolean foundMultiple = false;
for (int i = 0; !foundMultiple && i < tempSize; i++) {
Phrase phrase = tempPhrases.get(i);
//check if the last token of this phrase has the same span
int index = phrase.length() - 1;
if (phrase.getPos(index) == start) { //check if start also matches
isSameSpan = true; //there is a token with the same span
//but first check for multiple phrases with different termIds
int id = phrase.getTerm(index);
if (tId == Long.MIN_VALUE) { //store the phraseId
tId = id;
} else if (id != tId) {
//encountered multiple phrases with different termIds
// ... stop here (error handling is done by calling method
foundMultiple = true;
} //else multiple phrases with same termId
//do not append immediately (because we should not change the state
//in case we will find multiple phrases with different termIds
addPhraseNum++;
if (addPhraseNum != i) { //write validated back to tempPhrases
tempPhrases.set(addPhraseNum, phrase);
} //else the current element is this one
} //only end matches -> not the same start/end offset -> ignore
}
if (!foundMultiple && addPhraseNum >= 0) {
addPos = end; //just to set addPos > 0
//now finally append to phrases with same span
for (int i = 0; i <= addPhraseNum; i++) {
tempPhrases.get(i).add(termId, start, end);
}
}
} //no span with the same end offset ... can only be case (1)
//handle case (1)
if (!isSameSpan) {
//NOTE that branchPos might not be available if the removed token
//was at the beginning of the text. So use the start offset of the
//parsed token if branchPos < 0
return branch(termId, branchPos < 0 ? start : branchPos, end);
}
}
return addPos >= 0;
}
/**
* Creates branch(es) for an alternate term at the parsed start/end char
* offsets. Also inserts created {@link Phrase}s to {@link #phrases} keeping
* elements in {@link #phrases} sorted by {@link Phrase#pStart}. No return
* value as the state will be stored in the {@link #phrases} collection.<p>
* Note this method is only called for {@link TokenStream}s with alternate
* tokens (<code>{@link PositionIncrementAttribute#getPositionIncrement() posInc}
* == 0</code>). So this rather complex operation will only be executed for
* labels that do result in such tokens.
*
* @param termId the termId to add right after the branch
* @param start the start of the term. Also the position of the branch
* @param end the end of the term
* @return <code>true</code> if the termId was successfully processed.
* Otherwise <code>false</code>
*/
private boolean branch(int termId, int start, int end) {
int size = phrases.size();
tempPhrases.clear(); //need to clear before using
boolean create = true; //if not a branch create a new phrase
//we need to create a branch for all phrases starting before the parsed term
int i = 0;
for (; i < size; i++) {
Phrase phrase = phrases.get(i);
if (phrase.pStart < start) {
if (phrase.hasPos(start)) {
create = false; // this is a branch
Phrase branch = phrase.clone();
branch.pStart = start;
if (branch.set(termId, start, end)) {
tempPhrases.add(branch);
} //else no need to branch, because the parsed termId equals
//the previous one.
} //else the phrase starts earlier, but does not have a term that ends
//at the start position of the current one (it skips this position
//with a term of a posLen > 1). So we do not need to create a branch.
} else if (phrase.pStart > start) {
//stop here, because it is the position in phrases where we need to
//start inserting the creates branches.
break;
}
}
if (create) {
return create(termId, start, end) != null;
} else { //insert branches into phrases
int bSize = tempPhrases.size();
if (bSize > 0) { //insert branch(es) in sorted phrases list
int numSwap = size - i;
for (int j = 0; j < bSize; j++, i++) {
if (i < size) {
//swap the 'j' element of branches with the 'i' of #phrases
tempPhrases.set(j, phrases.set(i, tempPhrases.get(j)));
} else {
phrases.add(tempPhrases.get(j));
}
}
for (; i < size; i++) { //add remaining elements in phrases as we need to
tempPhrases.add(phrases.get(i)); //append them to have a sorted list
}
//finally add Phrases swapped to branches to the end of #phrases
for (int j = 0; j < numSwap; j++) {
phrases.add(tempPhrases.get(j));
}
//now #phrases is again sorted by Phrase#pStart
} //else no branch created (branch would have same termId as existing one)
return true;
}
}
/**
* Getter for the {@link IntsRef}s of the phrases build from terms parsed to
* the {@link #addTerm(int, int, int, int, int)} method.
*
* @return An array containing the created phrases. Each phrase is represented
* by a {@link IntsRef}s of its termIds.
*/
public IntsRef[] getPhrases() {
int size = phrases.size();
IntsRef[] refs = new IntsRef[phrases.size()];
for (int i = 0; i < size; i++) {
refs[i] = phrases.get(i).getPath();
}
return refs;
}
/**
* Resets this {@link PhraseBuilder} instance to its initial state.
* This allows to reuse the same instance to build phrases for multiple
* {@link TokenStream}s.
*/
public void reset() {
phrases.clear();
startOffset = -1;
}
/**
* Private class used to build up a single phrase. An {@link IntsRef} is used
* to build up the phrase. Words are represented by the integer termId.
*
* @author Rupert Westenthaler
*/
static class Phrase implements Cloneable {
/**
* The path
*/
private final IntsRef path;
/**
* stores the start offsets of terms contained in this phrase. NOTE that
* this array only contains as many valid values as the number of
* termIds in {@link #path}.
*/
private int[] pos;
/**
* the current end offset of the phrase.
*/
protected int pEnd;
/**
* The index at that this phrase was created. This is the char offset where
* the first term of this phrase is different as of other phrases. This
* information is required to know when one needs to create alternate
* phrases for alternate tokens.
*/
protected int pStart;
/**
* Creates a new (empty) path with the given capacity
*/
Phrase(int initialCapacity) {
this(new IntsRef(initialCapacity), new int[initialCapacity], -1);
}
/**
* Internally used by {@link #clone()} to construct a new Phrase with
* data copied from the cloned instance.
*
* @param path
* @param pos
* @param pEnd
* @see #clone()
*/
private Phrase(IntsRef path, int[] pos, int pEnd) {
this.path = path;
this.pos = pos;
this.pEnd = pEnd;
this.pStart = -1;
}
/**
* Adds a term to the {@link IntsRef} representing the path
*
* @param termId the termId to add
* @param tEnd the end position of the term
*/
void add(int termId, int start, int end) {
// assert start >= pEnd; //the added term MUST be at the end of the Phrase
path.grow(++path.length); //add an element to the path
path.ints[path.length - 1] = termId;
if (pos.length < path.length) { //increase pos array size
pos = ArrayUtil.grow(pos);
}
pos[path.length - 1] = start;
pEnd = end;
}
/**
* Sets the term at the according position of the phrase. Also removes
* all follow up elements from the phrase
*
* @param termId the term represented by the termId
* @param start the start offset of the term. Will be used to determine the
* correct position within the phrase
* @param end the end offset of the term.
*/
boolean set(int termId, int start, int end) {
assert start < pEnd;
//backward lookup as we expect to replace the last element most of the time
for (int idx = path.length - 1; idx >= 0; idx--) {
if (pos[idx] <= start) { //found the index
int oldTermId = path.ints[idx];
if (oldTermId != termId) {
path.ints[idx] = termId;
path.length = idx + 1;
pEnd = end; //update the end
return true;
} else {
return false;
}
}
}
//save guard
throw new IllegalStateException("Should be unreachable. Please report as "
+ "a bug!");
}
int length() {
return path.length;
}
/**
* Checks if a term in this phrase has the given start position
*
* @param pos the position to check
* @return <code>true</code> if such a term exists. Otherwise <code>false</code>
*/
boolean hasPos(int pos) {
//search backwards in pos array as we expect this method will ask about
//the last term in the phrase. Only in rare cases about an earlier.
for (int idx = path.length - 1; idx >= 0; idx--) {
int value = this.pos[idx];
if (value == pos) {
return true;
}
if (value < pos) {
return false;
}
}
return false;
}
/**
* Returns the start offset of the term at the parsed index within the
* phrase.
*
* @param index the index
* @return
*/
int getPos(int index) {
return pos[index];
}
/**
* Gets the termId of a term in the phrase
*
* @param index the index of the element
* @return the termId
*/
int getTerm(int index) {
return path.ints[index];
}
/**
* The {@link IntsRef} representing this path
*
* @return
*/
public IntsRef getPath() {
return path;
}
/**
* The end position of this path
*
* @return
*/
public int getEnd() {
return pEnd;
}
/**
* A "deep" clone AKA copy. Uses same array size over-allocation.
*/
@Override
public Phrase clone() {
//Could use IntsRef.deepClone() but lets use same over-capacity
int[] pathClone = new int[path.ints.length]; //use same capacity
System.arraycopy(path.ints, 0, pathClone, 0, path.length); //copy data
//also clone the positions of the path
int[] posClone = new int[pos.length];//use same capacity
System.arraycopy(pos, 0, posClone, 0, path.length); //only path.length items
return new Phrase(new IntsRef(pathClone, 0, path.length), posClone, pEnd);
}
}
} |
55184_1 | package com.x.meeting.assemble.control.jaxrs.meeting;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.organization.Person;
import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.PropertyTools;
import com.x.meeting.assemble.control.wrapout.WrapOutMeeting;
import com.x.meeting.core.entity.MeetingConfigProperties;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.organization.OrganizationDefinition;
import com.x.base.core.project.organization.OrganizationDefinition.DistinguishedNameCategory;
import com.x.base.core.project.tools.ListTools;
import com.x.meeting.assemble.control.Business;
import com.x.meeting.core.entity.ConfirmStatus;
import com.x.meeting.core.entity.Meeting;
import com.x.meeting.core.entity.Meeting_;
abstract class BaseAction extends StandardJaxrsAction {
private static Logger logger = LoggerFactory.getLogger(BaseAction.class);
// @SuppressWarnings("unused")
// protected void notifyMeetingInviteMessage(Business business, Meeting meeting) throws Exception {
// if (ListTools.isNotEmpty(meeting.getInvitePersonList())) {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.nullToEmpty(meeting.getInvitePersonList())) {
// logger.debug("send old meeting invite message to:{}, message body:{}", str, meeting);
//// MeetingInviteMessage message = new MeetingInviteMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingCancelMessage(Business business, Meeting meeting) throws Exception {
// if (ListTools.isNotEmpty(meeting.getInvitePersonList())) {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
// // "会议室:" + room.getName() + ",会议地点:" + building.getName() +
// // building.getAddress() + ".",
// // "meetingReject");
//// MeetingCancelMessage message = new MeetingCancelMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingAcceptMessage(Business business, Meeting meeting, String person) throws Exception {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
// // Collaboration.notification(str, "会议接受提醒.", person + "接受会议邀请:" +
// // meeting.getSubject(),
// // "会议室:" + room.getName() + ",会议地点:" + building.getName() +
// // building.getAddress() + ".",
// // "meetingAccept");
//// MeetingAcceptMessage message = new MeetingAcceptMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
//
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingRejectMessage(Business business, Meeting meeting, String person) throws Exception {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
//// MeetingRejectMessage message = new MeetingRejectMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
protected List<String> convertToPerson(Business business, List<String> list) throws Exception {
List<String> os = new ArrayList<>();
DistinguishedNameCategory category = OrganizationDefinition.distinguishedNameCategory(list);
if (ListTools.isNotEmpty(category.getPersonList())) {
os.addAll(business.organization().person().list(category.getPersonList()));
}
if (ListTools.isNotEmpty(category.getIdentityList())) {
os.addAll(business.organization().person().listWithIdentity(category.getIdentityList()));
}
if (ListTools.isNotEmpty(category.getUnitList())) {
os.addAll(business.organization().person().listWithUnitSubDirect(category.getUnitList()));
}
if (ListTools.isNotEmpty(category.getGroupList())) {
os.addAll(business.organization().person().listWithGroup(category.getGroupList()));
}
if (ListTools.isNotEmpty(category.getUnknownList())) {
os.addAll(business.organization().person().list(category.getUnknownList()));
}
os = ListTools.trim(os, true, true);
return os;
}
protected Predicate filterManualCompleted(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
Boolean manualCompleted) {
if (null != manualCompleted) {
p = cb.and(p, cb.equal(root.get(Meeting_.manualCompleted), manualCompleted));
}
return p;
}
protected Predicate filterCheckinPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String checkinPerson) {
if (!StringUtils.isBlank(checkinPerson)) {
p = cb.and(p, cb.isMember(checkinPerson.trim(), root.get(Meeting_.checkinPersonList)));
}
return p;
}
protected Predicate filterAcceptPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
String acceptPersonList) {
if (!StringUtils.isBlank(acceptPersonList)) {
p = cb.and(p, cb.isMember(acceptPersonList.trim(), root.get(Meeting_.acceptPersonList)));
}
return p;
}
protected Predicate filterInvitePerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
String invitePersonList) {
if (!StringUtils.isBlank(invitePersonList)) {
p = cb.and(p, cb.isMember(invitePersonList.trim(), root.get(Meeting_.invitePersonList)));
}
return p;
}
protected Predicate filterApplicant(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String applicant) {
if (!StringUtils.isBlank(applicant)) {
p = cb.and(p, cb.equal(root.get(Meeting_.applicant), applicant));
}
return p;
}
protected Predicate filterConfirmStatus(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String confirmStatus) {
if (!StringUtils.isBlank(confirmStatus)) {
p = cb.and(p, cb.equal(root.get(Meeting_.confirmStatus), ConfirmStatus.valueOf(confirmStatus)));
}
return p;
}
protected Predicate filterCompletedTime(CriteriaBuilder cb, Root<Meeting> root, Predicate p, Date completedTime) {
if (null != completedTime) {
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Meeting_.completedTime), completedTime));
}
return p;
}
protected Predicate filterStartTime(CriteriaBuilder cb, Root<Meeting> root, Predicate p, Date startTime) {
if (null != startTime) {
p = cb.and(p, cb.greaterThanOrEqualTo(root.get(Meeting_.startTime), startTime));
}
return p;
}
protected Predicate filterMeetingStatus(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String meetingStatus) {
if (meetingStatus.equalsIgnoreCase("completed")) {
p = cb.and(p, cb.or(cb.lessThan(root.get(Meeting_.completedTime), new Date()),
cb.equal(root.get(Meeting_.manualCompleted), true)));
}
if (meetingStatus.equalsIgnoreCase("processing")) {
Date date = new Date();
p = cb.and(p, cb.notEqual(root.get(Meeting_.manualCompleted), true));
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Meeting_.startTime), date));
p = cb.and(p, cb.greaterThanOrEqualTo(root.get(Meeting_.completedTime), date));
}
if (meetingStatus.equalsIgnoreCase("wait")) {
p = cb.and(p, cb.notEqual(root.get(Meeting_.manualCompleted), true));
p = cb.and(p, cb.greaterThan(root.get(Meeting_.startTime), new Date()));
}
return p;
}
protected Predicate filterRoom(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String room) {
if (!StringUtils.isBlank(room)) {
p = cb.and(p, cb.equal(root.get(Meeting_.room), room));
}
return p;
}
protected Predicate filterSubject(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String subject) {
if (!StringUtils.isBlank(subject)) {
p = cb.and(p, cb.like(root.get(Meeting_.subject), "%" + subject + "%"));
}
return p;
}
protected Predicate filterHostUnit(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String hostUnit) {
if (!StringUtils.isBlank(hostUnit)) {
p = cb.and(p, cb.like(root.get(Meeting_.hostUnit), "%" + hostUnit + "%"));
}
return p;
}
protected Predicate filterHostPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String hostPerson) {
if (!StringUtils.isBlank(hostPerson)) {
p = cb.and(p, cb.like(root.get(Meeting_.hostPerson), "%" + hostPerson + "%"));
}
return p;
}
protected Predicate filterType(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String type) {
if (!StringUtils.isBlank(type)) {
p = cb.and(p, cb.like(root.get(Meeting_.type), "%" + type + "%"));
}
return p;
}
protected String generateHstPwd(String userId) throws Exception{
String content = userId+"#"+System.currentTimeMillis();
return Crypto.rsaEncrypt(content, Config.publicKey());
}
protected void setOnlineLink(Business business, EffectivePerson effectivePerson, List<? extends WrapOutMeeting> wos) throws Exception{
MeetingConfigProperties config = business.getConfig();
if(config.onLineEnabled()){
for(WrapOutMeeting wo : wos) {
if(StringUtils.isBlank(wo.getRoomLink())){
continue;
}
if (BooleanUtils.isTrue(config.getOnlineConfig().getHstAuth())) {
Person person = business.organization().person().getObject(effectivePerson.getDistinguishedName());
String userId = PropertyTools.getOrElse(person, config.getOnlineConfig().getO2ToHstUid(), String.class, person.getUnique());
userId = StringUtils.isNoneBlank(userId) ? userId : person.getUnique();
wo.setRoomLink(wo.getRoomLink() + "&userName=" + userId + "&userPwd=" + URLEncoder.encode(generateHstPwd(userId), DefaultCharset.charset));
} else {
wo.setRoomLink(wo.getRoomLink() + "&userName=" + effectivePerson.getName());
}
}
}
}
}
| o2oa/o2oa | o2server/x_meeting_assemble_control/src/main/java/com/x/meeting/assemble/control/jaxrs/meeting/BaseAction.java | 3,629 | // if (ListTools.isNotEmpty(meeting.getInvitePersonList())) { | line_comment | nl | package com.x.meeting.assemble.control.jaxrs.meeting;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.organization.Person;
import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.PropertyTools;
import com.x.meeting.assemble.control.wrapout.WrapOutMeeting;
import com.x.meeting.core.entity.MeetingConfigProperties;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.organization.OrganizationDefinition;
import com.x.base.core.project.organization.OrganizationDefinition.DistinguishedNameCategory;
import com.x.base.core.project.tools.ListTools;
import com.x.meeting.assemble.control.Business;
import com.x.meeting.core.entity.ConfirmStatus;
import com.x.meeting.core.entity.Meeting;
import com.x.meeting.core.entity.Meeting_;
abstract class BaseAction extends StandardJaxrsAction {
private static Logger logger = LoggerFactory.getLogger(BaseAction.class);
// @SuppressWarnings("unused")
// protected void notifyMeetingInviteMessage(Business business, Meeting meeting) throws Exception {
// if (ListTools.isNotEmpty(meeting.getInvitePersonList()))<SUF>
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.nullToEmpty(meeting.getInvitePersonList())) {
// logger.debug("send old meeting invite message to:{}, message body:{}", str, meeting);
//// MeetingInviteMessage message = new MeetingInviteMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingCancelMessage(Business business, Meeting meeting) throws Exception {
// if (ListTools.isNotEmpty(meeting.getInvitePersonList())) {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
// // "会议室:" + room.getName() + ",会议地点:" + building.getName() +
// // building.getAddress() + ".",
// // "meetingReject");
//// MeetingCancelMessage message = new MeetingCancelMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingAcceptMessage(Business business, Meeting meeting, String person) throws Exception {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
// // Collaboration.notification(str, "会议接受提醒.", person + "接受会议邀请:" +
// // meeting.getSubject(),
// // "会议室:" + room.getName() + ",会议地点:" + building.getName() +
// // building.getAddress() + ".",
// // "meetingAccept");
//// MeetingAcceptMessage message = new MeetingAcceptMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
//
// }
// @SuppressWarnings("unused")
// protected void notifyMeetingRejectMessage(Business business, Meeting meeting, String person) throws Exception {
// Room room = business.entityManagerContainer().find(meeting.getRoom(), Room.class, ExceptionWhen.not_found);
// Building building = business.entityManagerContainer().find(room.getBuilding(), Building.class,
// ExceptionWhen.not_found);
// for (String str : ListTools.trim(meeting.getInvitePersonList(), true, true, meeting.getApplicant())) {
//// MeetingRejectMessage message = new MeetingRejectMessage(str, building.getId(), room.getId(),
//// meeting.getId());
//// Collaboration.send(message);
// }
// }
protected List<String> convertToPerson(Business business, List<String> list) throws Exception {
List<String> os = new ArrayList<>();
DistinguishedNameCategory category = OrganizationDefinition.distinguishedNameCategory(list);
if (ListTools.isNotEmpty(category.getPersonList())) {
os.addAll(business.organization().person().list(category.getPersonList()));
}
if (ListTools.isNotEmpty(category.getIdentityList())) {
os.addAll(business.organization().person().listWithIdentity(category.getIdentityList()));
}
if (ListTools.isNotEmpty(category.getUnitList())) {
os.addAll(business.organization().person().listWithUnitSubDirect(category.getUnitList()));
}
if (ListTools.isNotEmpty(category.getGroupList())) {
os.addAll(business.organization().person().listWithGroup(category.getGroupList()));
}
if (ListTools.isNotEmpty(category.getUnknownList())) {
os.addAll(business.organization().person().list(category.getUnknownList()));
}
os = ListTools.trim(os, true, true);
return os;
}
protected Predicate filterManualCompleted(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
Boolean manualCompleted) {
if (null != manualCompleted) {
p = cb.and(p, cb.equal(root.get(Meeting_.manualCompleted), manualCompleted));
}
return p;
}
protected Predicate filterCheckinPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String checkinPerson) {
if (!StringUtils.isBlank(checkinPerson)) {
p = cb.and(p, cb.isMember(checkinPerson.trim(), root.get(Meeting_.checkinPersonList)));
}
return p;
}
protected Predicate filterAcceptPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
String acceptPersonList) {
if (!StringUtils.isBlank(acceptPersonList)) {
p = cb.and(p, cb.isMember(acceptPersonList.trim(), root.get(Meeting_.acceptPersonList)));
}
return p;
}
protected Predicate filterInvitePerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p,
String invitePersonList) {
if (!StringUtils.isBlank(invitePersonList)) {
p = cb.and(p, cb.isMember(invitePersonList.trim(), root.get(Meeting_.invitePersonList)));
}
return p;
}
protected Predicate filterApplicant(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String applicant) {
if (!StringUtils.isBlank(applicant)) {
p = cb.and(p, cb.equal(root.get(Meeting_.applicant), applicant));
}
return p;
}
protected Predicate filterConfirmStatus(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String confirmStatus) {
if (!StringUtils.isBlank(confirmStatus)) {
p = cb.and(p, cb.equal(root.get(Meeting_.confirmStatus), ConfirmStatus.valueOf(confirmStatus)));
}
return p;
}
protected Predicate filterCompletedTime(CriteriaBuilder cb, Root<Meeting> root, Predicate p, Date completedTime) {
if (null != completedTime) {
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Meeting_.completedTime), completedTime));
}
return p;
}
protected Predicate filterStartTime(CriteriaBuilder cb, Root<Meeting> root, Predicate p, Date startTime) {
if (null != startTime) {
p = cb.and(p, cb.greaterThanOrEqualTo(root.get(Meeting_.startTime), startTime));
}
return p;
}
protected Predicate filterMeetingStatus(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String meetingStatus) {
if (meetingStatus.equalsIgnoreCase("completed")) {
p = cb.and(p, cb.or(cb.lessThan(root.get(Meeting_.completedTime), new Date()),
cb.equal(root.get(Meeting_.manualCompleted), true)));
}
if (meetingStatus.equalsIgnoreCase("processing")) {
Date date = new Date();
p = cb.and(p, cb.notEqual(root.get(Meeting_.manualCompleted), true));
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Meeting_.startTime), date));
p = cb.and(p, cb.greaterThanOrEqualTo(root.get(Meeting_.completedTime), date));
}
if (meetingStatus.equalsIgnoreCase("wait")) {
p = cb.and(p, cb.notEqual(root.get(Meeting_.manualCompleted), true));
p = cb.and(p, cb.greaterThan(root.get(Meeting_.startTime), new Date()));
}
return p;
}
protected Predicate filterRoom(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String room) {
if (!StringUtils.isBlank(room)) {
p = cb.and(p, cb.equal(root.get(Meeting_.room), room));
}
return p;
}
protected Predicate filterSubject(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String subject) {
if (!StringUtils.isBlank(subject)) {
p = cb.and(p, cb.like(root.get(Meeting_.subject), "%" + subject + "%"));
}
return p;
}
protected Predicate filterHostUnit(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String hostUnit) {
if (!StringUtils.isBlank(hostUnit)) {
p = cb.and(p, cb.like(root.get(Meeting_.hostUnit), "%" + hostUnit + "%"));
}
return p;
}
protected Predicate filterHostPerson(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String hostPerson) {
if (!StringUtils.isBlank(hostPerson)) {
p = cb.and(p, cb.like(root.get(Meeting_.hostPerson), "%" + hostPerson + "%"));
}
return p;
}
protected Predicate filterType(CriteriaBuilder cb, Root<Meeting> root, Predicate p, String type) {
if (!StringUtils.isBlank(type)) {
p = cb.and(p, cb.like(root.get(Meeting_.type), "%" + type + "%"));
}
return p;
}
protected String generateHstPwd(String userId) throws Exception{
String content = userId+"#"+System.currentTimeMillis();
return Crypto.rsaEncrypt(content, Config.publicKey());
}
protected void setOnlineLink(Business business, EffectivePerson effectivePerson, List<? extends WrapOutMeeting> wos) throws Exception{
MeetingConfigProperties config = business.getConfig();
if(config.onLineEnabled()){
for(WrapOutMeeting wo : wos) {
if(StringUtils.isBlank(wo.getRoomLink())){
continue;
}
if (BooleanUtils.isTrue(config.getOnlineConfig().getHstAuth())) {
Person person = business.organization().person().getObject(effectivePerson.getDistinguishedName());
String userId = PropertyTools.getOrElse(person, config.getOnlineConfig().getO2ToHstUid(), String.class, person.getUnique());
userId = StringUtils.isNoneBlank(userId) ? userId : person.getUnique();
wo.setRoomLink(wo.getRoomLink() + "&userName=" + userId + "&userPwd=" + URLEncoder.encode(generateHstPwd(userId), DefaultCharset.charset));
} else {
wo.setRoomLink(wo.getRoomLink() + "&userName=" + effectivePerson.getName());
}
}
}
}
}
|
15147_7 | package osoc.leiedal.android.aandacht.View;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
import osoc.leiedal.android.aandacht.R;
import osoc.leiedal.android.aandacht.View.fragments.ReportTabFragment;
public class ViewReportsActivity extends ParentActivity implements View.OnCreateContextMenuListener {
/* ============================================================================================
NESTED CLASSES
============================================================================================ */
private class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {
getResources().getString(R.string.tab_reports_active),
getResources().getString(R.string.tab_reports_all),
getResources().getString(R.string.tab_reports_mine)
};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
return ReportTabFragment.instantiate(position);
}
}
/* ============================================================================================
METHODS
============================================================================================ */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.view_reports, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
//clear login data
getSharedPreferences(getResources().getString(R.string.app_pref), 0).edit().clear().commit();
this.startActivity(new Intent(this, LoginActivity.class));
}
public void call(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reports_popup_title);
builder.setMessage(R.string.reports_popup_text);
builder.setPositiveButton(R.string.reports_btnCall, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0478927411"));
startActivity(callIntent);
}
});
builder.setNegativeButton(R.string.reports_popup_btnCancel, null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.show();
}
// --------------------------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get reports in area
setContentView(R.layout.activity_view_reports);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
tabs.setIndicatorColor(getResources().getColor(R.color.aandacht_dark_blue));
tabs.setTextColor(getResources().getColor(R.color.aandacht_dark_blue));
tabs.setBackgroundColor(getResources().getColor(R.color.aandacht_background));
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
@Override
protected void onResume() {
super.onResume();
}
// UNUSED METHOD
/**
public void send(final View view) {
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action",
"com.google.android.gcm.demo.app.ECHO_NOW");
String id = Long.toString(System.currentTimeMillis());
GoogleCloudMessaging.getInstance(getApplicationContext())
.send(LoginActivity.SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
*/
}
| oSoc14/Leiedal-ComProNet-Android | Aandacht/app/src/main/java/osoc/leiedal/android/aandacht/View/ViewReportsActivity.java | 1,544 | //get reports in area | line_comment | nl | package osoc.leiedal.android.aandacht.View;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
import osoc.leiedal.android.aandacht.R;
import osoc.leiedal.android.aandacht.View.fragments.ReportTabFragment;
public class ViewReportsActivity extends ParentActivity implements View.OnCreateContextMenuListener {
/* ============================================================================================
NESTED CLASSES
============================================================================================ */
private class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {
getResources().getString(R.string.tab_reports_active),
getResources().getString(R.string.tab_reports_all),
getResources().getString(R.string.tab_reports_mine)
};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
return ReportTabFragment.instantiate(position);
}
}
/* ============================================================================================
METHODS
============================================================================================ */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.view_reports, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
//clear login data
getSharedPreferences(getResources().getString(R.string.app_pref), 0).edit().clear().commit();
this.startActivity(new Intent(this, LoginActivity.class));
}
public void call(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reports_popup_title);
builder.setMessage(R.string.reports_popup_text);
builder.setPositiveButton(R.string.reports_btnCall, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0478927411"));
startActivity(callIntent);
}
});
builder.setNegativeButton(R.string.reports_popup_btnCancel, null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.show();
}
// --------------------------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get reports<SUF>
setContentView(R.layout.activity_view_reports);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
tabs.setIndicatorColor(getResources().getColor(R.color.aandacht_dark_blue));
tabs.setTextColor(getResources().getColor(R.color.aandacht_dark_blue));
tabs.setBackgroundColor(getResources().getColor(R.color.aandacht_background));
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
@Override
protected void onResume() {
super.onResume();
}
// UNUSED METHOD
/**
public void send(final View view) {
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action",
"com.google.android.gcm.demo.app.ECHO_NOW");
String id = Long.toString(System.currentTimeMillis());
GoogleCloudMessaging.getInstance(getApplicationContext())
.send(LoginActivity.SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
*/
}
|
131342_10 | package com.opentransport.rdfmapper.nmbs;
import com.opentransport.rdfmapper.nmbs.containers.LiveBoard;
import com.opentransport.rdfmapper.nmbs.containers.NextStop;
import com.opentransport.rdfmapper.nmbs.containers.Service;
import com.opentransport.rdfmapper.nmbs.containers.Stop;
import com.opentransport.rdfmapper.nmbs.containers.TrainId;
import com.opentransport.rdfmapper.nmbs.containers.TrainInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
*
* @author Nicola De Clercq
*/
public class LiveBoardFetcher {
private static final int NUMBER_OF_CONNECTIONS = 100;
private static final int CONNECTION_TIMEOUT_IN_MILLISECONDS = 3000;
private static final long POOL_TIMEOUT = 60;
private int trainsDelayed =1;
private int trainsCancelled =1;
private Map<String,String> trainDelays = new HashMap();
private Map<String,String> trainCanceled = new HashMap();
private Map<String,String> totalTrains = new HashMap();
private Map<String,String> trainDelayed = new HashMap();
private Map<TrainId,TrainInfo> trainCache;
private Map<String,String> sources;
private Map<String,String> retries;
public LiveBoardFetcher() {
trainCache = new ConcurrentHashMap<>();
sources = new ConcurrentHashMap<>();
retries = new ConcurrentHashMap<>();
}
public List<LiveBoard> getLiveBoards(List<String> stationIds, String date, String time, int numberOfResults) {
sources.clear();
trainCache.clear();
retries.clear();
ExecutorService sourcesPool = Executors.newFixedThreadPool(NUMBER_OF_CONNECTIONS);
long start1 = System.currentTimeMillis();
for (int i = 0; i < stationIds.size(); i++) {
final int number = i + 1;
final String stationId = stationIds.get(i);
final String link = "http://www.belgianrail.be/jpm/sncb-nmbs-routeplanner/stboard.exe/nox"
+ "?input=" + stationId + "&date=" + date + "&time=" + time
+ "&maxJourneys=" + numberOfResults + "&boardType=dep"
+ "&productsFilter=0111111000&start=yes";
sourcesPool.execute(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String source = getUrlSource(link);
if (source != null) {
sources.put(stationId,source);
}
else {
retries.put(stationId,link);
}
long end = System.currentTimeMillis();
// System.out.println("LIVEBOARD FETCH " + number + " (" + (end - start) + " ms)");
}
});
}
sourcesPool.shutdown();
try {
sourcesPool.awaitTermination(POOL_TIMEOUT,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
ExecutorService retriesPool = Executors.newFixedThreadPool(2);
for (Entry e : retries.entrySet()) {
final String stationId = (String) e.getKey();
final String link = (String) e.getValue();
retriesPool.execute(new Runnable() {
@Override
public void run() {
String source = getUrlSource(link);
if (source != null) {
sources.put(stationId,source);
// System.out.println("RETRIED " + stationId);
}
else {
String newLink = link.replaceAll("&maxJourneys=[0-9]*","&maxJourneys=10");
String newSource = getUrlSource(newLink);
if (newSource != null) {
sources.put(stationId,newSource);
System.out.println("ONLY 10 SERVICES "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
else {
sources.put(stationId,"");
System.out.println("FAILED "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
}
}
});
}
retriesPool.shutdown();
try {
retriesPool.awaitTermination(POOL_TIMEOUT / 2,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
long end1 = System.currentTimeMillis();
System.out.println("LIVEBOARD FETCHING (" + (end1 - start1) + " ms)");
System.out.println("NUMBER OF LIVEBOARDS: " + sources.size());
long start2 = System.currentTimeMillis();
ExecutorService trainCachePool = Executors.newFixedThreadPool(NUMBER_OF_CONNECTIONS);
for (int i = 0; i < stationIds.size(); i++) {
final int numberI = i + 1;
String stationId = stationIds.get(i);
Document doc = Jsoup.parse(sources.get(stationId));
Elements trains = doc.select(".journey");
for (int j = 0; j < trains.size(); j++) {
final int numberJ = j + 1;
Element train = trains.get(j);
Elements trainA = train.select("a");
final String trainLink = trainA.attr("href");
final String trainNumber = trainA.text();
//Train Number is Trip ID
String stationInfo = train.ownText().replaceAll(">","").trim();
String trainTarget = stationInfo;
int split = stationInfo.indexOf(" perron ");
if (split != -1) {
trainTarget = stationInfo.substring(0,split);
}
final String destination = trainTarget;
String trainDelay = train.select(".delay").text().replaceAll("\\+","");
totalTrains.put(trainNumber, trainDelay);
if (trainDelay.length() > 0) {
if (trainDelay.equals("0")) {
}else{
try{
int num = Integer.parseInt(trainDelay);
trainDelayed.put(trainNumber, "Afgeschaft");
} catch (NumberFormatException e) {
// not an integer!
}
//System.out.println("Current Delay is " + trainDelay + "minutes for train " + trainNumber);
trainDelays.put(trainNumber, trainDelay);
}
}
if (trainDelay.equals("Afgeschaft")) {
// System.out.println("Cancelled Train Found " + trainNumber);
trainDelays.put(trainNumber, "Afgeschaft");
trainCanceled.put(trainNumber, "Afgeschaft");
}
if (!trainDelay.equals("Afgeschaft")) {
trainCachePool.execute(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
if (!trainCache.containsKey(new TrainId(trainNumber,destination))) {
insertTrain(trainNumber,destination,trainLink);
}
long end = System.currentTimeMillis();
// System.out.println("TRAIN FETCH " + numberI + " - " + numberJ + " (" + (end - start) + " ms)");
}
});
}
}
}
System.out.println("Trains cancelled " + trainCanceled.size());
System.out.println("Trains delayed " + trainDelayed.size());
double percentageOfDelays = 0+ trainDelays.size();
System.out.println("Total number of trains " + totalTrains.size());
percentageOfDelays = (percentageOfDelays / totalTrains.size()) *100;
System.out.println("Percentage of Trains having issues is " +percentageOfDelays);
System.out.println("Finished Reading Trains number of trains having issues is "+ trainDelays.size() +" ");
ScrapeTrip scrapeDelayedTrains = new ScrapeTrip();
scrapeDelayedTrains.startScrape(trainDelays);
trainCachePool.shutdown();
try {
trainCachePool.awaitTermination(POOL_TIMEOUT,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
long end2 = System.currentTimeMillis();
long start3 = System.currentTimeMillis();
List<LiveBoard> liveBoards = new ArrayList<>();
// for (int i = 0; i < stationIds.size(); i++) {
// // LiveBoard liveBoard = parseLiveBoard(stationIds.get(i));
// // liveBoards.add(liveBoard);
// }
long end3 = System.currentTimeMillis();
return liveBoards;
}
public LiveBoard getLiveBoard(String stationId, String date, String time, int numberOfResults) {
ArrayList<String> stations = new ArrayList<>();
stations.add(stationId);
List<LiveBoard> liveBoards = getLiveBoards(stations,date,time,numberOfResults);
return liveBoards.get(0);
}
private LiveBoard parseLiveBoard(String stationId) {
LiveBoard liveBoard = new LiveBoard();
List<Service> services = new ArrayList<>();
liveBoard.setStationInfo(StationDatabase.getInstance().getStationInfo(stationId));
Document doc = Jsoup.parse(sources.get(stationId));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm,dd/MM/yy");
Calendar time = Calendar.getInstance();
String[] timeA = null;
if (doc.select(".qs").isEmpty()) {
System.out.println("ERROR IN LIVEBOARD "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
else {
Element timeE = doc.select(".qs").get(0);
String timeS = timeE.ownText().replaceAll("Vertrek ","");
timeA = timeS.split(",");
try {
Date t = sdf.parse(timeS);
time.setTime(t);
} catch (ParseException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
}
Elements trains = doc.select(".journey");
for (int i = 0; i < trains.size(); i++) {
Service service = new Service();
Element train = trains.get(i);
Elements trainA = train.select("a");
service.setTrainNumber(trainA.text());
String stationInfo = train.ownText().replaceAll(">","").trim();
String trainTarget = stationInfo;
String trainPlatform = "";
int split = stationInfo.indexOf(" perron ");
if (split != -1) {
trainTarget = stationInfo.substring(0,split);
trainPlatform = stationInfo.substring(split + 8);
}
else {
String platf = train.select(".platformChange").text().replaceAll("perron ","");
if (!platf.isEmpty()) {
trainPlatform = platf;
}
}
service.setDestination(trainTarget);
service.setPlatform(trainPlatform);
service.setScheduledDepartureTime(train.select("strong").get(1).text());
String trainDelay = train.select(".delay").text().replaceAll("\\+","");
service.setDelay(trainDelay);
service.setNextStop(getNextStop(service.getTrainNumber(),
service.getDestination(),liveBoard.getStationInfo().getName()));
if (trainDelay.equals("Afgeschaft")) {
service.setDelay("CANCELLED");
if (service.getNextStop() != null) {
service.getNextStop().setDelay("CANCELLED");
}
}
//ISO 8601
SimpleDateFormat isoSDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Calendar depC = Calendar.getInstance();
try {
Date d = sdf.parse(service.getScheduledDepartureTime() + "," + timeA[1]);
depC.setTime(d);
} catch (ParseException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
Calendar actualDepC = (Calendar) depC.clone();
int departureDelay = 0;
try {
departureDelay = Integer.parseInt(service.getDelay());
} catch (NumberFormatException ex) {
}
actualDepC.add(Calendar.MINUTE,departureDelay);
if (actualDepC.before(time)) {
depC.add(Calendar.DATE,1);
actualDepC.add(Calendar.DATE,1);
}
else {
Calendar temp = (Calendar) time.clone();
temp.add(Calendar.DATE,1);
if (!temp.after(actualDepC)) {
depC.add(Calendar.DATE,-1);
actualDepC.add(Calendar.DATE,-1);
}
}
service.setScheduledDepartureTime(isoSDF.format(depC.getTime()));
service.setActualDepartureTime(isoSDF.format(actualDepC.getTime()));
if (service.getNextStop() != null) {
Calendar arrC = (Calendar) depC.clone();
String[] arrTime = service.getNextStop().getScheduledArrivalTime().split(":");
arrC.set(Calendar.HOUR_OF_DAY,Integer.parseInt(arrTime[0]));
arrC.set(Calendar.MINUTE,Integer.parseInt(arrTime[1]));
Calendar actualArrC = (Calendar) arrC.clone();
int arrivalDelay = 0;
try {
arrivalDelay = Integer.parseInt(service.getNextStop().getDelay());
} catch (NumberFormatException ex) {
}
actualArrC.add(Calendar.MINUTE,arrivalDelay);
while (arrC.before(depC)) {
arrC.add(Calendar.DATE,1);
}
while (actualArrC.before(actualDepC)) {
actualArrC.add(Calendar.DATE,1);
}
service.getNextStop().setScheduledArrivalTime(isoSDF.format(arrC.getTime()));
service.getNextStop().setActualArrivalTime(isoSDF.format(actualArrC.getTime()));
}
services.add(service);
}
liveBoard.setServices(services);
return liveBoard;
}
private NextStop getNextStop(String trainNumber, String destination, String stationName) {
TrainInfo info = trainCache.get(new TrainId(trainNumber,destination));
if (info != null) {
List<Stop> stops = info.getStops();
for (int i = 0; i < stops.size(); i++) {
if (stops.get(i).getName().equals(stationName)) {
Stop stop = stops.get(i + 1);
NextStop nextStop = new NextStop();
nextStop.setName(stop.getName());
nextStop.setScheduledArrivalTime(stop.getArrivalTime());
nextStop.setDelay(stop.getArrivalDelay());
nextStop.setPlatform(stop.getPlatform());
return nextStop;
}
}
}
return null;
}
private void insertTrain(String trainNumber, String destination, String trainLink) {
List<Stop> stopsList = new ArrayList<>();
Document doc = Jsoup.parse(getUrlSource(trainLink.replaceAll("sqIdx=[0-9]*","sqIdx=0")));
Elements route = doc.select(".trainRoute");
if (route.isEmpty()) {
return;
}
Elements stops = route.get(0).select("tr");
for (int i = 0; i < stops.size(); i++) {
Elements tds = stops.get(i).select("td");
if (tds.size() == 5) {
Element arrivalTimeTd = tds.get(2);
String arrivalTime = arrivalTimeTd.ownText().replaceAll("\u00A0","");
Element departureTimeTd = tds.get(3);
String departureTime = departureTimeTd.ownText().replaceAll("\u00A0","");
if (arrivalTime.matches("[0-9][0-9]:[0-9][0-9]") || departureTime.matches("[0-9][0-9]:[0-9][0-9]")) {
Stop stop = new Stop();
stop.setName(tds.get(1).text());
stop.setArrivalTime(arrivalTime);
stop.setArrivalDelay(arrivalTimeTd.select(".delay").text().replaceAll("\\+",""));
stop.setDepartureTime(departureTime);
stop.setDepartureDelay(departureTimeTd.select(".delay").text().replaceAll("\\+",""));
stop.setPlatform(tds.get(4).text().replaceAll("\u00A0",""));
stopsList.add(stop);
}
}
}
trainCache.put(new TrainId(trainNumber,destination),new TrainInfo(trainNumber,destination,stopsList));
}
private String getUrlSource(String link) {
URL url = null;
try {
url = new URL(link);
} catch (MalformedURLException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT_IN_MILLISECONDS);
conn.setConnectTimeout(CONNECTION_TIMEOUT_IN_MILLISECONDS);
} catch (IOException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
BufferedReader br;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
} catch (IOException ex) {
// Probeert het ophalen van de pagina opnieuw
// System.out.println("########## RETRY ##########");
return getUrlSource(link);
}
String source = sb.toString();
if (source.contains("<title>Fout</title>")) {
return null;
}
return source;
}
} | oSoc15/brail2gtfs-rt | src/main/java/com/opentransport/rdfmapper/nmbs/LiveBoardFetcher.java | 5,669 | // Probeert het ophalen van de pagina opnieuw | line_comment | nl | package com.opentransport.rdfmapper.nmbs;
import com.opentransport.rdfmapper.nmbs.containers.LiveBoard;
import com.opentransport.rdfmapper.nmbs.containers.NextStop;
import com.opentransport.rdfmapper.nmbs.containers.Service;
import com.opentransport.rdfmapper.nmbs.containers.Stop;
import com.opentransport.rdfmapper.nmbs.containers.TrainId;
import com.opentransport.rdfmapper.nmbs.containers.TrainInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
*
* @author Nicola De Clercq
*/
public class LiveBoardFetcher {
private static final int NUMBER_OF_CONNECTIONS = 100;
private static final int CONNECTION_TIMEOUT_IN_MILLISECONDS = 3000;
private static final long POOL_TIMEOUT = 60;
private int trainsDelayed =1;
private int trainsCancelled =1;
private Map<String,String> trainDelays = new HashMap();
private Map<String,String> trainCanceled = new HashMap();
private Map<String,String> totalTrains = new HashMap();
private Map<String,String> trainDelayed = new HashMap();
private Map<TrainId,TrainInfo> trainCache;
private Map<String,String> sources;
private Map<String,String> retries;
public LiveBoardFetcher() {
trainCache = new ConcurrentHashMap<>();
sources = new ConcurrentHashMap<>();
retries = new ConcurrentHashMap<>();
}
public List<LiveBoard> getLiveBoards(List<String> stationIds, String date, String time, int numberOfResults) {
sources.clear();
trainCache.clear();
retries.clear();
ExecutorService sourcesPool = Executors.newFixedThreadPool(NUMBER_OF_CONNECTIONS);
long start1 = System.currentTimeMillis();
for (int i = 0; i < stationIds.size(); i++) {
final int number = i + 1;
final String stationId = stationIds.get(i);
final String link = "http://www.belgianrail.be/jpm/sncb-nmbs-routeplanner/stboard.exe/nox"
+ "?input=" + stationId + "&date=" + date + "&time=" + time
+ "&maxJourneys=" + numberOfResults + "&boardType=dep"
+ "&productsFilter=0111111000&start=yes";
sourcesPool.execute(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String source = getUrlSource(link);
if (source != null) {
sources.put(stationId,source);
}
else {
retries.put(stationId,link);
}
long end = System.currentTimeMillis();
// System.out.println("LIVEBOARD FETCH " + number + " (" + (end - start) + " ms)");
}
});
}
sourcesPool.shutdown();
try {
sourcesPool.awaitTermination(POOL_TIMEOUT,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
ExecutorService retriesPool = Executors.newFixedThreadPool(2);
for (Entry e : retries.entrySet()) {
final String stationId = (String) e.getKey();
final String link = (String) e.getValue();
retriesPool.execute(new Runnable() {
@Override
public void run() {
String source = getUrlSource(link);
if (source != null) {
sources.put(stationId,source);
// System.out.println("RETRIED " + stationId);
}
else {
String newLink = link.replaceAll("&maxJourneys=[0-9]*","&maxJourneys=10");
String newSource = getUrlSource(newLink);
if (newSource != null) {
sources.put(stationId,newSource);
System.out.println("ONLY 10 SERVICES "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
else {
sources.put(stationId,"");
System.out.println("FAILED "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
}
}
});
}
retriesPool.shutdown();
try {
retriesPool.awaitTermination(POOL_TIMEOUT / 2,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
long end1 = System.currentTimeMillis();
System.out.println("LIVEBOARD FETCHING (" + (end1 - start1) + " ms)");
System.out.println("NUMBER OF LIVEBOARDS: " + sources.size());
long start2 = System.currentTimeMillis();
ExecutorService trainCachePool = Executors.newFixedThreadPool(NUMBER_OF_CONNECTIONS);
for (int i = 0; i < stationIds.size(); i++) {
final int numberI = i + 1;
String stationId = stationIds.get(i);
Document doc = Jsoup.parse(sources.get(stationId));
Elements trains = doc.select(".journey");
for (int j = 0; j < trains.size(); j++) {
final int numberJ = j + 1;
Element train = trains.get(j);
Elements trainA = train.select("a");
final String trainLink = trainA.attr("href");
final String trainNumber = trainA.text();
//Train Number is Trip ID
String stationInfo = train.ownText().replaceAll(">","").trim();
String trainTarget = stationInfo;
int split = stationInfo.indexOf(" perron ");
if (split != -1) {
trainTarget = stationInfo.substring(0,split);
}
final String destination = trainTarget;
String trainDelay = train.select(".delay").text().replaceAll("\\+","");
totalTrains.put(trainNumber, trainDelay);
if (trainDelay.length() > 0) {
if (trainDelay.equals("0")) {
}else{
try{
int num = Integer.parseInt(trainDelay);
trainDelayed.put(trainNumber, "Afgeschaft");
} catch (NumberFormatException e) {
// not an integer!
}
//System.out.println("Current Delay is " + trainDelay + "minutes for train " + trainNumber);
trainDelays.put(trainNumber, trainDelay);
}
}
if (trainDelay.equals("Afgeschaft")) {
// System.out.println("Cancelled Train Found " + trainNumber);
trainDelays.put(trainNumber, "Afgeschaft");
trainCanceled.put(trainNumber, "Afgeschaft");
}
if (!trainDelay.equals("Afgeschaft")) {
trainCachePool.execute(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
if (!trainCache.containsKey(new TrainId(trainNumber,destination))) {
insertTrain(trainNumber,destination,trainLink);
}
long end = System.currentTimeMillis();
// System.out.println("TRAIN FETCH " + numberI + " - " + numberJ + " (" + (end - start) + " ms)");
}
});
}
}
}
System.out.println("Trains cancelled " + trainCanceled.size());
System.out.println("Trains delayed " + trainDelayed.size());
double percentageOfDelays = 0+ trainDelays.size();
System.out.println("Total number of trains " + totalTrains.size());
percentageOfDelays = (percentageOfDelays / totalTrains.size()) *100;
System.out.println("Percentage of Trains having issues is " +percentageOfDelays);
System.out.println("Finished Reading Trains number of trains having issues is "+ trainDelays.size() +" ");
ScrapeTrip scrapeDelayedTrains = new ScrapeTrip();
scrapeDelayedTrains.startScrape(trainDelays);
trainCachePool.shutdown();
try {
trainCachePool.awaitTermination(POOL_TIMEOUT,TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
long end2 = System.currentTimeMillis();
long start3 = System.currentTimeMillis();
List<LiveBoard> liveBoards = new ArrayList<>();
// for (int i = 0; i < stationIds.size(); i++) {
// // LiveBoard liveBoard = parseLiveBoard(stationIds.get(i));
// // liveBoards.add(liveBoard);
// }
long end3 = System.currentTimeMillis();
return liveBoards;
}
public LiveBoard getLiveBoard(String stationId, String date, String time, int numberOfResults) {
ArrayList<String> stations = new ArrayList<>();
stations.add(stationId);
List<LiveBoard> liveBoards = getLiveBoards(stations,date,time,numberOfResults);
return liveBoards.get(0);
}
private LiveBoard parseLiveBoard(String stationId) {
LiveBoard liveBoard = new LiveBoard();
List<Service> services = new ArrayList<>();
liveBoard.setStationInfo(StationDatabase.getInstance().getStationInfo(stationId));
Document doc = Jsoup.parse(sources.get(stationId));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm,dd/MM/yy");
Calendar time = Calendar.getInstance();
String[] timeA = null;
if (doc.select(".qs").isEmpty()) {
System.out.println("ERROR IN LIVEBOARD "
+ StationDatabase.getInstance().getStationInfo(stationId).getName()
+ " [" + stationId + "]");
}
else {
Element timeE = doc.select(".qs").get(0);
String timeS = timeE.ownText().replaceAll("Vertrek ","");
timeA = timeS.split(",");
try {
Date t = sdf.parse(timeS);
time.setTime(t);
} catch (ParseException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
}
Elements trains = doc.select(".journey");
for (int i = 0; i < trains.size(); i++) {
Service service = new Service();
Element train = trains.get(i);
Elements trainA = train.select("a");
service.setTrainNumber(trainA.text());
String stationInfo = train.ownText().replaceAll(">","").trim();
String trainTarget = stationInfo;
String trainPlatform = "";
int split = stationInfo.indexOf(" perron ");
if (split != -1) {
trainTarget = stationInfo.substring(0,split);
trainPlatform = stationInfo.substring(split + 8);
}
else {
String platf = train.select(".platformChange").text().replaceAll("perron ","");
if (!platf.isEmpty()) {
trainPlatform = platf;
}
}
service.setDestination(trainTarget);
service.setPlatform(trainPlatform);
service.setScheduledDepartureTime(train.select("strong").get(1).text());
String trainDelay = train.select(".delay").text().replaceAll("\\+","");
service.setDelay(trainDelay);
service.setNextStop(getNextStop(service.getTrainNumber(),
service.getDestination(),liveBoard.getStationInfo().getName()));
if (trainDelay.equals("Afgeschaft")) {
service.setDelay("CANCELLED");
if (service.getNextStop() != null) {
service.getNextStop().setDelay("CANCELLED");
}
}
//ISO 8601
SimpleDateFormat isoSDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Calendar depC = Calendar.getInstance();
try {
Date d = sdf.parse(service.getScheduledDepartureTime() + "," + timeA[1]);
depC.setTime(d);
} catch (ParseException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
Calendar actualDepC = (Calendar) depC.clone();
int departureDelay = 0;
try {
departureDelay = Integer.parseInt(service.getDelay());
} catch (NumberFormatException ex) {
}
actualDepC.add(Calendar.MINUTE,departureDelay);
if (actualDepC.before(time)) {
depC.add(Calendar.DATE,1);
actualDepC.add(Calendar.DATE,1);
}
else {
Calendar temp = (Calendar) time.clone();
temp.add(Calendar.DATE,1);
if (!temp.after(actualDepC)) {
depC.add(Calendar.DATE,-1);
actualDepC.add(Calendar.DATE,-1);
}
}
service.setScheduledDepartureTime(isoSDF.format(depC.getTime()));
service.setActualDepartureTime(isoSDF.format(actualDepC.getTime()));
if (service.getNextStop() != null) {
Calendar arrC = (Calendar) depC.clone();
String[] arrTime = service.getNextStop().getScheduledArrivalTime().split(":");
arrC.set(Calendar.HOUR_OF_DAY,Integer.parseInt(arrTime[0]));
arrC.set(Calendar.MINUTE,Integer.parseInt(arrTime[1]));
Calendar actualArrC = (Calendar) arrC.clone();
int arrivalDelay = 0;
try {
arrivalDelay = Integer.parseInt(service.getNextStop().getDelay());
} catch (NumberFormatException ex) {
}
actualArrC.add(Calendar.MINUTE,arrivalDelay);
while (arrC.before(depC)) {
arrC.add(Calendar.DATE,1);
}
while (actualArrC.before(actualDepC)) {
actualArrC.add(Calendar.DATE,1);
}
service.getNextStop().setScheduledArrivalTime(isoSDF.format(arrC.getTime()));
service.getNextStop().setActualArrivalTime(isoSDF.format(actualArrC.getTime()));
}
services.add(service);
}
liveBoard.setServices(services);
return liveBoard;
}
private NextStop getNextStop(String trainNumber, String destination, String stationName) {
TrainInfo info = trainCache.get(new TrainId(trainNumber,destination));
if (info != null) {
List<Stop> stops = info.getStops();
for (int i = 0; i < stops.size(); i++) {
if (stops.get(i).getName().equals(stationName)) {
Stop stop = stops.get(i + 1);
NextStop nextStop = new NextStop();
nextStop.setName(stop.getName());
nextStop.setScheduledArrivalTime(stop.getArrivalTime());
nextStop.setDelay(stop.getArrivalDelay());
nextStop.setPlatform(stop.getPlatform());
return nextStop;
}
}
}
return null;
}
private void insertTrain(String trainNumber, String destination, String trainLink) {
List<Stop> stopsList = new ArrayList<>();
Document doc = Jsoup.parse(getUrlSource(trainLink.replaceAll("sqIdx=[0-9]*","sqIdx=0")));
Elements route = doc.select(".trainRoute");
if (route.isEmpty()) {
return;
}
Elements stops = route.get(0).select("tr");
for (int i = 0; i < stops.size(); i++) {
Elements tds = stops.get(i).select("td");
if (tds.size() == 5) {
Element arrivalTimeTd = tds.get(2);
String arrivalTime = arrivalTimeTd.ownText().replaceAll("\u00A0","");
Element departureTimeTd = tds.get(3);
String departureTime = departureTimeTd.ownText().replaceAll("\u00A0","");
if (arrivalTime.matches("[0-9][0-9]:[0-9][0-9]") || departureTime.matches("[0-9][0-9]:[0-9][0-9]")) {
Stop stop = new Stop();
stop.setName(tds.get(1).text());
stop.setArrivalTime(arrivalTime);
stop.setArrivalDelay(arrivalTimeTd.select(".delay").text().replaceAll("\\+",""));
stop.setDepartureTime(departureTime);
stop.setDepartureDelay(departureTimeTd.select(".delay").text().replaceAll("\\+",""));
stop.setPlatform(tds.get(4).text().replaceAll("\u00A0",""));
stopsList.add(stop);
}
}
}
trainCache.put(new TrainId(trainNumber,destination),new TrainInfo(trainNumber,destination,stopsList));
}
private String getUrlSource(String link) {
URL url = null;
try {
url = new URL(link);
} catch (MalformedURLException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT_IN_MILLISECONDS);
conn.setConnectTimeout(CONNECTION_TIMEOUT_IN_MILLISECONDS);
} catch (IOException ex) {
Logger.getLogger(LiveBoardFetcher.class.getName()).log(Level.SEVERE,null,ex);
}
BufferedReader br;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
} catch (IOException ex) {
// Probeert het<SUF>
// System.out.println("########## RETRY ##########");
return getUrlSource(link);
}
String source = sb.toString();
if (source.contains("<title>Fout</title>")) {
return null;
}
return source;
}
} |
200395_4 | import javax.swing.*;
import java.awt.*;
/**
* @author Oscar Baume & Dorain Gillioz
*/
public class Digital extends Clock{
// label qui affiche l'heure
JLabel label;
/**
* Constructeur de l'horloge digital
* @param subject = sujet de l'horloge
*/
Digital(Chrono subject) {
// on appele le constructeur d'horloge
super(subject);
// on mets le background en gris
setBackground(Color.gray);
// on crée un Jlabel
label = new JLabel();
// on utilise un gridbaglayout pour que le label soit centré sans faire + de manip
this.setLayout(new GridBagLayout());
// on ajoute le label au JPanel
add(label);
}
@Override
public void update(){
super.update();
// on met à jour le contenu du label
label.setText(subject.name() + " : " + hour +"h "+ minute +"m "+ second +"s");
}
}
| obaume/MCR_Labo1 | code/Horloge/src/Digital.java | 276 | // on mets le background en gris | line_comment | nl | import javax.swing.*;
import java.awt.*;
/**
* @author Oscar Baume & Dorain Gillioz
*/
public class Digital extends Clock{
// label qui affiche l'heure
JLabel label;
/**
* Constructeur de l'horloge digital
* @param subject = sujet de l'horloge
*/
Digital(Chrono subject) {
// on appele le constructeur d'horloge
super(subject);
// on mets<SUF>
setBackground(Color.gray);
// on crée un Jlabel
label = new JLabel();
// on utilise un gridbaglayout pour que le label soit centré sans faire + de manip
this.setLayout(new GridBagLayout());
// on ajoute le label au JPanel
add(label);
}
@Override
public void update(){
super.update();
// on met à jour le contenu du label
label.setText(subject.name() + " : " + hour +"h "+ minute +"m "+ second +"s");
}
}
|
107781_3 | import java.util.*;
public class JData { //JData stands for Julian Date, as used in astronomy.
private int dia, mes, ano;
private int julianData;
//--- CONSTRUTORES --------------------------------------------
public JData(int dia, int mes , int ano) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.julianData = dataToJData(dia, mes, ano);
}
public JData() {
Calendar cal = Calendar.getInstance();
this.ano = cal.get(Calendar.YEAR);
this.mes = cal.get(Calendar.MONTH) + 1;
this.dia = cal.get(Calendar.DAY_OF_MONTH);
this.julianData = dataToJData(this.dia, this.mes, this.ano);
}
//--- METODOS ------------------------------------------------
//--- getters
public int getDia() {
return dia;
}
public int getMes() {
return mes;
}
public int getAno() {
return ano;
}
public int getJulianData() {
return julianData;
}
//--- print functions
public void printData() {
System.out.printf("%02d-%02d-%04d",dia, mes, ano);
}
public void printDataExtenso(int dia, int mes, int ano) {
System.out.print(getDia() + " de " + nomeDoMes() + " de " + getAno());
}
//--- conversion functions
public int dataToJData(int dia, int mes, int ano) { // only for dates after 01-01-2000
int diasTotal = 0;
int diasExtra = (ano - 2000) / 4;
diasTotal = (ano - 2000) * 365 + diasExtra;
for (int i = 0; i < mes; i++) {
diasTotal += diasNoMes(i, ano);
}
diasTotal += dia;
return diasTotal;
}
public String nomeDoMes() {
String[] meses = {"Janeiro", "Fevereiro", "Marco", "Abril", "Maio",
"Junho", "Julho", "Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"};
return meses[mes - 1];
}
public void vaiParaAmanha() {
if (dia < diasNoMes(mes, ano)) {
dia++;
} else {
dia = 1;
if (mes == 12) {
mes = 1;
ano++;
} else {
mes++;
}
}
//~ dataArray[0] += 1;
}
public void vaiParaOntem() {
if (dia > 1) {
dia--;
} else {
if (mes == 1) {
mes = 12;
ano--;
} else {
mes--;
}
dia = diasNoMes(mes, ano);
}
//~ dataArray[0] -= 1;
}
public boolean dataIgual(JData oldData) {
if (julianData == oldData.julianData) {
return true;
}
return false;
}
public boolean dataMaior(JData oldData) {
if (julianData > oldData.julianData) {
return true;
}
return false;
}
public boolean dataMenor(JData oldData) {
if (julianData < oldData.julianData) {
return true;
}
return false;
}
public int subtract(JData oldData) {
return julianData - oldData.julianData;
}
//--- METODODOS DA CLASSE ------------------------------------
public static boolean bissexto(int ano) {
return ((ano % 4 == 0) && (ano % 100 != 0) || (ano % 400 == 0));
}
public static int diasNoMes(int mes, int ano) {
int dias = 0;
switch (mes) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
default: //Fevereiro
return (bissexto(ano)) ? 28 : 29;
}
}
public static boolean validarData(int dia, int mes, int ano) {
return((dia <= diasNoMes(mes, ano)) && (mes > 0 && mes < 13));
}
}
| obiwit/100cerebros | Ano 1/P2/LuisMoura/aula03/JData.java | 1,317 | //--- getters | line_comment | nl | import java.util.*;
public class JData { //JData stands for Julian Date, as used in astronomy.
private int dia, mes, ano;
private int julianData;
//--- CONSTRUTORES --------------------------------------------
public JData(int dia, int mes , int ano) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.julianData = dataToJData(dia, mes, ano);
}
public JData() {
Calendar cal = Calendar.getInstance();
this.ano = cal.get(Calendar.YEAR);
this.mes = cal.get(Calendar.MONTH) + 1;
this.dia = cal.get(Calendar.DAY_OF_MONTH);
this.julianData = dataToJData(this.dia, this.mes, this.ano);
}
//--- METODOS ------------------------------------------------
//--- getters<SUF>
public int getDia() {
return dia;
}
public int getMes() {
return mes;
}
public int getAno() {
return ano;
}
public int getJulianData() {
return julianData;
}
//--- print functions
public void printData() {
System.out.printf("%02d-%02d-%04d",dia, mes, ano);
}
public void printDataExtenso(int dia, int mes, int ano) {
System.out.print(getDia() + " de " + nomeDoMes() + " de " + getAno());
}
//--- conversion functions
public int dataToJData(int dia, int mes, int ano) { // only for dates after 01-01-2000
int diasTotal = 0;
int diasExtra = (ano - 2000) / 4;
diasTotal = (ano - 2000) * 365 + diasExtra;
for (int i = 0; i < mes; i++) {
diasTotal += diasNoMes(i, ano);
}
diasTotal += dia;
return diasTotal;
}
public String nomeDoMes() {
String[] meses = {"Janeiro", "Fevereiro", "Marco", "Abril", "Maio",
"Junho", "Julho", "Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"};
return meses[mes - 1];
}
public void vaiParaAmanha() {
if (dia < diasNoMes(mes, ano)) {
dia++;
} else {
dia = 1;
if (mes == 12) {
mes = 1;
ano++;
} else {
mes++;
}
}
//~ dataArray[0] += 1;
}
public void vaiParaOntem() {
if (dia > 1) {
dia--;
} else {
if (mes == 1) {
mes = 12;
ano--;
} else {
mes--;
}
dia = diasNoMes(mes, ano);
}
//~ dataArray[0] -= 1;
}
public boolean dataIgual(JData oldData) {
if (julianData == oldData.julianData) {
return true;
}
return false;
}
public boolean dataMaior(JData oldData) {
if (julianData > oldData.julianData) {
return true;
}
return false;
}
public boolean dataMenor(JData oldData) {
if (julianData < oldData.julianData) {
return true;
}
return false;
}
public int subtract(JData oldData) {
return julianData - oldData.julianData;
}
//--- METODODOS DA CLASSE ------------------------------------
public static boolean bissexto(int ano) {
return ((ano % 4 == 0) && (ano % 100 != 0) || (ano % 400 == 0));
}
public static int diasNoMes(int mes, int ano) {
int dias = 0;
switch (mes) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
default: //Fevereiro
return (bissexto(ano)) ? 28 : 29;
}
}
public static boolean validarData(int dia, int mes, int ano) {
return((dia <= diasNoMes(mes, ano)) && (mes > 0 && mes < 13));
}
}
|
96396_19 | /*
* Copyright (c) 2009 - 2021 by Oli B.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 04.10.2009 by Oli B. ([email protected])
*/
package gdv.xport.satz;
import gdv.xport.config.Config;
import gdv.xport.feld.*;
import gdv.xport.io.ImportException;
import gdv.xport.util.NotUniqueException;
import gdv.xport.util.SatzTyp;
import gdv.xport.util.SimpleConstraintViolation;
import net.sf.oval.ConstraintViolation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import static gdv.xport.feld.Bezeichner.SATZART;
/**
* Ein Teildatensatz hat immer genau 256 Bytes. Dies wird beim Export
* beruecksichtigt. Und ein Teildatensatz besteht aus mehreren Datenfeldern.
*
* @author [email protected]
* @since 04.10.2009
*/
public class Teildatensatz extends Satz {
private static final Logger LOG = LogManager.getLogger(Teildatensatz.class);
private final Collection<Feld> datenfelder = Config.getInstance().isDebug() ? new TreeSet<>() : new ArrayList<>();
/** Dieses Feld brauchen wir, um die Satznummer abzuspeichern. */
protected Satznummer satznummer = new Satznummer();
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart.
*
* @param satzTyp z.B. 0220.050
*/
public Teildatensatz(final SatzTyp satzTyp) {
super();
this.initDatenfelder(satzTyp);
}
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart und
* Nummer.
*
* @param satzTyp z.B. 0220.050
* @param nr Nummer des Teildatensatzes (zwischen 1 und 9)
*/
public Teildatensatz(final SatzTyp satzTyp, final int nr) {
this(satzTyp);
initSatznummer(satzTyp, nr);
this.setGdvSatzartName(satzTyp.toString());
if (satzTyp.hasGdvSatzartNummer())
this.setGdvSatzartNummer(String.valueOf(satzTyp.getGdvSatzartNummer()));
}
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart, Nummer
* und Version des zugeheorigen Satzes.
*
* @param satz z.B. 100
* @param nr Nummer des Teildatensatzes (zwischen 1 und 9)
*/
public Teildatensatz(final Satz satz, final int nr) {
super(satz, 0);
initSatznummer(satz.getSatzTyp(), nr);
}
/**
* Dies ist der Copy-Constructor, falls man eine Kopie eines Teildatensatzes
* braucht.
*
* @param other der andere Teildatensatz
*/
public Teildatensatz(final Teildatensatz other) {
super(other, 0);
this.satznummer = other.satznummer;
for (Feld f : other.datenfelder) {
Feld copy = (Feld) f.clone();
this.datenfelder.add(copy);
}
}
/**
* Inits the satznummer.
*
* @param nr the nr
*/
private void initSatznummer(final SatzTyp satzTyp, final int nr) {
if ((nr < 1) || (nr > 9)) {
throw new IllegalArgumentException("Satznummer (" + nr
+ ") muss zwischen 1 und 9 liegen");
}
this.satznummer.setInhalt(Character.forDigit(nr, 10));
this.initDatenfelder(satzTyp);
}
private void initDatenfelder(SatzTyp satzTyp) {
NumFeld satzart = new NumFeld((SATZART), 4, 1).mitConfig(getConfig());
satzart.setInhalt(satzTyp.getSatzart());
this.add(satzart);
}
@Override
public NumFeld getSatzartFeld() {
Optional<Feld> satzart = findFeld(Bezeichner.SATZART);
return satzart.map(feld -> (NumFeld) feld).orElseGet(() -> new NumFeld(SATZART, 4, 1));
}
/**
* Liefert die Satznummer zurueck. Sie loest die alte
* getNummer()-Methode ab.
*
* @return Satznummer als einzelnes Zeichen ('1' ... '9')
* @since 5.0
*/
public Zeichen getSatznummer() {
if ((this.satznummer.getByteAdresse() == 256) && hasFeld(Bezeichner.SATZNUMMER)) {
Satznummer nr = getFeld(Bezeichner.SATZNUMMER, Satznummer.class);
if (nr.isEmpty() || nr.isInvalid()) {
nr.setInhalt(this.satznummer.getInhalt());
}
this.satznummer = nr;
}
return new Zeichen(this.satznummer);
}
/**
* Fuegt das angegebene Feld in den Teildatensatz ein.
* Bei Einfuegen wird ueberprueft, ob es zu Ueberschneidungen mit
* anderen Feldern kommt. Ausnahme hierbei ist das Satznummern-Feld
* auf Byte 256, mit dem der Teildatensatz vorinitialisiert wurde.
* Kommt es hier zu einer Ueberlappung, wird das Satznummern-Feld
* entfernt, da nicht alle Saetze dieses Feld besitzen.
*
* @param feld Feld mit Name
*/
@Override
public void add(final Feld feld) {
for (Feld f : getFelder()) {
if (LOG.isDebugEnabled() && f.getBezeichnung().startsWith("Satznummer")
&& feld.getBezeichnung().startsWith("Satznummer")) {
LOG.debug(f.getBezeichnung() + "(" + f.getBezeichner().getTechnischerName() + ") gefunden in "
+ this + this.getSatznummer());
}
if (!feld.equals(f) && feld.overlapsWith(f)) {
throw new IllegalArgumentException("conflict: " + feld + " overlaps with " + f);
} else if (feld.compareTo(f) == 0) {
remove(f);
LOG.debug("{} wird durch {} ersetzt.", f, feld);
}
}
setUpFeld(feld);
this.datenfelder.add(feld);
}
private void setUpFeld(Feld feld) {
if (feld.getBezeichnung().startsWith("Satznummernwiederholung")) {
feld.setInhalt(this.satznummer.getInhalt());
} else if (feld.getBezeichnung().startsWith("Satznummer")) {
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(), this);
feld.setInhalt(this.satznummer.getInhalt());
if (this.getSatznummer().getByteAdresse() >= feld.getByteAdresse()) {
this.satznummer = new Satznummer(feld);
}
} else if (feld.getBezeichner().equals(Bezeichner.ZUSAETZLICHE_SATZKENNUNG)) {
feld.setInhalt("X");
} else if (feld.getBezeichnung().startsWith("Vorzeichen")) {
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(), this);
feld.setInhalt("+");
} else if (this.getSatzart() == 1 && feld.getBezeichner().getTechnischerName().equals("Satzart0001")) {
LOG.debug("{}({}) einfuegen in {} {}}", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(),
this, this.getSatzversion());
feld.setInhalt(this.getSatzversion().getInhalt());
} else if (this.getGdvSatzartName().startsWith("0220.020")
&& feld.getBezeichner().getTechnischerName().startsWith("FolgeNrZurLaufendenPersonenNrUnterNr")) {
// bei den 0220.020er-Saetzen ist die KrankenFolgeNr wichtig fuer die Erkennbarkeit der
// Satzart.
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner()
.getTechnischerName(), this);
feld.setInhalt(this.getSatzTyp().getKrankenFolgeNr());
}
}
/**
* Falls ein Feld zuviel gesetzt wurde, kann es mit 'remove" wieder
* entfernt werden.
*
* @param feld das Feld, das entfernt werden soll
*/
public void remove(final Feld feld) {
datenfelder.remove(feld);
}
/**
* Falls ein Feld zuviel gesetzt wurde, kann es mit 'remove" wieder entfernt
* werden.
*
* @param bezeichner der Feld-Beezeichner
* @since 1.0
*/
@Override
public void remove(final Bezeichner bezeichner) {
if (hasFeld(bezeichner)) {
datenfelder.remove(getFeld(bezeichner));
LOG.debug("{} was removed from {}.", bezeichner, this);
}
}
/**
* Setzt das gewuenschte Feld. Falls es nicht vorhanden ist, wird analog
* zur Oberklasse eine {@link IllegalArgumentException} geworfen.
*
* @param name der Name des Feldes
* @param value der gewuenschte Werte als String
* @since 5.2
*/
@Override
public void setFeld(final Bezeichner name, final String value) {
List<Feld> felder = this.getAllFelder(name);
if (felder.isEmpty()) {
throw new IllegalArgumentException("Feld \"" + name + "\" not found");
}
if (felder.size() > 1) {
LOG.info("Mit Bezeichner {} werden mehrere Felder in '{}' mit '{}' belegt: {}", name,this, value, felder);
throw new NotUniqueException(String.format("Bezeichner '%s' in %s nicht eindeutig: %s, %s...", name, toShortString(), felder.get(0), felder.get(1)));
}
for (Feld x : felder) {
setFeld(x, value);
}
}
/**
* Setzt das gewuenschte Feld anhand der uebergebenen ByteAdresse.
*
* @param adresse Adresse des gewuenschten Feldes
* @param value Wert
* @since 5.0
* @deprecated wurde durch {@link Teildatensatz#setFeld(ByteAdresse, String)} ersetzt
*/
@Deprecated
public void set(final ByteAdresse adresse, final String value) {
Feld x = this.getFeld(adresse);
x.setInhalt(value);
}
/**
* Setzt das gewuenschte Feld anhand der uebergebenen ByteAdresse.
*
* @param adresse Adresse des gewuenschten Feldes
* @param value Wert
* @since 5.2
*/
@Override
public void setFeld(final ByteAdresse adresse, final String value) {
Feld x = this.getFeld(adresse);
setFeld(x, value);
}
private void setFeld(Feld x, String value) {
try {
LOG.debug("{} in '{}' wird mit '{}' belegt.", x, this, value);
x.setInhalt(value);
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException(String.format(
"%s: illegal value '%s' for %s", this.toShortString(), value, x), iae);
}
}
/**
* Liefert das gewuenschte Feld.
* <p>
* Falls kein Feld mit dem Bezeichner vorhanden ist, wird eine
* {@link IllegalArgumentException} geworfen. Ebenso wenn das Feld
* nicht eindeutig ist. Dann gibt es eine {@link NotUniqueException}
* (Ausnahme: Satznummer).
* </p>
* @param bezeichner gewuenschter Bezeichner des Feldes
* @return das gesuchte Feld
*/
@Override
public Feld getFeld(final Bezeichner bezeichner) {
List<Feld> found = getAllFelder(bezeichner);
if (found.isEmpty()) {
Optional<Feld> feld = findFeld(bezeichner);
if (feld.isPresent()) {
return feld.get();
}
throw new IllegalArgumentException("Feld \"" + bezeichner + "\" nicht in " + this.toShortString()
+ " nicht vorhanden!");
} else if ((found.size() > 1)) {
checkUniqueness(found);
}
return found.get(0);
}
private static void checkUniqueness(List<Feld> felder) {
Feld f1 = felder.get(0);
for (int i = 1; i < felder.size(); i++) {
Feld fn = felder.get(i);
if (!f1.getInhalt().equals(fn.getInhalt())) {
throw new NotUniqueException(String.format("same Bezeichner, different values: '%s', '%s'", f1, fn));
}
}
LOG.debug("{} hat gleichen Wert wie gleichlautende Felder.", f1);
}
private List<Feld> getAllFelder(Bezeichner bezeichner) {
List<Feld> found = new ArrayList<>();
for (Bezeichner b : bezeichner.getVariants()) {
for (Feld feld : datenfelder) {
if (b.equals(feld.getBezeichner())) {
found.add(feld);
}
}
}
return found;
}
private Optional<Feld> findFeld(final Bezeichner bezeichner) {
if (datenfelder == null) {
return Optional.empty();
}
for (Feld f : datenfelder) {
if (f.getBezeichner().getName().equals(bezeichner.getName())) {
return Optional.of(f);
}
}
return Optional.empty();
}
/**
* Liefert das Feld mit der gewuenschten Nummer zurueck.
*
* @param nr z.B. 1
* @return das Feld (z.B. mit der Satzart)
*/
public Feld getFeld(final int nr) {
int myNr = nr;
// 2018er-Version: in SA0100, TD1: es gibt kein Feld-Nr 27! Die SatzNr ist
// Feld 26 !!!
// 2018er-Version: in SA0210.050, TD1: es gibt kein Feld-Nr 35! Die SatzNr
// ist Feld 34 !!!
// 2018er-Version: in SA0220.010.13.1, TD1: es gibt kein Feld-Nr 46! Die
// Satznummer ist Feld 45 !!!
// 2018er-Version: in SA0600, TD2: es gibt kein Feld-Nr 13! Die Satznummer
// ist Feld 12 !!!
// 2018er-Version: in SA0600, TD3: es gibt kein Feld-Nr 14! Die Satznummer
// ist Feld 13 !!!
// 2018er-Version: in SA9950, TD1: es gibt kein Feld-Nr 11! Die Satznummer
// ist Feld 10 !!!
// 2018er-Version: in SA9951, TD1: es gibt kein Feld-Nr 11! Die Satznummer
// ist Feld 10 !!!
switch (this.getGdvSatzartName()) {
case "0100":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 27)
myNr--;
break;
case "0210.050":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 35)
myNr--;
break;
case "0220.010.13.1":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 46)
myNr--;
break;
case "0600":
if (("2").equals(this.getSatznummer()
.getInhalt()) && myNr == 13)
{
myNr--;
}
else if (("3").equals(this.getSatznummer()
.getInhalt()) && myNr == 14)
myNr--;
break;
case "9950":
case "9951":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 11)
myNr--;
break;
default:
break;
}
return (Feld) getFelder().toArray()[myNr - 1];
}
/**
* Liefert das Feld mit der angegebenen Byte-Adresse. Im Gegensatz zur
* Nr. in {@link #getFeld(int)} aendert sich diese nicht, wenn neue
* Elemente in einem Teildatensatz hinzukommen.
*
* @param adresse zwischen 1 und 256
* @return das entsprechende Feld
* @since 5.0
*/
public Feld getFeld(final ByteAdresse adresse) {
for (Feld f : datenfelder) {
if (adresse.intValue() == f.getByteAdresse()) {
return f;
}
}
throw new IllegalArgumentException(
String.format("Adresse %s existiert nicht in %s", adresse, this.toShortString()));
}
/**
* Fraegt ab, ob das entsprechende Feld vorhanden ist.
*
* @param bezeichner gewuenschter Bezeichner des Feldes
* @return true / false
* @see gdv.xport.satz.Satz#hasFeld(Bezeichner)
* @since 1.0
*/
@Override
public boolean hasFeld(final Bezeichner bezeichner) {
for (Bezeichner b : bezeichner.getVariants()) {
for (Feld f : datenfelder) {
if (b.equals(f.getBezeichner())) {
return true;
}
}
}
return false;
}
/**
* Ueberprueft, ob das uebergebene Feld vorhanden ist.
* <p>
* Anmerkung: Mit 4.4 wird nicht nur der Name ueberprueft sondern alle
* Attribute.
* </p>
*
* @param feld the feld
* @return true, if successful
* @since 1.0
*/
public boolean hasFeld(final Feld feld) {
for (Feld f : datenfelder) {
if (feld.equals(f)) {
return true;
}
}
return false;
}
/**
* Liefert alle Felder in der Reihenfolge innerhalb des Teildatensatzes
* zurueck.
*
* @return List der Felder (sortiert)
* @since 0.2
*/
@Override
public final Collection<Feld> getFelder() {
return new TreeSet<>(datenfelder);
}
/**
* Liefert die Liste der speziellen Kennzeichen zur Identifikation beim Import zurueck.
* Jedes Element enthaelt Byte-Adresse und Inhalt.
*
* @return Liste der speziellen Kennzeichen
*/
public List<Zeichen> getSatzIdent() {
String[] identBezeichner = {"FolgeNrZurLaufendenPersonenNrUnterNrBzwLaufendenNrTarif",
"FolgeNrZurLaufendenPersonenNrUnterNrLaufendeNrTarif", "SatzNr", "SatzNr1",
"SatzNr2", "SatzNr3", "SatzNr4", "SatzNr9", "SatzNrnwiederholung",
"SatzNrnwiederholung1", "SatzNrnwiederholung2", "SatzNrnwiederholung3",
"Satznummer", "ZusaetzlicheSatzkennung"};
List<Zeichen> satzIdent = new ArrayList<>();
for (String s : identBezeichner) {
Bezeichner b = Bezeichner.of(s);
if (hasFeld(b)) {
satzIdent.add(getFeld(b, Zeichen.class));
}
}
return satzIdent;
}
/* (non-Javadoc)
* @see gdv.xport.satz.Datensatz#export(java.io.Writer)
*/
@Override
public void export(final Writer writer) throws IOException {
String eod = getConfig().getProperty("gdv.eod", System.lineSeparator());
export(writer, eod);
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#export(java.io.Writer, java.lang.String)
*/
@Override
public void export(final Writer writer, final String eod) throws IOException {
StringBuilder data = new StringBuilder(256);
for (int i = 0; i < 256; i++) {
data.append(' ');
}
for (Feld feld : datenfelder) {
int start = feld.getByteAdresse() - 1;
int end = start + feld.getAnzahlBytes();
data.replace(start, end, feld.getInhalt());
}
assert data.length() == 256 : "Teildatensatz ist " + data.length() + " und nicht 256 Bytes lang";
writer.write(data.toString());
writer.write(eod);
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#importFrom(java.lang.String)
*/
@Override
public Teildatensatz importFrom(final String content) throws IOException {
for (Feld feld : datenfelder) {
int begin = (feld.getByteAdresse() - 1) % 256;
int end = begin + feld.getAnzahlBytes();
if (end > content.length()) {
throw new ImportException("input string is too short (" + (end - content.length())
+ " bytes missing): " + content);
}
String s = content.substring(begin, end);
feld.setInhalt(s);
}
return this;
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#isValid()
*/
@Override
public boolean isValid() {
if (!super.isValid()) {
return false;
}
for (Feld feld : datenfelder) {
if (!feld.isValid()) {
LOG.info(feld + " is not valid");
return false;
}
}
return true;
}
@Override
public List<ConstraintViolation> validate(Config validationConfig) {
List<ConstraintViolation> violations = validateSatznummern(validationConfig);
for (Feld feld : datenfelder) {
violations.addAll(feld.validate(validationConfig));
}
return violations;
}
private List<ConstraintViolation> validateSatznummern(Config validationConfig) {
List<ConstraintViolation> violations = new ArrayList<>();
if (validationConfig.getValidateMode() != Config.ValidateMode.OFF) {
LOG.debug("Satznummern werden validiert in {}.", this);
Zeichen satznr = getSatznummer();
for (Feld feld : datenfelder) {
if (feld.getBezeichner().isVariantOf(Bezeichner.SATZNUMMER)
&& !satznr.getInhalt().equals(feld.getInhalt())) {
ConstraintViolation cv = new SimpleConstraintViolation("different Satznummern: " + satznr,
this, feld);
violations.add(cv);
}
}
}
return violations;
}
@Override
public String toShortString() {
if (datenfelder.size() < 4)
return String.format("Teildatensatz Satzart %04d", getSatzart());
else
return String.format("Teildatensatz %c Satzart %s", this.getSatznummer().toChar(),
this.getSatzTyp());
}
/**
* Legt eine Kopie des Teildatensatzes an.
*
* @return Kopie
* @see Cloneable
*/
@Override
public Object clone() {
return new Teildatensatz(this);
}
} | oboehm/gdv.xport | lib/src/main/java/gdv/xport/satz/Teildatensatz.java | 7,161 | // Feld 26 !!! | line_comment | nl | /*
* Copyright (c) 2009 - 2021 by Oli B.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 04.10.2009 by Oli B. ([email protected])
*/
package gdv.xport.satz;
import gdv.xport.config.Config;
import gdv.xport.feld.*;
import gdv.xport.io.ImportException;
import gdv.xport.util.NotUniqueException;
import gdv.xport.util.SatzTyp;
import gdv.xport.util.SimpleConstraintViolation;
import net.sf.oval.ConstraintViolation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import static gdv.xport.feld.Bezeichner.SATZART;
/**
* Ein Teildatensatz hat immer genau 256 Bytes. Dies wird beim Export
* beruecksichtigt. Und ein Teildatensatz besteht aus mehreren Datenfeldern.
*
* @author [email protected]
* @since 04.10.2009
*/
public class Teildatensatz extends Satz {
private static final Logger LOG = LogManager.getLogger(Teildatensatz.class);
private final Collection<Feld> datenfelder = Config.getInstance().isDebug() ? new TreeSet<>() : new ArrayList<>();
/** Dieses Feld brauchen wir, um die Satznummer abzuspeichern. */
protected Satznummer satznummer = new Satznummer();
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart.
*
* @param satzTyp z.B. 0220.050
*/
public Teildatensatz(final SatzTyp satzTyp) {
super();
this.initDatenfelder(satzTyp);
}
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart und
* Nummer.
*
* @param satzTyp z.B. 0220.050
* @param nr Nummer des Teildatensatzes (zwischen 1 und 9)
*/
public Teildatensatz(final SatzTyp satzTyp, final int nr) {
this(satzTyp);
initSatznummer(satzTyp, nr);
this.setGdvSatzartName(satzTyp.toString());
if (satzTyp.hasGdvSatzartNummer())
this.setGdvSatzartNummer(String.valueOf(satzTyp.getGdvSatzartNummer()));
}
/**
* Instantiiert einen neuen Teildatensatz mit der angegebenen Satzart, Nummer
* und Version des zugeheorigen Satzes.
*
* @param satz z.B. 100
* @param nr Nummer des Teildatensatzes (zwischen 1 und 9)
*/
public Teildatensatz(final Satz satz, final int nr) {
super(satz, 0);
initSatznummer(satz.getSatzTyp(), nr);
}
/**
* Dies ist der Copy-Constructor, falls man eine Kopie eines Teildatensatzes
* braucht.
*
* @param other der andere Teildatensatz
*/
public Teildatensatz(final Teildatensatz other) {
super(other, 0);
this.satznummer = other.satznummer;
for (Feld f : other.datenfelder) {
Feld copy = (Feld) f.clone();
this.datenfelder.add(copy);
}
}
/**
* Inits the satznummer.
*
* @param nr the nr
*/
private void initSatznummer(final SatzTyp satzTyp, final int nr) {
if ((nr < 1) || (nr > 9)) {
throw new IllegalArgumentException("Satznummer (" + nr
+ ") muss zwischen 1 und 9 liegen");
}
this.satznummer.setInhalt(Character.forDigit(nr, 10));
this.initDatenfelder(satzTyp);
}
private void initDatenfelder(SatzTyp satzTyp) {
NumFeld satzart = new NumFeld((SATZART), 4, 1).mitConfig(getConfig());
satzart.setInhalt(satzTyp.getSatzart());
this.add(satzart);
}
@Override
public NumFeld getSatzartFeld() {
Optional<Feld> satzart = findFeld(Bezeichner.SATZART);
return satzart.map(feld -> (NumFeld) feld).orElseGet(() -> new NumFeld(SATZART, 4, 1));
}
/**
* Liefert die Satznummer zurueck. Sie loest die alte
* getNummer()-Methode ab.
*
* @return Satznummer als einzelnes Zeichen ('1' ... '9')
* @since 5.0
*/
public Zeichen getSatznummer() {
if ((this.satznummer.getByteAdresse() == 256) && hasFeld(Bezeichner.SATZNUMMER)) {
Satznummer nr = getFeld(Bezeichner.SATZNUMMER, Satznummer.class);
if (nr.isEmpty() || nr.isInvalid()) {
nr.setInhalt(this.satznummer.getInhalt());
}
this.satznummer = nr;
}
return new Zeichen(this.satznummer);
}
/**
* Fuegt das angegebene Feld in den Teildatensatz ein.
* Bei Einfuegen wird ueberprueft, ob es zu Ueberschneidungen mit
* anderen Feldern kommt. Ausnahme hierbei ist das Satznummern-Feld
* auf Byte 256, mit dem der Teildatensatz vorinitialisiert wurde.
* Kommt es hier zu einer Ueberlappung, wird das Satznummern-Feld
* entfernt, da nicht alle Saetze dieses Feld besitzen.
*
* @param feld Feld mit Name
*/
@Override
public void add(final Feld feld) {
for (Feld f : getFelder()) {
if (LOG.isDebugEnabled() && f.getBezeichnung().startsWith("Satznummer")
&& feld.getBezeichnung().startsWith("Satznummer")) {
LOG.debug(f.getBezeichnung() + "(" + f.getBezeichner().getTechnischerName() + ") gefunden in "
+ this + this.getSatznummer());
}
if (!feld.equals(f) && feld.overlapsWith(f)) {
throw new IllegalArgumentException("conflict: " + feld + " overlaps with " + f);
} else if (feld.compareTo(f) == 0) {
remove(f);
LOG.debug("{} wird durch {} ersetzt.", f, feld);
}
}
setUpFeld(feld);
this.datenfelder.add(feld);
}
private void setUpFeld(Feld feld) {
if (feld.getBezeichnung().startsWith("Satznummernwiederholung")) {
feld.setInhalt(this.satznummer.getInhalt());
} else if (feld.getBezeichnung().startsWith("Satznummer")) {
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(), this);
feld.setInhalt(this.satznummer.getInhalt());
if (this.getSatznummer().getByteAdresse() >= feld.getByteAdresse()) {
this.satznummer = new Satznummer(feld);
}
} else if (feld.getBezeichner().equals(Bezeichner.ZUSAETZLICHE_SATZKENNUNG)) {
feld.setInhalt("X");
} else if (feld.getBezeichnung().startsWith("Vorzeichen")) {
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(), this);
feld.setInhalt("+");
} else if (this.getSatzart() == 1 && feld.getBezeichner().getTechnischerName().equals("Satzart0001")) {
LOG.debug("{}({}) einfuegen in {} {}}", feld.getBezeichnung(), feld.getBezeichner().getTechnischerName(),
this, this.getSatzversion());
feld.setInhalt(this.getSatzversion().getInhalt());
} else if (this.getGdvSatzartName().startsWith("0220.020")
&& feld.getBezeichner().getTechnischerName().startsWith("FolgeNrZurLaufendenPersonenNrUnterNr")) {
// bei den 0220.020er-Saetzen ist die KrankenFolgeNr wichtig fuer die Erkennbarkeit der
// Satzart.
LOG.debug("{}({}) einfuegen in {} +", feld.getBezeichnung(), feld.getBezeichner()
.getTechnischerName(), this);
feld.setInhalt(this.getSatzTyp().getKrankenFolgeNr());
}
}
/**
* Falls ein Feld zuviel gesetzt wurde, kann es mit 'remove" wieder
* entfernt werden.
*
* @param feld das Feld, das entfernt werden soll
*/
public void remove(final Feld feld) {
datenfelder.remove(feld);
}
/**
* Falls ein Feld zuviel gesetzt wurde, kann es mit 'remove" wieder entfernt
* werden.
*
* @param bezeichner der Feld-Beezeichner
* @since 1.0
*/
@Override
public void remove(final Bezeichner bezeichner) {
if (hasFeld(bezeichner)) {
datenfelder.remove(getFeld(bezeichner));
LOG.debug("{} was removed from {}.", bezeichner, this);
}
}
/**
* Setzt das gewuenschte Feld. Falls es nicht vorhanden ist, wird analog
* zur Oberklasse eine {@link IllegalArgumentException} geworfen.
*
* @param name der Name des Feldes
* @param value der gewuenschte Werte als String
* @since 5.2
*/
@Override
public void setFeld(final Bezeichner name, final String value) {
List<Feld> felder = this.getAllFelder(name);
if (felder.isEmpty()) {
throw new IllegalArgumentException("Feld \"" + name + "\" not found");
}
if (felder.size() > 1) {
LOG.info("Mit Bezeichner {} werden mehrere Felder in '{}' mit '{}' belegt: {}", name,this, value, felder);
throw new NotUniqueException(String.format("Bezeichner '%s' in %s nicht eindeutig: %s, %s...", name, toShortString(), felder.get(0), felder.get(1)));
}
for (Feld x : felder) {
setFeld(x, value);
}
}
/**
* Setzt das gewuenschte Feld anhand der uebergebenen ByteAdresse.
*
* @param adresse Adresse des gewuenschten Feldes
* @param value Wert
* @since 5.0
* @deprecated wurde durch {@link Teildatensatz#setFeld(ByteAdresse, String)} ersetzt
*/
@Deprecated
public void set(final ByteAdresse adresse, final String value) {
Feld x = this.getFeld(adresse);
x.setInhalt(value);
}
/**
* Setzt das gewuenschte Feld anhand der uebergebenen ByteAdresse.
*
* @param adresse Adresse des gewuenschten Feldes
* @param value Wert
* @since 5.2
*/
@Override
public void setFeld(final ByteAdresse adresse, final String value) {
Feld x = this.getFeld(adresse);
setFeld(x, value);
}
private void setFeld(Feld x, String value) {
try {
LOG.debug("{} in '{}' wird mit '{}' belegt.", x, this, value);
x.setInhalt(value);
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException(String.format(
"%s: illegal value '%s' for %s", this.toShortString(), value, x), iae);
}
}
/**
* Liefert das gewuenschte Feld.
* <p>
* Falls kein Feld mit dem Bezeichner vorhanden ist, wird eine
* {@link IllegalArgumentException} geworfen. Ebenso wenn das Feld
* nicht eindeutig ist. Dann gibt es eine {@link NotUniqueException}
* (Ausnahme: Satznummer).
* </p>
* @param bezeichner gewuenschter Bezeichner des Feldes
* @return das gesuchte Feld
*/
@Override
public Feld getFeld(final Bezeichner bezeichner) {
List<Feld> found = getAllFelder(bezeichner);
if (found.isEmpty()) {
Optional<Feld> feld = findFeld(bezeichner);
if (feld.isPresent()) {
return feld.get();
}
throw new IllegalArgumentException("Feld \"" + bezeichner + "\" nicht in " + this.toShortString()
+ " nicht vorhanden!");
} else if ((found.size() > 1)) {
checkUniqueness(found);
}
return found.get(0);
}
private static void checkUniqueness(List<Feld> felder) {
Feld f1 = felder.get(0);
for (int i = 1; i < felder.size(); i++) {
Feld fn = felder.get(i);
if (!f1.getInhalt().equals(fn.getInhalt())) {
throw new NotUniqueException(String.format("same Bezeichner, different values: '%s', '%s'", f1, fn));
}
}
LOG.debug("{} hat gleichen Wert wie gleichlautende Felder.", f1);
}
private List<Feld> getAllFelder(Bezeichner bezeichner) {
List<Feld> found = new ArrayList<>();
for (Bezeichner b : bezeichner.getVariants()) {
for (Feld feld : datenfelder) {
if (b.equals(feld.getBezeichner())) {
found.add(feld);
}
}
}
return found;
}
private Optional<Feld> findFeld(final Bezeichner bezeichner) {
if (datenfelder == null) {
return Optional.empty();
}
for (Feld f : datenfelder) {
if (f.getBezeichner().getName().equals(bezeichner.getName())) {
return Optional.of(f);
}
}
return Optional.empty();
}
/**
* Liefert das Feld mit der gewuenschten Nummer zurueck.
*
* @param nr z.B. 1
* @return das Feld (z.B. mit der Satzart)
*/
public Feld getFeld(final int nr) {
int myNr = nr;
// 2018er-Version: in SA0100, TD1: es gibt kein Feld-Nr 27! Die SatzNr ist
// Feld 26<SUF>
// 2018er-Version: in SA0210.050, TD1: es gibt kein Feld-Nr 35! Die SatzNr
// ist Feld 34 !!!
// 2018er-Version: in SA0220.010.13.1, TD1: es gibt kein Feld-Nr 46! Die
// Satznummer ist Feld 45 !!!
// 2018er-Version: in SA0600, TD2: es gibt kein Feld-Nr 13! Die Satznummer
// ist Feld 12 !!!
// 2018er-Version: in SA0600, TD3: es gibt kein Feld-Nr 14! Die Satznummer
// ist Feld 13 !!!
// 2018er-Version: in SA9950, TD1: es gibt kein Feld-Nr 11! Die Satznummer
// ist Feld 10 !!!
// 2018er-Version: in SA9951, TD1: es gibt kein Feld-Nr 11! Die Satznummer
// ist Feld 10 !!!
switch (this.getGdvSatzartName()) {
case "0100":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 27)
myNr--;
break;
case "0210.050":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 35)
myNr--;
break;
case "0220.010.13.1":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 46)
myNr--;
break;
case "0600":
if (("2").equals(this.getSatznummer()
.getInhalt()) && myNr == 13)
{
myNr--;
}
else if (("3").equals(this.getSatznummer()
.getInhalt()) && myNr == 14)
myNr--;
break;
case "9950":
case "9951":
if (("1").equals(this.getSatznummer()
.getInhalt()) && myNr == 11)
myNr--;
break;
default:
break;
}
return (Feld) getFelder().toArray()[myNr - 1];
}
/**
* Liefert das Feld mit der angegebenen Byte-Adresse. Im Gegensatz zur
* Nr. in {@link #getFeld(int)} aendert sich diese nicht, wenn neue
* Elemente in einem Teildatensatz hinzukommen.
*
* @param adresse zwischen 1 und 256
* @return das entsprechende Feld
* @since 5.0
*/
public Feld getFeld(final ByteAdresse adresse) {
for (Feld f : datenfelder) {
if (adresse.intValue() == f.getByteAdresse()) {
return f;
}
}
throw new IllegalArgumentException(
String.format("Adresse %s existiert nicht in %s", adresse, this.toShortString()));
}
/**
* Fraegt ab, ob das entsprechende Feld vorhanden ist.
*
* @param bezeichner gewuenschter Bezeichner des Feldes
* @return true / false
* @see gdv.xport.satz.Satz#hasFeld(Bezeichner)
* @since 1.0
*/
@Override
public boolean hasFeld(final Bezeichner bezeichner) {
for (Bezeichner b : bezeichner.getVariants()) {
for (Feld f : datenfelder) {
if (b.equals(f.getBezeichner())) {
return true;
}
}
}
return false;
}
/**
* Ueberprueft, ob das uebergebene Feld vorhanden ist.
* <p>
* Anmerkung: Mit 4.4 wird nicht nur der Name ueberprueft sondern alle
* Attribute.
* </p>
*
* @param feld the feld
* @return true, if successful
* @since 1.0
*/
public boolean hasFeld(final Feld feld) {
for (Feld f : datenfelder) {
if (feld.equals(f)) {
return true;
}
}
return false;
}
/**
* Liefert alle Felder in der Reihenfolge innerhalb des Teildatensatzes
* zurueck.
*
* @return List der Felder (sortiert)
* @since 0.2
*/
@Override
public final Collection<Feld> getFelder() {
return new TreeSet<>(datenfelder);
}
/**
* Liefert die Liste der speziellen Kennzeichen zur Identifikation beim Import zurueck.
* Jedes Element enthaelt Byte-Adresse und Inhalt.
*
* @return Liste der speziellen Kennzeichen
*/
public List<Zeichen> getSatzIdent() {
String[] identBezeichner = {"FolgeNrZurLaufendenPersonenNrUnterNrBzwLaufendenNrTarif",
"FolgeNrZurLaufendenPersonenNrUnterNrLaufendeNrTarif", "SatzNr", "SatzNr1",
"SatzNr2", "SatzNr3", "SatzNr4", "SatzNr9", "SatzNrnwiederholung",
"SatzNrnwiederholung1", "SatzNrnwiederholung2", "SatzNrnwiederholung3",
"Satznummer", "ZusaetzlicheSatzkennung"};
List<Zeichen> satzIdent = new ArrayList<>();
for (String s : identBezeichner) {
Bezeichner b = Bezeichner.of(s);
if (hasFeld(b)) {
satzIdent.add(getFeld(b, Zeichen.class));
}
}
return satzIdent;
}
/* (non-Javadoc)
* @see gdv.xport.satz.Datensatz#export(java.io.Writer)
*/
@Override
public void export(final Writer writer) throws IOException {
String eod = getConfig().getProperty("gdv.eod", System.lineSeparator());
export(writer, eod);
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#export(java.io.Writer, java.lang.String)
*/
@Override
public void export(final Writer writer, final String eod) throws IOException {
StringBuilder data = new StringBuilder(256);
for (int i = 0; i < 256; i++) {
data.append(' ');
}
for (Feld feld : datenfelder) {
int start = feld.getByteAdresse() - 1;
int end = start + feld.getAnzahlBytes();
data.replace(start, end, feld.getInhalt());
}
assert data.length() == 256 : "Teildatensatz ist " + data.length() + " und nicht 256 Bytes lang";
writer.write(data.toString());
writer.write(eod);
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#importFrom(java.lang.String)
*/
@Override
public Teildatensatz importFrom(final String content) throws IOException {
for (Feld feld : datenfelder) {
int begin = (feld.getByteAdresse() - 1) % 256;
int end = begin + feld.getAnzahlBytes();
if (end > content.length()) {
throw new ImportException("input string is too short (" + (end - content.length())
+ " bytes missing): " + content);
}
String s = content.substring(begin, end);
feld.setInhalt(s);
}
return this;
}
/* (non-Javadoc)
* @see gdv.xport.satz.Satz#isValid()
*/
@Override
public boolean isValid() {
if (!super.isValid()) {
return false;
}
for (Feld feld : datenfelder) {
if (!feld.isValid()) {
LOG.info(feld + " is not valid");
return false;
}
}
return true;
}
@Override
public List<ConstraintViolation> validate(Config validationConfig) {
List<ConstraintViolation> violations = validateSatznummern(validationConfig);
for (Feld feld : datenfelder) {
violations.addAll(feld.validate(validationConfig));
}
return violations;
}
private List<ConstraintViolation> validateSatznummern(Config validationConfig) {
List<ConstraintViolation> violations = new ArrayList<>();
if (validationConfig.getValidateMode() != Config.ValidateMode.OFF) {
LOG.debug("Satznummern werden validiert in {}.", this);
Zeichen satznr = getSatznummer();
for (Feld feld : datenfelder) {
if (feld.getBezeichner().isVariantOf(Bezeichner.SATZNUMMER)
&& !satznr.getInhalt().equals(feld.getInhalt())) {
ConstraintViolation cv = new SimpleConstraintViolation("different Satznummern: " + satznr,
this, feld);
violations.add(cv);
}
}
}
return violations;
}
@Override
public String toShortString() {
if (datenfelder.size() < 4)
return String.format("Teildatensatz Satzart %04d", getSatzart());
else
return String.format("Teildatensatz %c Satzart %s", this.getSatznummer().toChar(),
this.getSatzTyp());
}
/**
* Legt eine Kopie des Teildatensatzes an.
*
* @return Kopie
* @see Cloneable
*/
@Override
public Object clone() {
return new Teildatensatz(this);
}
} |
28381_0 | package com.odenktools.authserver.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* @author Odenktools
*/
@Getter
@Setter
@JsonSerialize
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "Permission")
@Table(name = "permissions",
uniqueConstraints = {@UniqueConstraint(columnNames = {"name_permission", "readable_name"})})
@JsonIgnoreProperties(
ignoreUnknown = true,
value = {"createdAt", "updatedAt"},
allowGetters = true
)
public class Permission implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_perm", nullable = false)
private Long idPerm;
/**
* Alias untuk kolum ``readableName``. ini digunakan agar data tetap konstant, tidak berpengaruh oleh update.
* Ini harus digenerate ``UNIQUE`` berdasarkan kolum ``readableName``.
* Misalkan :
* named = Write ApiKey
* coded = ROLE_WRITE_APIKEY (UPPERCASE, hapus SPACE menjadi UNDERSCORES, Tambahkan ROLE_)
* </p>
*/
@NotNull
@Column(name = "name_permission", nullable = false)
private String namePermission;
@NotNull
@Column(name = "readable_name", nullable = false)
private String readableName;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", updatable = false)
@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@Column(name = "updated_at")
private Date updatedAt;
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@Column(name = "deleted_at")
private Date deletedAt;
public Permission(@NotNull @Size(max = 100) String namePermission,
@NotNull @Size(max = 100) String readableName) {
this.namePermission = namePermission;
this.readableName = readableName;
}
/**
* Sets created_at before insert.
*/
@PrePersist
public void setCreationDate() {
this.createdAt = new Date();
}
/**
* Sets updated_at before update.
*/
@PreUpdate
public void setChangedDate() {
this.updatedAt = new Date();
}
@ManyToMany(mappedBy = "usersPermissions")
private Set<Group> usersGroups;
}
| odenktools/springboot-oauth2-jwt | authorization_server/src/main/java/com/odenktools/authserver/entity/Permission.java | 949 | /**
* @author Odenktools
*/ | block_comment | nl | package com.odenktools.authserver.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* @author Odenktools
<SUF>*/
@Getter
@Setter
@JsonSerialize
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "Permission")
@Table(name = "permissions",
uniqueConstraints = {@UniqueConstraint(columnNames = {"name_permission", "readable_name"})})
@JsonIgnoreProperties(
ignoreUnknown = true,
value = {"createdAt", "updatedAt"},
allowGetters = true
)
public class Permission implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_perm", nullable = false)
private Long idPerm;
/**
* Alias untuk kolum ``readableName``. ini digunakan agar data tetap konstant, tidak berpengaruh oleh update.
* Ini harus digenerate ``UNIQUE`` berdasarkan kolum ``readableName``.
* Misalkan :
* named = Write ApiKey
* coded = ROLE_WRITE_APIKEY (UPPERCASE, hapus SPACE menjadi UNDERSCORES, Tambahkan ROLE_)
* </p>
*/
@NotNull
@Column(name = "name_permission", nullable = false)
private String namePermission;
@NotNull
@Column(name = "readable_name", nullable = false)
private String readableName;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", updatable = false)
@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@Column(name = "updated_at")
private Date updatedAt;
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@Column(name = "deleted_at")
private Date deletedAt;
public Permission(@NotNull @Size(max = 100) String namePermission,
@NotNull @Size(max = 100) String readableName) {
this.namePermission = namePermission;
this.readableName = readableName;
}
/**
* Sets created_at before insert.
*/
@PrePersist
public void setCreationDate() {
this.createdAt = new Date();
}
/**
* Sets updated_at before update.
*/
@PreUpdate
public void setChangedDate() {
this.updatedAt = new Date();
}
@ManyToMany(mappedBy = "usersPermissions")
private Set<Group> usersGroups;
}
|
106656_20 | package TripleT;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
import javax.swing.InputMap;
import javax.swing.Timer;
import javax.swing.KeyStroke;
import javax.swing.InputMap;
import javax.swing.ActionMap;
import java.util.LinkedList;
import java.util.Iterator;
/**
* The second level of the game (world 1, level 2).
*
* In light of my decision to cease development on Triple T,
* this is now going to be the vacuum stage that I'd planned to save for later in the game.
* @author Owen Jow
*/
public class Level2 extends LevelPanel implements ActionListener {
private int yTraveled, timeRemaining, blockDamage, postGameTimer;
private LinkedList<Block> blocks = new LinkedList<Block>();
// Constants
private static final int NUM_BLOCKS = 145, XRANGE = 400, Y_DIST = 105,
INITIAL_IMG_OFFSET = 14500, KIRBY_INITIAL_Y = 142, DAMAGE_GOAL = 180,
POST_GAME_HANGTIME = 350, FONT_SIZE_SM = 14, FONT_SIZE_BIG = 21,
BASE_POSTG_Y = 195;
// Constants that are also text/meter coordinates.
// (There are actually additional coordinates in paintComponent.)
private static final int CLOGMETER_X = 318, CLOGMETER_Y = 25;
public Level2() {
backgroundImg = Images.get("level2Backdrop");
}
/**
* Reset everything to its initial state.
* After this method is executed, Kirby will be at the top of the level
* and the vacuum will be 0% clogged.
*/
protected void reset() {
isPaused = false;
pauseIndex = 0;
yTraveled = 0;
kirby = new Level2Kirby(42, KIRBY_INITIAL_Y, Kirby.Animation.SOMERSAULTING);
blockDamage = 0;
postGameTimer = 0;
timeRemaining = INITIAL_IMG_OFFSET;
// Clear and initialize our collection of blocks
blocks.clear();
for (int i = 0; i < NUM_BLOCKS; i++) {
blocks.add(new Block((int) (Math.random() * XRANGE), i * Y_DIST));
}
}
/**
* Specifies whether all action should have ceased.
* Like the development of this game.
*/
private boolean isGameOver() {
return (blockDamage >= DAMAGE_GOAL) || (timeRemaining <= 0);
}
@Override
public void actionPerformed(ActionEvent evt) {
if (!isPaused) {
if (blockDamage >= DAMAGE_GOAL) {
// You win! ...the whole game, now that I've ceased development!
postGameTimer += 1;
if (postGameTimer >= POST_GAME_HANGTIME) {
// Transition to the congratulatory screen
deactivate();
GameState.layout.show(GameState.contentPanel, "congratulations");
GameState.congratulatoryPanel.activate();
// Save the player into the hall of fame (100% hooray)
file.incrementLevel();
file.updatePercentage();
TripleT.savePersistentInfo(GameState.pInfo);
}
} else if (timeRemaining <= 0) {
// You lose! Dang, you suck even more than that vacuum. ;)
kirby.flyUpward();
if (kirby.getY() < -kirby.spriteHeight) {
postGameTimer += 1;
if (postGameTimer >= POST_GAME_HANGTIME) {
// Transition to the game over screen
deactivate();
GameState.layout.show(GameState.contentPanel, "gameOver");
GameState.gameOverPanel.activate(file);
}
}
} else {
yTraveled += 2;
timeRemaining -= 2;
kirby.move();
if (kirby.getFrame() == kirby.getAnimation().getLength()) {
kirby.setCurrentFrame(0);
} else if (kirby.getFrame() > 0) {
kirby.updateFrame();
}
// Iterate through the blocks
Iterator<Block> blockIter = blocks.iterator();
while (blockIter.hasNext()) {
Block b = blockIter.next();
if (b.getRectangle().intersects(kirby.getRectangle())) {
b.accelerated = true;
kirby.setCurrentFrame(1);
}
if (b.accelerated) {
b.yPos -= 3;
if (b.yPos < -Block.BIG_BLOCKSIZE) {
// This one was hit by Kirby, so it does block damage
blockDamage += (b.isBig) ? 5 : 2;
}
} else {
b.yPos -= 1;
}
if (b.yPos < -Block.BIG_BLOCKSIZE) {
blockIter.remove();
}
}
}
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(backgroundImg, 0, -INITIAL_IMG_OFFSET + yTraveled, null);
for (Block b : blocks) {
g2.drawImage(b.img, b.xPos, b.yPos, null);
if (b.yPos > TripleTWindow.SCR_HEIGHT) {
break;
}
}
kirby.drawImage(g2); // Kirby
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); // antialiasing
// Draw the objective + "clog meter" text
g.setFont(new Font("Verdana", Font.BOLD, FONT_SIZE_SM));
g.setColor(Color.WHITE);
g2.drawString("Objective:", 5, 21); // (x, y) coordinates
g2.drawString("Hit blocks upward", 5, 40);
g2.drawString("and clog the vacuum!", 5, 54);
g2.drawString("ClogMeter: ", CLOGMETER_X + 1, 21);
g2.drawString("Time Remaining: " + timeRemaining, CLOGMETER_X + 1, 56);
g.setColor(Color.BLACK);
g2.drawString("Objective: ", 4, 20);
g2.drawString("Hit blocks upward", 4, 39);
g2.drawString("and clog the vacuum!", 4, 53);
g2.drawString("ClogMeter: ", CLOGMETER_X, 20);
g2.drawString("Time Remaining: " + timeRemaining, CLOGMETER_X, 55);
// The clog meter itself
g.setColor(Color.WHITE);
g2.fill3DRect(CLOGMETER_X, CLOGMETER_Y, DAMAGE_GOAL + 2, 15, true);
g.setColor(Color.BLACK);
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, DAMAGE_GOAL, 13, true);
g.setColor(Color.GREEN);
if (blockDamage < DAMAGE_GOAL) {
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, blockDamage, 13, true);
} else {
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, DAMAGE_GOAL, 13, true);
}
// Post-game text display
if (postGameTimer > 0) {
if (blockDamage >= DAMAGE_GOAL) {
g.setFont(new Font("Verdana", Font.BOLD, FONT_SIZE_BIG));
g.setColor(Color.WHITE);
g2.drawString("You did it!", 187, BASE_POSTG_Y + 1);
g2.drawString("That vacuum isn't getting YOU...", 70, BASE_POSTG_Y + 25);
g.setColor(Color.BLACK);
g2.drawString("You did it!", 186, BASE_POSTG_Y);
g2.drawString("That vacuum isn't getting YOU...", 69, BASE_POSTG_Y + 24);
} else {
g.setFont(new Font("Verdana", Font.BOLD, 21));
g.setColor(Color.WHITE);
g2.drawString("The vacuum got you...", 129, BASE_POSTG_Y + 1);
g.setColor(Color.BLACK);
g2.drawString("The vacuum got you...", 128, BASE_POSTG_Y);
}
}
if (isPaused) {
g2.drawImage(Images.get("pauseOverlay" + pauseIndex), 0, 0, null);
}
}
/**
* Set them key bindings.
* The controls involved in Level 2 are RIGHT, LEFT, and PAUSE/SELECT.
*/
void setKeyBindings() {
// Input map bindings [pressed]
InputMap iMap = getInputMap();
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0), RIGHT_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0), LEFT_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.downKey, 0), DOWN_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.upKey, 0), UP_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.pauseKey, 0), PAUSELECT);
iMap.put(KeyStroke.getKeyStroke("ENTER"), ENTER_PRESSED);
// [Released]
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true), RIGHT_RELEASED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true), LEFT_RELEASED);
// Action map bindings [pressed]
ActionMap aMap = getActionMap();
aMap.put(RIGHT_PRESSED, new RightPressedAction());
aMap.put(LEFT_PRESSED, new LeftPressedAction());
aMap.put(DOWN_PRESSED, new DownPressedAction());
aMap.put(UP_PRESSED, new UpPressedAction());
aMap.put(PAUSELECT, new PauselectAction());
aMap.put(ENTER_PRESSED, new EnterPressedAction());
// [Released]
aMap.put(RIGHT_RELEASED, new RightReleasedAction());
aMap.put(LEFT_RELEASED, new LeftReleasedAction());
}
@Override
void updateKeyBindings(KeyStroke oldKey, KeyStroke newKey, boolean shouldRemove) {
InputMap iMap = getInputMap();
if (RIGHT_PRESSED.equals(iMap.get(oldKey))) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true),
RIGHT_RELEASED);
} else if (LEFT_PRESSED.equals(iMap.get(oldKey))) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true),
LEFT_RELEASED);
}
iMap.put(newKey, iMap.get(oldKey));
if (shouldRemove) { iMap.remove(oldKey); }
}
@Override
void updateKeyBindings(KeyStroke oldKey, KeyStroke newKey, String oldAction, boolean shouldRemove) {
InputMap iMap = getInputMap();
if (RIGHT_PRESSED.equals(oldAction)) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true),
RIGHT_RELEASED);
} else if (LEFT_PRESSED.equals(oldAction)) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true),
LEFT_RELEASED);
}
iMap.put(newKey, oldAction);
if (shouldRemove) { iMap.remove(oldKey); }
}
//================================================================================
// Overridden action methods
//================================================================================
protected void rightPressed() {
if (!isPaused && !isGameOver()) {
kirby.rightPressed();
repaint();
}
}
protected void leftPressed() {
if (!isPaused && !isGameOver()) {
kirby.leftPressed();
repaint();
}
}
protected void downPressed() {
if (isPaused) {
pauseIndex = 1 - pauseIndex;
}
repaint();
}
protected void upPressed() {
if (isPaused) {
pauseIndex = 1 - pauseIndex;
}
repaint();
}
protected void enterPressed() {
if (isPaused) {
if (pauseIndex == 0) {
isPaused = false;
} else {
deactivate();
GameState.layout.show(GameState.contentPanel, "mainMenu");
GameState.menuPanel.requestFocus();
}
}
}
protected void rightReleased() {
if (!isGameOver()) {
kirby.rightReleased();
repaint();
}
}
protected void leftReleased() {
if (!isGameOver()) {
kirby.leftReleased();
repaint();
}
}
//================================================================================
// Inner classes
//================================================================================
/**
* A block, meant for Kirby to collide with.
* Used exclusively in Level 2 as an interactive object.
*/
private class Block {
int xPos, yPos;
Image img;
boolean isBig;
boolean accelerated;
static final int BIG_BLOCKSIZE = 32, SMALL_BLOCKSIZE = 16;
/**
* Constructor. Sets x- and y- coordinates for the block.
* Determines randomly whether or not it is a big block or a small block.
* @param xPos the x-coordinate
* @param yPos the y-coordinate
*/
Block(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
if (Math.random() >= 0.5) {
img = Images.get("bigBlock");
isBig = true;
} else {
img = Images.get("smallBlock");
}
}
/**
* Gets the rectangle associated with the block, to be used for collision detection.
*/
Rectangle getRectangle() {
if (isBig) {
return new Rectangle(xPos, yPos, BIG_BLOCKSIZE, BIG_BLOCKSIZE);
} else {
return new Rectangle(xPos, yPos, SMALL_BLOCKSIZE, SMALL_BLOCKSIZE);
}
}
}
}
| ohjay/TripleTGame | TripleT/Level2.java | 4,510 | // Overridden action methods | line_comment | nl | package TripleT;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
import javax.swing.InputMap;
import javax.swing.Timer;
import javax.swing.KeyStroke;
import javax.swing.InputMap;
import javax.swing.ActionMap;
import java.util.LinkedList;
import java.util.Iterator;
/**
* The second level of the game (world 1, level 2).
*
* In light of my decision to cease development on Triple T,
* this is now going to be the vacuum stage that I'd planned to save for later in the game.
* @author Owen Jow
*/
public class Level2 extends LevelPanel implements ActionListener {
private int yTraveled, timeRemaining, blockDamage, postGameTimer;
private LinkedList<Block> blocks = new LinkedList<Block>();
// Constants
private static final int NUM_BLOCKS = 145, XRANGE = 400, Y_DIST = 105,
INITIAL_IMG_OFFSET = 14500, KIRBY_INITIAL_Y = 142, DAMAGE_GOAL = 180,
POST_GAME_HANGTIME = 350, FONT_SIZE_SM = 14, FONT_SIZE_BIG = 21,
BASE_POSTG_Y = 195;
// Constants that are also text/meter coordinates.
// (There are actually additional coordinates in paintComponent.)
private static final int CLOGMETER_X = 318, CLOGMETER_Y = 25;
public Level2() {
backgroundImg = Images.get("level2Backdrop");
}
/**
* Reset everything to its initial state.
* After this method is executed, Kirby will be at the top of the level
* and the vacuum will be 0% clogged.
*/
protected void reset() {
isPaused = false;
pauseIndex = 0;
yTraveled = 0;
kirby = new Level2Kirby(42, KIRBY_INITIAL_Y, Kirby.Animation.SOMERSAULTING);
blockDamage = 0;
postGameTimer = 0;
timeRemaining = INITIAL_IMG_OFFSET;
// Clear and initialize our collection of blocks
blocks.clear();
for (int i = 0; i < NUM_BLOCKS; i++) {
blocks.add(new Block((int) (Math.random() * XRANGE), i * Y_DIST));
}
}
/**
* Specifies whether all action should have ceased.
* Like the development of this game.
*/
private boolean isGameOver() {
return (blockDamage >= DAMAGE_GOAL) || (timeRemaining <= 0);
}
@Override
public void actionPerformed(ActionEvent evt) {
if (!isPaused) {
if (blockDamage >= DAMAGE_GOAL) {
// You win! ...the whole game, now that I've ceased development!
postGameTimer += 1;
if (postGameTimer >= POST_GAME_HANGTIME) {
// Transition to the congratulatory screen
deactivate();
GameState.layout.show(GameState.contentPanel, "congratulations");
GameState.congratulatoryPanel.activate();
// Save the player into the hall of fame (100% hooray)
file.incrementLevel();
file.updatePercentage();
TripleT.savePersistentInfo(GameState.pInfo);
}
} else if (timeRemaining <= 0) {
// You lose! Dang, you suck even more than that vacuum. ;)
kirby.flyUpward();
if (kirby.getY() < -kirby.spriteHeight) {
postGameTimer += 1;
if (postGameTimer >= POST_GAME_HANGTIME) {
// Transition to the game over screen
deactivate();
GameState.layout.show(GameState.contentPanel, "gameOver");
GameState.gameOverPanel.activate(file);
}
}
} else {
yTraveled += 2;
timeRemaining -= 2;
kirby.move();
if (kirby.getFrame() == kirby.getAnimation().getLength()) {
kirby.setCurrentFrame(0);
} else if (kirby.getFrame() > 0) {
kirby.updateFrame();
}
// Iterate through the blocks
Iterator<Block> blockIter = blocks.iterator();
while (blockIter.hasNext()) {
Block b = blockIter.next();
if (b.getRectangle().intersects(kirby.getRectangle())) {
b.accelerated = true;
kirby.setCurrentFrame(1);
}
if (b.accelerated) {
b.yPos -= 3;
if (b.yPos < -Block.BIG_BLOCKSIZE) {
// This one was hit by Kirby, so it does block damage
blockDamage += (b.isBig) ? 5 : 2;
}
} else {
b.yPos -= 1;
}
if (b.yPos < -Block.BIG_BLOCKSIZE) {
blockIter.remove();
}
}
}
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(backgroundImg, 0, -INITIAL_IMG_OFFSET + yTraveled, null);
for (Block b : blocks) {
g2.drawImage(b.img, b.xPos, b.yPos, null);
if (b.yPos > TripleTWindow.SCR_HEIGHT) {
break;
}
}
kirby.drawImage(g2); // Kirby
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); // antialiasing
// Draw the objective + "clog meter" text
g.setFont(new Font("Verdana", Font.BOLD, FONT_SIZE_SM));
g.setColor(Color.WHITE);
g2.drawString("Objective:", 5, 21); // (x, y) coordinates
g2.drawString("Hit blocks upward", 5, 40);
g2.drawString("and clog the vacuum!", 5, 54);
g2.drawString("ClogMeter: ", CLOGMETER_X + 1, 21);
g2.drawString("Time Remaining: " + timeRemaining, CLOGMETER_X + 1, 56);
g.setColor(Color.BLACK);
g2.drawString("Objective: ", 4, 20);
g2.drawString("Hit blocks upward", 4, 39);
g2.drawString("and clog the vacuum!", 4, 53);
g2.drawString("ClogMeter: ", CLOGMETER_X, 20);
g2.drawString("Time Remaining: " + timeRemaining, CLOGMETER_X, 55);
// The clog meter itself
g.setColor(Color.WHITE);
g2.fill3DRect(CLOGMETER_X, CLOGMETER_Y, DAMAGE_GOAL + 2, 15, true);
g.setColor(Color.BLACK);
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, DAMAGE_GOAL, 13, true);
g.setColor(Color.GREEN);
if (blockDamage < DAMAGE_GOAL) {
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, blockDamage, 13, true);
} else {
g2.fill3DRect(CLOGMETER_X + 1, CLOGMETER_Y + 1, DAMAGE_GOAL, 13, true);
}
// Post-game text display
if (postGameTimer > 0) {
if (blockDamage >= DAMAGE_GOAL) {
g.setFont(new Font("Verdana", Font.BOLD, FONT_SIZE_BIG));
g.setColor(Color.WHITE);
g2.drawString("You did it!", 187, BASE_POSTG_Y + 1);
g2.drawString("That vacuum isn't getting YOU...", 70, BASE_POSTG_Y + 25);
g.setColor(Color.BLACK);
g2.drawString("You did it!", 186, BASE_POSTG_Y);
g2.drawString("That vacuum isn't getting YOU...", 69, BASE_POSTG_Y + 24);
} else {
g.setFont(new Font("Verdana", Font.BOLD, 21));
g.setColor(Color.WHITE);
g2.drawString("The vacuum got you...", 129, BASE_POSTG_Y + 1);
g.setColor(Color.BLACK);
g2.drawString("The vacuum got you...", 128, BASE_POSTG_Y);
}
}
if (isPaused) {
g2.drawImage(Images.get("pauseOverlay" + pauseIndex), 0, 0, null);
}
}
/**
* Set them key bindings.
* The controls involved in Level 2 are RIGHT, LEFT, and PAUSE/SELECT.
*/
void setKeyBindings() {
// Input map bindings [pressed]
InputMap iMap = getInputMap();
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0), RIGHT_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0), LEFT_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.downKey, 0), DOWN_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.upKey, 0), UP_PRESSED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.pauseKey, 0), PAUSELECT);
iMap.put(KeyStroke.getKeyStroke("ENTER"), ENTER_PRESSED);
// [Released]
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true), RIGHT_RELEASED);
addToInputMap(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true), LEFT_RELEASED);
// Action map bindings [pressed]
ActionMap aMap = getActionMap();
aMap.put(RIGHT_PRESSED, new RightPressedAction());
aMap.put(LEFT_PRESSED, new LeftPressedAction());
aMap.put(DOWN_PRESSED, new DownPressedAction());
aMap.put(UP_PRESSED, new UpPressedAction());
aMap.put(PAUSELECT, new PauselectAction());
aMap.put(ENTER_PRESSED, new EnterPressedAction());
// [Released]
aMap.put(RIGHT_RELEASED, new RightReleasedAction());
aMap.put(LEFT_RELEASED, new LeftReleasedAction());
}
@Override
void updateKeyBindings(KeyStroke oldKey, KeyStroke newKey, boolean shouldRemove) {
InputMap iMap = getInputMap();
if (RIGHT_PRESSED.equals(iMap.get(oldKey))) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true),
RIGHT_RELEASED);
} else if (LEFT_PRESSED.equals(iMap.get(oldKey))) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true),
LEFT_RELEASED);
}
iMap.put(newKey, iMap.get(oldKey));
if (shouldRemove) { iMap.remove(oldKey); }
}
@Override
void updateKeyBindings(KeyStroke oldKey, KeyStroke newKey, String oldAction, boolean shouldRemove) {
InputMap iMap = getInputMap();
if (RIGHT_PRESSED.equals(oldAction)) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.rightKey, 0, true),
RIGHT_RELEASED);
} else if (LEFT_PRESSED.equals(oldAction)) {
updateReleasedKeyBindings(iMap, KeyStroke.getKeyStroke(GameState.pInfo.leftKey, 0, true),
LEFT_RELEASED);
}
iMap.put(newKey, oldAction);
if (shouldRemove) { iMap.remove(oldKey); }
}
//================================================================================
// Overridden action<SUF>
//================================================================================
protected void rightPressed() {
if (!isPaused && !isGameOver()) {
kirby.rightPressed();
repaint();
}
}
protected void leftPressed() {
if (!isPaused && !isGameOver()) {
kirby.leftPressed();
repaint();
}
}
protected void downPressed() {
if (isPaused) {
pauseIndex = 1 - pauseIndex;
}
repaint();
}
protected void upPressed() {
if (isPaused) {
pauseIndex = 1 - pauseIndex;
}
repaint();
}
protected void enterPressed() {
if (isPaused) {
if (pauseIndex == 0) {
isPaused = false;
} else {
deactivate();
GameState.layout.show(GameState.contentPanel, "mainMenu");
GameState.menuPanel.requestFocus();
}
}
}
protected void rightReleased() {
if (!isGameOver()) {
kirby.rightReleased();
repaint();
}
}
protected void leftReleased() {
if (!isGameOver()) {
kirby.leftReleased();
repaint();
}
}
//================================================================================
// Inner classes
//================================================================================
/**
* A block, meant for Kirby to collide with.
* Used exclusively in Level 2 as an interactive object.
*/
private class Block {
int xPos, yPos;
Image img;
boolean isBig;
boolean accelerated;
static final int BIG_BLOCKSIZE = 32, SMALL_BLOCKSIZE = 16;
/**
* Constructor. Sets x- and y- coordinates for the block.
* Determines randomly whether or not it is a big block or a small block.
* @param xPos the x-coordinate
* @param yPos the y-coordinate
*/
Block(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
if (Math.random() >= 0.5) {
img = Images.get("bigBlock");
isBig = true;
} else {
img = Images.get("smallBlock");
}
}
/**
* Gets the rectangle associated with the block, to be used for collision detection.
*/
Rectangle getRectangle() {
if (isBig) {
return new Rectangle(xPos, yPos, BIG_BLOCKSIZE, BIG_BLOCKSIZE);
} else {
return new Rectangle(xPos, yPos, SMALL_BLOCKSIZE, SMALL_BLOCKSIZE);
}
}
}
}
|
179559_1 | package fr.imie.servlet;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import fr.imie.formation.DTO.CompetenceDTO;
import fr.imie.formation.DTO.NiveauDTO;
import fr.imie.formation.DTO.ProjetDTO;
import fr.imie.formation.DTO.PromotionDTO;
import fr.imie.formation.DTO.UtilisateurDTO;
import fr.imie.formation.factory.DAOFactory1;
import fr.imie.formation.services.exceptions.ServiceException;
import fr.imie.formation.transactionalFramework.exception.TransactionalConnectionException;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/UserForm")
public class UserForm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// Affichage utilisateur
if (request.getParameter("numligneutil") != null
&& request.getParameter("update") == null
&& request.getParameter("delete") == null) {
int ligne = Integer.valueOf(request.getParameter("numligneutil"));
Object listObj = session.getAttribute("listeUtilisateur");
Object listObj1 = session.getAttribute("ListeNivUtil");
Object listObj2 =session.getAttribute("listeUtil");
UtilisateurDTO utilisateur = null;
if (listObj1 != null) {
List<NiveauDTO> listNiveau = (List<NiveauDTO>) listObj1;
utilisateur = listNiveau.get(ligne).getUtilisateur();
session.removeAttribute("ListeNivUtil");
}
else if (listObj2 != null) {
List<UtilisateurDTO> listUtil = (List<UtilisateurDTO>) listObj2;
utilisateur = listUtil.get(ligne);
session.removeAttribute("listeUtil");
}
else {
List<UtilisateurDTO> listUtilisateur = (List<UtilisateurDTO>) listObj;
utilisateur = listUtilisateur.get(ligne);
session.removeAttribute("listeUtilisateur");
}
try {
UtilisateurDTO utilisateurDTO = DAOFactory1.getInstance()
.createUtilisateurService(null)
.readUtilisateur(utilisateur);
request.setAttribute("utilisateur", utilisateurDTO);
List<NiveauDTO> listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(utilisateurDTO);
request.setAttribute("ListeCompNiv", listCompNiv);
List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(utilisateurDTO);
request.setAttribute("ListeUtilProjet", listUtilProjet);
List<ProjetDTO >listeProjetForInvit = DAOFactory1.getInstance().createProjetService(null).readAllProjets();
//request.setAttribute("listeProjetForInvit", listeProjetForInvit);
request.setAttribute("listeProjetForInvit", listeProjetForInvit);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
// création utilisateur
else if (request.getParameter("create") != null
&& request.getParameter("create").equals("creer")) {
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.getRequestDispatcher("./UserCreate.jsp").forward(request,
response);
}
// modification utilisateur
else if (request.getParameter("update") != null
&& request.getParameter("update").equals("modifier")) {
request.setAttribute("utilisateur",
getUser(request.getParameter("numUtilisateur")));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtilisateur")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtilisateur")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ServiceException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
} // suppression utilisateur
else if (request.getParameter("delete") != null
& request.getParameter("delete").equals("supprimer")) {
request.setAttribute("utilisateur",
getUser(request.getParameter("numUtilisateur")));
request.getRequestDispatcher("./UserDelete.jsp").forward(request,
response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Modifier un utilisateur
if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Confirmer")) {
UtilisateurDTO utilisateurUpdate = getUser(request
.getParameter("numUtilisateur"));
utilisateurUpdate.setNom(request.getParameter("nom"));
utilisateurUpdate.setPrenom(request.getParameter("prenom"));
String userDateNaisParam = request.getParameter("dateNaissance");
Date userDateNais = new Date();
try {
userDateNais = new SimpleDateFormat("dd/MM/yyyy")
.parse(userDateNaisParam);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
utilisateurUpdate.setDateNaissance(userDateNais);
utilisateurUpdate.setAdresse(request.getParameter("adresse"));
utilisateurUpdate.setTel(request.getParameter("tel"));
utilisateurUpdate.setMail(request.getParameter("mail"));
String promoParam = request.getParameter("promotion");
PromotionDTO promo = new PromotionDTO();
Integer promoNum = null;
if (promoParam != null) {
promoNum = Integer.valueOf(promoParam);
}
if (promoNum != null) {
PromotionDTO promoUpdate = new PromotionDTO();
promoUpdate.setNum(promoNum);
try {
promo = DAOFactory1.getInstance()
.createPromotionService(null)
.readPromotion(promoUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
utilisateurUpdate.setPromotion(promo);
utilisateurUpdate.setLogin(request.getParameter("login"));
utilisateurUpdate.setPassword(request.getParameter("password"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.updateUtilisateur(utilisateurUpdate);
List<NiveauDTO> listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(utilisateurUpdate);
List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(utilisateurUpdate);
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
//request.setAttribute("action", "updateAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("utilisateur",
utilisateurUpdate);
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
//Ajout des compétences d'un utilisateur
else if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Enregistrer")){
UtilisateurDTO util = getUser(request.getParameter("numUtil"));
NiveauDTO niveau = getNiveau(request.getParameter("niveau"));
CompetenceDTO comp = getComp(request.getParameter("comp"));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
DAOFactory1.getInstance().createCompetenceNiveauService(null).addCompUtil(util, comp, niveau);
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtil")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.setAttribute("utilisateur", getUser(request.getParameter("numUtil")));
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
}
//Modification des compétences d'un utilisateur
else if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Ok")){
UtilisateurDTO util = getUser(request.getParameter("numUtil"));
NiveauDTO niveau = getNiveau(request.getParameter("niveau"));
CompetenceDTO comp = getComp(request.getParameter("comp"));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
DAOFactory1.getInstance().createCompetenceNiveauService(null).updateCompUtil(util, comp, niveau);
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtil")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.setAttribute("utilisateur", getUser(request.getParameter("numUtil")));
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
}
// Ajouter un utilisateur
else if (request.getParameter("createAction") != null
&& request.getParameter("createAction").equals("ajouter")) {
UtilisateurDTO utilisateurCreate = new UtilisateurDTO();
utilisateurCreate.setNom(request.getParameter("nom"));
utilisateurCreate.setPrenom(request.getParameter("prenom"));
String userDateNaisParam = request.getParameter("dateNaissance");
Date userDateNais = new Date();
try {
userDateNais = new SimpleDateFormat("dd/MM/yyyy")
.parse(userDateNaisParam);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
utilisateurCreate.setDateNaissance(userDateNais);
utilisateurCreate.setAdresse(request.getParameter("adresse"));
utilisateurCreate.setTel(request.getParameter("tel"));
utilisateurCreate.setMail(request.getParameter("mail"));
String promoParam = request.getParameter("promotion");
PromotionDTO promo = new PromotionDTO();
Integer promoNum = null;
if (promoParam != null) {
promoNum = Integer.valueOf(promoParam);
}
if (promoNum != null) {
PromotionDTO promoUpdate = new PromotionDTO();
promoUpdate.setNum(promoNum);
try {
promo = DAOFactory1.getInstance()
.createPromotionService(null)
.readPromotion(promoUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
utilisateurCreate.setPromotion(promo);
utilisateurCreate.setLogin(request.getParameter("login"));
utilisateurCreate.setPassword(request.getParameter("password"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.createUtilisateur(utilisateurCreate);
request.setAttribute("action", "createAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("utilisateur", utilisateurCreate);
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
// Supprimer un utilisateur
else if (request.getParameter("deleteAction") != null
&& request.getParameter("deleteAction").equals("supprimer")) {
UtilisateurDTO utilisateurDelete = getUser(request
.getParameter("numUtilisateur"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.deleteUtilisateur(utilisateurDelete);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./ListUserView");
}
}
private UtilisateurDTO getUser(String requestNumUtilisateur) {
UtilisateurDTO utilisateurDTO = new UtilisateurDTO();
int numUtilisateur = Integer.valueOf(requestNumUtilisateur);
UtilisateurDTO utilisateurTemp = new UtilisateurDTO();
utilisateurTemp.setNum(numUtilisateur);
try {
utilisateurDTO = DAOFactory1.getInstance()
.createUtilisateurService(null)
.readUtilisateur(utilisateurTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return utilisateurDTO;
}
private CompetenceDTO getComp(String requestNumComp) {
CompetenceDTO compDTO = new CompetenceDTO();
int numComp = Integer.valueOf(requestNumComp);
CompetenceDTO compTemp = new CompetenceDTO();
compTemp.setNum(numComp);
try {
compDTO = DAOFactory1.getInstance()
.createCompetenceNiveauService(null).readCompetence(compTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return compDTO;
}
private NiveauDTO getNiveau(String requestNumNiveau) {
NiveauDTO niveauDTO = new NiveauDTO();
int numComp = Integer.valueOf(requestNumNiveau);
NiveauDTO niveauTemp = new NiveauDTO();
niveauTemp.setNum(numComp);
try {
niveauDTO = DAOFactory1.getInstance()
.createCompetenceNiveauService(null).readNiveau(niveauTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return niveauDTO;
}
}
| old-sources/DLCDI08-ICompetence-G3 | Servlets/src/fr/imie/servlet/UserForm.java | 5,851 | /**
* @see HttpServlet#HttpServlet()
*/ | block_comment | nl | package fr.imie.servlet;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import fr.imie.formation.DTO.CompetenceDTO;
import fr.imie.formation.DTO.NiveauDTO;
import fr.imie.formation.DTO.ProjetDTO;
import fr.imie.formation.DTO.PromotionDTO;
import fr.imie.formation.DTO.UtilisateurDTO;
import fr.imie.formation.factory.DAOFactory1;
import fr.imie.formation.services.exceptions.ServiceException;
import fr.imie.formation.transactionalFramework.exception.TransactionalConnectionException;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/UserForm")
public class UserForm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
<SUF>*/
public UserForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// Affichage utilisateur
if (request.getParameter("numligneutil") != null
&& request.getParameter("update") == null
&& request.getParameter("delete") == null) {
int ligne = Integer.valueOf(request.getParameter("numligneutil"));
Object listObj = session.getAttribute("listeUtilisateur");
Object listObj1 = session.getAttribute("ListeNivUtil");
Object listObj2 =session.getAttribute("listeUtil");
UtilisateurDTO utilisateur = null;
if (listObj1 != null) {
List<NiveauDTO> listNiveau = (List<NiveauDTO>) listObj1;
utilisateur = listNiveau.get(ligne).getUtilisateur();
session.removeAttribute("ListeNivUtil");
}
else if (listObj2 != null) {
List<UtilisateurDTO> listUtil = (List<UtilisateurDTO>) listObj2;
utilisateur = listUtil.get(ligne);
session.removeAttribute("listeUtil");
}
else {
List<UtilisateurDTO> listUtilisateur = (List<UtilisateurDTO>) listObj;
utilisateur = listUtilisateur.get(ligne);
session.removeAttribute("listeUtilisateur");
}
try {
UtilisateurDTO utilisateurDTO = DAOFactory1.getInstance()
.createUtilisateurService(null)
.readUtilisateur(utilisateur);
request.setAttribute("utilisateur", utilisateurDTO);
List<NiveauDTO> listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(utilisateurDTO);
request.setAttribute("ListeCompNiv", listCompNiv);
List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(utilisateurDTO);
request.setAttribute("ListeUtilProjet", listUtilProjet);
List<ProjetDTO >listeProjetForInvit = DAOFactory1.getInstance().createProjetService(null).readAllProjets();
//request.setAttribute("listeProjetForInvit", listeProjetForInvit);
request.setAttribute("listeProjetForInvit", listeProjetForInvit);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
// création utilisateur
else if (request.getParameter("create") != null
&& request.getParameter("create").equals("creer")) {
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.getRequestDispatcher("./UserCreate.jsp").forward(request,
response);
}
// modification utilisateur
else if (request.getParameter("update") != null
&& request.getParameter("update").equals("modifier")) {
request.setAttribute("utilisateur",
getUser(request.getParameter("numUtilisateur")));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtilisateur")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtilisateur")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ServiceException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
} // suppression utilisateur
else if (request.getParameter("delete") != null
& request.getParameter("delete").equals("supprimer")) {
request.setAttribute("utilisateur",
getUser(request.getParameter("numUtilisateur")));
request.getRequestDispatcher("./UserDelete.jsp").forward(request,
response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Modifier un utilisateur
if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Confirmer")) {
UtilisateurDTO utilisateurUpdate = getUser(request
.getParameter("numUtilisateur"));
utilisateurUpdate.setNom(request.getParameter("nom"));
utilisateurUpdate.setPrenom(request.getParameter("prenom"));
String userDateNaisParam = request.getParameter("dateNaissance");
Date userDateNais = new Date();
try {
userDateNais = new SimpleDateFormat("dd/MM/yyyy")
.parse(userDateNaisParam);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
utilisateurUpdate.setDateNaissance(userDateNais);
utilisateurUpdate.setAdresse(request.getParameter("adresse"));
utilisateurUpdate.setTel(request.getParameter("tel"));
utilisateurUpdate.setMail(request.getParameter("mail"));
String promoParam = request.getParameter("promotion");
PromotionDTO promo = new PromotionDTO();
Integer promoNum = null;
if (promoParam != null) {
promoNum = Integer.valueOf(promoParam);
}
if (promoNum != null) {
PromotionDTO promoUpdate = new PromotionDTO();
promoUpdate.setNum(promoNum);
try {
promo = DAOFactory1.getInstance()
.createPromotionService(null)
.readPromotion(promoUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
utilisateurUpdate.setPromotion(promo);
utilisateurUpdate.setLogin(request.getParameter("login"));
utilisateurUpdate.setPassword(request.getParameter("password"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.updateUtilisateur(utilisateurUpdate);
List<NiveauDTO> listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(utilisateurUpdate);
List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(utilisateurUpdate);
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
//request.setAttribute("action", "updateAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("utilisateur",
utilisateurUpdate);
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
//Ajout des compétences d'un utilisateur
else if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Enregistrer")){
UtilisateurDTO util = getUser(request.getParameter("numUtil"));
NiveauDTO niveau = getNiveau(request.getParameter("niveau"));
CompetenceDTO comp = getComp(request.getParameter("comp"));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
DAOFactory1.getInstance().createCompetenceNiveauService(null).addCompUtil(util, comp, niveau);
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtil")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.setAttribute("utilisateur", getUser(request.getParameter("numUtil")));
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
}
//Modification des compétences d'un utilisateur
else if (request.getParameter("updateAction") != null
&& request.getParameter("updateAction").equals("Ok")){
UtilisateurDTO util = getUser(request.getParameter("numUtil"));
NiveauDTO niveau = getNiveau(request.getParameter("niveau"));
CompetenceDTO comp = getComp(request.getParameter("comp"));
List<ProjetDTO> listUtilProjet = null;
List<PromotionDTO> listPromo = null;
List<NiveauDTO> listCompNiv = null;
List<NiveauDTO> listNiveau =null;
List<CompetenceDTO> listComp = null;
try {
DAOFactory1.getInstance().createCompetenceNiveauService(null).updateCompUtil(util, comp, niveau);
listUtilProjet = DAOFactory1
.getInstance()
.createProjetService(null)
.readProjetByUtilisateur(
getUser(request.getParameter("numUtil")));
listPromo = DAOFactory1.getInstance()
.createPromotionService(null).readAllPromotion();
listCompNiv = DAOFactory1.getInstance()
.createCompetenceNiveauService(null)
.readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil")));
listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence();
listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau();
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("ListeCompNiv", listCompNiv);
request.setAttribute("ListeUtilProjet", listUtilProjet);
request.setAttribute("ListePromo", listPromo);
request.setAttribute("ListeComp", listComp);
request.setAttribute("ListeNiveau", listNiveau);
request.setAttribute("utilisateur", getUser(request.getParameter("numUtil")));
request.getRequestDispatcher("./UserUpdate.jsp").forward(request,
response);
}
// Ajouter un utilisateur
else if (request.getParameter("createAction") != null
&& request.getParameter("createAction").equals("ajouter")) {
UtilisateurDTO utilisateurCreate = new UtilisateurDTO();
utilisateurCreate.setNom(request.getParameter("nom"));
utilisateurCreate.setPrenom(request.getParameter("prenom"));
String userDateNaisParam = request.getParameter("dateNaissance");
Date userDateNais = new Date();
try {
userDateNais = new SimpleDateFormat("dd/MM/yyyy")
.parse(userDateNaisParam);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
utilisateurCreate.setDateNaissance(userDateNais);
utilisateurCreate.setAdresse(request.getParameter("adresse"));
utilisateurCreate.setTel(request.getParameter("tel"));
utilisateurCreate.setMail(request.getParameter("mail"));
String promoParam = request.getParameter("promotion");
PromotionDTO promo = new PromotionDTO();
Integer promoNum = null;
if (promoParam != null) {
promoNum = Integer.valueOf(promoParam);
}
if (promoNum != null) {
PromotionDTO promoUpdate = new PromotionDTO();
promoUpdate.setNum(promoNum);
try {
promo = DAOFactory1.getInstance()
.createPromotionService(null)
.readPromotion(promoUpdate);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
utilisateurCreate.setPromotion(promo);
utilisateurCreate.setLogin(request.getParameter("login"));
utilisateurCreate.setPassword(request.getParameter("password"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.createUtilisateur(utilisateurCreate);
request.setAttribute("action", "createAction");
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("utilisateur", utilisateurCreate);
request.getRequestDispatcher("./UserRead.jsp").forward(request,
response);
}
// Supprimer un utilisateur
else if (request.getParameter("deleteAction") != null
&& request.getParameter("deleteAction").equals("supprimer")) {
UtilisateurDTO utilisateurDelete = getUser(request
.getParameter("numUtilisateur"));
try {
DAOFactory1.getInstance().createUtilisateurService(null)
.deleteUtilisateur(utilisateurDelete);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("./ListUserView");
}
}
private UtilisateurDTO getUser(String requestNumUtilisateur) {
UtilisateurDTO utilisateurDTO = new UtilisateurDTO();
int numUtilisateur = Integer.valueOf(requestNumUtilisateur);
UtilisateurDTO utilisateurTemp = new UtilisateurDTO();
utilisateurTemp.setNum(numUtilisateur);
try {
utilisateurDTO = DAOFactory1.getInstance()
.createUtilisateurService(null)
.readUtilisateur(utilisateurTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return utilisateurDTO;
}
private CompetenceDTO getComp(String requestNumComp) {
CompetenceDTO compDTO = new CompetenceDTO();
int numComp = Integer.valueOf(requestNumComp);
CompetenceDTO compTemp = new CompetenceDTO();
compTemp.setNum(numComp);
try {
compDTO = DAOFactory1.getInstance()
.createCompetenceNiveauService(null).readCompetence(compTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return compDTO;
}
private NiveauDTO getNiveau(String requestNumNiveau) {
NiveauDTO niveauDTO = new NiveauDTO();
int numComp = Integer.valueOf(requestNumNiveau);
NiveauDTO niveauTemp = new NiveauDTO();
niveauTemp.setNum(numComp);
try {
niveauDTO = DAOFactory1.getInstance()
.createCompetenceNiveauService(null).readNiveau(niveauTemp);
} catch (TransactionalConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return niveauDTO;
}
}
|
22678_23 | package ambiorix.spelbord.scoreberekenaars;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import ambiorix.spelbord.Gebied;
import ambiorix.spelbord.Pion;
import ambiorix.spelbord.ScoreBerekenaar;
import ambiorix.spelbord.Tegel;
import ambiorix.spelbord.TegelTypeVerzameling;
import ambiorix.spelbord.Terrein;
import ambiorix.spelbord.TerreinTypeVerzameling;
import ambiorix.spelbord.TegelBasis.RICHTING;
import ambiorix.spelers.Speler;
public class SimpelScoreBerekenaar implements ScoreBerekenaar {
public boolean eindeSpel;
public SimpelScoreBerekenaar() {
}
@Override
public void zetEindeSpel(boolean eindeSpel) {
this.eindeSpel = eindeSpel;
}
@Override
public boolean isEindeSpel() {
return eindeSpel;
}
@Override
public int berekenScore(Gebied gebied, Speler speler) {
// KORTE OPMERKING :
// KLOOSTER-gebieden zijn ALTIJD volledig als er een tegel met een
// klooster is geplaatst.
// De berekening isVolledig kijkt immers NIET of er 9 tegels
// rondliggen!!! (ander concept)
// hier dus rekening mee houden !
if (!eindeSpel) {
// tijdens het spel krijg je enkel punten voor VOLLEDIGE gebieden
if (!gebied.isVolledig())
return 0;
// na het spel krijg je ook punten voor onafgewerkte gebieden
}
// als er geen pionnen op staan, kunnen we ook geen score hebben
if (gebied.getPionnen().size() == 0)
return 0;
int spelerHeeftMeestePionnen = spelerHeeftMeestePionnen(gebied, speler);
if (spelerHeeftMeestePionnen == -1)
return 0;
if (gebied.getType() == TerreinTypeVerzameling.getInstantie().getType(
"TerreinType_Weg")) {
// aantal tegels waaruit de weg bestaat is meteen ook de score
// bij eindeSpel is dit nog altijd zo, dus geen aanpassingen nodig
return gebied.getTegels().size();
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Burcht")) {
// kasteel is (tegels * 2) + (schilden * 2) als volledig
// als niet volledig bij eindeSpel : * 1
int vermenigvuldiger = 2;
if (eindeSpel) {
if (!gebied.isVolledig()) // anders blijft de score *2
// natuurlijk
vermenigvuldiger = 1;
}
Vector<Tegel> tegels = gebied.getTegels();
int result = vermenigvuldiger * tegels.size();
for (Tegel tegel : tegels) {
// enkel die heeft voorlopig schildjes mogelijk
// als er nog andere zouden bijkomen moeten we daar hier gewoon
// ook op checken
if (tegel.getType() == TegelTypeVerzameling.getInstantie()
.getType("TegelType_BBBBB_MetSchild")) {
result += vermenigvuldiger;
}
}
return result;
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Klooster")) {
// klooster volledig omringd is 9 punten
// anders 1 punt per tegel errond
// dat dan nog eens + 1
// => gebied is altijd afgemaakt natuurlijk, we moeten de tegel gaan
// controleren op zijn buren !
Tegel tegel = gebied.getTegels().get(0);
int aantalBuren = 1;
Tegel bovenBuur = tegel.getBuur(RICHTING.BOVEN);
Tegel onderBuur = tegel.getBuur(RICHTING.ONDER);
Tegel linkerBuur = tegel.getBuur(RICHTING.LINKS);
Tegel rechterBuur = tegel.getBuur(RICHTING.RECHTS);
if (bovenBuur != null)
aantalBuren++;
if (onderBuur != null)
aantalBuren++;
if (linkerBuur != null) {
aantalBuren++;
if (linkerBuur.getBuur(RICHTING.BOVEN) != null)
aantalBuren++;
if (linkerBuur.getBuur(RICHTING.ONDER) != null)
aantalBuren++;
} else {
// kijken of we aan de tegel linksboven kunnen komen via boven
if (bovenBuur != null)
if (bovenBuur.getBuur(RICHTING.LINKS) != null)
aantalBuren++;
// kijken of we aan de tegel linksonder kunnen komen via onder
if (onderBuur != null)
if (onderBuur.getBuur(RICHTING.LINKS) != null)
aantalBuren++;
}
if (rechterBuur != null) {
aantalBuren++;
if (rechterBuur.getBuur(RICHTING.BOVEN) != null)
aantalBuren++;
if (rechterBuur.getBuur(RICHTING.ONDER) != null)
aantalBuren++;
} else {
// kijken of we aan de tegel rechtsboven kunnen komen via boven
if (bovenBuur != null)
if (bovenBuur.getBuur(RICHTING.RECHTS) != null)
aantalBuren++;
// kijken of we aan de tegel rechtsonder kunnen komen via onder
if (onderBuur != null)
if (onderBuur.getBuur(RICHTING.RECHTS) != null)
aantalBuren++;
}
if (!eindeSpel) {
// enkel punten als er 8 tegels rond liggen
// checken op 9 want aantalBuren begint op 1 (dan is het
// automatisch gelijk aan het aantal punten)
if (aantalBuren != 9)
return 0;
}
return aantalBuren;
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Gras")) {
// OPM : we komen hier enkel bij eindeSpel !
// punten per AFGEWERKT KASTEEL dat grenst aan gras...
// mogelijk algoritme : alle tegels in gebied afgaan en kijken welke
// een stuk kasteel op zich hebben.
// daar braaf de kastelen berekenen, en zo weten we welke volledig
// zijn.
Vector<Tegel> tegels = gebied.getTegels();
Vector<Gebied> gevondenSteden = new Vector<Gebied>();
/*
* De boeren verzorgen enkel afgewerkte steden langs hun weiland.
* Voor elke afgewerkte stad krijgt de speler met de meeste boeren
* in dat weiland 4 punten.
*/
int result = 0;
for (Tegel tegel : tegels) {
// TODO : REKENING HOUDEN MET MEERDERE STEDEN-STUKKEN OP 1 TEGEL
// !!!!
// hoewel dit maar HEEEEL zelden zal voorkomen, dus laten we dit
// momenteel EVENTJES buiten beschouwing
Terrein burchtStart = tegel
.getTerreinVanType(TerreinTypeVerzameling
.getInstantie().getType("TerreinType_Burcht"));
if (burchtStart != null) // anders geen Burcht op deze tegel
{
// eersrt kijken of het Terrein nog geen stukje is van een
// reeds gevonden burcht
for (Gebied burchtGebied : gevondenSteden) {
for (Tegel burchtTegel : burchtGebied.getTegels()) {
if (burchtTegel == burchtStart.getTegel())
continue;
}
}
Gebied burcht = tegel.getGebied(burchtStart);
gevondenSteden.add(burcht);
if (burcht.isVolledig())
result += 4;
}
}
return result;
} else
return 0;
}
/*
* Functie geeft -1 terug als de speler niet het meeste pionnen heeft, 0 als
* er 2 of meer spelers gelijk aantal hebben en 1 als de speler het meeste
* pionnen heeft.
*/
private int spelerHeeftMeestePionnen(Gebied gebied, Speler speler) {
HashMap<Speler, Integer> pionnenPerSpeler = getPionnenPerSpeler(gebied);
int besteAantal = 0;
int spelerAantal = -1;
if (pionnenPerSpeler.get(speler) != null)
spelerAantal = pionnenPerSpeler.get(speler);
Set<Speler> spelers = pionnenPerSpeler.keySet();
for (Speler spelerIt : spelers) {
if (pionnenPerSpeler.get(spelerIt) > besteAantal) {
besteAantal = pionnenPerSpeler.get(spelerIt);
}
}
if (besteAantal == spelerAantal)
return 0;
if (besteAantal > spelerAantal)
return -1;
else
// speler heeft wel beste
return 1;
}
private HashMap<Speler, Integer> getPionnenPerSpeler(Gebied gebied) {
HashMap<Speler, Integer> output = new HashMap<Speler, Integer>();
Set<Pion> pionnen = gebied.getPionnen();
for (Pion pion : pionnen) {
if (output.get(pion.getSpeler()) == null)
output.put(pion.getSpeler(), 1);
else
output.put(pion.getSpeler(), output.get(pion.getSpeler()) + 1);
}
return output;
}
}
| oliviersels/ambiorix | ambiorix/src/ambiorix/spelbord/scoreberekenaars/SimpelScoreBerekenaar.java | 2,936 | // kijken of we aan de tegel linksonder kunnen komen via onder | line_comment | nl | package ambiorix.spelbord.scoreberekenaars;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import ambiorix.spelbord.Gebied;
import ambiorix.spelbord.Pion;
import ambiorix.spelbord.ScoreBerekenaar;
import ambiorix.spelbord.Tegel;
import ambiorix.spelbord.TegelTypeVerzameling;
import ambiorix.spelbord.Terrein;
import ambiorix.spelbord.TerreinTypeVerzameling;
import ambiorix.spelbord.TegelBasis.RICHTING;
import ambiorix.spelers.Speler;
public class SimpelScoreBerekenaar implements ScoreBerekenaar {
public boolean eindeSpel;
public SimpelScoreBerekenaar() {
}
@Override
public void zetEindeSpel(boolean eindeSpel) {
this.eindeSpel = eindeSpel;
}
@Override
public boolean isEindeSpel() {
return eindeSpel;
}
@Override
public int berekenScore(Gebied gebied, Speler speler) {
// KORTE OPMERKING :
// KLOOSTER-gebieden zijn ALTIJD volledig als er een tegel met een
// klooster is geplaatst.
// De berekening isVolledig kijkt immers NIET of er 9 tegels
// rondliggen!!! (ander concept)
// hier dus rekening mee houden !
if (!eindeSpel) {
// tijdens het spel krijg je enkel punten voor VOLLEDIGE gebieden
if (!gebied.isVolledig())
return 0;
// na het spel krijg je ook punten voor onafgewerkte gebieden
}
// als er geen pionnen op staan, kunnen we ook geen score hebben
if (gebied.getPionnen().size() == 0)
return 0;
int spelerHeeftMeestePionnen = spelerHeeftMeestePionnen(gebied, speler);
if (spelerHeeftMeestePionnen == -1)
return 0;
if (gebied.getType() == TerreinTypeVerzameling.getInstantie().getType(
"TerreinType_Weg")) {
// aantal tegels waaruit de weg bestaat is meteen ook de score
// bij eindeSpel is dit nog altijd zo, dus geen aanpassingen nodig
return gebied.getTegels().size();
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Burcht")) {
// kasteel is (tegels * 2) + (schilden * 2) als volledig
// als niet volledig bij eindeSpel : * 1
int vermenigvuldiger = 2;
if (eindeSpel) {
if (!gebied.isVolledig()) // anders blijft de score *2
// natuurlijk
vermenigvuldiger = 1;
}
Vector<Tegel> tegels = gebied.getTegels();
int result = vermenigvuldiger * tegels.size();
for (Tegel tegel : tegels) {
// enkel die heeft voorlopig schildjes mogelijk
// als er nog andere zouden bijkomen moeten we daar hier gewoon
// ook op checken
if (tegel.getType() == TegelTypeVerzameling.getInstantie()
.getType("TegelType_BBBBB_MetSchild")) {
result += vermenigvuldiger;
}
}
return result;
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Klooster")) {
// klooster volledig omringd is 9 punten
// anders 1 punt per tegel errond
// dat dan nog eens + 1
// => gebied is altijd afgemaakt natuurlijk, we moeten de tegel gaan
// controleren op zijn buren !
Tegel tegel = gebied.getTegels().get(0);
int aantalBuren = 1;
Tegel bovenBuur = tegel.getBuur(RICHTING.BOVEN);
Tegel onderBuur = tegel.getBuur(RICHTING.ONDER);
Tegel linkerBuur = tegel.getBuur(RICHTING.LINKS);
Tegel rechterBuur = tegel.getBuur(RICHTING.RECHTS);
if (bovenBuur != null)
aantalBuren++;
if (onderBuur != null)
aantalBuren++;
if (linkerBuur != null) {
aantalBuren++;
if (linkerBuur.getBuur(RICHTING.BOVEN) != null)
aantalBuren++;
if (linkerBuur.getBuur(RICHTING.ONDER) != null)
aantalBuren++;
} else {
// kijken of we aan de tegel linksboven kunnen komen via boven
if (bovenBuur != null)
if (bovenBuur.getBuur(RICHTING.LINKS) != null)
aantalBuren++;
// kijken of<SUF>
if (onderBuur != null)
if (onderBuur.getBuur(RICHTING.LINKS) != null)
aantalBuren++;
}
if (rechterBuur != null) {
aantalBuren++;
if (rechterBuur.getBuur(RICHTING.BOVEN) != null)
aantalBuren++;
if (rechterBuur.getBuur(RICHTING.ONDER) != null)
aantalBuren++;
} else {
// kijken of we aan de tegel rechtsboven kunnen komen via boven
if (bovenBuur != null)
if (bovenBuur.getBuur(RICHTING.RECHTS) != null)
aantalBuren++;
// kijken of we aan de tegel rechtsonder kunnen komen via onder
if (onderBuur != null)
if (onderBuur.getBuur(RICHTING.RECHTS) != null)
aantalBuren++;
}
if (!eindeSpel) {
// enkel punten als er 8 tegels rond liggen
// checken op 9 want aantalBuren begint op 1 (dan is het
// automatisch gelijk aan het aantal punten)
if (aantalBuren != 9)
return 0;
}
return aantalBuren;
} else if (gebied.getType() == TerreinTypeVerzameling.getInstantie()
.getType("TerreinType_Gras")) {
// OPM : we komen hier enkel bij eindeSpel !
// punten per AFGEWERKT KASTEEL dat grenst aan gras...
// mogelijk algoritme : alle tegels in gebied afgaan en kijken welke
// een stuk kasteel op zich hebben.
// daar braaf de kastelen berekenen, en zo weten we welke volledig
// zijn.
Vector<Tegel> tegels = gebied.getTegels();
Vector<Gebied> gevondenSteden = new Vector<Gebied>();
/*
* De boeren verzorgen enkel afgewerkte steden langs hun weiland.
* Voor elke afgewerkte stad krijgt de speler met de meeste boeren
* in dat weiland 4 punten.
*/
int result = 0;
for (Tegel tegel : tegels) {
// TODO : REKENING HOUDEN MET MEERDERE STEDEN-STUKKEN OP 1 TEGEL
// !!!!
// hoewel dit maar HEEEEL zelden zal voorkomen, dus laten we dit
// momenteel EVENTJES buiten beschouwing
Terrein burchtStart = tegel
.getTerreinVanType(TerreinTypeVerzameling
.getInstantie().getType("TerreinType_Burcht"));
if (burchtStart != null) // anders geen Burcht op deze tegel
{
// eersrt kijken of het Terrein nog geen stukje is van een
// reeds gevonden burcht
for (Gebied burchtGebied : gevondenSteden) {
for (Tegel burchtTegel : burchtGebied.getTegels()) {
if (burchtTegel == burchtStart.getTegel())
continue;
}
}
Gebied burcht = tegel.getGebied(burchtStart);
gevondenSteden.add(burcht);
if (burcht.isVolledig())
result += 4;
}
}
return result;
} else
return 0;
}
/*
* Functie geeft -1 terug als de speler niet het meeste pionnen heeft, 0 als
* er 2 of meer spelers gelijk aantal hebben en 1 als de speler het meeste
* pionnen heeft.
*/
private int spelerHeeftMeestePionnen(Gebied gebied, Speler speler) {
HashMap<Speler, Integer> pionnenPerSpeler = getPionnenPerSpeler(gebied);
int besteAantal = 0;
int spelerAantal = -1;
if (pionnenPerSpeler.get(speler) != null)
spelerAantal = pionnenPerSpeler.get(speler);
Set<Speler> spelers = pionnenPerSpeler.keySet();
for (Speler spelerIt : spelers) {
if (pionnenPerSpeler.get(spelerIt) > besteAantal) {
besteAantal = pionnenPerSpeler.get(spelerIt);
}
}
if (besteAantal == spelerAantal)
return 0;
if (besteAantal > spelerAantal)
return -1;
else
// speler heeft wel beste
return 1;
}
private HashMap<Speler, Integer> getPionnenPerSpeler(Gebied gebied) {
HashMap<Speler, Integer> output = new HashMap<Speler, Integer>();
Set<Pion> pionnen = gebied.getPionnen();
for (Pion pion : pionnen) {
if (output.get(pion.getSpeler()) == null)
output.put(pion.getSpeler(), 1);
else
output.put(pion.getSpeler(), output.get(pion.getSpeler()) + 1);
}
return output;
}
}
|
126655_20 | package com.programmeren4.turnahead.server.model.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.programmeren4.turnahead.server.database.DBConnector;
import com.programmeren4.turnahead.shared.dto.ItemDTO;
import com.programmeren4.turnahead.shared.dto.KarakterDTO;
import com.programmeren4.turnahead.shared.exception.DAOException;
public class KarakterDataDao {
// attributen
private Connection conn;
private String sql;
// private String tabelnaam = "KARAKTER";
// private String[] tabelvelden =
// {"CHARACTERID","CHARACTERNAME","CURRENTLOCATION", "CREATION_DATE", "LASTUSE_DATE", "USERID","LOCATIONID"};
// constructor
public KarakterDataDao() {
}
// getters en setters
// SELECT - UPDATE - INSERT - DELETE
/**
* Gegevens van een karakter opvragen (SELECT)
*/
public KarakterDTO getKarakterData(KarakterDTO karakterData)
throws DAOException {
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
}
if (!rs.isBeforeFirst() ) {
System.out.println("No data");
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.close(rs);
DBConnector.getInstance().closeConn();
}
return karakterReturn;
}
/**
* Karakter toevoegen (INSERT) of wijzigen (UPDATE)
*/
public void addKarakterData(KarakterDTO karakterData) throws DAOException {
// Controle (Bestaat Karakter al in tabel Karakter ?)
boolean karakterTest = this.VerifyKarakterId(karakterData);
// Naam en id van eerste Locatie in tabel LOCATION ophalen
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
if (karakterTest == true) {
// JA -> UPDATE bestaande record
// "UPDATE programmeren4.KARAKTER SET
// *veld='karakterData.getX()',*veld='karakterData.getY()',
// "WHERE KARAKTERID=" + karakterData.getKarakterId();
String sql = "UPDATE programmeren4.KARAKTER SET ";
sql += "CHARACTERNAME='" + karakterData.getKarakterName().toUpperCase() + "', ";
sql += " CURRENTLOCATION='" + karakterData.getCurrentLocation().toUpperCase() + "'";
sql += " WHERE CHARACTERID=" + karakterData.getKarakterId();
conn.createStatement().executeUpdate(sql);
} else {
// NEEN -> Karakter toevoegen aan de database>
// INSERT INTO programmeren4.KARAKTER(Columns db) VALUES
// (karakterData.getXXX(),
// karakterData.getYYY(), karakterData.getZZZ())
String sql = "INSERT INTO programmeren4.KARAKTER(";
sql += "CHARACTERNAME, CURRENTLOCATION, USERID, LOCATIONID) VALUES ('";
sql += karakterData.getKarakterName() + "', '";
sql += "SMIDSE', '";
sql += karakterData.getUserId() + "','"; // UserId van de User die Karakter
sql += "1";
sql += "')";
conn.createStatement().executeUpdate(sql);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
/**
* Karakter verwijderen (DELETE)
*/
public void deleteKarakterData(KarakterDTO karakterData)
throws DAOException {
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "DELETE FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
conn.createStatement().executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
// LIST
/**
* Lijst van alle karakters (LIST ALL)
*/
public List<KarakterDTO> getKarakters() throws DAOException {
String query = "SELECT * FROM programmeren4.KARAKTER";
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
/**
* LIST BY USER - Lijst van alle karakters voor één UserId
*/
public List<KarakterDTO> getKaraktersOfUserId(KarakterDTO karakterData)
throws DAOException {
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
String query = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID="
+ karakterData.getUserId();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
System.out.println(karakterReturn);
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
/**
* LIST BY LOCATION - Lijst van alle karakters voor één LocationId
*/
public List<KarakterDTO> getKaraktersOfLocationId(KarakterDTO karakterData)
throws DAOException {
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
String query = "SELECT * FROM programmeren4.KARAKTER WHERE LOCATIONID="
+ karakterData.getLocationId();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
//Itemownership
/**
* TODO - verify
* Methode om een item toe te wijzen aan een karakter
*/
public void AllocateItemToKarakter(KarakterDTO karakterData, ItemDTO itemData){
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "UPDATE programmeren4.ITEMOWNERSHIP SET ";
sql += "CHARACTERID='" + karakterData.getKarakterId() + "', ";
sql += "LOCATIONID=null ";
sql += "WHERE ITEMID=" + itemData.getItemId();
conn.createStatement().executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
// Overige methodes
/**
* Methode om te controleren of een karakter al aanwezig is (in de database)
* (op basis van een KarakterId)
*/
public boolean VerifyKarakterId(KarakterDTO karakterData)
throws DAOException {
ResultSet rs = null;
boolean inDatabase = false;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
rs = conn.createStatement().executeQuery(sql);
// System.out.println("karakterData KarakterID: " +
// userData.getUserId());
if (rs.next()) {
long a = new Long(rs.getLong("CHARACTERID"));
// System.out.println(a);
if (a == karakterData.getKarakterId()) {
inDatabase = true;
System.out.println("IF-true");
} else {
inDatabase = false;
System.out.println("IF-false");
}
}
System.out.println(inDatabase);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return inDatabase;
}
/**
* Methode om te controleren of een Karakter al aanwezig is in de database
* (op basis van Karakternaam)
*/
public boolean VerifyKarakterNaam(KarakterDTO karakterData)
throws DAOException {
ResultSet rs = null;
boolean inDatabase = false;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERNAME='"
+ karakterData.getKarakterName().toUpperCase() + "'";
rs = conn.createStatement().executeQuery(sql);
// System.out.println("karakterData KarakterID: " + karakterData.getKarakterId());
if (rs.next()) {
if (rs.getRow() == 1
& new String(rs.getString("CHARACTERNAME").toUpperCase()).equals(karakterData.getKarakterName().toUpperCase())) {
inDatabase = true;
} else {
inDatabase = false;
}
}
System.out.println(inDatabase);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return inDatabase;
}
}
| oliviervanroey/turnahead | src/main/java/com/programmeren4/turnahead/server/model/dao/KarakterDataDao.java | 4,148 | /**
* LIST BY LOCATION - Lijst van alle karakters voor één LocationId
*/ | block_comment | nl | package com.programmeren4.turnahead.server.model.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.programmeren4.turnahead.server.database.DBConnector;
import com.programmeren4.turnahead.shared.dto.ItemDTO;
import com.programmeren4.turnahead.shared.dto.KarakterDTO;
import com.programmeren4.turnahead.shared.exception.DAOException;
public class KarakterDataDao {
// attributen
private Connection conn;
private String sql;
// private String tabelnaam = "KARAKTER";
// private String[] tabelvelden =
// {"CHARACTERID","CHARACTERNAME","CURRENTLOCATION", "CREATION_DATE", "LASTUSE_DATE", "USERID","LOCATIONID"};
// constructor
public KarakterDataDao() {
}
// getters en setters
// SELECT - UPDATE - INSERT - DELETE
/**
* Gegevens van een karakter opvragen (SELECT)
*/
public KarakterDTO getKarakterData(KarakterDTO karakterData)
throws DAOException {
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
}
if (!rs.isBeforeFirst() ) {
System.out.println("No data");
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.close(rs);
DBConnector.getInstance().closeConn();
}
return karakterReturn;
}
/**
* Karakter toevoegen (INSERT) of wijzigen (UPDATE)
*/
public void addKarakterData(KarakterDTO karakterData) throws DAOException {
// Controle (Bestaat Karakter al in tabel Karakter ?)
boolean karakterTest = this.VerifyKarakterId(karakterData);
// Naam en id van eerste Locatie in tabel LOCATION ophalen
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
if (karakterTest == true) {
// JA -> UPDATE bestaande record
// "UPDATE programmeren4.KARAKTER SET
// *veld='karakterData.getX()',*veld='karakterData.getY()',
// "WHERE KARAKTERID=" + karakterData.getKarakterId();
String sql = "UPDATE programmeren4.KARAKTER SET ";
sql += "CHARACTERNAME='" + karakterData.getKarakterName().toUpperCase() + "', ";
sql += " CURRENTLOCATION='" + karakterData.getCurrentLocation().toUpperCase() + "'";
sql += " WHERE CHARACTERID=" + karakterData.getKarakterId();
conn.createStatement().executeUpdate(sql);
} else {
// NEEN -> Karakter toevoegen aan de database>
// INSERT INTO programmeren4.KARAKTER(Columns db) VALUES
// (karakterData.getXXX(),
// karakterData.getYYY(), karakterData.getZZZ())
String sql = "INSERT INTO programmeren4.KARAKTER(";
sql += "CHARACTERNAME, CURRENTLOCATION, USERID, LOCATIONID) VALUES ('";
sql += karakterData.getKarakterName() + "', '";
sql += "SMIDSE', '";
sql += karakterData.getUserId() + "','"; // UserId van de User die Karakter
sql += "1";
sql += "')";
conn.createStatement().executeUpdate(sql);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
/**
* Karakter verwijderen (DELETE)
*/
public void deleteKarakterData(KarakterDTO karakterData)
throws DAOException {
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "DELETE FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
conn.createStatement().executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
// LIST
/**
* Lijst van alle karakters (LIST ALL)
*/
public List<KarakterDTO> getKarakters() throws DAOException {
String query = "SELECT * FROM programmeren4.KARAKTER";
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
/**
* LIST BY USER - Lijst van alle karakters voor één UserId
*/
public List<KarakterDTO> getKaraktersOfUserId(KarakterDTO karakterData)
throws DAOException {
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
String query = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID="
+ karakterData.getUserId();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
System.out.println(karakterReturn);
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
/**
* LIST BY LOCATION<SUF>*/
public List<KarakterDTO> getKaraktersOfLocationId(KarakterDTO karakterData)
throws DAOException {
List<KarakterDTO> list = new ArrayList<KarakterDTO>();
KarakterDTO karakterReturn = null;
ResultSet rs = null;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
String query = "SELECT * FROM programmeren4.KARAKTER WHERE LOCATIONID="
+ karakterData.getLocationId();
rs = conn.createStatement().executeQuery(query);
while (rs.next()) {
karakterReturn = new KarakterDTO();
karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));
karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));
karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));
karakterReturn.setUserId(rs.getLong("USERID"));
karakterReturn.setLocationId(rs.getLong("LOCATIONID"));
list.add(karakterReturn);
}
if (list.isEmpty()) {
System.out.println("List fetched from database is empty.");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return list;
}
//Itemownership
/**
* TODO - verify
* Methode om een item toe te wijzen aan een karakter
*/
public void AllocateItemToKarakter(KarakterDTO karakterData, ItemDTO itemData){
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "UPDATE programmeren4.ITEMOWNERSHIP SET ";
sql += "CHARACTERID='" + karakterData.getKarakterId() + "', ";
sql += "LOCATIONID=null ";
sql += "WHERE ITEMID=" + itemData.getItemId();
conn.createStatement().executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().closeConn();
}
}
// Overige methodes
/**
* Methode om te controleren of een karakter al aanwezig is (in de database)
* (op basis van een KarakterId)
*/
public boolean VerifyKarakterId(KarakterDTO karakterData)
throws DAOException {
ResultSet rs = null;
boolean inDatabase = false;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();
rs = conn.createStatement().executeQuery(sql);
// System.out.println("karakterData KarakterID: " +
// userData.getUserId());
if (rs.next()) {
long a = new Long(rs.getLong("CHARACTERID"));
// System.out.println(a);
if (a == karakterData.getKarakterId()) {
inDatabase = true;
System.out.println("IF-true");
} else {
inDatabase = false;
System.out.println("IF-false");
}
}
System.out.println(inDatabase);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return inDatabase;
}
/**
* Methode om te controleren of een Karakter al aanwezig is in de database
* (op basis van Karakternaam)
*/
public boolean VerifyKarakterNaam(KarakterDTO karakterData)
throws DAOException {
ResultSet rs = null;
boolean inDatabase = false;
try {
DBConnector.getInstance().init();
this.conn = DBConnector.getInstance().getConn();
sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERNAME='"
+ karakterData.getKarakterName().toUpperCase() + "'";
rs = conn.createStatement().executeQuery(sql);
// System.out.println("karakterData KarakterID: " + karakterData.getKarakterId());
if (rs.next()) {
if (rs.getRow() == 1
& new String(rs.getString("CHARACTERNAME").toUpperCase()).equals(karakterData.getKarakterName().toUpperCase())) {
inDatabase = true;
} else {
inDatabase = false;
}
}
System.out.println(inDatabase);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnector.getInstance().close(rs);
DBConnector.getInstance().closeConn();
}
return inDatabase;
}
}
|
105239_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.MC114AnvilChunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain();
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setMaterial(x, y, z, activeMaterials[i]);
// TODOMC13: solve this more generically (in the post processor?):
if (activeMaterials[i].isNamedOneOf(MC_WATER, MC_LAVA) && (chunk instanceof MC114AnvilChunk)) {
// Make sure the fluid will actually flow
((MC114AnvilChunk) chunk).addLiquidTick(x, y, z);
}
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
Random random = new Random();
settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, nether ? 0 : 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, 0, maxHeight - 1, nether ? 0 : 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, 0, 63, nether ? 0 : 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, nether ? 0 : 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, 0, 15, nether ? 0 : 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, 0, 15, nether ? 0 : 8, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 0, 31, nether ? 0 : ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 1), random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, 0, maxHeight - 1, nether ? ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 6) : 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, 0, maxHeight - 1, nether ? 0 : 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, 0, 15, nether ? 0 : 2, random.nextLong()));
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("deprecation") // Legacy support
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
version = 1;
// Not sure how, but the liquids are reverting to the stationary
// variants (something to do with the Minecraft 1.14 migration?).
// Just keep changing them back
if (settings.containsKey(STATIONARY_WATER)) {
settings.put(WATER, settings.get(STATIONARY_WATER));
settings.remove(STATIONARY_WATER);
}
if (settings.containsKey(STATIONARY_LAVA)) {
settings.put(LAVA, settings.get(STATIONARY_LAVA));
settings.remove(STATIONARY_LAVA);
}
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} | omalley/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java | 4,790 | /**
*
* @author pepijn
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.MC114AnvilChunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
<SUF>*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain();
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setMaterial(x, y, z, activeMaterials[i]);
// TODOMC13: solve this more generically (in the post processor?):
if (activeMaterials[i].isNamedOneOf(MC_WATER, MC_LAVA) && (chunk instanceof MC114AnvilChunk)) {
// Make sure the fluid will actually flow
((MC114AnvilChunk) chunk).addLiquidTick(x, y, z);
}
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
Random random = new Random();
settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, nether ? 0 : 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, 0, maxHeight - 1, nether ? 0 : 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, 0, 63, nether ? 0 : 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, nether ? 0 : 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, 0, 15, nether ? 0 : 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, 0, 15, nether ? 0 : 8, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 0, 31, nether ? 0 : ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 1), random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, 0, maxHeight - 1, nether ? ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 6) : 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, 0, maxHeight - 1, nether ? 0 : 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, 0, 15, nether ? 0 : 2, random.nextLong()));
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("deprecation") // Legacy support
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
version = 1;
// Not sure how, but the liquids are reverting to the stationary
// variants (something to do with the Minecraft 1.14 migration?).
// Just keep changing them back
if (settings.containsKey(STATIONARY_WATER)) {
settings.put(WATER, settings.get(STATIONARY_WATER));
settings.remove(STATIONARY_WATER);
}
if (settings.containsKey(STATIONARY_LAVA)) {
settings.put(LAVA, settings.get(STATIONARY_LAVA));
settings.remove(STATIONARY_LAVA);
}
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} |
111174_3 | /*
* #%L
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.formats.in;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import loci.common.DateTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.RandomAccessInputStream;
import loci.common.xml.BaseHandler;
import loci.common.xml.XMLTools;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.Timestamp;
import ome.units.quantity.Length;
import ome.units.quantity.Time;
import ome.units.UNITS;
import org.xml.sax.Attributes;
/**
* FEITiffReader is the file format reader for TIFF files produced by various
* FEI software.
*/
public class FEITiffReader extends BaseTiffReader {
// -- Constants --
public static final int SFEG_TAG = 34680;
public static final int HELIOS_TAG = 34682;
public static final int TITAN_TAG = 34683;
private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss a";
private static final double MAG_MULTIPLIER = 0.0024388925;
// -- Fields --
private String imageName;
private String imageDescription;
private String date;
private String userName;
private String microscopeModel;
private Length stageX, stageY, stageZ;
private Double sizeX, sizeY, timeIncrement;
private ArrayList<String> detectors;
private Double magnification;
// -- Constructor --
public FEITiffReader() {
super("FEI TIFF", new String[] {"tif", "tiff"});
suffixSufficient = false;
domains = new String[] {FormatTools.SEM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
return ifd.containsKey(SFEG_TAG) || ifd.containsKey(HELIOS_TAG) || ifd.containsKey(TITAN_TAG);
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
imageName = null;
imageDescription = null;
date = null;
userName = null;
microscopeModel = null;
stageX = stageY = stageZ = null;
sizeX = sizeY = timeIncrement = null;
detectors = null;
magnification = null;
}
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
@Override
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
boolean helios = ifds.get(0).containsKey(HELIOS_TAG);
boolean titan = ifds.get(0).containsKey(TITAN_TAG);
// Helios etc data might have a stray Titan tag
if (titan && ifds.get(0).getIFDTextValue(TITAN_TAG).trim().isEmpty()) {
titan = false;
}
// Titan data (always?) has an empty Helios tag as well, so the Titan tag is checked first
String software = "S-FEG";
if (titan) {
software = "Titan";
}
else if (helios) {
software = "Helios NanoLab";
}
addGlobalMeta("Software", software);
int tagKey = SFEG_TAG;
if (titan) {
tagKey = TITAN_TAG;
}
else if (helios) {
tagKey = HELIOS_TAG;
}
String tag = ifds.get(0).getIFDTextValue(tagKey);
if (tag == null) {
return;
}
tag = tag.trim();
if (tag.isEmpty()) {
return;//fall back to regular reader
}
// store metadata for later conversion to OME-XML
if (tag.startsWith("<")) {
XMLTools.parseXML(tag, new FEIHandler());
}
else {
IniParser parser = new IniParser();
IniList ini = parser.parseINI(new BufferedReader(new StringReader(tag)));
detectors = new ArrayList<String>();
if (helios) {
IniTable userTable = ini.getTable("User");
date = userTable.get("Date") + " " + userTable.get("Time");
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
userName = userTable.get("User");
IniTable systemTable = ini.getTable("System");
if (systemTable == null) {
systemTable = ini.getTable("SYSTEM");
}
if (systemTable != null) {
microscopeModel = systemTable.get("SystemType");
}
IniTable beamTable = ini.getTable("Beam");
if (beamTable != null) {
String beamTableName = beamTable.get("Beam");
if (beamTableName != null) {
beamTable = ini.getTable(beamTableName);
}
}
if (beamTable != null) {
String beamX = beamTable.get("StageX");
String beamY = beamTable.get("StageY");
String beamZ = beamTable.get("StageZ");
IniTable stageTable = ini.getTable("Stage");
if (beamX != null) {
final Double number = Double.valueOf(beamX);
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageX"));
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
if (beamY != null) {
final Double number = Double.valueOf(beamY);
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageY"));
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
if (beamZ != null) {
final Double number = Double.valueOf(beamZ);
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageZ"));
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
}
IniTable scanTable = ini.getTable("Scan");
// physical sizes are stored in meters
sizeX = new Double(scanTable.get("PixelWidth")) * 1000000;
sizeY = new Double(scanTable.get("PixelHeight")) * 1000000;
timeIncrement = new Double(scanTable.get("FrameTime"));
}
}
else {
IniTable dataTable = ini.getTable("DatabarData");
imageName = dataTable.get("ImageName");
imageDescription = dataTable.get("szUserText");
String magnification = ini.getTable("Vector").get("Magnification");
sizeX = new Double(magnification) * MAG_MULTIPLIER;
sizeY = new Double(magnification) * MAG_MULTIPLIER;
IniTable scanTable = ini.getTable("Vector.Sysscan");
final Double posX = Double.valueOf(scanTable.get("PositionX"));
final Double posY = Double.valueOf(scanTable.get("PositionY"));
stageX = new Length(posX, UNITS.REFERENCEFRAME);
stageY = new Length(posY, UNITS.REFERENCEFRAME);
IniTable detectorTable = ini.getTable("Vector.Video.Detectors");
int detectorCount =
Integer.parseInt(detectorTable.get("NrDetectorsConnected"));
for (int i=0; i<detectorCount; i++) {
detectors.add(detectorTable.get("Detector_" + i + "_Name"));
}
}
// store everything else in the metadata hashtable
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
HashMap<String, String> iniMap = ini.flattenIntoHashMap();
metadata.putAll(iniMap);
}
}
}
/* @see BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
super.initMetadataStore();
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
if (date != null) {
date = DateTools.formatDate(date, DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), 0);
}
}
if (imageName != null) {
store.setImageName(imageName, 0);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (imageDescription != null) {
store.setImageDescription(imageDescription, 0);
}
if (userName != null) {
store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0);
store.setExperimenterLastName(userName, 0);
}
if (microscopeModel != null) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
store.setMicroscopeModel(microscopeModel, 0);
}
if (detectors != null && detectors.size() > 0) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
for (int i=0; i<detectors.size(); i++) {
String detectorID = MetadataTools.createLSID("Detector", 0, i);
store.setDetectorID(detectorID, 0, i);
store.setDetectorModel(detectors.get(i), 0, i);
store.setDetectorType(getDetectorType("Other"), 0, i);
}
}
if (magnification != null) {
store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0);
store.setObjectiveNominalMagnification(magnification, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
}
store.setStageLabelX(stageX, 0);
store.setStageLabelY(stageY, 0);
store.setStageLabelZ(stageZ, 0);
store.setStageLabelName("", 0);
Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
if (physicalSizeX != null) {
store.setPixelsPhysicalSizeX(physicalSizeX, 0);
}
if (physicalSizeY != null) {
store.setPixelsPhysicalSizeY(physicalSizeY, 0);
}
if (timeIncrement != null) {
store.setPixelsTimeIncrement(new Time(timeIncrement, UNITS.S), 0);
}
}
}
// -- Helper class --
class FEIHandler extends BaseHandler {
private String key, value;
private String qName;
private Deque<String> parentNames = new ArrayDeque<String>();
// -- DefaultHandler API methods --
@Override
public void characters(char[] data, int start, int len) {
String d = new String(data, start, len).trim();
if (d.isEmpty()) {
return;
}
String parent = parentNames.peek();
if (parent == null) {
return;
}
if (parent.equals(qName)) {
parentNames.pop();
parent = parentNames.peek();
}
if (qName.equals("Label")) {
key = d;
value = null;
}
else if (qName.equals("Value")) {
value = d;
}
else {
key = parent + " " + qName;
value = d;
}
if (key != null && value != null) {
addGlobalMeta(key, value);
if (key.equals("Stage X") || ("StagePosition".equals(parent) && key.equals("X"))) {
final Double number = Double.valueOf(value);
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Stage Y") || ("StagePosition".equals(parent) && key.equals("Y"))) {
final Double number = Double.valueOf(value);
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Stage Z") || ("StagePosition".equals(parent) && key.equals("Z"))) {
final Double number = Double.valueOf(value);
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Microscope")) {
microscopeModel = value;
}
else if (key.equals("User")) {
userName = value;
}
else if (key.equals("Magnification")) {
magnification = new Double(value);
}
// physical sizes stored in meters, but usually too small to be used without converting
else if (key.endsWith("X") && "PixelSize".equals(parent)) {
sizeX = new Double(value) * 1000000;
}
else if (key.endsWith("Y") && "PixelSize".equals(parent)) {
sizeY = new Double(value) * 1000000;
}
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
this.qName = qName;
parentNames.push(qName);
}
@Override
public void endElement(String uri, String localName, String qName)
{
if (parentNames.size() > 0) {
String name = parentNames.peek();
if (qName.equals(name)) {
parentNames.pop();
}
}
}
}
}
| ome/bioformats | components/formats-gpl/src/loci/formats/in/FEITiffReader.java | 4,471 | // -- Fields -- | line_comment | nl | /*
* #%L
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.formats.in;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import loci.common.DateTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.RandomAccessInputStream;
import loci.common.xml.BaseHandler;
import loci.common.xml.XMLTools;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.Timestamp;
import ome.units.quantity.Length;
import ome.units.quantity.Time;
import ome.units.UNITS;
import org.xml.sax.Attributes;
/**
* FEITiffReader is the file format reader for TIFF files produced by various
* FEI software.
*/
public class FEITiffReader extends BaseTiffReader {
// -- Constants --
public static final int SFEG_TAG = 34680;
public static final int HELIOS_TAG = 34682;
public static final int TITAN_TAG = 34683;
private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss a";
private static final double MAG_MULTIPLIER = 0.0024388925;
// -- Fields<SUF>
private String imageName;
private String imageDescription;
private String date;
private String userName;
private String microscopeModel;
private Length stageX, stageY, stageZ;
private Double sizeX, sizeY, timeIncrement;
private ArrayList<String> detectors;
private Double magnification;
// -- Constructor --
public FEITiffReader() {
super("FEI TIFF", new String[] {"tif", "tiff"});
suffixSufficient = false;
domains = new String[] {FormatTools.SEM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
return ifd.containsKey(SFEG_TAG) || ifd.containsKey(HELIOS_TAG) || ifd.containsKey(TITAN_TAG);
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
imageName = null;
imageDescription = null;
date = null;
userName = null;
microscopeModel = null;
stageX = stageY = stageZ = null;
sizeX = sizeY = timeIncrement = null;
detectors = null;
magnification = null;
}
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
@Override
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
boolean helios = ifds.get(0).containsKey(HELIOS_TAG);
boolean titan = ifds.get(0).containsKey(TITAN_TAG);
// Helios etc data might have a stray Titan tag
if (titan && ifds.get(0).getIFDTextValue(TITAN_TAG).trim().isEmpty()) {
titan = false;
}
// Titan data (always?) has an empty Helios tag as well, so the Titan tag is checked first
String software = "S-FEG";
if (titan) {
software = "Titan";
}
else if (helios) {
software = "Helios NanoLab";
}
addGlobalMeta("Software", software);
int tagKey = SFEG_TAG;
if (titan) {
tagKey = TITAN_TAG;
}
else if (helios) {
tagKey = HELIOS_TAG;
}
String tag = ifds.get(0).getIFDTextValue(tagKey);
if (tag == null) {
return;
}
tag = tag.trim();
if (tag.isEmpty()) {
return;//fall back to regular reader
}
// store metadata for later conversion to OME-XML
if (tag.startsWith("<")) {
XMLTools.parseXML(tag, new FEIHandler());
}
else {
IniParser parser = new IniParser();
IniList ini = parser.parseINI(new BufferedReader(new StringReader(tag)));
detectors = new ArrayList<String>();
if (helios) {
IniTable userTable = ini.getTable("User");
date = userTable.get("Date") + " " + userTable.get("Time");
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
userName = userTable.get("User");
IniTable systemTable = ini.getTable("System");
if (systemTable == null) {
systemTable = ini.getTable("SYSTEM");
}
if (systemTable != null) {
microscopeModel = systemTable.get("SystemType");
}
IniTable beamTable = ini.getTable("Beam");
if (beamTable != null) {
String beamTableName = beamTable.get("Beam");
if (beamTableName != null) {
beamTable = ini.getTable(beamTableName);
}
}
if (beamTable != null) {
String beamX = beamTable.get("StageX");
String beamY = beamTable.get("StageY");
String beamZ = beamTable.get("StageZ");
IniTable stageTable = ini.getTable("Stage");
if (beamX != null) {
final Double number = Double.valueOf(beamX);
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageX"));
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
if (beamY != null) {
final Double number = Double.valueOf(beamY);
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageY"));
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
if (beamZ != null) {
final Double number = Double.valueOf(beamZ);
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
else if (stageTable != null) {
final Double number = Double.valueOf(stageTable.get("StageZ"));
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
}
IniTable scanTable = ini.getTable("Scan");
// physical sizes are stored in meters
sizeX = new Double(scanTable.get("PixelWidth")) * 1000000;
sizeY = new Double(scanTable.get("PixelHeight")) * 1000000;
timeIncrement = new Double(scanTable.get("FrameTime"));
}
}
else {
IniTable dataTable = ini.getTable("DatabarData");
imageName = dataTable.get("ImageName");
imageDescription = dataTable.get("szUserText");
String magnification = ini.getTable("Vector").get("Magnification");
sizeX = new Double(magnification) * MAG_MULTIPLIER;
sizeY = new Double(magnification) * MAG_MULTIPLIER;
IniTable scanTable = ini.getTable("Vector.Sysscan");
final Double posX = Double.valueOf(scanTable.get("PositionX"));
final Double posY = Double.valueOf(scanTable.get("PositionY"));
stageX = new Length(posX, UNITS.REFERENCEFRAME);
stageY = new Length(posY, UNITS.REFERENCEFRAME);
IniTable detectorTable = ini.getTable("Vector.Video.Detectors");
int detectorCount =
Integer.parseInt(detectorTable.get("NrDetectorsConnected"));
for (int i=0; i<detectorCount; i++) {
detectors.add(detectorTable.get("Detector_" + i + "_Name"));
}
}
// store everything else in the metadata hashtable
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
HashMap<String, String> iniMap = ini.flattenIntoHashMap();
metadata.putAll(iniMap);
}
}
}
/* @see BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
super.initMetadataStore();
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
if (date != null) {
date = DateTools.formatDate(date, DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), 0);
}
}
if (imageName != null) {
store.setImageName(imageName, 0);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (imageDescription != null) {
store.setImageDescription(imageDescription, 0);
}
if (userName != null) {
store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0);
store.setExperimenterLastName(userName, 0);
}
if (microscopeModel != null) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
store.setMicroscopeModel(microscopeModel, 0);
}
if (detectors != null && detectors.size() > 0) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
for (int i=0; i<detectors.size(); i++) {
String detectorID = MetadataTools.createLSID("Detector", 0, i);
store.setDetectorID(detectorID, 0, i);
store.setDetectorModel(detectors.get(i), 0, i);
store.setDetectorType(getDetectorType("Other"), 0, i);
}
}
if (magnification != null) {
store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0);
store.setObjectiveNominalMagnification(magnification, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
}
store.setStageLabelX(stageX, 0);
store.setStageLabelY(stageY, 0);
store.setStageLabelZ(stageZ, 0);
store.setStageLabelName("", 0);
Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
if (physicalSizeX != null) {
store.setPixelsPhysicalSizeX(physicalSizeX, 0);
}
if (physicalSizeY != null) {
store.setPixelsPhysicalSizeY(physicalSizeY, 0);
}
if (timeIncrement != null) {
store.setPixelsTimeIncrement(new Time(timeIncrement, UNITS.S), 0);
}
}
}
// -- Helper class --
class FEIHandler extends BaseHandler {
private String key, value;
private String qName;
private Deque<String> parentNames = new ArrayDeque<String>();
// -- DefaultHandler API methods --
@Override
public void characters(char[] data, int start, int len) {
String d = new String(data, start, len).trim();
if (d.isEmpty()) {
return;
}
String parent = parentNames.peek();
if (parent == null) {
return;
}
if (parent.equals(qName)) {
parentNames.pop();
parent = parentNames.peek();
}
if (qName.equals("Label")) {
key = d;
value = null;
}
else if (qName.equals("Value")) {
value = d;
}
else {
key = parent + " " + qName;
value = d;
}
if (key != null && value != null) {
addGlobalMeta(key, value);
if (key.equals("Stage X") || ("StagePosition".equals(parent) && key.equals("X"))) {
final Double number = Double.valueOf(value);
stageX = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Stage Y") || ("StagePosition".equals(parent) && key.equals("Y"))) {
final Double number = Double.valueOf(value);
stageY = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Stage Z") || ("StagePosition".equals(parent) && key.equals("Z"))) {
final Double number = Double.valueOf(value);
stageZ = new Length(number, UNITS.REFERENCEFRAME);
}
else if (key.equals("Microscope")) {
microscopeModel = value;
}
else if (key.equals("User")) {
userName = value;
}
else if (key.equals("Magnification")) {
magnification = new Double(value);
}
// physical sizes stored in meters, but usually too small to be used without converting
else if (key.endsWith("X") && "PixelSize".equals(parent)) {
sizeX = new Double(value) * 1000000;
}
else if (key.endsWith("Y") && "PixelSize".equals(parent)) {
sizeY = new Double(value) * 1000000;
}
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
this.qName = qName;
parentNames.push(qName);
}
@Override
public void endElement(String uri, String localName, String qName)
{
if (parentNames.size() > 0) {
String name = parentNames.peek();
if (qName.equals(name)) {
parentNames.pop();
}
}
}
}
}
|
61976_7 | package org;
import java.awt.Point;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.citygml4j.builder.CityGMLBuilder;
import org.citygml4j.CityGMLContext;
import org.citygml4j.builder.jaxb.JAXBBuilder;
import org.citygml4j.factory.DimensionMismatchException;
import org.citygml4j.factory.GMLGeometryFactory;
import org.citygml4j.model.citygml.CityGMLClass;
import org.citygml4j.model.citygml.building.AbstractBoundarySurface;
import org.citygml4j.model.citygml.building.BoundarySurfaceProperty;
import org.citygml4j.model.citygml.building.Building;
import org.citygml4j.model.citygml.building.Door;
import org.citygml4j.model.citygml.building.FloorSurface;
import org.citygml4j.model.citygml.building.GroundSurface;
import org.citygml4j.model.citygml.building.InteriorWallSurface;
import org.citygml4j.model.citygml.building.OpeningProperty;
import org.citygml4j.model.citygml.building.RoofSurface;
import org.citygml4j.model.citygml.building.WallSurface;
import org.citygml4j.model.citygml.building.Window;
import org.citygml4j.model.citygml.core.CityModel;
import org.citygml4j.model.citygml.core.CityObjectMember;
import org.citygml4j.model.gml.geometry.aggregates.MultiSurface;
import org.citygml4j.model.gml.geometry.aggregates.MultiSurfaceProperty;
import org.citygml4j.model.gml.geometry.complexes.CompositeSurface;
import org.citygml4j.model.gml.geometry.primitives.DirectPositionList;
import org.citygml4j.model.gml.geometry.primitives.Exterior;
import org.citygml4j.model.gml.geometry.primitives.LinearRing;
import org.citygml4j.model.gml.geometry.primitives.Polygon;
import org.citygml4j.model.gml.geometry.primitives.Solid;
import org.citygml4j.model.gml.geometry.primitives.SolidProperty;
import org.citygml4j.model.gml.geometry.primitives.SurfaceProperty;
import org.citygml4j.model.module.citygml.CityGMLVersion;
import org.citygml4j.util.gmlid.DefaultGMLIdManager;
import org.citygml4j.util.gmlid.GMLIdManager;
import org.citygml4j.xml.io.CityGMLOutputFactory;
import org.citygml4j.xml.io.writer.CityGMLWriter;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.sql.*;
// to read csv file in java:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NodeRedLod2Plus {
public static void main(String[] args) throws Exception {
new NodeRedLod2Plus().doMain();
}
public void doMain() throws Exception {
SimpleDateFormat df = new SimpleDateFormat("[HH:mm:ss] ");
System.out.println(df.format(new Date()) + "setting up citygml4j context and JAXB builder");
CityGMLContext ctx = new CityGMLContext();
CityGMLBuilder builder = ctx.createCityGMLBuilder();
System.out.println(df.format(new Date()) + "creating LOD2+ building as citygml4j in-memory object tree");
GMLGeometryFactory geom = new GMLGeometryFactory();
JAXBBuilder builder2 = ctx.createJAXBBuilder();
System.out.println(df.format(new Date()) + "creating LOD4 building as citygml4j in-memory object tree");
GMLGeometryFactory geom2 = new GMLGeometryFactory();
GMLIdManager gmlIdManager = DefaultGMLIdManager.getInstance();
Building building = new Building();
List<Foot> foots = readFootsFromCSV("E:\\Thesis Indoor Mapping\\node-red-0.16.0\\node-red-0.16.0\\finalFootprint.csv");
List<List<Double>> RXYZs = new ArrayList<List<Double>>();
// Convert from GPS to WGS84 coordinate system
//double EarthRadius = 6337000;
for (Foot b: foots) {
List<Double> RXYZ = new ArrayList<Double>();
double Re = 6378137;
double Rp = 6356752.31424518;
double ref = b.getRef();
double latrad = b.getLat()/180.0*Math.PI;
double lonrad = b.getLon()/180.0*Math.PI;
double coslat = Math.cos(latrad);
double sinlat = Math.sin(latrad);
double coslon = Math.cos(lonrad);
double sinlon = Math.sin(lonrad);
double term1 = (Re*Re*coslat)/Math.sqrt(Re*Re*coslat*coslat + Rp*Rp*sinlat*sinlat);
double term2 = 520*coslat + term1;
double x=coslon*term2;
double y=sinlon*term2;
double z = 520*sinlat + (Rp*Rp*sinlat)/
Math.sqrt(Re*Re*coslat*coslat + Rp*Rp*sinlat*sinlat);
System.out.println((int)ref+" "+x+" "+y+" "+z);
RXYZ.add(ref);
RXYZ.add(x);
RXYZ.add(y);
RXYZ.add(z);
RXYZs.add(RXYZ);
}
// read ref values of way
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder mybuilder = dbFactory.newDocumentBuilder();
Document doc = mybuilder.parse("E://Thesis Indoor Mapping//node-red-0.16.0//node-red-0.16.0//TUM_footprint.osm");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//nd/@ref");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
doc.getDocumentElement().normalize();
//System.out.println("Reference values of the way:");
// Ground floor
int count = 0;
double[] myArrayForGround = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
//System.out.println(nl.item(i).getTextContent());
// end of reading ref values of way
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1));
myArrayForGround[count] = RXYZs.get(j).get(1);
myArrayForGround[count+1] = RXYZs.get(j).get(2);
myArrayForGround[count+2] = RXYZs.get(j).get(3);
count = count+3;
}
}
}
Polygon ground = geom.createLinearPolygon(myArrayForGround,3);
// roof
// compute normal to the ground floor polygon
double x1 = RXYZs.get(1).get(1);
double y1 = RXYZs.get(1).get(2);
double z1 = RXYZs.get(1).get(3);
double x2 = RXYZs.get(3).get(1);
double y2 = RXYZs.get(3).get(2);
double z2 = RXYZs.get(3).get(3);
double x3 = RXYZs.get(5).get(1);
double y3 = RXYZs.get(5).get(2);
double z3 = RXYZs.get(5).get(3);
double u1, u2, u3, v1, v2, v3;
u1 = x1 - x2;
u2 = y1 - y2;
u3 = z1 - z2;
v1 = x3 - x2;
v2 = y3 - y2;
v3 = z3 - z2;
double uvi, uvj, uvk; // normal to ground floor, so we can shift the ground floor with building height to form the roof in direction of this normaal
uvi = u2 * v3 - v2 * u3;
uvj = v1 * u3 - u1 * v3;
uvk = u1 * v2 - v1 * u2;
//normal unit vector
double un1 = uvi/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
double un2 = uvj/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
double un3 = uvk/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
System.out.println("The cross product of the 2 vectors \n u = " + u1
+ "i + " + u2 + "j + " + u3 + "k and \n v = " + u1 + "i + "
+ u2 + "j + " + u3 + "k \n ");
System.out.println("u X v : " + uvi + "i +" + uvj + "j+ " + uvk + "k ");
System.out.println("unit vector of u X v : " + un1 + "i +" + un2 + "j+ " + un3 + "k ");
// real building height
double h = 24;
// computed building height vector for shifting ground
double new_h_v1 = h * un1;
double new_h_v2 = h * un2;
double new_h_v3 = h * un3;
int count2 = 0;
double[] myArrayForRoof = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
//System.out.println(nl.item(i).getTextContent());
// end of reading ref values of way
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1));
myArrayForRoof[count2] = RXYZs.get(j).get(1)+new_h_v1;
myArrayForRoof[count2+1] = RXYZs.get(j).get(2)+new_h_v2;
myArrayForRoof[count2+2] = RXYZs.get(j).get(3)+new_h_v3;
count2 = count2+3;
}
}
}
Polygon roof = geom.createLinearPolygon(myArrayForRoof,3);
// Floors
// assume we have received number of floors and each floor height
// now we want to add these floors to our model
List<Polygon> floors = new ArrayList<Polygon>();
int num_of_floors = 3; // except ground floor and roof
double [] each_floor_height = {6, 12, 18};
for (int t =0; t<num_of_floors; t++){
double floor_h = each_floor_height[t];
// computed floor height vector for shifting ground
double new_fh_v1 = floor_h * un1;
double new_fh_v2 = floor_h * un2;
double new_fh_v3 = floor_h * un3;
int counter2 = 0;
double[] myArrayForFloor = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1));
myArrayForFloor[counter2] = RXYZs.get(j).get(1)+new_fh_v1;
myArrayForFloor[counter2+1] = RXYZs.get(j).get(2)+new_fh_v2;
myArrayForFloor[counter2+2] = RXYZs.get(j).get(3)+new_fh_v3;
counter2 = counter2+3;
}
}
}
Polygon floor = geom.createLinearPolygon(myArrayForFloor,3);
floors.add(floor);
for (int i=0; i<floors.size(); i++){
floors.get(i).setId(gmlIdManager.generateUUID());
}
}
// walls
List<Polygon> walls = new ArrayList<Polygon>();
int k=0;
for (int i=0; i<3*RXYZs.size(); i++){
walls.add(geom.createLinearPolygon(new double[] {
myArrayForGround[k],myArrayForGround[k+1], myArrayForGround[k+2],
myArrayForGround[k+3],myArrayForGround[k+4], myArrayForGround[k+5],
myArrayForRoof[k+3],myArrayForRoof[k+4], myArrayForRoof[k+5],
myArrayForRoof[k],myArrayForRoof[k+1], myArrayForRoof[k+2],
myArrayForGround[k],myArrayForGround[k+1], myArrayForGround[k+2]},3));
if (k+3 <3*RXYZs.size()-3)
k+=3;
}
System.out.println(walls.size());
for (int i=0; i<walls.size(); i++){
walls.get(i).setId(gmlIdManager.generateUUID());
}
ground.setId(gmlIdManager.generateUUID());
roof.setId(gmlIdManager.generateUUID());
// lod2 solid
List<SurfaceProperty> surfaceMember = new ArrayList<SurfaceProperty>();
surfaceMember.add(new SurfaceProperty('#' + ground.getId()));
surfaceMember.add(new SurfaceProperty('#' + roof.getId()));
for (int i=0; i<walls.size(); i++){
surfaceMember.add(new SurfaceProperty('#' + walls.get(i).getId()));
}
for (int i=0; i<floors.size(); i++){
surfaceMember.add(new SurfaceProperty('#' + floors.get(i).getId()));
}
// Assume an OI transition detected at wall number 1
int I_O = 1;
BoundarySurfaceProperty wall_1_BSurf = createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, walls.get(I_O));
createDoor(wall_1_BSurf);
CompositeSurface compositeSurface = new CompositeSurface();
compositeSurface.setSurfaceMember(surfaceMember);
Solid solid = new Solid();
solid.setExterior(new SurfaceProperty(compositeSurface));
building.setLod4Solid(new SolidProperty(solid));
// thematic boundary surfaces
List<BoundarySurfaceProperty> boundedBy = new ArrayList<BoundarySurfaceProperty>();
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_GROUND_SURFACE, ground));
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_ROOF_SURFACE, roof));
boundedBy.add(wall_1_BSurf);
for (int i=0; i<walls.size(); i++){
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, walls.get(i)));
}
for (int i=0; i<floors.size(); i++){
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_FLOOR_SURFACE, floors.get(i)));
}
//BoundarySurfaceProperty wall3_2_BSurf = createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, wall_3);
//createWindow(wall3_2_BSurf);
//boundedBy.add(wall3_2_BSurf);
building.setBoundedBySurface(boundedBy);
CityModel cityModel = new CityModel();
cityModel.setBoundedBy(building.calcBoundedBy(false));
cityModel.addCityObjectMember(new CityObjectMember(building));
System.out.println(df.format(new Date()) + "writing citygml4j object tree");
CityGMLOutputFactory out = builder.createCityGMLOutputFactory(CityGMLVersion.DEFAULT);
CityGMLWriter writer = out.createCityGMLWriter(new File("MainCampGround.gml"));
writer.setPrefixes(CityGMLVersion.DEFAULT);
writer.setSchemaLocations(CityGMLVersion.DEFAULT);
writer.setIndentString(" ");
writer.write(cityModel);
writer.close();
System.out.println(df.format(new Date()) + "CityGML file LOD4_Building_v200.gml written");
System.out.println(df.format(new Date()) + "sample citygml4j application successfully finished");
}
public void createDoor(BoundarySurfaceProperty bsp) throws DimensionMismatchException {
System.out.println("c");
AbstractBoundarySurface b = bsp.getBoundarySurface();
if (b instanceof WallSurface) {
System.out.println("IS wall surf");
GMLGeometryFactory geom = new GMLGeometryFactory();
WallSurface ws = (WallSurface) b;
Door door = new Door();
OpeningProperty openingProperty = new OpeningProperty();
openingProperty.setObject(door);
//Polygon doorPoly= geom.createLinearPolygon(new double[] {-3.5,0.1,0, -6.5,0.1,0, -6.5,0.1,2.3, -3.5,0.1,2.3, -3.5,0.1,0}, 3);
//Polygon doorPoly2 = geom.createLinearPolygon(new double[] {-3.5,-0.1,0, -6.5,-0.1,0, -6.5,-0.1,2.3, -3.5,-0.1,2.3, -3.5,-0.1,0}, 3);
//List l = new ArrayList();
//l.add(doorPoly);
//l.add(doorPoly2);
//door.setLod4MultiSurface(new MultiSurfaceProperty(new MultiSurface(l)));
ws.addOpening(openingProperty);
}
}
public void createWindow(BoundarySurfaceProperty bsp) throws DimensionMismatchException {
System.out.println("c");
AbstractBoundarySurface b = bsp.getBoundarySurface();
if (b instanceof WallSurface) {
System.out.println("IS wall surf");
GMLGeometryFactory geom = new GMLGeometryFactory();
WallSurface ws = (WallSurface) b;
Window window3 = new Window();
OpeningProperty openingProperty = new OpeningProperty();
openingProperty.setObject(window3);
ws.addOpening(openingProperty);
}
}
private BoundarySurfaceProperty createBoundarySurface(CityGMLClass type, Polygon geometry) {
AbstractBoundarySurface boundarySurface = null;
switch (type) {
case BUILDING_WALL_SURFACE:
boundarySurface = new WallSurface();
break;
case BUILDING_ROOF_SURFACE:
boundarySurface = new RoofSurface();
break;
case BUILDING_GROUND_SURFACE:
boundarySurface = new GroundSurface();
break;
case BUILDING_FLOOR_SURFACE:
boundarySurface = new FloorSurface();
break;
default:
break;
}
if (boundarySurface != null) {
boundarySurface.setLod4MultiSurface(new MultiSurfaceProperty(new MultiSurface(geometry)));
return new BoundarySurfaceProperty(boundarySurface);
}
return null;
}
private static List<Foot> readFootsFromCSV(String fileName) {
List<Foot> foots = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
// create an instance of BufferedReader
// using try with resource, Java 7 feature to close resources
try (BufferedReader br = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
if (line.length()==0){
line = br.readLine();
}else {
String[] attributes = line.split(",");
Foot foot = createFoot(attributes);
// adding book into ArrayList
foots.add(foot);
//read next line before looping
//if end of file reached,
line = br.readLine();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return foots;
}
private static Foot createFoot(String[] metadata) {
double ref = Double.parseDouble(metadata[0]);
double lat = Double.parseDouble(metadata[1]);
double lon = Double.parseDouble(metadata[2]);
// create and return foot of this meta data
return new Foot(ref,lat, lon);
}
}
| omidrad2017/Crowdsourced-vertical-indoor-mapping | NodeRedLod2Plus.java | 6,702 | //System.out.println(RXYZs.get(j).get(1));
| line_comment | nl | package org;
import java.awt.Point;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.citygml4j.builder.CityGMLBuilder;
import org.citygml4j.CityGMLContext;
import org.citygml4j.builder.jaxb.JAXBBuilder;
import org.citygml4j.factory.DimensionMismatchException;
import org.citygml4j.factory.GMLGeometryFactory;
import org.citygml4j.model.citygml.CityGMLClass;
import org.citygml4j.model.citygml.building.AbstractBoundarySurface;
import org.citygml4j.model.citygml.building.BoundarySurfaceProperty;
import org.citygml4j.model.citygml.building.Building;
import org.citygml4j.model.citygml.building.Door;
import org.citygml4j.model.citygml.building.FloorSurface;
import org.citygml4j.model.citygml.building.GroundSurface;
import org.citygml4j.model.citygml.building.InteriorWallSurface;
import org.citygml4j.model.citygml.building.OpeningProperty;
import org.citygml4j.model.citygml.building.RoofSurface;
import org.citygml4j.model.citygml.building.WallSurface;
import org.citygml4j.model.citygml.building.Window;
import org.citygml4j.model.citygml.core.CityModel;
import org.citygml4j.model.citygml.core.CityObjectMember;
import org.citygml4j.model.gml.geometry.aggregates.MultiSurface;
import org.citygml4j.model.gml.geometry.aggregates.MultiSurfaceProperty;
import org.citygml4j.model.gml.geometry.complexes.CompositeSurface;
import org.citygml4j.model.gml.geometry.primitives.DirectPositionList;
import org.citygml4j.model.gml.geometry.primitives.Exterior;
import org.citygml4j.model.gml.geometry.primitives.LinearRing;
import org.citygml4j.model.gml.geometry.primitives.Polygon;
import org.citygml4j.model.gml.geometry.primitives.Solid;
import org.citygml4j.model.gml.geometry.primitives.SolidProperty;
import org.citygml4j.model.gml.geometry.primitives.SurfaceProperty;
import org.citygml4j.model.module.citygml.CityGMLVersion;
import org.citygml4j.util.gmlid.DefaultGMLIdManager;
import org.citygml4j.util.gmlid.GMLIdManager;
import org.citygml4j.xml.io.CityGMLOutputFactory;
import org.citygml4j.xml.io.writer.CityGMLWriter;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.sql.*;
// to read csv file in java:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NodeRedLod2Plus {
public static void main(String[] args) throws Exception {
new NodeRedLod2Plus().doMain();
}
public void doMain() throws Exception {
SimpleDateFormat df = new SimpleDateFormat("[HH:mm:ss] ");
System.out.println(df.format(new Date()) + "setting up citygml4j context and JAXB builder");
CityGMLContext ctx = new CityGMLContext();
CityGMLBuilder builder = ctx.createCityGMLBuilder();
System.out.println(df.format(new Date()) + "creating LOD2+ building as citygml4j in-memory object tree");
GMLGeometryFactory geom = new GMLGeometryFactory();
JAXBBuilder builder2 = ctx.createJAXBBuilder();
System.out.println(df.format(new Date()) + "creating LOD4 building as citygml4j in-memory object tree");
GMLGeometryFactory geom2 = new GMLGeometryFactory();
GMLIdManager gmlIdManager = DefaultGMLIdManager.getInstance();
Building building = new Building();
List<Foot> foots = readFootsFromCSV("E:\\Thesis Indoor Mapping\\node-red-0.16.0\\node-red-0.16.0\\finalFootprint.csv");
List<List<Double>> RXYZs = new ArrayList<List<Double>>();
// Convert from GPS to WGS84 coordinate system
//double EarthRadius = 6337000;
for (Foot b: foots) {
List<Double> RXYZ = new ArrayList<Double>();
double Re = 6378137;
double Rp = 6356752.31424518;
double ref = b.getRef();
double latrad = b.getLat()/180.0*Math.PI;
double lonrad = b.getLon()/180.0*Math.PI;
double coslat = Math.cos(latrad);
double sinlat = Math.sin(latrad);
double coslon = Math.cos(lonrad);
double sinlon = Math.sin(lonrad);
double term1 = (Re*Re*coslat)/Math.sqrt(Re*Re*coslat*coslat + Rp*Rp*sinlat*sinlat);
double term2 = 520*coslat + term1;
double x=coslon*term2;
double y=sinlon*term2;
double z = 520*sinlat + (Rp*Rp*sinlat)/
Math.sqrt(Re*Re*coslat*coslat + Rp*Rp*sinlat*sinlat);
System.out.println((int)ref+" "+x+" "+y+" "+z);
RXYZ.add(ref);
RXYZ.add(x);
RXYZ.add(y);
RXYZ.add(z);
RXYZs.add(RXYZ);
}
// read ref values of way
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder mybuilder = dbFactory.newDocumentBuilder();
Document doc = mybuilder.parse("E://Thesis Indoor Mapping//node-red-0.16.0//node-red-0.16.0//TUM_footprint.osm");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//nd/@ref");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
doc.getDocumentElement().normalize();
//System.out.println("Reference values of the way:");
// Ground floor
int count = 0;
double[] myArrayForGround = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
//System.out.println(nl.item(i).getTextContent());
// end of reading ref values of way
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1)); <SUF>
myArrayForGround[count] = RXYZs.get(j).get(1);
myArrayForGround[count+1] = RXYZs.get(j).get(2);
myArrayForGround[count+2] = RXYZs.get(j).get(3);
count = count+3;
}
}
}
Polygon ground = geom.createLinearPolygon(myArrayForGround,3);
// roof
// compute normal to the ground floor polygon
double x1 = RXYZs.get(1).get(1);
double y1 = RXYZs.get(1).get(2);
double z1 = RXYZs.get(1).get(3);
double x2 = RXYZs.get(3).get(1);
double y2 = RXYZs.get(3).get(2);
double z2 = RXYZs.get(3).get(3);
double x3 = RXYZs.get(5).get(1);
double y3 = RXYZs.get(5).get(2);
double z3 = RXYZs.get(5).get(3);
double u1, u2, u3, v1, v2, v3;
u1 = x1 - x2;
u2 = y1 - y2;
u3 = z1 - z2;
v1 = x3 - x2;
v2 = y3 - y2;
v3 = z3 - z2;
double uvi, uvj, uvk; // normal to ground floor, so we can shift the ground floor with building height to form the roof in direction of this normaal
uvi = u2 * v3 - v2 * u3;
uvj = v1 * u3 - u1 * v3;
uvk = u1 * v2 - v1 * u2;
//normal unit vector
double un1 = uvi/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
double un2 = uvj/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
double un3 = uvk/Math.sqrt(Math.pow(uvi, 2)+Math.pow(uvj, 2)+Math.pow(uvk, 2));
System.out.println("The cross product of the 2 vectors \n u = " + u1
+ "i + " + u2 + "j + " + u3 + "k and \n v = " + u1 + "i + "
+ u2 + "j + " + u3 + "k \n ");
System.out.println("u X v : " + uvi + "i +" + uvj + "j+ " + uvk + "k ");
System.out.println("unit vector of u X v : " + un1 + "i +" + un2 + "j+ " + un3 + "k ");
// real building height
double h = 24;
// computed building height vector for shifting ground
double new_h_v1 = h * un1;
double new_h_v2 = h * un2;
double new_h_v3 = h * un3;
int count2 = 0;
double[] myArrayForRoof = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
//System.out.println(nl.item(i).getTextContent());
// end of reading ref values of way
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1));
myArrayForRoof[count2] = RXYZs.get(j).get(1)+new_h_v1;
myArrayForRoof[count2+1] = RXYZs.get(j).get(2)+new_h_v2;
myArrayForRoof[count2+2] = RXYZs.get(j).get(3)+new_h_v3;
count2 = count2+3;
}
}
}
Polygon roof = geom.createLinearPolygon(myArrayForRoof,3);
// Floors
// assume we have received number of floors and each floor height
// now we want to add these floors to our model
List<Polygon> floors = new ArrayList<Polygon>();
int num_of_floors = 3; // except ground floor and roof
double [] each_floor_height = {6, 12, 18};
for (int t =0; t<num_of_floors; t++){
double floor_h = each_floor_height[t];
// computed floor height vector for shifting ground
double new_fh_v1 = floor_h * un1;
double new_fh_v2 = floor_h * un2;
double new_fh_v3 = floor_h * un3;
int counter2 = 0;
double[] myArrayForFloor = new double[RXYZs.size()*3];
for (int i = 0; i < nl.getLength(); i++){
for (int j = 0; j < RXYZs.size(); j++){
if (Double.parseDouble(nl.item(i).getTextContent())==RXYZs.get(j).get(0)){
//System.out.println(RXYZs.get(j).get(1));
myArrayForFloor[counter2] = RXYZs.get(j).get(1)+new_fh_v1;
myArrayForFloor[counter2+1] = RXYZs.get(j).get(2)+new_fh_v2;
myArrayForFloor[counter2+2] = RXYZs.get(j).get(3)+new_fh_v3;
counter2 = counter2+3;
}
}
}
Polygon floor = geom.createLinearPolygon(myArrayForFloor,3);
floors.add(floor);
for (int i=0; i<floors.size(); i++){
floors.get(i).setId(gmlIdManager.generateUUID());
}
}
// walls
List<Polygon> walls = new ArrayList<Polygon>();
int k=0;
for (int i=0; i<3*RXYZs.size(); i++){
walls.add(geom.createLinearPolygon(new double[] {
myArrayForGround[k],myArrayForGround[k+1], myArrayForGround[k+2],
myArrayForGround[k+3],myArrayForGround[k+4], myArrayForGround[k+5],
myArrayForRoof[k+3],myArrayForRoof[k+4], myArrayForRoof[k+5],
myArrayForRoof[k],myArrayForRoof[k+1], myArrayForRoof[k+2],
myArrayForGround[k],myArrayForGround[k+1], myArrayForGround[k+2]},3));
if (k+3 <3*RXYZs.size()-3)
k+=3;
}
System.out.println(walls.size());
for (int i=0; i<walls.size(); i++){
walls.get(i).setId(gmlIdManager.generateUUID());
}
ground.setId(gmlIdManager.generateUUID());
roof.setId(gmlIdManager.generateUUID());
// lod2 solid
List<SurfaceProperty> surfaceMember = new ArrayList<SurfaceProperty>();
surfaceMember.add(new SurfaceProperty('#' + ground.getId()));
surfaceMember.add(new SurfaceProperty('#' + roof.getId()));
for (int i=0; i<walls.size(); i++){
surfaceMember.add(new SurfaceProperty('#' + walls.get(i).getId()));
}
for (int i=0; i<floors.size(); i++){
surfaceMember.add(new SurfaceProperty('#' + floors.get(i).getId()));
}
// Assume an OI transition detected at wall number 1
int I_O = 1;
BoundarySurfaceProperty wall_1_BSurf = createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, walls.get(I_O));
createDoor(wall_1_BSurf);
CompositeSurface compositeSurface = new CompositeSurface();
compositeSurface.setSurfaceMember(surfaceMember);
Solid solid = new Solid();
solid.setExterior(new SurfaceProperty(compositeSurface));
building.setLod4Solid(new SolidProperty(solid));
// thematic boundary surfaces
List<BoundarySurfaceProperty> boundedBy = new ArrayList<BoundarySurfaceProperty>();
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_GROUND_SURFACE, ground));
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_ROOF_SURFACE, roof));
boundedBy.add(wall_1_BSurf);
for (int i=0; i<walls.size(); i++){
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, walls.get(i)));
}
for (int i=0; i<floors.size(); i++){
boundedBy.add(createBoundarySurface(CityGMLClass.BUILDING_FLOOR_SURFACE, floors.get(i)));
}
//BoundarySurfaceProperty wall3_2_BSurf = createBoundarySurface(CityGMLClass.BUILDING_WALL_SURFACE, wall_3);
//createWindow(wall3_2_BSurf);
//boundedBy.add(wall3_2_BSurf);
building.setBoundedBySurface(boundedBy);
CityModel cityModel = new CityModel();
cityModel.setBoundedBy(building.calcBoundedBy(false));
cityModel.addCityObjectMember(new CityObjectMember(building));
System.out.println(df.format(new Date()) + "writing citygml4j object tree");
CityGMLOutputFactory out = builder.createCityGMLOutputFactory(CityGMLVersion.DEFAULT);
CityGMLWriter writer = out.createCityGMLWriter(new File("MainCampGround.gml"));
writer.setPrefixes(CityGMLVersion.DEFAULT);
writer.setSchemaLocations(CityGMLVersion.DEFAULT);
writer.setIndentString(" ");
writer.write(cityModel);
writer.close();
System.out.println(df.format(new Date()) + "CityGML file LOD4_Building_v200.gml written");
System.out.println(df.format(new Date()) + "sample citygml4j application successfully finished");
}
public void createDoor(BoundarySurfaceProperty bsp) throws DimensionMismatchException {
System.out.println("c");
AbstractBoundarySurface b = bsp.getBoundarySurface();
if (b instanceof WallSurface) {
System.out.println("IS wall surf");
GMLGeometryFactory geom = new GMLGeometryFactory();
WallSurface ws = (WallSurface) b;
Door door = new Door();
OpeningProperty openingProperty = new OpeningProperty();
openingProperty.setObject(door);
//Polygon doorPoly= geom.createLinearPolygon(new double[] {-3.5,0.1,0, -6.5,0.1,0, -6.5,0.1,2.3, -3.5,0.1,2.3, -3.5,0.1,0}, 3);
//Polygon doorPoly2 = geom.createLinearPolygon(new double[] {-3.5,-0.1,0, -6.5,-0.1,0, -6.5,-0.1,2.3, -3.5,-0.1,2.3, -3.5,-0.1,0}, 3);
//List l = new ArrayList();
//l.add(doorPoly);
//l.add(doorPoly2);
//door.setLod4MultiSurface(new MultiSurfaceProperty(new MultiSurface(l)));
ws.addOpening(openingProperty);
}
}
public void createWindow(BoundarySurfaceProperty bsp) throws DimensionMismatchException {
System.out.println("c");
AbstractBoundarySurface b = bsp.getBoundarySurface();
if (b instanceof WallSurface) {
System.out.println("IS wall surf");
GMLGeometryFactory geom = new GMLGeometryFactory();
WallSurface ws = (WallSurface) b;
Window window3 = new Window();
OpeningProperty openingProperty = new OpeningProperty();
openingProperty.setObject(window3);
ws.addOpening(openingProperty);
}
}
private BoundarySurfaceProperty createBoundarySurface(CityGMLClass type, Polygon geometry) {
AbstractBoundarySurface boundarySurface = null;
switch (type) {
case BUILDING_WALL_SURFACE:
boundarySurface = new WallSurface();
break;
case BUILDING_ROOF_SURFACE:
boundarySurface = new RoofSurface();
break;
case BUILDING_GROUND_SURFACE:
boundarySurface = new GroundSurface();
break;
case BUILDING_FLOOR_SURFACE:
boundarySurface = new FloorSurface();
break;
default:
break;
}
if (boundarySurface != null) {
boundarySurface.setLod4MultiSurface(new MultiSurfaceProperty(new MultiSurface(geometry)));
return new BoundarySurfaceProperty(boundarySurface);
}
return null;
}
private static List<Foot> readFootsFromCSV(String fileName) {
List<Foot> foots = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
// create an instance of BufferedReader
// using try with resource, Java 7 feature to close resources
try (BufferedReader br = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
if (line.length()==0){
line = br.readLine();
}else {
String[] attributes = line.split(",");
Foot foot = createFoot(attributes);
// adding book into ArrayList
foots.add(foot);
//read next line before looping
//if end of file reached,
line = br.readLine();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return foots;
}
private static Foot createFoot(String[] metadata) {
double ref = Double.parseDouble(metadata[0]);
double lat = Double.parseDouble(metadata[1]);
double lon = Double.parseDouble(metadata[2]);
// create and return foot of this meta data
return new Foot(ref,lat, lon);
}
}
|
58224_2 | /*--------------------------------------------------------------*
Copyright (C) 2006-2015 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
'License' for details on this and other legal matters.
*--------------------------------------------------------------*/
package org.omnetpp.cdt.build;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.omnetpp.cdt.Activator;
import org.omnetpp.common.util.FileUtils;
import org.omnetpp.common.util.StringUtils;
/**
* Utility functions for Makefile generation.
*
* @author Andras
*/
public class MakefileTools {
// standard C headers, see e.g. http://www-ccs.ucsd.edu/c/lib_over.html
public static final String C_HEADERS =
"assert.h ctype.h errno.h float.h iso646.h limits.h locale.h " +
"math.h setjmp.h signal.h stdarg.h stddef.h stdio.h stdlib.h " +
"string.h time.h wchar.h wctype.h";
// C headers added by C99, see http://en.wikipedia.org/wiki/C_standard_library
public static final String C99_HEADERS =
"complex.h fenv.h inttypes.h stdbool.h stdint.h tgmath.h";
// standard C++ headers, see http://en.wikipedia.org/wiki/C++_standard_library#Standard_headers
public static final String CPLUSPLUS_HEADERS =
"bitset deque list map queue set stack vector algorithm functional iterator " +
"locale memory stdexcept utility string fstream ios iostream iosfwd iomanip " +
"istream ostream sstream streambuf complex numeric valarray exception limits " +
"new typeinfo cassert cctype cerrno cfloat climits cmath csetjmp csignal " +
"cstdlib cstddef cstdarg ctime cstdio cstring cwchar cwctype";
// POSIX headers, see http://en.wikipedia.org/wiki/C_POSIX_library
public static final String POSIX_HEADERS =
"cpio.h dirent.h fcntl.h grp.h pwd.h sys/ipc.h sys/msg.h sys/sem.h " +
"sys/stat.h sys/time.h sys/types.h sys/utsname.h sys/wait.h tar.h termios.h " +
"unistd.h utime.h";
// all standard C/C++ headers -- we'll ignore these #includes when looking for cross-folder dependencies
public static final String ALL_STANDARD_HEADERS =
C_HEADERS + " " + C99_HEADERS + " " + CPLUSPLUS_HEADERS + " " + POSIX_HEADERS;
// directories we'll not search for source files
public static final String IGNORABLE_DIRS[] = "CVS RCS SCCS _darcs blib .git .svn .git .bzr .hg backups".split(" +");
private MakefileTools() {
}
/**
* Returns true if the given resource is a file with "cc", "cpp" or "h" extension,
* but not _m.cc/cpp/h or _n.cc/cpp/h.
*/
public static boolean isNonGeneratedCppFile(IResource resource) {
// not an _m.cc or _n.cc file
return isCppFile(resource) && !resource.getName().matches(".*_[mn]\\.[^.]+$");
}
/**
* Returns true if the given resource is a file with "cc", "cpp" or "h" extension.
*/
public static boolean isCppFile(IResource resource) {
if (resource instanceof IFile) {
String fileExtension = ((IFile)resource).getFileExtension();
if ("cc".equalsIgnoreCase(fileExtension) || "cpp".equalsIgnoreCase(fileExtension) || "h".equalsIgnoreCase(fileExtension))
return true;
}
return false;
}
/**
* Returns true if the given resource is a file with "msg" extension.
*/
public static boolean isMsgFile(IResource resource) {
return resource instanceof IFile && "msg".equals(((IFile)resource).getFileExtension());
}
/**
* Returns true if the given resource is a file with "sm" extension.
*/
public static boolean isSmFile(IResource resource) {
return resource instanceof IFile && "sm".equals(((IFile)resource).getFileExtension());
}
/**
* Returns true if the resource is a potential source folder
* (not team private or backups folder). Does NOT check whether
* folder is marked as excluded in CDT.
*/
public static boolean isGoodFolder(IResource resource) {
// note: we explicitly check for "CVS", "_darcs" etc, because they are only recognized by
// isTeamPrivateMember() if the corresponding plugin is installed
return (resource instanceof IContainer &&
!resource.getName().startsWith(".") &&
!ArrayUtils.contains(MakefileTools.IGNORABLE_DIRS, resource.getName()) &&
!((IContainer)resource).isTeamPrivateMember());
}
/**
* Converts inputPath to be relative to referenceDir. This is not possible
* if the two paths are from different devices, so in this case the method
* returns the original inputPath unchanged.
*/
public static IPath makeRelativePath(IPath inputPath, IPath referenceDir) {
Assert.isTrue(inputPath.isAbsolute());
Assert.isTrue(referenceDir.isAbsolute());
if (referenceDir.equals(inputPath))
return new Path(".");
if (!StringUtils.equals(inputPath.getDevice(), referenceDir.getDevice()))
return inputPath;
int commonPrefixLen = inputPath.matchingFirstSegments(referenceDir);
int upLevels = referenceDir.segmentCount() - commonPrefixLen;
return new Path(StringUtils.removeEnd(StringUtils.repeat("../", upLevels), "/")).append(inputPath.removeFirstSegments(commonPrefixLen));
}
public static void ensureFileContent(IFile file, byte[] bytes, IProgressMonitor monitor) throws CoreException {
// only overwrites file if its content is not already what's desired
try {
file.refreshLocal(IResource.DEPTH_ZERO, monitor);
if (!file.exists())
file.create(new ByteArrayInputStream(bytes), true, monitor);
else if (!Arrays.equals(FileUtils.readBinaryFile(file.getContents()), bytes)) // NOTE: byte[].equals does NOT compare content, only references!!!
file.setContents(new ByteArrayInputStream(bytes), true, false, monitor);
}
catch (IOException e) {
throw Activator.wrapIntoCoreException(e);
}
}
/**
* Utility function to determine whether a given container is covered by
* a given makefile. CDT source dirs and exclusions (CSourceEntry) are ignored,
* instead there is excludedFolders (list of folder-relative paths to be excluded;
* it excludes subtrees not single folders), and makeFolders (i.e. the given folder
* may falls into the tree of another makefile).
*
* Both excludedFolders and makeFolders may be null.
*/
public static boolean makefileCovers(IContainer makefileFolder, IContainer folder, boolean deep, List<String> excludedFolders, List<IContainer> makeFolders) {
if (!deep) {
return folder.equals(makefileFolder);
}
else {
if (!makefileFolder.getFullPath().isPrefixOf(folder.getFullPath()))
return false; // not under that folder
if (excludedFolders != null) {
IPath folderRelativePath = folder.getFullPath().removeFirstSegments(makefileFolder.getFullPath().segmentCount());
for (String exludedFolder : excludedFolders)
if (new Path(exludedFolder).isPrefixOf(folderRelativePath))
return false; // excluded
}
if (makeFolders != null) {
// we visit the ancestors of this folder; if we find another makefile first, the answer is "false"
for (IContainer tmp = folder; !tmp.equals(makefileFolder); tmp = tmp.getParent())
if (makeFolders.contains(tmp))
return false;
}
return true;
}
}
//XXX experimental
//
// public static void updateProjectIncludePaths(ICProjectDescription projectDescription) throws CoreException {
// List<IContainer> desiredIncDirs = MakefileTools.collectDirs(projectDescription, null);
// for (ICConfigurationDescription config : projectDescription.getConfigurations()) {
// ICFolderDescription rootFolderDesc = (ICFolderDescription)config.getResourceDescription(new Path(""), true);
// ICLanguageSetting[] languageSettings = rootFolderDesc.getLanguageSettings();
//
// ICLanguageSetting languageSetting = null;
// for (ICLanguageSetting l : languageSettings) {
// Debug.println("name:" + l.getName() + " langsettingid:" + l.getId() + " parentid:" + l.getParent().toString() + " langID:" + l.getLanguageId());
// List<ICLanguageSettingEntry> list = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH);
// //list.add(new CIncludePathEntry("/hello/bubu", ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.READONLY | ICSettingEntry.BUILTIN));
// //list.add(new CIncludePathEntry("/hello/bubu"+System.currentTimeMillis(), ~0));
// list.add(new CIncludePathEntry("/hello/syspath"+System.currentTimeMillis(), ICSettingEntry.READONLY | ICSettingEntry.BUILTIN));
// for (ICLanguageSettingEntry e : list)
// Debug.println(" " + e);
// // possible flags: BUILTIN, READONLY, LOCAL (??), VALUE_WORKSPACE_PATH, RESOLVED
// l.setSettingEntries(ICSettingEntry.INCLUDE_PATH, list); // ===> DOES NOT WORK, BUILTIN/READONLY FLAGS GET CLEARED BY CDT
//
// List<ICLanguageSettingEntry> list2 = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH);
// for (ICLanguageSettingEntry e : list2) {
// if (e instanceof CIncludePathEntry) {
// ReflectionUtils.setFieldValue(e, "fFlags", e.getFlags() | ICSettingEntry.READONLY);
// }
// Debug.println(" " + e);
// }
// }
// // remove existing include paths
// // add new include paths
// //XXX language settings! and folder specific!! AAARGH....
// }
//
// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=206372
//
// // testing CoreModel.setRawPathEntries() -- yields editable entries like ICLangageSettingEntry...
// IProject project = projectDescription.getProject();
// ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName());
// IPathEntry[] rawPathEntries = CoreModel.getRawPathEntries(cproject);
// for (IPathEntry e : rawPathEntries)
// Debug.println("** ENTRY: " + e);
// IncludeEntry newEntry = new IncludeEntry(new Path(""), new Path(""), new Path(""), new Path("/someproj/inc-"+System.currentTimeMillis()), true, new IPath[]{}, false);
// rawPathEntries = (IPathEntry[])ArrayUtils.add(rawPathEntries, newEntry);
// CoreModel.setRawPathEntries(cproject, rawPathEntries, null);
//
// // random test code...
// IDiscoveredPathInfo discoveredInfo = MakeCorePlugin.getDefault().getDiscoveryManager().getDiscoveredInfo(project);
// Debug.println(discoveredInfo);
// }
}
| omnetpp/omnetpp | ui/org.omnetpp.cdt/src/org/omnetpp/cdt/build/MakefileTools.java | 3,279 | // standard C headers, see e.g. http://www-ccs.ucsd.edu/c/lib_over.html | line_comment | nl | /*--------------------------------------------------------------*
Copyright (C) 2006-2015 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
'License' for details on this and other legal matters.
*--------------------------------------------------------------*/
package org.omnetpp.cdt.build;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.omnetpp.cdt.Activator;
import org.omnetpp.common.util.FileUtils;
import org.omnetpp.common.util.StringUtils;
/**
* Utility functions for Makefile generation.
*
* @author Andras
*/
public class MakefileTools {
// standard C<SUF>
public static final String C_HEADERS =
"assert.h ctype.h errno.h float.h iso646.h limits.h locale.h " +
"math.h setjmp.h signal.h stdarg.h stddef.h stdio.h stdlib.h " +
"string.h time.h wchar.h wctype.h";
// C headers added by C99, see http://en.wikipedia.org/wiki/C_standard_library
public static final String C99_HEADERS =
"complex.h fenv.h inttypes.h stdbool.h stdint.h tgmath.h";
// standard C++ headers, see http://en.wikipedia.org/wiki/C++_standard_library#Standard_headers
public static final String CPLUSPLUS_HEADERS =
"bitset deque list map queue set stack vector algorithm functional iterator " +
"locale memory stdexcept utility string fstream ios iostream iosfwd iomanip " +
"istream ostream sstream streambuf complex numeric valarray exception limits " +
"new typeinfo cassert cctype cerrno cfloat climits cmath csetjmp csignal " +
"cstdlib cstddef cstdarg ctime cstdio cstring cwchar cwctype";
// POSIX headers, see http://en.wikipedia.org/wiki/C_POSIX_library
public static final String POSIX_HEADERS =
"cpio.h dirent.h fcntl.h grp.h pwd.h sys/ipc.h sys/msg.h sys/sem.h " +
"sys/stat.h sys/time.h sys/types.h sys/utsname.h sys/wait.h tar.h termios.h " +
"unistd.h utime.h";
// all standard C/C++ headers -- we'll ignore these #includes when looking for cross-folder dependencies
public static final String ALL_STANDARD_HEADERS =
C_HEADERS + " " + C99_HEADERS + " " + CPLUSPLUS_HEADERS + " " + POSIX_HEADERS;
// directories we'll not search for source files
public static final String IGNORABLE_DIRS[] = "CVS RCS SCCS _darcs blib .git .svn .git .bzr .hg backups".split(" +");
private MakefileTools() {
}
/**
* Returns true if the given resource is a file with "cc", "cpp" or "h" extension,
* but not _m.cc/cpp/h or _n.cc/cpp/h.
*/
public static boolean isNonGeneratedCppFile(IResource resource) {
// not an _m.cc or _n.cc file
return isCppFile(resource) && !resource.getName().matches(".*_[mn]\\.[^.]+$");
}
/**
* Returns true if the given resource is a file with "cc", "cpp" or "h" extension.
*/
public static boolean isCppFile(IResource resource) {
if (resource instanceof IFile) {
String fileExtension = ((IFile)resource).getFileExtension();
if ("cc".equalsIgnoreCase(fileExtension) || "cpp".equalsIgnoreCase(fileExtension) || "h".equalsIgnoreCase(fileExtension))
return true;
}
return false;
}
/**
* Returns true if the given resource is a file with "msg" extension.
*/
public static boolean isMsgFile(IResource resource) {
return resource instanceof IFile && "msg".equals(((IFile)resource).getFileExtension());
}
/**
* Returns true if the given resource is a file with "sm" extension.
*/
public static boolean isSmFile(IResource resource) {
return resource instanceof IFile && "sm".equals(((IFile)resource).getFileExtension());
}
/**
* Returns true if the resource is a potential source folder
* (not team private or backups folder). Does NOT check whether
* folder is marked as excluded in CDT.
*/
public static boolean isGoodFolder(IResource resource) {
// note: we explicitly check for "CVS", "_darcs" etc, because they are only recognized by
// isTeamPrivateMember() if the corresponding plugin is installed
return (resource instanceof IContainer &&
!resource.getName().startsWith(".") &&
!ArrayUtils.contains(MakefileTools.IGNORABLE_DIRS, resource.getName()) &&
!((IContainer)resource).isTeamPrivateMember());
}
/**
* Converts inputPath to be relative to referenceDir. This is not possible
* if the two paths are from different devices, so in this case the method
* returns the original inputPath unchanged.
*/
public static IPath makeRelativePath(IPath inputPath, IPath referenceDir) {
Assert.isTrue(inputPath.isAbsolute());
Assert.isTrue(referenceDir.isAbsolute());
if (referenceDir.equals(inputPath))
return new Path(".");
if (!StringUtils.equals(inputPath.getDevice(), referenceDir.getDevice()))
return inputPath;
int commonPrefixLen = inputPath.matchingFirstSegments(referenceDir);
int upLevels = referenceDir.segmentCount() - commonPrefixLen;
return new Path(StringUtils.removeEnd(StringUtils.repeat("../", upLevels), "/")).append(inputPath.removeFirstSegments(commonPrefixLen));
}
public static void ensureFileContent(IFile file, byte[] bytes, IProgressMonitor monitor) throws CoreException {
// only overwrites file if its content is not already what's desired
try {
file.refreshLocal(IResource.DEPTH_ZERO, monitor);
if (!file.exists())
file.create(new ByteArrayInputStream(bytes), true, monitor);
else if (!Arrays.equals(FileUtils.readBinaryFile(file.getContents()), bytes)) // NOTE: byte[].equals does NOT compare content, only references!!!
file.setContents(new ByteArrayInputStream(bytes), true, false, monitor);
}
catch (IOException e) {
throw Activator.wrapIntoCoreException(e);
}
}
/**
* Utility function to determine whether a given container is covered by
* a given makefile. CDT source dirs and exclusions (CSourceEntry) are ignored,
* instead there is excludedFolders (list of folder-relative paths to be excluded;
* it excludes subtrees not single folders), and makeFolders (i.e. the given folder
* may falls into the tree of another makefile).
*
* Both excludedFolders and makeFolders may be null.
*/
public static boolean makefileCovers(IContainer makefileFolder, IContainer folder, boolean deep, List<String> excludedFolders, List<IContainer> makeFolders) {
if (!deep) {
return folder.equals(makefileFolder);
}
else {
if (!makefileFolder.getFullPath().isPrefixOf(folder.getFullPath()))
return false; // not under that folder
if (excludedFolders != null) {
IPath folderRelativePath = folder.getFullPath().removeFirstSegments(makefileFolder.getFullPath().segmentCount());
for (String exludedFolder : excludedFolders)
if (new Path(exludedFolder).isPrefixOf(folderRelativePath))
return false; // excluded
}
if (makeFolders != null) {
// we visit the ancestors of this folder; if we find another makefile first, the answer is "false"
for (IContainer tmp = folder; !tmp.equals(makefileFolder); tmp = tmp.getParent())
if (makeFolders.contains(tmp))
return false;
}
return true;
}
}
//XXX experimental
//
// public static void updateProjectIncludePaths(ICProjectDescription projectDescription) throws CoreException {
// List<IContainer> desiredIncDirs = MakefileTools.collectDirs(projectDescription, null);
// for (ICConfigurationDescription config : projectDescription.getConfigurations()) {
// ICFolderDescription rootFolderDesc = (ICFolderDescription)config.getResourceDescription(new Path(""), true);
// ICLanguageSetting[] languageSettings = rootFolderDesc.getLanguageSettings();
//
// ICLanguageSetting languageSetting = null;
// for (ICLanguageSetting l : languageSettings) {
// Debug.println("name:" + l.getName() + " langsettingid:" + l.getId() + " parentid:" + l.getParent().toString() + " langID:" + l.getLanguageId());
// List<ICLanguageSettingEntry> list = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH);
// //list.add(new CIncludePathEntry("/hello/bubu", ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.READONLY | ICSettingEntry.BUILTIN));
// //list.add(new CIncludePathEntry("/hello/bubu"+System.currentTimeMillis(), ~0));
// list.add(new CIncludePathEntry("/hello/syspath"+System.currentTimeMillis(), ICSettingEntry.READONLY | ICSettingEntry.BUILTIN));
// for (ICLanguageSettingEntry e : list)
// Debug.println(" " + e);
// // possible flags: BUILTIN, READONLY, LOCAL (??), VALUE_WORKSPACE_PATH, RESOLVED
// l.setSettingEntries(ICSettingEntry.INCLUDE_PATH, list); // ===> DOES NOT WORK, BUILTIN/READONLY FLAGS GET CLEARED BY CDT
//
// List<ICLanguageSettingEntry> list2 = l.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH);
// for (ICLanguageSettingEntry e : list2) {
// if (e instanceof CIncludePathEntry) {
// ReflectionUtils.setFieldValue(e, "fFlags", e.getFlags() | ICSettingEntry.READONLY);
// }
// Debug.println(" " + e);
// }
// }
// // remove existing include paths
// // add new include paths
// //XXX language settings! and folder specific!! AAARGH....
// }
//
// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=206372
//
// // testing CoreModel.setRawPathEntries() -- yields editable entries like ICLangageSettingEntry...
// IProject project = projectDescription.getProject();
// ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName());
// IPathEntry[] rawPathEntries = CoreModel.getRawPathEntries(cproject);
// for (IPathEntry e : rawPathEntries)
// Debug.println("** ENTRY: " + e);
// IncludeEntry newEntry = new IncludeEntry(new Path(""), new Path(""), new Path(""), new Path("/someproj/inc-"+System.currentTimeMillis()), true, new IPath[]{}, false);
// rawPathEntries = (IPathEntry[])ArrayUtils.add(rawPathEntries, newEntry);
// CoreModel.setRawPathEntries(cproject, rawPathEntries, null);
//
// // random test code...
// IDiscoveredPathInfo discoveredInfo = MakeCorePlugin.getDefault().getDiscoveryManager().getDiscoveredInfo(project);
// Debug.println(discoveredInfo);
// }
}
|
127996_1 | /*
* Copyright (C) 2012 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core.querybuilder;
import java.util.ArrayList;
import java.util.List;
import com.datastax.driver.core.TableMetadata;
/**
* A built DELETE statement.
*/
public class Delete extends BuiltStatement {
private final String keyspace;
private final String table;
private final List<Object> columnNames;
private final Where where;
private final Options usings;
Delete(String keyspace, String table, List<Object> columnNames) {
super();
this.keyspace = keyspace;
this.table = table;
this.columnNames = columnNames;
this.where = new Where(this);
this.usings = new Options(this);
}
Delete(TableMetadata table, List<Object> columnNames) {
super(table);
this.keyspace = table.getKeyspace().getName();
this.table = table.getName();
this.columnNames = columnNames;
this.where = new Where(this);
this.usings = new Options(this);
}
@Override
protected StringBuilder buildQueryString() {
StringBuilder builder = new StringBuilder();
builder.append("DELETE ");
if (columnNames != null)
Utils.joinAndAppendNames(builder, ",", columnNames);
builder.append(" FROM ");
if (keyspace != null)
Utils.appendName(keyspace, builder).append(".");
Utils.appendName(table, builder);
if (!usings.usings.isEmpty()) {
builder.append(" USING ");
Utils.joinAndAppend(builder, " AND ", usings.usings);
}
if (!where.clauses.isEmpty()) {
builder.append(" WHERE ");
Utils.joinAndAppend(builder, " AND ", where.clauses);
}
return builder;
}
/**
* Adds a WHERE clause to this statement.
*
* This is a shorter/more readable version for {@code where().and(clause)}.
*
* @param clause the clause to add.
* @return the where clause of this query to which more clause can be added.
*/
public Where where(Clause clause) {
return where.and(clause);
}
/**
* Returns a Where statement for this query without adding clause.
*
* @return the where clause of this query to which more clause can be added.
*/
public Where where() {
return where;
}
/**
* Adds a new options for this DELETE statement.
*
* @param using the option to add.
* @return the options of this DELETE statement.
*/
public Options using(Using using) {
return usings.and(using);
}
/**
* The WHERE clause of a DELETE statement.
*/
public static class Where extends BuiltStatement.ForwardingStatement<Delete> {
private final List<Clause> clauses = new ArrayList<Clause>();
Where(Delete statement) {
super(statement);
}
/**
* Adds the provided clause to this WHERE clause.
*
* @param clause the clause to add.
* @return this WHERE clause.
*/
public Where and(Clause clause)
{
clauses.add(clause);
statement.maybeAddRoutingKey(clause.name(), clause.firstValue());
setDirty();
return this;
}
/**
* Adds an option to the DELETE statement this WHERE clause is part of.
*
* @param using the using clause to add.
* @return the options of the DELETE statement this WHERE clause is part of.
*/
public Options using(Using using) {
return statement.using(using);
}
}
/**
* The options of a DELETE statement.
*/
public static class Options extends BuiltStatement.ForwardingStatement<Delete> {
private final List<Using> usings = new ArrayList<Using>();
Options(Delete statement) {
super(statement);
}
/**
* Adds the provided option.
*
* @param using a DELETE option.
* @return this {@code Options} object.
*/
public Options and(Using using) {
usings.add(using);
setDirty();
return this;
}
/**
* Adds a where clause to the DELETE statement these options are part of.
*
* @param clause clause to add.
* @return the WHERE clause of the DELETE statement these options are part of.
*/
public Where where(Clause clause) {
return statement.where(clause);
}
}
/**
* An in-construction DELETE statement.
*/
public static class Builder {
protected List<Object> columnNames;
protected Builder() {}
Builder(List<Object> columnNames) {
this.columnNames = columnNames;
}
/**
* Adds the table to delete from.
*
* @param table the name of the table to delete from.
* @return a newly built DELETE statement that deletes from {@code table}.
*/
public Delete from(String table) {
return from(null, table);
}
/**
* Adds the table to delete from.
*
* @param keyspace the name of the keyspace to delete from.
* @param table the name of the table to delete from.
* @return a newly built DELETE statement that deletes from {@code keyspace.table}.
*/
public Delete from(String keyspace, String table) {
return new Delete(keyspace, table, columnNames);
}
/**
* Adds the table to delete from.
*
* @param table the table to delete from.
* @return a newly built DELETE statement that deletes from {@code table}.
*/
public Delete from(TableMetadata table) {
return new Delete(table, columnNames);
}
}
/**
* An column selection clause for an in-construction DELETE statement.
*/
public static class Selection extends Builder {
/**
* Deletes all columns (i.e. "DELETE FROM ...")
*
* @return an in-build DELETE statement.
*
* @throws IllegalStateException if some columns had already been selected for this builder.
*/
public Builder all() {
if (columnNames != null)
throw new IllegalStateException(String.format("Some columns (%s) have already been selected.", columnNames));
return (Builder)this;
}
/**
* Deletes the provided column.
*
* @param name the column name to select for deletion.
* @return this in-build DELETE Selection
*/
public Selection column(String name) {
if (columnNames == null)
columnNames = new ArrayList<Object>();
columnNames.add(name);
return this;
}
/**
* Deletes the provided list element.
*
* @param columnName the name of the list column.
* @param idx the index of the element to delete.
* @return this in-build DELETE Selection
*/
public Selection listElt(String columnName, int idx) {
StringBuilder sb = new StringBuilder();
Utils.appendName(columnName, sb);
return column(sb.append("[").append(idx).append("]").toString());
}
/**
* Deletes a map element given a key.
*
* @param columnName the name of the map column.
* @param key the key for the element to delete.
* @return this in-build DELETE Selection
*/
public Selection mapElt(String columnName, Object key) {
StringBuilder sb = new StringBuilder();
Utils.appendName(columnName, sb);
sb.append("[");
Utils.appendFlatValue(key, sb);
return column(sb.append("]").toString());
}
}
}
| omnifone/datastax-java-driver | driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java | 2,175 | /**
* A built DELETE statement.
*/ | block_comment | nl | /*
* Copyright (C) 2012 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core.querybuilder;
import java.util.ArrayList;
import java.util.List;
import com.datastax.driver.core.TableMetadata;
/**
* A built DELETE<SUF>*/
public class Delete extends BuiltStatement {
private final String keyspace;
private final String table;
private final List<Object> columnNames;
private final Where where;
private final Options usings;
Delete(String keyspace, String table, List<Object> columnNames) {
super();
this.keyspace = keyspace;
this.table = table;
this.columnNames = columnNames;
this.where = new Where(this);
this.usings = new Options(this);
}
Delete(TableMetadata table, List<Object> columnNames) {
super(table);
this.keyspace = table.getKeyspace().getName();
this.table = table.getName();
this.columnNames = columnNames;
this.where = new Where(this);
this.usings = new Options(this);
}
@Override
protected StringBuilder buildQueryString() {
StringBuilder builder = new StringBuilder();
builder.append("DELETE ");
if (columnNames != null)
Utils.joinAndAppendNames(builder, ",", columnNames);
builder.append(" FROM ");
if (keyspace != null)
Utils.appendName(keyspace, builder).append(".");
Utils.appendName(table, builder);
if (!usings.usings.isEmpty()) {
builder.append(" USING ");
Utils.joinAndAppend(builder, " AND ", usings.usings);
}
if (!where.clauses.isEmpty()) {
builder.append(" WHERE ");
Utils.joinAndAppend(builder, " AND ", where.clauses);
}
return builder;
}
/**
* Adds a WHERE clause to this statement.
*
* This is a shorter/more readable version for {@code where().and(clause)}.
*
* @param clause the clause to add.
* @return the where clause of this query to which more clause can be added.
*/
public Where where(Clause clause) {
return where.and(clause);
}
/**
* Returns a Where statement for this query without adding clause.
*
* @return the where clause of this query to which more clause can be added.
*/
public Where where() {
return where;
}
/**
* Adds a new options for this DELETE statement.
*
* @param using the option to add.
* @return the options of this DELETE statement.
*/
public Options using(Using using) {
return usings.and(using);
}
/**
* The WHERE clause of a DELETE statement.
*/
public static class Where extends BuiltStatement.ForwardingStatement<Delete> {
private final List<Clause> clauses = new ArrayList<Clause>();
Where(Delete statement) {
super(statement);
}
/**
* Adds the provided clause to this WHERE clause.
*
* @param clause the clause to add.
* @return this WHERE clause.
*/
public Where and(Clause clause)
{
clauses.add(clause);
statement.maybeAddRoutingKey(clause.name(), clause.firstValue());
setDirty();
return this;
}
/**
* Adds an option to the DELETE statement this WHERE clause is part of.
*
* @param using the using clause to add.
* @return the options of the DELETE statement this WHERE clause is part of.
*/
public Options using(Using using) {
return statement.using(using);
}
}
/**
* The options of a DELETE statement.
*/
public static class Options extends BuiltStatement.ForwardingStatement<Delete> {
private final List<Using> usings = new ArrayList<Using>();
Options(Delete statement) {
super(statement);
}
/**
* Adds the provided option.
*
* @param using a DELETE option.
* @return this {@code Options} object.
*/
public Options and(Using using) {
usings.add(using);
setDirty();
return this;
}
/**
* Adds a where clause to the DELETE statement these options are part of.
*
* @param clause clause to add.
* @return the WHERE clause of the DELETE statement these options are part of.
*/
public Where where(Clause clause) {
return statement.where(clause);
}
}
/**
* An in-construction DELETE statement.
*/
public static class Builder {
protected List<Object> columnNames;
protected Builder() {}
Builder(List<Object> columnNames) {
this.columnNames = columnNames;
}
/**
* Adds the table to delete from.
*
* @param table the name of the table to delete from.
* @return a newly built DELETE statement that deletes from {@code table}.
*/
public Delete from(String table) {
return from(null, table);
}
/**
* Adds the table to delete from.
*
* @param keyspace the name of the keyspace to delete from.
* @param table the name of the table to delete from.
* @return a newly built DELETE statement that deletes from {@code keyspace.table}.
*/
public Delete from(String keyspace, String table) {
return new Delete(keyspace, table, columnNames);
}
/**
* Adds the table to delete from.
*
* @param table the table to delete from.
* @return a newly built DELETE statement that deletes from {@code table}.
*/
public Delete from(TableMetadata table) {
return new Delete(table, columnNames);
}
}
/**
* An column selection clause for an in-construction DELETE statement.
*/
public static class Selection extends Builder {
/**
* Deletes all columns (i.e. "DELETE FROM ...")
*
* @return an in-build DELETE statement.
*
* @throws IllegalStateException if some columns had already been selected for this builder.
*/
public Builder all() {
if (columnNames != null)
throw new IllegalStateException(String.format("Some columns (%s) have already been selected.", columnNames));
return (Builder)this;
}
/**
* Deletes the provided column.
*
* @param name the column name to select for deletion.
* @return this in-build DELETE Selection
*/
public Selection column(String name) {
if (columnNames == null)
columnNames = new ArrayList<Object>();
columnNames.add(name);
return this;
}
/**
* Deletes the provided list element.
*
* @param columnName the name of the list column.
* @param idx the index of the element to delete.
* @return this in-build DELETE Selection
*/
public Selection listElt(String columnName, int idx) {
StringBuilder sb = new StringBuilder();
Utils.appendName(columnName, sb);
return column(sb.append("[").append(idx).append("]").toString());
}
/**
* Deletes a map element given a key.
*
* @param columnName the name of the map column.
* @param key the key for the element to delete.
* @return this in-build DELETE Selection
*/
public Selection mapElt(String columnName, Object key) {
StringBuilder sb = new StringBuilder();
Utils.appendName(columnName, sb);
sb.append("[");
Utils.appendFlatValue(key, sb);
return column(sb.append("]").toString());
}
}
}
|
180313_24 | package com.hitler.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import com.hitler.common.model.annotation.Checked;
import com.hitler.common.model.support.CheckableEntity;
import com.hitler.common.util.StringUtils;
/**
* 用户
* @author
*
*/
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "TB_USER", indexes = {
@Index(name = "IDX_PARENT_ID", columnList = "PARENT_ID")
})
public class User extends CheckableEntity<Integer> {
private static final long serialVersionUID = 3589877365682748474L;
/**
* 用户帐号
*/
@Checked
@Column(name = "USER_NAME", columnDefinition="varchar(16) COMMENT '用户帐号'", unique = true, nullable = false)
private String userName;
/**
* 昵称
*/
@Column(name = "NICK_NAME", columnDefinition="varchar(12) COMMENT '昵称'", nullable = false)
private String nickName = "";
/**
* 登录密码
*/
@Checked
@Column(name = "PWD_LOGIN", columnDefinition="varchar(32) COMMENT '登录密码'", nullable = false)
private String loginPassword;
/**
* 资金密码
*/
@Checked
@Column(name = "PWD_FUNDS", columnDefinition="varchar(32) COMMENT '资金密码'")
private String fundsPassword;
/**
* 加盐
*/
@Checked
@Column(name = "PWD_SALT", columnDefinition="varchar(32) COMMENT '加盐'", nullable = false)
private String passwordSalt;
/**
* 分层锁定状态
*/
@Checked
@Column(name = "LAYER_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '分层锁定状态'")
private Boolean layerLocked = Boolean.FALSE;
/**
* 账户余额
*/
@Checked
@Column(name = "BALANCE_ACCOUNT", columnDefinition="DECIMAL(10,2) DEFAULT 0.0 COMMENT '账户余额'")
private Double accountBalance = 0D;
/**
* QQ号码
*/
@Column(name = "QQ", columnDefinition="varchar(15) COMMENT 'QQ号码'")
private String qq = "";
/**
* 邮箱
*/
@Column(name = "EMAIL", columnDefinition="varchar(40) COMMENT '邮箱'")
private String email = "";
/**
* 手机号码
*/
@Column(name = "MOBILE", columnDefinition="varchar(20) COMMENT '手机号码'")
private String mobile = "";
/**
* 登录冻结状态
*/
@Checked
@Column(name = "LOGIN_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '登录冻结状态'")
private Boolean loginLocked = Boolean.FALSE;
/**
* 用户银行锁定状态
*/
@Checked
@Column(name = "BANK_CARD_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '用户银行锁定状态'")
private Boolean bankCardLocked = Boolean.FALSE;
/**
* 最后提款时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_WITHDRAW_TIME", columnDefinition="TIMESTAMP NULL COMMENT '最后提款时间'")
private Date lastWithdrawTime;
/**
* 最后登录时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_LOGIN_TIME", columnDefinition="TIMESTAMP NULL COMMENT '最后登录时间'")
private Date lastLoginTime;
/**
* 最后登录IP地址
*/
@Column(name = "LAST_LOGIN_ADDR", columnDefinition="varchar(20) COMMENT '最后登录IP地址'")
private String lastLoginAddress = "";
/**
* 登录失败次数
*/
@Checked
@Column(name = "LOGIN_FAILURE_TIMES", columnDefinition="INT DEFAULT 0 COMMENT '登录失败次数'")
private Integer loginFailureTimes = 0;
/**
* 登录锁定解冻时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LOGIN_LOCKED_DUE_TIME", columnDefinition="TIMESTAMP NULL COMMENT '登录锁定解冻时间'")
private Date loginLockedDueTime;
/**
* 登录密码最后修改时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LOGIN_PWD_LAST_MODIFIED_DATE", columnDefinition="TIMESTAMP NULL COMMENT '登录密码最后修改时间'")
private Date loginPasswordLastModifiedDate;
/**
* 资金密码最后修改时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "FUNDS_PWD_LAST_MODIFIED_DATE", columnDefinition="TIMESTAMP NULL COMMENT '资金密码最后修改时间'")
private Date fundsPasswordLastModifiedDate;
/**
* 直属上级ID
*/
@Checked
@Column(name = "PARENT_ID", columnDefinition="INT COMMENT '直属上级ID'")
private Integer parentId;
/**
* 直属上级帐号
*/
@Checked
@Column(name = "PARENT_NAME", columnDefinition="varchar(16) COMMENT '直属上级帐号'")
private String parentName;
/**
* 邮箱激活码
*/
@Checked
@Column(name = "EMAIL_CODE", columnDefinition="varchar(50) COMMENT '邮箱激活码'")
private String emailCode;
/**
* 是否激活
*/
@Checked
@Column(name = "IS_EMAIL_ACTIVE", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '邮箱是否激活'")
private Boolean isEmailActive= Boolean.FALSE;
//====================== 未持久化字段 begin ======================
public User() {
}
public User(Integer id, String userName) {
this.setId(id);
this.setUserName(userName);
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(Double accountBalance) {
this.accountBalance = accountBalance;
}
public String getLoginPassword() {
return loginPassword;
}
public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}
public String getFundsPassword() {
return fundsPassword;
}
public void setFundsPassword(String fundsPassword) {
this.fundsPassword = fundsPassword;
}
public String getPasswordSalt() {
return passwordSalt;
}
public void setPasswordSalt(String passwordSalt) {
this.passwordSalt = passwordSalt;
}
public Boolean getLoginLocked() {
return loginLocked;
}
public void setLoginLocked(Boolean loginLocked) {
this.loginLocked = loginLocked;
}
public Boolean getBankCardLocked() {
return bankCardLocked;
}
public void setBankCardLocked(Boolean bankCardLocked) {
this.bankCardLocked = bankCardLocked;
}
public Boolean getLayerLocked() {
return layerLocked;
}
public void setLayerLocked(Boolean layerLocked) {
this.layerLocked = layerLocked;
}
public Date getLoginPasswordLastModifiedDate() {
return loginPasswordLastModifiedDate;
}
public void setLoginPasswordLastModifiedDate(
Date loginPasswordLastModifiedDate) {
this.loginPasswordLastModifiedDate = loginPasswordLastModifiedDate;
}
public Date getFundsPasswordLastModifiedDate() {
return fundsPasswordLastModifiedDate;
}
public void setFundsPasswordLastModifiedDate(
Date fundsPasswordLastModifiedDate) {
this.fundsPasswordLastModifiedDate = fundsPasswordLastModifiedDate;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public Date getLastWithdrawTime() {
return lastWithdrawTime;
}
public void setLastWithdrawTime(Date lastWithdrawTime) {
this.lastWithdrawTime = lastWithdrawTime;
}
public String getLastLoginAddress() {
return lastLoginAddress;
}
public void setLastLoginAddress(String lastLoginAddress) {
this.lastLoginAddress = lastLoginAddress;
}
public Integer getLoginFailureTimes() {
return loginFailureTimes;
}
public void setLoginFailureTimes(Integer loginFailureTimes) {
this.loginFailureTimes = loginFailureTimes;
}
public Date getLoginLockedDueTime() {
return loginLockedDueTime;
}
public void setLoginLockedDueTime(Date loginLockedDueTime) {
this.loginLockedDueTime = loginLockedDueTime;
}
public Boolean hasParent() {
return StringUtils.isNotBlank(getParentName());
}
public Boolean validateInformation(String regex) {
if (userName != null && userName.matches(regex)) {
return Boolean.FALSE;
}
if (nickName != null && nickName.matches(regex)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
public String getEmailCode() {
return emailCode;
}
public void setEmailCode(String emailCode) {
this.emailCode = emailCode;
}
public Boolean getIsEmailActive() {
return isEmailActive;
}
public void setIsEmailActive(Boolean isEmailActive) {
this.isEmailActive = isEmailActive;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
| onsoul/saas-db | saas-mycat/saas/src/main/java/com/hitler/model/User.java | 3,194 | //====================== 未持久化字段 begin ====================== | line_comment | nl | package com.hitler.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import com.hitler.common.model.annotation.Checked;
import com.hitler.common.model.support.CheckableEntity;
import com.hitler.common.util.StringUtils;
/**
* 用户
* @author
*
*/
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "TB_USER", indexes = {
@Index(name = "IDX_PARENT_ID", columnList = "PARENT_ID")
})
public class User extends CheckableEntity<Integer> {
private static final long serialVersionUID = 3589877365682748474L;
/**
* 用户帐号
*/
@Checked
@Column(name = "USER_NAME", columnDefinition="varchar(16) COMMENT '用户帐号'", unique = true, nullable = false)
private String userName;
/**
* 昵称
*/
@Column(name = "NICK_NAME", columnDefinition="varchar(12) COMMENT '昵称'", nullable = false)
private String nickName = "";
/**
* 登录密码
*/
@Checked
@Column(name = "PWD_LOGIN", columnDefinition="varchar(32) COMMENT '登录密码'", nullable = false)
private String loginPassword;
/**
* 资金密码
*/
@Checked
@Column(name = "PWD_FUNDS", columnDefinition="varchar(32) COMMENT '资金密码'")
private String fundsPassword;
/**
* 加盐
*/
@Checked
@Column(name = "PWD_SALT", columnDefinition="varchar(32) COMMENT '加盐'", nullable = false)
private String passwordSalt;
/**
* 分层锁定状态
*/
@Checked
@Column(name = "LAYER_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '分层锁定状态'")
private Boolean layerLocked = Boolean.FALSE;
/**
* 账户余额
*/
@Checked
@Column(name = "BALANCE_ACCOUNT", columnDefinition="DECIMAL(10,2) DEFAULT 0.0 COMMENT '账户余额'")
private Double accountBalance = 0D;
/**
* QQ号码
*/
@Column(name = "QQ", columnDefinition="varchar(15) COMMENT 'QQ号码'")
private String qq = "";
/**
* 邮箱
*/
@Column(name = "EMAIL", columnDefinition="varchar(40) COMMENT '邮箱'")
private String email = "";
/**
* 手机号码
*/
@Column(name = "MOBILE", columnDefinition="varchar(20) COMMENT '手机号码'")
private String mobile = "";
/**
* 登录冻结状态
*/
@Checked
@Column(name = "LOGIN_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '登录冻结状态'")
private Boolean loginLocked = Boolean.FALSE;
/**
* 用户银行锁定状态
*/
@Checked
@Column(name = "BANK_CARD_LOCKED", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '用户银行锁定状态'")
private Boolean bankCardLocked = Boolean.FALSE;
/**
* 最后提款时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_WITHDRAW_TIME", columnDefinition="TIMESTAMP NULL COMMENT '最后提款时间'")
private Date lastWithdrawTime;
/**
* 最后登录时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_LOGIN_TIME", columnDefinition="TIMESTAMP NULL COMMENT '最后登录时间'")
private Date lastLoginTime;
/**
* 最后登录IP地址
*/
@Column(name = "LAST_LOGIN_ADDR", columnDefinition="varchar(20) COMMENT '最后登录IP地址'")
private String lastLoginAddress = "";
/**
* 登录失败次数
*/
@Checked
@Column(name = "LOGIN_FAILURE_TIMES", columnDefinition="INT DEFAULT 0 COMMENT '登录失败次数'")
private Integer loginFailureTimes = 0;
/**
* 登录锁定解冻时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LOGIN_LOCKED_DUE_TIME", columnDefinition="TIMESTAMP NULL COMMENT '登录锁定解冻时间'")
private Date loginLockedDueTime;
/**
* 登录密码最后修改时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LOGIN_PWD_LAST_MODIFIED_DATE", columnDefinition="TIMESTAMP NULL COMMENT '登录密码最后修改时间'")
private Date loginPasswordLastModifiedDate;
/**
* 资金密码最后修改时间
*/
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "FUNDS_PWD_LAST_MODIFIED_DATE", columnDefinition="TIMESTAMP NULL COMMENT '资金密码最后修改时间'")
private Date fundsPasswordLastModifiedDate;
/**
* 直属上级ID
*/
@Checked
@Column(name = "PARENT_ID", columnDefinition="INT COMMENT '直属上级ID'")
private Integer parentId;
/**
* 直属上级帐号
*/
@Checked
@Column(name = "PARENT_NAME", columnDefinition="varchar(16) COMMENT '直属上级帐号'")
private String parentName;
/**
* 邮箱激活码
*/
@Checked
@Column(name = "EMAIL_CODE", columnDefinition="varchar(50) COMMENT '邮箱激活码'")
private String emailCode;
/**
* 是否激活
*/
@Checked
@Column(name = "IS_EMAIL_ACTIVE", columnDefinition="TINYINT(2) DEFAULT 0 COMMENT '邮箱是否激活'")
private Boolean isEmailActive= Boolean.FALSE;
//====================== 未持久化字段<SUF>
public User() {
}
public User(Integer id, String userName) {
this.setId(id);
this.setUserName(userName);
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(Double accountBalance) {
this.accountBalance = accountBalance;
}
public String getLoginPassword() {
return loginPassword;
}
public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}
public String getFundsPassword() {
return fundsPassword;
}
public void setFundsPassword(String fundsPassword) {
this.fundsPassword = fundsPassword;
}
public String getPasswordSalt() {
return passwordSalt;
}
public void setPasswordSalt(String passwordSalt) {
this.passwordSalt = passwordSalt;
}
public Boolean getLoginLocked() {
return loginLocked;
}
public void setLoginLocked(Boolean loginLocked) {
this.loginLocked = loginLocked;
}
public Boolean getBankCardLocked() {
return bankCardLocked;
}
public void setBankCardLocked(Boolean bankCardLocked) {
this.bankCardLocked = bankCardLocked;
}
public Boolean getLayerLocked() {
return layerLocked;
}
public void setLayerLocked(Boolean layerLocked) {
this.layerLocked = layerLocked;
}
public Date getLoginPasswordLastModifiedDate() {
return loginPasswordLastModifiedDate;
}
public void setLoginPasswordLastModifiedDate(
Date loginPasswordLastModifiedDate) {
this.loginPasswordLastModifiedDate = loginPasswordLastModifiedDate;
}
public Date getFundsPasswordLastModifiedDate() {
return fundsPasswordLastModifiedDate;
}
public void setFundsPasswordLastModifiedDate(
Date fundsPasswordLastModifiedDate) {
this.fundsPasswordLastModifiedDate = fundsPasswordLastModifiedDate;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public Date getLastWithdrawTime() {
return lastWithdrawTime;
}
public void setLastWithdrawTime(Date lastWithdrawTime) {
this.lastWithdrawTime = lastWithdrawTime;
}
public String getLastLoginAddress() {
return lastLoginAddress;
}
public void setLastLoginAddress(String lastLoginAddress) {
this.lastLoginAddress = lastLoginAddress;
}
public Integer getLoginFailureTimes() {
return loginFailureTimes;
}
public void setLoginFailureTimes(Integer loginFailureTimes) {
this.loginFailureTimes = loginFailureTimes;
}
public Date getLoginLockedDueTime() {
return loginLockedDueTime;
}
public void setLoginLockedDueTime(Date loginLockedDueTime) {
this.loginLockedDueTime = loginLockedDueTime;
}
public Boolean hasParent() {
return StringUtils.isNotBlank(getParentName());
}
public Boolean validateInformation(String regex) {
if (userName != null && userName.matches(regex)) {
return Boolean.FALSE;
}
if (nickName != null && nickName.matches(regex)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
public String getEmailCode() {
return emailCode;
}
public void setEmailCode(String emailCode) {
this.emailCode = emailCode;
}
public Boolean getIsEmailActive() {
return isEmailActive;
}
public void setIsEmailActive(Boolean isEmailActive) {
this.isEmailActive = isEmailActive;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
|
139816_15 | package com.articulate.sigma.nlg;
import com.articulate.sigma.KB;
import com.articulate.sigma.wordNet.WordNet;
import com.articulate.sigma.wordNet.WordNetUtilities;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Sets;
/**
* Handles verb functionality for a SUMO process.
*/
public class SumoProcess {
private final String verb;
private VerbProperties.Polarity polarity = VerbProperties.Polarity.AFFIRMATIVE;
private final KB kb;
public SumoProcess(SumoProcess process, KB kb) {
this.verb = process.getVerb();
this.polarity = process.getPolarity();
this.kb = kb;
}
private String surfaceForm;
public SumoProcess(String verb, KB kb) {
this.verb = verb;
this.kb = kb;
}
/**************************************************************************************************************
* Indirectly invoked by SumoProcessCollector.toString( ).
* @return
*/
@Override
public String toString() {
return verb;
}
/**************************************************************************************************************
*
* @return
*/
public String getSurfaceForm() {
return surfaceForm;
}
/**************************************************************************************************************
*
* @param surfaceForm
*/
void setSurfaceForm(String surfaceForm) {
this.surfaceForm = surfaceForm;
}
/**************************************************************************************************************
* Try to phrase the verb into natural language, setting this object's internal state appropriately.
* @param sentence
*/
public void formulateNaturalVerb(Sentence sentence) {
String verbSurfaceForm = SumoProcess.getVerbRootForm(this.verb);
if (verbSurfaceForm == null || verbSurfaceForm.isEmpty()) {
setVerbAndDirectObject(sentence);
}
else {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
verbSurfaceForm = SumoProcess.verbRootToThirdPersonSingular(verbSurfaceForm);
}
setSurfaceForm(polarityPrefix + verbSurfaceForm);
}
}
/**************************************************************************************************************
* Return the correct prefix for negative sentences--"don't" or "doesn't". For affirmatives return empty string.
* @param polarity
* @param singularPlural
* @return
*/
private static String getPolarityPrefix(VerbProperties.Polarity polarity, SVOElement.NUMBER singularPlural) {
if (polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
return "";
}
// Singular negative.
if (singularPlural.equals(SVOElement.NUMBER.SINGULAR)) {
return "doesn't ";
}
// Plural negative
return "don't ";
}
/**************************************************************************************************************
* For a process which does not have a language representation, get a reasonable way of paraphrasing it.
* Sets both verb and direct object of the sentence.
*/
void setVerbAndDirectObject(Sentence sentence) {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
// Set the verb, depending on the subject's case role and number.
String surfaceForm = "experience";
Multiset<CaseRole> experienceSubjectCaseRoles = HashMultiset.create(Sets.newHashSet(CaseRole.AGENT));
if(! Multisets.intersection(sentence.getSubject().getConsumedCaseRoles(), experienceSubjectCaseRoles).isEmpty()) {
surfaceForm = "perform";
}
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.getPolarity().equals(VerbProperties.Polarity.AFFIRMATIVE)) {
surfaceForm = surfaceForm + "s";
}
setSurfaceForm(polarityPrefix + surfaceForm);
// Now determine and set the direct object (which may end up displacing what would otherwise have been a
// direct object for this sentence).
// Turn, e.g. "IntentionalProcess" into "intentional process".
String formattedTerm = this.kb.getTermFormatMap("EnglishLanguage").get(this.verb);
String phrase = "";
if (formattedTerm != null && ! formattedTerm.isEmpty()) {
if (!kb.isSubclass(this.verb, "Substance")) {
String article = Noun.aOrAn(formattedTerm);
phrase = phrase + article + " ";
}
phrase = phrase + formattedTerm;
}
else {
phrase = phrase + "a " + this.verb.toLowerCase();
}
sentence.getDirectObject().setSurfaceForm(phrase);
sentence.getDirectObject().addConsumedCaseRole(CaseRole.PATIENT);
}
/**************************************************************************************************************
*
* @return
*/
public String getVerb() {
return verb;
}
/**************************************************************************************
* Getter and setter for polarity field.
*
*/
VerbProperties.Polarity getPolarity() {
return polarity;
}
public void setPolarity(VerbProperties.Polarity polarity) {
this.polarity = polarity;
}
/**************************************************************************************************************
*
* @param verbRoot
* @return
*/
public static String verbRootToThirdPersonSingular(String verbRoot) {
// FIXME: verbPlural is a misnomer; it finds the simple present singular form
return WordNetUtilities.verbPlural(verbRoot);
}
/**************************************************************************************************************
* Get the root of the given verb.
* @param gerund
* the verb in gerund (-ing) form.
* @return
* the root of the given verb, or null if not found
*/
public static String getVerbRootForm(String gerund) {
return WordNet.wn.verbRootForm(gerund, gerund.toLowerCase());
}
}
| ontologyportal/sigmakee | src/java/com/articulate/sigma/nlg/SumoProcess.java | 1,735 | /**************************************************************************************************************
*
* @param verbRoot
* @return
*/ | block_comment | nl | package com.articulate.sigma.nlg;
import com.articulate.sigma.KB;
import com.articulate.sigma.wordNet.WordNet;
import com.articulate.sigma.wordNet.WordNetUtilities;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Sets;
/**
* Handles verb functionality for a SUMO process.
*/
public class SumoProcess {
private final String verb;
private VerbProperties.Polarity polarity = VerbProperties.Polarity.AFFIRMATIVE;
private final KB kb;
public SumoProcess(SumoProcess process, KB kb) {
this.verb = process.getVerb();
this.polarity = process.getPolarity();
this.kb = kb;
}
private String surfaceForm;
public SumoProcess(String verb, KB kb) {
this.verb = verb;
this.kb = kb;
}
/**************************************************************************************************************
* Indirectly invoked by SumoProcessCollector.toString( ).
* @return
*/
@Override
public String toString() {
return verb;
}
/**************************************************************************************************************
*
* @return
*/
public String getSurfaceForm() {
return surfaceForm;
}
/**************************************************************************************************************
*
* @param surfaceForm
*/
void setSurfaceForm(String surfaceForm) {
this.surfaceForm = surfaceForm;
}
/**************************************************************************************************************
* Try to phrase the verb into natural language, setting this object's internal state appropriately.
* @param sentence
*/
public void formulateNaturalVerb(Sentence sentence) {
String verbSurfaceForm = SumoProcess.getVerbRootForm(this.verb);
if (verbSurfaceForm == null || verbSurfaceForm.isEmpty()) {
setVerbAndDirectObject(sentence);
}
else {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
verbSurfaceForm = SumoProcess.verbRootToThirdPersonSingular(verbSurfaceForm);
}
setSurfaceForm(polarityPrefix + verbSurfaceForm);
}
}
/**************************************************************************************************************
* Return the correct prefix for negative sentences--"don't" or "doesn't". For affirmatives return empty string.
* @param polarity
* @param singularPlural
* @return
*/
private static String getPolarityPrefix(VerbProperties.Polarity polarity, SVOElement.NUMBER singularPlural) {
if (polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
return "";
}
// Singular negative.
if (singularPlural.equals(SVOElement.NUMBER.SINGULAR)) {
return "doesn't ";
}
// Plural negative
return "don't ";
}
/**************************************************************************************************************
* For a process which does not have a language representation, get a reasonable way of paraphrasing it.
* Sets both verb and direct object of the sentence.
*/
void setVerbAndDirectObject(Sentence sentence) {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
// Set the verb, depending on the subject's case role and number.
String surfaceForm = "experience";
Multiset<CaseRole> experienceSubjectCaseRoles = HashMultiset.create(Sets.newHashSet(CaseRole.AGENT));
if(! Multisets.intersection(sentence.getSubject().getConsumedCaseRoles(), experienceSubjectCaseRoles).isEmpty()) {
surfaceForm = "perform";
}
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.getPolarity().equals(VerbProperties.Polarity.AFFIRMATIVE)) {
surfaceForm = surfaceForm + "s";
}
setSurfaceForm(polarityPrefix + surfaceForm);
// Now determine and set the direct object (which may end up displacing what would otherwise have been a
// direct object for this sentence).
// Turn, e.g. "IntentionalProcess" into "intentional process".
String formattedTerm = this.kb.getTermFormatMap("EnglishLanguage").get(this.verb);
String phrase = "";
if (formattedTerm != null && ! formattedTerm.isEmpty()) {
if (!kb.isSubclass(this.verb, "Substance")) {
String article = Noun.aOrAn(formattedTerm);
phrase = phrase + article + " ";
}
phrase = phrase + formattedTerm;
}
else {
phrase = phrase + "a " + this.verb.toLowerCase();
}
sentence.getDirectObject().setSurfaceForm(phrase);
sentence.getDirectObject().addConsumedCaseRole(CaseRole.PATIENT);
}
/**************************************************************************************************************
*
* @return
*/
public String getVerb() {
return verb;
}
/**************************************************************************************
* Getter and setter for polarity field.
*
*/
VerbProperties.Polarity getPolarity() {
return polarity;
}
public void setPolarity(VerbProperties.Polarity polarity) {
this.polarity = polarity;
}
/**************************************************************************************************************
*
* @param verbRoot
<SUF>*/
public static String verbRootToThirdPersonSingular(String verbRoot) {
// FIXME: verbPlural is a misnomer; it finds the simple present singular form
return WordNetUtilities.verbPlural(verbRoot);
}
/**************************************************************************************************************
* Get the root of the given verb.
* @param gerund
* the verb in gerund (-ing) form.
* @return
* the root of the given verb, or null if not found
*/
public static String getVerbRootForm(String gerund) {
return WordNet.wn.verbRootForm(gerund, gerund.toLowerCase());
}
}
|
135454_4 | package de.geeksfactory.opacclient.apis;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpClientFactory;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.LentItem;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.ReservedItem;
import okhttp3.FormBody;
/**
* API for the PICA OPAC by OCLC combined with LBS account functions Tested with LBS 4 in TU
* Hamburg-Harburg
*
* @author Johan von Forstner, 30.08.2015
*/
public class PicaLBS extends Pica {
private String lbsUrl;
@Override
public void init(Library lib, HttpClientFactory httpClientFactory, boolean debug) {
super.init(lib, httpClientFactory, debug);
this.lbsUrl = data.optString("lbs_url", this.opac_url);
}
@Override
public ReservationResult reservation(DetailedItem item, Account account,
int useraction, String selection) throws IOException {
try {
JSONArray json = new JSONArray(item.getReservation_info());
if (json.length() != 1 && selection == null) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.SELECTION_NEEDED);
res.setActionIdentifier(ReservationResult.ACTION_BRANCH);
List<Map<String, String>> selections = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
Map<String, String> selopt = new HashMap<>();
selopt.put("key", String.valueOf(i));
selopt.put("value", json.getJSONObject(i).getString("desc") + " (" + json.getJSONObject(i).getString("status") + ")");
selections.add(selopt);
}
res.setSelection(selections);
return res;
} else {
String url = json.getJSONObject(selection == null ? 0 : Integer.parseInt(selection)).getString("link");
Document doc = Jsoup.parse(httpGet(url, getDefaultLBSEncoding()));
if (doc.select("#opacVolumesForm").size() == 0) {
FormBody body = new FormBody.Builder()
.add("j_username", account.getName())
.add("j_password", account.getPassword())
.add("login", "Login").build();
doc = Jsoup.parse(httpPost(url, body, getDefaultLBSEncoding()));
}
if (doc.select(".error, font[color=red]").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".error, font[color=red]").text());
return res;
}
List<Connection.KeyVal> keyVals =
((FormElement) doc.select("#opacVolumesForm").first()).formData();
FormBody.Builder params = new FormBody.Builder();
for (Connection.KeyVal kv : keyVals) {
params.add(kv.key(), kv.value());
}
doc = Jsoup.parse(httpPost(url, params.build(), getDefaultEncoding()));
if (doc.select(".error").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".error").text());
return res;
} else if (doc.select(".info, .alertmessage").text().contains("Reservation saved")
|| doc.select(".info, .alertmessage").text().contains("vorgemerkt")
|| doc.select(".info, .alertmessage").text().contains("erfolgt")) {
return new ReservationResult(MultiStepResult.Status.OK);
} else if (doc.select(".alertmessage").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".alertmessage").text());
return res;
} else {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
return res;
}
}
} catch (JSONException e) {
e.printStackTrace();
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(stringProvider.getString(StringProvider.INTERNAL_ERROR));
return res;
}
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String selection) throws IOException {
FormBody body = new FormBody.Builder()
.add("renew", "Renew")
.add("_volumeNumbersToRenew", "")
.add("volumeNumbersToRenew", media).build();
String html = httpPost(lbsUrl + "/LBS_WEB/borrower/loans.htm", body,
getDefaultLBSEncoding());
Document doc = Jsoup.parse(html);
String message = doc.select(".alertmessage").text();
if (message.contains("wurde verlängert") || message.contains("has been renewed")) {
return new ProlongResult(MultiStepResult.Status.OK);
} else {
return new ProlongResult(MultiStepResult.Status.ERROR, message);
}
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction, String selection)
throws IOException {
return null;
}
@Override
public ProlongAllResult prolongMultiple(List<String> media,
Account account, int useraction, String selection) throws IOException {
return null;
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
FormBody body = new FormBody.Builder()
.add("cancel", "Cancel reservation")
.add("_volumeReservationsToCancel", "")
.add("volumeReservationsToCancel", media).build();
String html = httpPost(lbsUrl + "/LBS_WEB/borrower/reservations.htm", body,
getDefaultLBSEncoding());
Document doc = Jsoup.parse(html);
String message = doc.select(".alertmessage").text();
if (message.contains("ist storniert") || message.contains("has been cancelled")) {
return new CancelResult(MultiStepResult.Status.OK);
} else {
return new CancelResult(MultiStepResult.Status.ERROR, message);
}
}
@Override
public AccountData account(Account account)
throws IOException, JSONException, OpacErrorException {
if (!initialised) {
start();
}
login(account);
AccountData adata = new AccountData(account.getId());
Document dataDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm", getDefaultLBSEncoding()));
adata.setPendingFees(extractAccountInfo(dataDoc, "Total Costs", "Gesamtbetrag Kosten"));
adata.setValidUntil(extractAccountInfo(dataDoc, "Expires at", "endet am"));
Document lentDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/loans.htm", getDefaultLBSEncoding()));
adata.setLent(parseMediaList(lentDoc, stringProvider));
Document reservationsDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/reservations.htm", getDefaultLBSEncoding()));
adata.setReservations(parseResList(reservationsDoc, stringProvider));
return adata;
}
static List<LentItem> parseMediaList(Document doc, StringProvider stringProvider) {
List<LentItem> lent = new ArrayList<>();
for (Element tr : doc.select(".resultset > tbody > tr:has(.rec_title)")) {
LentItem item = new LentItem();
if (tr.select("input[name=volumeNumbersToRenew]").size() > 0) {
item.setProlongData(tr.select("input[name=volumeNumbersToRenew]").val());
} else {
item.setRenewable(false);
}
String[] titleAndAuthor = extractTitleAndAuthor(tr);
item.setTitle(titleAndAuthor[0]);
if (titleAndAuthor[1] != null) item.setAuthor(titleAndAuthor[1]);
String returndate =
extractAccountInfo(tr, "Returndate", "ausgeliehen bis",
"Ausleihfrist", "Leihfristende");
if (returndate != null) {
item.setDeadline(parseDate(returndate));
}
StringBuilder status = new StringBuilder();
String statusData = extractAccountInfo(tr, "Status", "Derzeit");
if (statusData != null) status.append(statusData);
String prolong = extractAccountInfo(tr, "No of Renewals", "Anzahl Verlängerungen",
"Verlängerungen");
if (prolong != null && !prolong.equals("0")) {
if (status.length() > 0) status.append(", ");
status.append(prolong).append("x ").append(stringProvider
.getString(StringProvider.PROLONGED_ABBR));
}
String reminder = extractAccountInfo(tr, "Remind.", "Mahnungen");
if (reminder != null && !reminder.equals("0")) {
if (status.length() > 0) status.append(", ");
status.append(reminder).append(" ").append(stringProvider
.getString(StringProvider.REMINDERS));
}
String error = tr.select(".error").text();
if (!error.equals("")) {
if (status.length() > 0) status.append(", ");
status.append(error);
}
item.setStatus(status.toString());
item.setHomeBranch(extractAccountInfo(tr, "Counter", "Theke"));
item.setBarcode(extractAccountInfo(tr, "Shelf mark", "Signatur"));
lent.add(item);
}
return lent;
}
private static String[] extractTitleAndAuthor(Element tr) {
String[] titleAndAuthor = new String[2];
String titleAuthor;
if (tr.select(".titleLine").size() > 0) {
titleAuthor = tr.select(".titleLine").text();
} else {
titleAuthor = extractAccountInfo(tr, "Title / Author", "Titel");
}
if (titleAuthor != null) {
String[] parts = titleAuthor.split(" / ");
titleAndAuthor[0] = parts[0];
if (parts.length == 2) {
if (parts[1].endsWith(":")) {
parts[1] = parts[1].substring(0, parts[1].length() - 1).trim();
}
titleAndAuthor[1] = parts[1];
}
}
return titleAndAuthor;
}
private static LocalDate parseDate(String date) {
try {
if (date.matches("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d")) {
return DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN)
.parseLocalDate(date);
} else if (date.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
return DateTimeFormat.forPattern("dd/MM/yyyy").withLocale(Locale.ENGLISH)
.parseLocalDate(date);
} else {
return null;
}
} catch (IllegalArgumentException e) {
return null;
}
}
static List<ReservedItem> parseResList(Document doc, StringProvider stringProvider) {
List<ReservedItem> reservations = new ArrayList<>();
for (Element tr : doc.select(".resultset > tbody > tr:has(.rec_title)")) {
ReservedItem item = new ReservedItem();
if (tr.select("input[name=volumeReservationsToCancel]").size() > 0) {
item.setCancelData(tr.select("input[name=volumeReservationsToCancel]").val());
}
String[] titleAndAuthor = extractTitleAndAuthor(tr);
item.setTitle(titleAndAuthor[0]);
if (titleAndAuthor[1] != null) item.setAuthor(titleAndAuthor[1]);
item.setBranch(extractAccountInfo(tr, "Destination", "Theke"));
// not supported: extractAccountInfo(tr, "Shelf mark", "Signatur")
StringBuilder status = new StringBuilder();
String numberOfReservations =
extractAccountInfo(tr, "Vormerkung", "Number of reservations");
if (numberOfReservations != null) {
try {
status.append(stringProvider.getQuantityString(
StringProvider.RESERVATIONS_NUMBER,
Integer.parseInt(numberOfReservations.trim()),
Integer.parseInt(numberOfReservations.trim())));
} catch (NumberFormatException e) {
status.append(numberOfReservations);
}
}
String reservationDate = extractAccountInfo(tr, "Reservationdate", "Vormerkungsdatum");
if (reservationDate != null) {
if (status.length() > 0) {
status.append(", ");
}
status.append(stringProvider.getFormattedString(
StringProvider.RESERVED_AT_DATE, reservationDate));
}
if (status.length() > 0) item.setStatus(status.toString());
// TODO: I don't know how reservations are marked that are already available
reservations.add(item);
}
return reservations;
}
private static String extractAccountInfo(Element doc, String... dataNames) {
StringBuilder labelSelector = new StringBuilder();
boolean first = true;
for (String dataName : dataNames) {
if (first) {
first = false;
} else {
labelSelector.append(", ");
}
labelSelector.append(".rec_data > .label:contains(").append(dataName).append(")");
}
if (doc.select(labelSelector.toString()).size() > 0) {
String data = doc.select(labelSelector.toString()).first()
.parent() // td
.parent() // tr
.select("td").get(1) // second column
.text();
if (data.equals("")) return null; else return data;
} else {
return null;
}
}
@Override
public void checkAccountData(Account account)
throws IOException, JSONException, OpacErrorException {
login(account);
}
private void login(Account account) throws IOException, OpacErrorException {
// check if already logged in
String html = httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm",
getDefaultLBSEncoding(), true);
if (!html.contains("class=\"error\"") && !html.contains("Login") && !html.equals("") && !html.contains("Systemfehler") &&
!html.contains("nicht aktiv gewesen")) {
return;
}
// Get JSESSIONID cookie
httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm?USR=1000&BES=" + db + "&LAN=" + getLang(),
getDefaultLBSEncoding());
FormBody body = new FormBody.Builder()
.add("j_username", account.getName())
.add("j_password", account.getPassword()).build();
Document doc = Jsoup.parse(httpPost(lbsUrl + "/LBS_WEB/j_spring_security_check",
body, getDefaultLBSEncoding()));
if (doc.select("font[color=red]").size() > 0) {
throw new OpacErrorException(doc.select("font[color=red]").text());
}
}
private String getDefaultLBSEncoding() {
return "ISO-8859-1";
}
}
| opacapp/opacclient | opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/PicaLBS.java | 4,548 | // Get JSESSIONID cookie | line_comment | nl | package de.geeksfactory.opacclient.apis;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpClientFactory;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.LentItem;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.ReservedItem;
import okhttp3.FormBody;
/**
* API for the PICA OPAC by OCLC combined with LBS account functions Tested with LBS 4 in TU
* Hamburg-Harburg
*
* @author Johan von Forstner, 30.08.2015
*/
public class PicaLBS extends Pica {
private String lbsUrl;
@Override
public void init(Library lib, HttpClientFactory httpClientFactory, boolean debug) {
super.init(lib, httpClientFactory, debug);
this.lbsUrl = data.optString("lbs_url", this.opac_url);
}
@Override
public ReservationResult reservation(DetailedItem item, Account account,
int useraction, String selection) throws IOException {
try {
JSONArray json = new JSONArray(item.getReservation_info());
if (json.length() != 1 && selection == null) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.SELECTION_NEEDED);
res.setActionIdentifier(ReservationResult.ACTION_BRANCH);
List<Map<String, String>> selections = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
Map<String, String> selopt = new HashMap<>();
selopt.put("key", String.valueOf(i));
selopt.put("value", json.getJSONObject(i).getString("desc") + " (" + json.getJSONObject(i).getString("status") + ")");
selections.add(selopt);
}
res.setSelection(selections);
return res;
} else {
String url = json.getJSONObject(selection == null ? 0 : Integer.parseInt(selection)).getString("link");
Document doc = Jsoup.parse(httpGet(url, getDefaultLBSEncoding()));
if (doc.select("#opacVolumesForm").size() == 0) {
FormBody body = new FormBody.Builder()
.add("j_username", account.getName())
.add("j_password", account.getPassword())
.add("login", "Login").build();
doc = Jsoup.parse(httpPost(url, body, getDefaultLBSEncoding()));
}
if (doc.select(".error, font[color=red]").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".error, font[color=red]").text());
return res;
}
List<Connection.KeyVal> keyVals =
((FormElement) doc.select("#opacVolumesForm").first()).formData();
FormBody.Builder params = new FormBody.Builder();
for (Connection.KeyVal kv : keyVals) {
params.add(kv.key(), kv.value());
}
doc = Jsoup.parse(httpPost(url, params.build(), getDefaultEncoding()));
if (doc.select(".error").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".error").text());
return res;
} else if (doc.select(".info, .alertmessage").text().contains("Reservation saved")
|| doc.select(".info, .alertmessage").text().contains("vorgemerkt")
|| doc.select(".info, .alertmessage").text().contains("erfolgt")) {
return new ReservationResult(MultiStepResult.Status.OK);
} else if (doc.select(".alertmessage").size() > 0) {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(doc.select(".alertmessage").text());
return res;
} else {
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
return res;
}
}
} catch (JSONException e) {
e.printStackTrace();
ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
res.setMessage(stringProvider.getString(StringProvider.INTERNAL_ERROR));
return res;
}
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String selection) throws IOException {
FormBody body = new FormBody.Builder()
.add("renew", "Renew")
.add("_volumeNumbersToRenew", "")
.add("volumeNumbersToRenew", media).build();
String html = httpPost(lbsUrl + "/LBS_WEB/borrower/loans.htm", body,
getDefaultLBSEncoding());
Document doc = Jsoup.parse(html);
String message = doc.select(".alertmessage").text();
if (message.contains("wurde verlängert") || message.contains("has been renewed")) {
return new ProlongResult(MultiStepResult.Status.OK);
} else {
return new ProlongResult(MultiStepResult.Status.ERROR, message);
}
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction, String selection)
throws IOException {
return null;
}
@Override
public ProlongAllResult prolongMultiple(List<String> media,
Account account, int useraction, String selection) throws IOException {
return null;
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
FormBody body = new FormBody.Builder()
.add("cancel", "Cancel reservation")
.add("_volumeReservationsToCancel", "")
.add("volumeReservationsToCancel", media).build();
String html = httpPost(lbsUrl + "/LBS_WEB/borrower/reservations.htm", body,
getDefaultLBSEncoding());
Document doc = Jsoup.parse(html);
String message = doc.select(".alertmessage").text();
if (message.contains("ist storniert") || message.contains("has been cancelled")) {
return new CancelResult(MultiStepResult.Status.OK);
} else {
return new CancelResult(MultiStepResult.Status.ERROR, message);
}
}
@Override
public AccountData account(Account account)
throws IOException, JSONException, OpacErrorException {
if (!initialised) {
start();
}
login(account);
AccountData adata = new AccountData(account.getId());
Document dataDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm", getDefaultLBSEncoding()));
adata.setPendingFees(extractAccountInfo(dataDoc, "Total Costs", "Gesamtbetrag Kosten"));
adata.setValidUntil(extractAccountInfo(dataDoc, "Expires at", "endet am"));
Document lentDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/loans.htm", getDefaultLBSEncoding()));
adata.setLent(parseMediaList(lentDoc, stringProvider));
Document reservationsDoc = Jsoup.parse(
httpGet(lbsUrl + "/LBS_WEB/borrower/reservations.htm", getDefaultLBSEncoding()));
adata.setReservations(parseResList(reservationsDoc, stringProvider));
return adata;
}
static List<LentItem> parseMediaList(Document doc, StringProvider stringProvider) {
List<LentItem> lent = new ArrayList<>();
for (Element tr : doc.select(".resultset > tbody > tr:has(.rec_title)")) {
LentItem item = new LentItem();
if (tr.select("input[name=volumeNumbersToRenew]").size() > 0) {
item.setProlongData(tr.select("input[name=volumeNumbersToRenew]").val());
} else {
item.setRenewable(false);
}
String[] titleAndAuthor = extractTitleAndAuthor(tr);
item.setTitle(titleAndAuthor[0]);
if (titleAndAuthor[1] != null) item.setAuthor(titleAndAuthor[1]);
String returndate =
extractAccountInfo(tr, "Returndate", "ausgeliehen bis",
"Ausleihfrist", "Leihfristende");
if (returndate != null) {
item.setDeadline(parseDate(returndate));
}
StringBuilder status = new StringBuilder();
String statusData = extractAccountInfo(tr, "Status", "Derzeit");
if (statusData != null) status.append(statusData);
String prolong = extractAccountInfo(tr, "No of Renewals", "Anzahl Verlängerungen",
"Verlängerungen");
if (prolong != null && !prolong.equals("0")) {
if (status.length() > 0) status.append(", ");
status.append(prolong).append("x ").append(stringProvider
.getString(StringProvider.PROLONGED_ABBR));
}
String reminder = extractAccountInfo(tr, "Remind.", "Mahnungen");
if (reminder != null && !reminder.equals("0")) {
if (status.length() > 0) status.append(", ");
status.append(reminder).append(" ").append(stringProvider
.getString(StringProvider.REMINDERS));
}
String error = tr.select(".error").text();
if (!error.equals("")) {
if (status.length() > 0) status.append(", ");
status.append(error);
}
item.setStatus(status.toString());
item.setHomeBranch(extractAccountInfo(tr, "Counter", "Theke"));
item.setBarcode(extractAccountInfo(tr, "Shelf mark", "Signatur"));
lent.add(item);
}
return lent;
}
private static String[] extractTitleAndAuthor(Element tr) {
String[] titleAndAuthor = new String[2];
String titleAuthor;
if (tr.select(".titleLine").size() > 0) {
titleAuthor = tr.select(".titleLine").text();
} else {
titleAuthor = extractAccountInfo(tr, "Title / Author", "Titel");
}
if (titleAuthor != null) {
String[] parts = titleAuthor.split(" / ");
titleAndAuthor[0] = parts[0];
if (parts.length == 2) {
if (parts[1].endsWith(":")) {
parts[1] = parts[1].substring(0, parts[1].length() - 1).trim();
}
titleAndAuthor[1] = parts[1];
}
}
return titleAndAuthor;
}
private static LocalDate parseDate(String date) {
try {
if (date.matches("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d")) {
return DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN)
.parseLocalDate(date);
} else if (date.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
return DateTimeFormat.forPattern("dd/MM/yyyy").withLocale(Locale.ENGLISH)
.parseLocalDate(date);
} else {
return null;
}
} catch (IllegalArgumentException e) {
return null;
}
}
static List<ReservedItem> parseResList(Document doc, StringProvider stringProvider) {
List<ReservedItem> reservations = new ArrayList<>();
for (Element tr : doc.select(".resultset > tbody > tr:has(.rec_title)")) {
ReservedItem item = new ReservedItem();
if (tr.select("input[name=volumeReservationsToCancel]").size() > 0) {
item.setCancelData(tr.select("input[name=volumeReservationsToCancel]").val());
}
String[] titleAndAuthor = extractTitleAndAuthor(tr);
item.setTitle(titleAndAuthor[0]);
if (titleAndAuthor[1] != null) item.setAuthor(titleAndAuthor[1]);
item.setBranch(extractAccountInfo(tr, "Destination", "Theke"));
// not supported: extractAccountInfo(tr, "Shelf mark", "Signatur")
StringBuilder status = new StringBuilder();
String numberOfReservations =
extractAccountInfo(tr, "Vormerkung", "Number of reservations");
if (numberOfReservations != null) {
try {
status.append(stringProvider.getQuantityString(
StringProvider.RESERVATIONS_NUMBER,
Integer.parseInt(numberOfReservations.trim()),
Integer.parseInt(numberOfReservations.trim())));
} catch (NumberFormatException e) {
status.append(numberOfReservations);
}
}
String reservationDate = extractAccountInfo(tr, "Reservationdate", "Vormerkungsdatum");
if (reservationDate != null) {
if (status.length() > 0) {
status.append(", ");
}
status.append(stringProvider.getFormattedString(
StringProvider.RESERVED_AT_DATE, reservationDate));
}
if (status.length() > 0) item.setStatus(status.toString());
// TODO: I don't know how reservations are marked that are already available
reservations.add(item);
}
return reservations;
}
private static String extractAccountInfo(Element doc, String... dataNames) {
StringBuilder labelSelector = new StringBuilder();
boolean first = true;
for (String dataName : dataNames) {
if (first) {
first = false;
} else {
labelSelector.append(", ");
}
labelSelector.append(".rec_data > .label:contains(").append(dataName).append(")");
}
if (doc.select(labelSelector.toString()).size() > 0) {
String data = doc.select(labelSelector.toString()).first()
.parent() // td
.parent() // tr
.select("td").get(1) // second column
.text();
if (data.equals("")) return null; else return data;
} else {
return null;
}
}
@Override
public void checkAccountData(Account account)
throws IOException, JSONException, OpacErrorException {
login(account);
}
private void login(Account account) throws IOException, OpacErrorException {
// check if already logged in
String html = httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm",
getDefaultLBSEncoding(), true);
if (!html.contains("class=\"error\"") && !html.contains("Login") && !html.equals("") && !html.contains("Systemfehler") &&
!html.contains("nicht aktiv gewesen")) {
return;
}
// Get JSESSIONID<SUF>
httpGet(lbsUrl + "/LBS_WEB/borrower/borrower.htm?USR=1000&BES=" + db + "&LAN=" + getLang(),
getDefaultLBSEncoding());
FormBody body = new FormBody.Builder()
.add("j_username", account.getName())
.add("j_password", account.getPassword()).build();
Document doc = Jsoup.parse(httpPost(lbsUrl + "/LBS_WEB/j_spring_security_check",
body, getDefaultLBSEncoding()));
if (doc.select("font[color=red]").size() > 0) {
throw new OpacErrorException(doc.select("font[color=red]").text());
}
}
private String getDefaultLBSEncoding() {
return "ISO-8859-1";
}
}
|
68057_2 | package edu.nps.moves.dis7;
import java.io.*;
/**
* Not specified in the standard. This is used by the ESPDU
*
* Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All
* rights reserved. This work is licensed under the BSD open source license,
* available at https://www.movesinstitute.org/licenses/bsd.html
*
* @author DMcG
*/
public class DeadReckoningParameters extends Object implements Serializable {
/**
* Algorithm to use in computing dead reckoning. See EBV doc.
*/
protected short deadReckoningAlgorithm;
/**
* Dead reckoning parameters. Contents depends on algorithm.
*/
protected short[] parameters = new short[15];
/**
* Linear acceleration of the entity
*/
protected Vector3Float entityLinearAcceleration = new Vector3Float();
/**
* Angular velocity of the entity
*/
protected Vector3Float entityAngularVelocity = new Vector3Float();
/**
* Constructor
*/
public DeadReckoningParameters() {
}
public int getMarshalledSize() {
int marshalSize = 0;
marshalSize = marshalSize + 1; // deadReckoningAlgorithm
marshalSize = marshalSize + 15 * 1; // parameters
marshalSize = marshalSize + entityLinearAcceleration.getMarshalledSize(); // entityLinearAcceleration
marshalSize = marshalSize + entityAngularVelocity.getMarshalledSize(); // entityAngularVelocity
return marshalSize;
}
public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) {
deadReckoningAlgorithm = pDeadReckoningAlgorithm;
}
public short getDeadReckoningAlgorithm() {
return deadReckoningAlgorithm;
}
public void setParameters(short[] pParameters) {
parameters = pParameters;
}
public short[] getParameters() {
return parameters;
}
public void setEntityLinearAcceleration(Vector3Float pEntityLinearAcceleration) {
entityLinearAcceleration = pEntityLinearAcceleration;
}
public Vector3Float getEntityLinearAcceleration() {
return entityLinearAcceleration;
}
public void setEntityAngularVelocity(Vector3Float pEntityAngularVelocity) {
entityAngularVelocity = pEntityAngularVelocity;
}
public Vector3Float getEntityAngularVelocity() {
return entityAngularVelocity;
}
public void marshal(DataOutputStream dos) {
try {
dos.writeByte((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
dos.writeByte(parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(dos);
entityAngularVelocity.marshal(dos);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of marshal method
public void unmarshal(DataInputStream dis) {
try {
deadReckoningAlgorithm = (short) dis.readUnsignedByte();
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = dis.readByte();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(dis);
entityAngularVelocity.unmarshal(dis);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of unmarshal method
/**
* Packs a Pdu into the ByteBuffer.
*
* @throws java.nio.BufferOverflowException if buff is too small
* @throws java.nio.ReadOnlyBufferException if buff is read only
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin writing
* @since ??
*/
public void marshal(java.nio.ByteBuffer buff) {
buff.put((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
buff.put((byte) parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(buff);
entityAngularVelocity.marshal(buff);
} // end of marshal method
/**
* Unpacks a Pdu from the underlying data.
*
* @throws java.nio.BufferUnderflowException if buff is too small
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin reading
* @since ??
*/
public void unmarshal(java.nio.ByteBuffer buff) {
deadReckoningAlgorithm = (short) (buff.get() & 0xFF);
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = buff.get();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(buff);
entityAngularVelocity.unmarshal(buff);
} // end of unmarshal method
/*
* The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return equalsImpl(obj);
}
/**
* Compare all fields that contribute to the state, ignoring transient and
* static fields, for <code>this</code> and the supplied object
*
* @param obj the object to compare to
* @return true if the objects are equal, false otherwise.
*/
public boolean equalsImpl(Object obj) {
boolean ivarsEqual = true;
if (!(obj instanceof DeadReckoningParameters)) {
return false;
}
final DeadReckoningParameters rhs = (DeadReckoningParameters) obj;
if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) {
ivarsEqual = false;
}
for (int idx = 0; idx < 15; idx++) {
if (!(parameters[idx] == rhs.parameters[idx])) {
ivarsEqual = false;
}
}
if (!(entityLinearAcceleration.equals(rhs.entityLinearAcceleration))) {
ivarsEqual = false;
}
if (!(entityAngularVelocity.equals(rhs.entityAngularVelocity))) {
ivarsEqual = false;
}
return ivarsEqual;
}
} // end of class
| open-dis/open-dis-java | src/main/java/edu/nps/moves/dis7/DeadReckoningParameters.java | 1,775 | /**
* Dead reckoning parameters. Contents depends on algorithm.
*/ | block_comment | nl | package edu.nps.moves.dis7;
import java.io.*;
/**
* Not specified in the standard. This is used by the ESPDU
*
* Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All
* rights reserved. This work is licensed under the BSD open source license,
* available at https://www.movesinstitute.org/licenses/bsd.html
*
* @author DMcG
*/
public class DeadReckoningParameters extends Object implements Serializable {
/**
* Algorithm to use in computing dead reckoning. See EBV doc.
*/
protected short deadReckoningAlgorithm;
/**
* Dead reckoning parameters.<SUF>*/
protected short[] parameters = new short[15];
/**
* Linear acceleration of the entity
*/
protected Vector3Float entityLinearAcceleration = new Vector3Float();
/**
* Angular velocity of the entity
*/
protected Vector3Float entityAngularVelocity = new Vector3Float();
/**
* Constructor
*/
public DeadReckoningParameters() {
}
public int getMarshalledSize() {
int marshalSize = 0;
marshalSize = marshalSize + 1; // deadReckoningAlgorithm
marshalSize = marshalSize + 15 * 1; // parameters
marshalSize = marshalSize + entityLinearAcceleration.getMarshalledSize(); // entityLinearAcceleration
marshalSize = marshalSize + entityAngularVelocity.getMarshalledSize(); // entityAngularVelocity
return marshalSize;
}
public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) {
deadReckoningAlgorithm = pDeadReckoningAlgorithm;
}
public short getDeadReckoningAlgorithm() {
return deadReckoningAlgorithm;
}
public void setParameters(short[] pParameters) {
parameters = pParameters;
}
public short[] getParameters() {
return parameters;
}
public void setEntityLinearAcceleration(Vector3Float pEntityLinearAcceleration) {
entityLinearAcceleration = pEntityLinearAcceleration;
}
public Vector3Float getEntityLinearAcceleration() {
return entityLinearAcceleration;
}
public void setEntityAngularVelocity(Vector3Float pEntityAngularVelocity) {
entityAngularVelocity = pEntityAngularVelocity;
}
public Vector3Float getEntityAngularVelocity() {
return entityAngularVelocity;
}
public void marshal(DataOutputStream dos) {
try {
dos.writeByte((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
dos.writeByte(parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(dos);
entityAngularVelocity.marshal(dos);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of marshal method
public void unmarshal(DataInputStream dis) {
try {
deadReckoningAlgorithm = (short) dis.readUnsignedByte();
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = dis.readByte();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(dis);
entityAngularVelocity.unmarshal(dis);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of unmarshal method
/**
* Packs a Pdu into the ByteBuffer.
*
* @throws java.nio.BufferOverflowException if buff is too small
* @throws java.nio.ReadOnlyBufferException if buff is read only
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin writing
* @since ??
*/
public void marshal(java.nio.ByteBuffer buff) {
buff.put((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
buff.put((byte) parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(buff);
entityAngularVelocity.marshal(buff);
} // end of marshal method
/**
* Unpacks a Pdu from the underlying data.
*
* @throws java.nio.BufferUnderflowException if buff is too small
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin reading
* @since ??
*/
public void unmarshal(java.nio.ByteBuffer buff) {
deadReckoningAlgorithm = (short) (buff.get() & 0xFF);
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = buff.get();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(buff);
entityAngularVelocity.unmarshal(buff);
} // end of unmarshal method
/*
* The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return equalsImpl(obj);
}
/**
* Compare all fields that contribute to the state, ignoring transient and
* static fields, for <code>this</code> and the supplied object
*
* @param obj the object to compare to
* @return true if the objects are equal, false otherwise.
*/
public boolean equalsImpl(Object obj) {
boolean ivarsEqual = true;
if (!(obj instanceof DeadReckoningParameters)) {
return false;
}
final DeadReckoningParameters rhs = (DeadReckoningParameters) obj;
if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) {
ivarsEqual = false;
}
for (int idx = 0; idx < 15; idx++) {
if (!(parameters[idx] == rhs.parameters[idx])) {
ivarsEqual = false;
}
}
if (!(entityLinearAcceleration.equals(rhs.entityLinearAcceleration))) {
ivarsEqual = false;
}
if (!(entityAngularVelocity.equals(rhs.entityAngularVelocity))) {
ivarsEqual = false;
}
return ivarsEqual;
}
} // end of class
|
97454_1 | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated using string template dis7javalicense.txt
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.usa.platform.surface;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>DDG138JWilliamMiddendorf</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>DDG138JWilliamMiddendorf.createInstance()</code> or <code>new DDG138JWilliamMiddendorf()</code>. </p>
* <ul>
* <li> Country: United States of America (USA) = <code>225</code>; </li>
* <li> Entity kind: PlatformDomain = <code>SURFACE</code>; </li>
* <li> Domain: Platform = <code>1</code>; </li>
* <li> Category: Guided Missile Destroyer = <code>4</code>; </li>
* <li> SubCategory: ArleighBurkeClass = <code>1</code>; </li>
* <li> Specific: DDG138JWilliamMiddendorf = <code>88</code>; </li>
* <li> Entity type uid: 36141; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SpecificElem@eaf8427. </p>
* @see Country#UNITED_STATES_OF_AMERICA_USA
* @see EntityKind#PLATFORM
* @see Domain
* @see PlatformDomain
* @see Category
* @see GuidedMissileDestroyer
* @see SubCategory
*/
public final class DDG138JWilliamMiddendorf extends EntityType
{
/** Default constructor */
public DDG138JWilliamMiddendorf()
{
setCountry(Country.UNITED_STATES_OF_AMERICA_USA);
setEntityKind(EntityKind.PLATFORM);
setDomain(Domain.inst(PlatformDomain.SURFACE));
setCategory((byte)4); // uid 11372, Guided Missile Destroyer
setSubCategory((byte)1); // uid 11373, Arleigh Burke Class
setSpecific((byte)88); // uid 36141, DDG 138 J. William Middendorf
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static DDG138JWilliamMiddendorf createInstance()
{
return new DDG138JWilliamMiddendorf();
}
}
| open-dis/opendis7-java | src-generated/edu/nps/moves/dis7/entities/usa/platform/surface/DDG138JWilliamMiddendorf.java | 938 | // header autogenerated using string template dis7javalicense.txt | line_comment | nl | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated<SUF>
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.usa.platform.surface;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>DDG138JWilliamMiddendorf</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>DDG138JWilliamMiddendorf.createInstance()</code> or <code>new DDG138JWilliamMiddendorf()</code>. </p>
* <ul>
* <li> Country: United States of America (USA) = <code>225</code>; </li>
* <li> Entity kind: PlatformDomain = <code>SURFACE</code>; </li>
* <li> Domain: Platform = <code>1</code>; </li>
* <li> Category: Guided Missile Destroyer = <code>4</code>; </li>
* <li> SubCategory: ArleighBurkeClass = <code>1</code>; </li>
* <li> Specific: DDG138JWilliamMiddendorf = <code>88</code>; </li>
* <li> Entity type uid: 36141; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SpecificElem@eaf8427. </p>
* @see Country#UNITED_STATES_OF_AMERICA_USA
* @see EntityKind#PLATFORM
* @see Domain
* @see PlatformDomain
* @see Category
* @see GuidedMissileDestroyer
* @see SubCategory
*/
public final class DDG138JWilliamMiddendorf extends EntityType
{
/** Default constructor */
public DDG138JWilliamMiddendorf()
{
setCountry(Country.UNITED_STATES_OF_AMERICA_USA);
setEntityKind(EntityKind.PLATFORM);
setDomain(Domain.inst(PlatformDomain.SURFACE));
setCategory((byte)4); // uid 11372, Guided Missile Destroyer
setSubCategory((byte)1); // uid 11373, Arleigh Burke Class
setSpecific((byte)88); // uid 36141, DDG 138 J. William Middendorf
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static DDG138JWilliamMiddendorf createInstance()
{
return new DDG138JWilliamMiddendorf();
}
}
|
31688_4 | package org.open4goods.crawler.extractors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.open4goods.config.yml.datasource.DataSourceProperties;
import org.open4goods.config.yml.datasource.ExtractorConfig;
import org.open4goods.config.yml.datasource.HtmlDataSourceProperties;
import org.open4goods.crawler.services.fetching.DataFragmentWebCrawler;
import org.open4goods.model.data.DataFragment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.w3c.dom.Document;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
/**
*
* @author goulven
*
*/
public class DeepExtractor extends Extractor {
@Autowired
private ApplicationContext applicationContext;
List<Extractor> extractors = null;
@Override
public void parse(final String url, final Page page, final HtmlParseData parseData, final Document document,
final DataSourceProperties providerConfig, final Locale locale,
final DataFragment p, final DataFragmentWebCrawler offerWebCrawler, final CrawlController controller) {
final ExtractorConfig ec = getExtractorConfig();
final HtmlDataSourceProperties webdatasource = providerConfig.webDataSource();
////////////////////////
// Instanciating extractors if first time
// TODO(gof) : should outside in another common classe. But could be more globally refactored into a non introspected manier. @see WebDatasourceFetchingService
////////////////////////
if (null == extractors) {
extractors = new ArrayList<>();
for (final ExtractorConfig conf : ec.getExtractors()) {
try {
final Extractor extractor = getInstance(conf, getDedicatedLogger());
applicationContext.getAutowireCapableBeanFactory().autowireBean(extractor);
extractors.add(extractor);
} catch (final Exception e) {
getDedicatedLogger().error("Cannot instanciate extractor {}", conf.getClass(), e);
}
}
}
///////////////////////////////
// Computing url base
//////////////////////////////
if (null == ec.getUrl()) {
getDedicatedLogger().warn("No url defined for DeepExtraction : {}",url);
return;
}
String targetUrl = evalAndLogs(document, ec.getUrl(), url);
if (null == targetUrl) {
getDedicatedLogger().warn("Cannot evalute targetUrl to DeepExtract : {} at {}",ec.getUrl(),url);
return;
}
// handling url replacement
if (null != ec.getUrlReplacement()) {
for (final Entry<String,String> repl : ec.getUrlReplacement().entrySet()) {
targetUrl = targetUrl.replace(repl.getKey(), repl.getValue());
}
}
if (!targetUrl.startsWith("http")) {
targetUrl = webdatasource.getBaseUrl() + (targetUrl.startsWith("/") ? targetUrl : "/"+targetUrl);
}
Integer current = ec.getStartPage();
boolean more = true;
while (more) {
if (StringUtils.hasLength(ec.getParameterPage())) {
targetUrl = getPaginatedUrl(targetUrl,ec.getParameterPage(),current);
}
if (StringUtils.hasLength(ec.getPathIncrementVariablePrefix())) {
targetUrl = getPathIncrementVariable(targetUrl,ec.getPathIncrementVariablePrefix(),ec.getPathIncrementVariableSuffix(), current);
}
current++;
if (current > ec.getPageLimit()) {
getDedicatedLogger().error("Stop deep visiting because it exceeds the page limt {} : {}",ec.getPageLimit(), targetUrl);
break;
}
getDedicatedLogger().info("Deep visiting {}",targetUrl);
final DataFragment deepData = offerWebCrawler.visitNow(controller, targetUrl, extractors);
more = false;
if (null == deepData) {
getDedicatedLogger().error("Stop deep visiting because no datafragment retrieved : {}",targetUrl);
break;
}
//TODO(gof) : complete with other extractors
for (final Extractor e : extractors) {
if (e instanceof CommentsExtractor) {
if (deepData.getComments().size() >0) {
p.getComments().addAll(deepData.getComments());
more = true;
}
} else if (e instanceof QuestionsExtractor) {
if (deepData.getQuestions().size() >0) {
p.getQuestions().addAll(deepData.getQuestions());
more = true;
}
} else if (e instanceof TableAttributeExtractor) {
if (deepData.getAttributes().size() >0) {
p.getAttributes().addAll(deepData.getAttributes());
more = true;
}
}
else {
getDedicatedLogger().error("The extractor {} has not been coded in DeepExtractors : {}",e.getClass().getSimpleName(),url);
}
}
if (!StringUtils.hasLength(ec.getPathIncrementVariablePrefix()) && !StringUtils.hasLength(ec.getParameterPage())) {
// If no parameter page url, this is a one shot deep crawling
more = false;
}
}
}
/**
* *
* @param targetUrl
* @param pathIncrementVariablePrefix
* @param current
* @return
*/
private String getPathIncrementVariable(final String targetUrl, final String pathIncrementVariablePrefix, final String pathIncrementVariableSuffix, final Integer current) {
final String prefix = targetUrl.substring(0,targetUrl.indexOf(pathIncrementVariablePrefix) + pathIncrementVariablePrefix.length());
final String suffix = targetUrl.substring(targetUrl.indexOf(pathIncrementVariableSuffix, prefix.length()));
return prefix+current+suffix;
}
private String getPaginatedUrl(final String baseUrl, final String parameterName, final Integer parameterValue) {
final StringBuilder b = new StringBuilder();
final UriComponents parsedUrl = UriComponentsBuilder.fromUriString(baseUrl).build();
b.append(parsedUrl.getScheme());
b.append("://");
b.append(parsedUrl.getHost());
if (!StringUtils.hasLength(parsedUrl.getPath())) {
b.append("/");
} else {
b.append(parsedUrl.getPath());
}
final MultiValueMap<String, String> params = parsedUrl.getQueryParams();
final Map<String, String> allParams = new HashMap<>();
for (final Entry<String, List<String>> str : params.entrySet()) {
if (str.getValue().size() != 1) {
getDedicatedLogger().warn("A multi valued param : {} has {} values in {}", str.getKey(), str.getValue().size(), baseUrl);
} else {
allParams.put(str.getKey(), str.getValue().get(0));
}
}
// Adding our param
allParams.put(parameterName, parameterValue.toString());
int counter = 0;
for (final Entry<String, String> str : allParams.entrySet()) {
b.append(counter == 0 ? "?" : "&");
b.append(str.getKey()).append("=").append(str.getValue());
counter++;
}
return b.toString();
}
}
| open4good/open4goods | crawler/src/main/java/org/open4goods/crawler/extractors/DeepExtractor.java | 2,132 | // handling url replacement | line_comment | nl | package org.open4goods.crawler.extractors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.open4goods.config.yml.datasource.DataSourceProperties;
import org.open4goods.config.yml.datasource.ExtractorConfig;
import org.open4goods.config.yml.datasource.HtmlDataSourceProperties;
import org.open4goods.crawler.services.fetching.DataFragmentWebCrawler;
import org.open4goods.model.data.DataFragment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.w3c.dom.Document;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
/**
*
* @author goulven
*
*/
public class DeepExtractor extends Extractor {
@Autowired
private ApplicationContext applicationContext;
List<Extractor> extractors = null;
@Override
public void parse(final String url, final Page page, final HtmlParseData parseData, final Document document,
final DataSourceProperties providerConfig, final Locale locale,
final DataFragment p, final DataFragmentWebCrawler offerWebCrawler, final CrawlController controller) {
final ExtractorConfig ec = getExtractorConfig();
final HtmlDataSourceProperties webdatasource = providerConfig.webDataSource();
////////////////////////
// Instanciating extractors if first time
// TODO(gof) : should outside in another common classe. But could be more globally refactored into a non introspected manier. @see WebDatasourceFetchingService
////////////////////////
if (null == extractors) {
extractors = new ArrayList<>();
for (final ExtractorConfig conf : ec.getExtractors()) {
try {
final Extractor extractor = getInstance(conf, getDedicatedLogger());
applicationContext.getAutowireCapableBeanFactory().autowireBean(extractor);
extractors.add(extractor);
} catch (final Exception e) {
getDedicatedLogger().error("Cannot instanciate extractor {}", conf.getClass(), e);
}
}
}
///////////////////////////////
// Computing url base
//////////////////////////////
if (null == ec.getUrl()) {
getDedicatedLogger().warn("No url defined for DeepExtraction : {}",url);
return;
}
String targetUrl = evalAndLogs(document, ec.getUrl(), url);
if (null == targetUrl) {
getDedicatedLogger().warn("Cannot evalute targetUrl to DeepExtract : {} at {}",ec.getUrl(),url);
return;
}
// handling url<SUF>
if (null != ec.getUrlReplacement()) {
for (final Entry<String,String> repl : ec.getUrlReplacement().entrySet()) {
targetUrl = targetUrl.replace(repl.getKey(), repl.getValue());
}
}
if (!targetUrl.startsWith("http")) {
targetUrl = webdatasource.getBaseUrl() + (targetUrl.startsWith("/") ? targetUrl : "/"+targetUrl);
}
Integer current = ec.getStartPage();
boolean more = true;
while (more) {
if (StringUtils.hasLength(ec.getParameterPage())) {
targetUrl = getPaginatedUrl(targetUrl,ec.getParameterPage(),current);
}
if (StringUtils.hasLength(ec.getPathIncrementVariablePrefix())) {
targetUrl = getPathIncrementVariable(targetUrl,ec.getPathIncrementVariablePrefix(),ec.getPathIncrementVariableSuffix(), current);
}
current++;
if (current > ec.getPageLimit()) {
getDedicatedLogger().error("Stop deep visiting because it exceeds the page limt {} : {}",ec.getPageLimit(), targetUrl);
break;
}
getDedicatedLogger().info("Deep visiting {}",targetUrl);
final DataFragment deepData = offerWebCrawler.visitNow(controller, targetUrl, extractors);
more = false;
if (null == deepData) {
getDedicatedLogger().error("Stop deep visiting because no datafragment retrieved : {}",targetUrl);
break;
}
//TODO(gof) : complete with other extractors
for (final Extractor e : extractors) {
if (e instanceof CommentsExtractor) {
if (deepData.getComments().size() >0) {
p.getComments().addAll(deepData.getComments());
more = true;
}
} else if (e instanceof QuestionsExtractor) {
if (deepData.getQuestions().size() >0) {
p.getQuestions().addAll(deepData.getQuestions());
more = true;
}
} else if (e instanceof TableAttributeExtractor) {
if (deepData.getAttributes().size() >0) {
p.getAttributes().addAll(deepData.getAttributes());
more = true;
}
}
else {
getDedicatedLogger().error("The extractor {} has not been coded in DeepExtractors : {}",e.getClass().getSimpleName(),url);
}
}
if (!StringUtils.hasLength(ec.getPathIncrementVariablePrefix()) && !StringUtils.hasLength(ec.getParameterPage())) {
// If no parameter page url, this is a one shot deep crawling
more = false;
}
}
}
/**
* *
* @param targetUrl
* @param pathIncrementVariablePrefix
* @param current
* @return
*/
private String getPathIncrementVariable(final String targetUrl, final String pathIncrementVariablePrefix, final String pathIncrementVariableSuffix, final Integer current) {
final String prefix = targetUrl.substring(0,targetUrl.indexOf(pathIncrementVariablePrefix) + pathIncrementVariablePrefix.length());
final String suffix = targetUrl.substring(targetUrl.indexOf(pathIncrementVariableSuffix, prefix.length()));
return prefix+current+suffix;
}
private String getPaginatedUrl(final String baseUrl, final String parameterName, final Integer parameterValue) {
final StringBuilder b = new StringBuilder();
final UriComponents parsedUrl = UriComponentsBuilder.fromUriString(baseUrl).build();
b.append(parsedUrl.getScheme());
b.append("://");
b.append(parsedUrl.getHost());
if (!StringUtils.hasLength(parsedUrl.getPath())) {
b.append("/");
} else {
b.append(parsedUrl.getPath());
}
final MultiValueMap<String, String> params = parsedUrl.getQueryParams();
final Map<String, String> allParams = new HashMap<>();
for (final Entry<String, List<String>> str : params.entrySet()) {
if (str.getValue().size() != 1) {
getDedicatedLogger().warn("A multi valued param : {} has {} values in {}", str.getKey(), str.getValue().size(), baseUrl);
} else {
allParams.put(str.getKey(), str.getValue().get(0));
}
}
// Adding our param
allParams.put(parameterName, parameterValue.toString());
int counter = 0;
for (final Entry<String, String> str : allParams.entrySet()) {
b.append(counter == 0 ? "?" : "&");
b.append(str.getKey()).append("=").append(str.getValue());
counter++;
}
return b.toString();
}
}
|
104134_7 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dslul.openboard.inputmethod.keyboard;
import android.util.SparseArray;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyVisualAttributes;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyboardIconsSet;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyboardParams;
import org.dslul.openboard.inputmethod.latin.common.Constants;
import org.dslul.openboard.inputmethod.latin.common.CoordinateUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard
* consists of rows of keys.
* <p>The layout file for a keyboard contains XML that looks like the following snippet:</p>
* <pre>
* <Keyboard
* latin:keyWidth="10%p"
* latin:rowHeight="50px"
* latin:horizontalGap="2%p"
* latin:verticalGap="2%p" >
* <Row latin:keyWidth="10%p" >
* <Key latin:keyLabel="A" />
* ...
* </Row>
* ...
* </Keyboard>
* </pre>
*/
public class Keyboard {
@Nonnull
public final KeyboardId mId;
public final int mThemeId;
/** Total height of the keyboard, including the padding and keys */
public final int mOccupiedHeight;
/** Total width of the keyboard, including the padding and keys */
public final int mOccupiedWidth;
/** Base height of the keyboard, used to calculate rows' height */
public final int mBaseHeight;
/** Base width of the keyboard, used to calculate keys' width */
public final int mBaseWidth;
/** The padding above the keyboard */
public final int mTopPadding;
/** Default gap between rows */
public final int mVerticalGap;
/** Per keyboard key visual parameters */
public final KeyVisualAttributes mKeyVisualAttributes;
public final int mMostCommonKeyHeight;
public final int mMostCommonKeyWidth;
/** More keys keyboard template */
public final int mMoreKeysTemplate;
/** Maximum column for more keys keyboard */
public final int mMaxMoreKeysKeyboardColumn;
/** List of keys in this keyboard */
@Nonnull
private final List<Key> mSortedKeys;
@Nonnull
public final List<Key> mShiftKeys;
@Nonnull
public final List<Key> mAltCodeKeysWhileTyping;
@Nonnull
public final KeyboardIconsSet mIconsSet;
private final SparseArray<Key> mKeyCache = new SparseArray<>();
@Nonnull
private final ProximityInfo mProximityInfo;
@Nonnull
private final KeyboardLayout mKeyboardLayout;
private final boolean mProximityCharsCorrectionEnabled;
public Keyboard(@Nonnull final KeyboardParams params) {
mId = params.mId;
mThemeId = params.mThemeId;
mOccupiedHeight = params.mOccupiedHeight;
mOccupiedWidth = params.mOccupiedWidth;
mBaseHeight = params.mBaseHeight;
mBaseWidth = params.mBaseWidth;
mMostCommonKeyHeight = params.mMostCommonKeyHeight;
mMostCommonKeyWidth = params.mMostCommonKeyWidth;
mMoreKeysTemplate = params.mMoreKeysTemplate;
mMaxMoreKeysKeyboardColumn = params.mMaxMoreKeysKeyboardColumn;
mKeyVisualAttributes = params.mKeyVisualAttributes;
mTopPadding = params.mTopPadding;
mVerticalGap = params.mVerticalGap;
mSortedKeys = Collections.unmodifiableList(new ArrayList<>(params.mSortedKeys));
mShiftKeys = Collections.unmodifiableList(params.mShiftKeys);
mAltCodeKeysWhileTyping = Collections.unmodifiableList(params.mAltCodeKeysWhileTyping);
mIconsSet = params.mIconsSet;
mProximityInfo = new ProximityInfo(params.GRID_WIDTH, params.GRID_HEIGHT,
mOccupiedWidth, mOccupiedHeight, mMostCommonKeyWidth, mMostCommonKeyHeight,
mSortedKeys, params.mTouchPositionCorrection);
mProximityCharsCorrectionEnabled = params.mProximityCharsCorrectionEnabled;
mKeyboardLayout = KeyboardLayout.newKeyboardLayout(mSortedKeys, mMostCommonKeyWidth,
mMostCommonKeyHeight, mOccupiedWidth, mOccupiedHeight);
}
protected Keyboard(@Nonnull final Keyboard keyboard) {
mId = keyboard.mId;
mThemeId = keyboard.mThemeId;
mOccupiedHeight = keyboard.mOccupiedHeight;
mOccupiedWidth = keyboard.mOccupiedWidth;
mBaseHeight = keyboard.mBaseHeight;
mBaseWidth = keyboard.mBaseWidth;
mMostCommonKeyHeight = keyboard.mMostCommonKeyHeight;
mMostCommonKeyWidth = keyboard.mMostCommonKeyWidth;
mMoreKeysTemplate = keyboard.mMoreKeysTemplate;
mMaxMoreKeysKeyboardColumn = keyboard.mMaxMoreKeysKeyboardColumn;
mKeyVisualAttributes = keyboard.mKeyVisualAttributes;
mTopPadding = keyboard.mTopPadding;
mVerticalGap = keyboard.mVerticalGap;
mSortedKeys = keyboard.mSortedKeys;
mShiftKeys = keyboard.mShiftKeys;
mAltCodeKeysWhileTyping = keyboard.mAltCodeKeysWhileTyping;
mIconsSet = keyboard.mIconsSet;
mProximityInfo = keyboard.mProximityInfo;
mProximityCharsCorrectionEnabled = keyboard.mProximityCharsCorrectionEnabled;
mKeyboardLayout = keyboard.mKeyboardLayout;
}
public boolean hasProximityCharsCorrection(final int code) {
if (!mProximityCharsCorrectionEnabled) {
return false;
}
// Note: The native code has the main keyboard layout only at this moment.
// TODO: Figure out how to handle proximity characters information of all layouts.
final boolean canAssumeNativeHasProximityCharsInfoOfAllKeys = (
mId.mElementId == KeyboardId.ELEMENT_ALPHABET
|| mId.mElementId == KeyboardId.ELEMENT_ALPHABET_AUTOMATIC_SHIFTED);
return canAssumeNativeHasProximityCharsInfoOfAllKeys || Character.isLetter(code);
}
@Nonnull
public ProximityInfo getProximityInfo() {
return mProximityInfo;
}
@Nonnull
public KeyboardLayout getKeyboardLayout() {
return mKeyboardLayout;
}
/**
* Return the sorted list of keys of this keyboard.
* The keys are sorted from top-left to bottom-right order.
* The list may contain {@link Key.Spacer} object as well.
* @return the sorted unmodifiable list of {@link Key}s of this keyboard.
*/
@Nonnull
public List<Key> getSortedKeys() {
return mSortedKeys;
}
@Nullable
public Key getKey(final int code) {
if (code == Constants.CODE_UNSPECIFIED) {
return null;
}
synchronized (mKeyCache) {
final int index = mKeyCache.indexOfKey(code);
if (index >= 0) {
return mKeyCache.valueAt(index);
}
for (final Key key : getSortedKeys()) {
if (key.getCode() == code) {
mKeyCache.put(code, key);
return key;
}
}
mKeyCache.put(code, null);
return null;
}
}
public boolean hasKey(@Nonnull final Key aKey) {
if (mKeyCache.indexOfValue(aKey) >= 0) {
return true;
}
for (final Key key : getSortedKeys()) {
if (key == aKey) {
mKeyCache.put(key.getCode(), key);
return true;
}
}
return false;
}
@Override
public String toString() {
return mId.toString();
}
/**
* Returns the array of the keys that are closest to the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the list of the nearest keys to the given point. If the given
* point is out of range, then an array of size zero is returned.
*/
@Nonnull
public List<Key> getNearestKeys(final int x, final int y) {
// Avoid dead pixels at edges of the keyboard
final int adjustedX = Math.max(0, Math.min(x, mOccupiedWidth - 1));
final int adjustedY = Math.max(0, Math.min(y, mOccupiedHeight - 1));
return mProximityInfo.getNearestKeys(adjustedX, adjustedY);
}
@Nonnull
public int[] getCoordinates(@Nonnull final int[] codePoints) {
final int length = codePoints.length;
final int[] coordinates = CoordinateUtils.newCoordinateArray(length);
for (int i = 0; i < length; ++i) {
final Key key = getKey(codePoints[i]);
if (null != key) {
CoordinateUtils.setXYInArray(coordinates, i,
key.getX() + key.getWidth() / 2, key.getY() + key.getHeight() / 2);
} else {
CoordinateUtils.setXYInArray(coordinates, i,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
}
return coordinates;
}
}
| openboard-team/openboard | app/src/main/java/org/dslul/openboard/inputmethod/keyboard/Keyboard.java | 2,798 | /** Default gap between rows */ | block_comment | nl | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dslul.openboard.inputmethod.keyboard;
import android.util.SparseArray;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyVisualAttributes;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyboardIconsSet;
import org.dslul.openboard.inputmethod.keyboard.internal.KeyboardParams;
import org.dslul.openboard.inputmethod.latin.common.Constants;
import org.dslul.openboard.inputmethod.latin.common.CoordinateUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard
* consists of rows of keys.
* <p>The layout file for a keyboard contains XML that looks like the following snippet:</p>
* <pre>
* <Keyboard
* latin:keyWidth="10%p"
* latin:rowHeight="50px"
* latin:horizontalGap="2%p"
* latin:verticalGap="2%p" >
* <Row latin:keyWidth="10%p" >
* <Key latin:keyLabel="A" />
* ...
* </Row>
* ...
* </Keyboard>
* </pre>
*/
public class Keyboard {
@Nonnull
public final KeyboardId mId;
public final int mThemeId;
/** Total height of the keyboard, including the padding and keys */
public final int mOccupiedHeight;
/** Total width of the keyboard, including the padding and keys */
public final int mOccupiedWidth;
/** Base height of the keyboard, used to calculate rows' height */
public final int mBaseHeight;
/** Base width of the keyboard, used to calculate keys' width */
public final int mBaseWidth;
/** The padding above the keyboard */
public final int mTopPadding;
/** Default gap between<SUF>*/
public final int mVerticalGap;
/** Per keyboard key visual parameters */
public final KeyVisualAttributes mKeyVisualAttributes;
public final int mMostCommonKeyHeight;
public final int mMostCommonKeyWidth;
/** More keys keyboard template */
public final int mMoreKeysTemplate;
/** Maximum column for more keys keyboard */
public final int mMaxMoreKeysKeyboardColumn;
/** List of keys in this keyboard */
@Nonnull
private final List<Key> mSortedKeys;
@Nonnull
public final List<Key> mShiftKeys;
@Nonnull
public final List<Key> mAltCodeKeysWhileTyping;
@Nonnull
public final KeyboardIconsSet mIconsSet;
private final SparseArray<Key> mKeyCache = new SparseArray<>();
@Nonnull
private final ProximityInfo mProximityInfo;
@Nonnull
private final KeyboardLayout mKeyboardLayout;
private final boolean mProximityCharsCorrectionEnabled;
public Keyboard(@Nonnull final KeyboardParams params) {
mId = params.mId;
mThemeId = params.mThemeId;
mOccupiedHeight = params.mOccupiedHeight;
mOccupiedWidth = params.mOccupiedWidth;
mBaseHeight = params.mBaseHeight;
mBaseWidth = params.mBaseWidth;
mMostCommonKeyHeight = params.mMostCommonKeyHeight;
mMostCommonKeyWidth = params.mMostCommonKeyWidth;
mMoreKeysTemplate = params.mMoreKeysTemplate;
mMaxMoreKeysKeyboardColumn = params.mMaxMoreKeysKeyboardColumn;
mKeyVisualAttributes = params.mKeyVisualAttributes;
mTopPadding = params.mTopPadding;
mVerticalGap = params.mVerticalGap;
mSortedKeys = Collections.unmodifiableList(new ArrayList<>(params.mSortedKeys));
mShiftKeys = Collections.unmodifiableList(params.mShiftKeys);
mAltCodeKeysWhileTyping = Collections.unmodifiableList(params.mAltCodeKeysWhileTyping);
mIconsSet = params.mIconsSet;
mProximityInfo = new ProximityInfo(params.GRID_WIDTH, params.GRID_HEIGHT,
mOccupiedWidth, mOccupiedHeight, mMostCommonKeyWidth, mMostCommonKeyHeight,
mSortedKeys, params.mTouchPositionCorrection);
mProximityCharsCorrectionEnabled = params.mProximityCharsCorrectionEnabled;
mKeyboardLayout = KeyboardLayout.newKeyboardLayout(mSortedKeys, mMostCommonKeyWidth,
mMostCommonKeyHeight, mOccupiedWidth, mOccupiedHeight);
}
protected Keyboard(@Nonnull final Keyboard keyboard) {
mId = keyboard.mId;
mThemeId = keyboard.mThemeId;
mOccupiedHeight = keyboard.mOccupiedHeight;
mOccupiedWidth = keyboard.mOccupiedWidth;
mBaseHeight = keyboard.mBaseHeight;
mBaseWidth = keyboard.mBaseWidth;
mMostCommonKeyHeight = keyboard.mMostCommonKeyHeight;
mMostCommonKeyWidth = keyboard.mMostCommonKeyWidth;
mMoreKeysTemplate = keyboard.mMoreKeysTemplate;
mMaxMoreKeysKeyboardColumn = keyboard.mMaxMoreKeysKeyboardColumn;
mKeyVisualAttributes = keyboard.mKeyVisualAttributes;
mTopPadding = keyboard.mTopPadding;
mVerticalGap = keyboard.mVerticalGap;
mSortedKeys = keyboard.mSortedKeys;
mShiftKeys = keyboard.mShiftKeys;
mAltCodeKeysWhileTyping = keyboard.mAltCodeKeysWhileTyping;
mIconsSet = keyboard.mIconsSet;
mProximityInfo = keyboard.mProximityInfo;
mProximityCharsCorrectionEnabled = keyboard.mProximityCharsCorrectionEnabled;
mKeyboardLayout = keyboard.mKeyboardLayout;
}
public boolean hasProximityCharsCorrection(final int code) {
if (!mProximityCharsCorrectionEnabled) {
return false;
}
// Note: The native code has the main keyboard layout only at this moment.
// TODO: Figure out how to handle proximity characters information of all layouts.
final boolean canAssumeNativeHasProximityCharsInfoOfAllKeys = (
mId.mElementId == KeyboardId.ELEMENT_ALPHABET
|| mId.mElementId == KeyboardId.ELEMENT_ALPHABET_AUTOMATIC_SHIFTED);
return canAssumeNativeHasProximityCharsInfoOfAllKeys || Character.isLetter(code);
}
@Nonnull
public ProximityInfo getProximityInfo() {
return mProximityInfo;
}
@Nonnull
public KeyboardLayout getKeyboardLayout() {
return mKeyboardLayout;
}
/**
* Return the sorted list of keys of this keyboard.
* The keys are sorted from top-left to bottom-right order.
* The list may contain {@link Key.Spacer} object as well.
* @return the sorted unmodifiable list of {@link Key}s of this keyboard.
*/
@Nonnull
public List<Key> getSortedKeys() {
return mSortedKeys;
}
@Nullable
public Key getKey(final int code) {
if (code == Constants.CODE_UNSPECIFIED) {
return null;
}
synchronized (mKeyCache) {
final int index = mKeyCache.indexOfKey(code);
if (index >= 0) {
return mKeyCache.valueAt(index);
}
for (final Key key : getSortedKeys()) {
if (key.getCode() == code) {
mKeyCache.put(code, key);
return key;
}
}
mKeyCache.put(code, null);
return null;
}
}
public boolean hasKey(@Nonnull final Key aKey) {
if (mKeyCache.indexOfValue(aKey) >= 0) {
return true;
}
for (final Key key : getSortedKeys()) {
if (key == aKey) {
mKeyCache.put(key.getCode(), key);
return true;
}
}
return false;
}
@Override
public String toString() {
return mId.toString();
}
/**
* Returns the array of the keys that are closest to the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the list of the nearest keys to the given point. If the given
* point is out of range, then an array of size zero is returned.
*/
@Nonnull
public List<Key> getNearestKeys(final int x, final int y) {
// Avoid dead pixels at edges of the keyboard
final int adjustedX = Math.max(0, Math.min(x, mOccupiedWidth - 1));
final int adjustedY = Math.max(0, Math.min(y, mOccupiedHeight - 1));
return mProximityInfo.getNearestKeys(adjustedX, adjustedY);
}
@Nonnull
public int[] getCoordinates(@Nonnull final int[] codePoints) {
final int length = codePoints.length;
final int[] coordinates = CoordinateUtils.newCoordinateArray(length);
for (int i = 0; i < length; ++i) {
final Key key = getKey(codePoints[i]);
if (null != key) {
CoordinateUtils.setXYInArray(coordinates, i,
key.getX() + key.getWidth() / 2, key.getY() + key.getHeight() / 2);
} else {
CoordinateUtils.setXYInArray(coordinates, i,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
}
return coordinates;
}
}
|
113916_3 | /*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.server.rest;
import org.opencb.opencga.core.tools.annotations.Api;
import org.opencb.opencga.core.tools.annotations.ApiOperation;
import org.opencb.opencga.core.tools.annotations.ApiParam;
import org.opencb.opencga.core.exceptions.VersionException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.util.Map;
@Path("/{apiVersion}/test")
@Api(value = "test", hidden = true, position = 12, description = "test web services")
public class TestWSServer extends OpenCGAWSServer {
public TestWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest, @Context HttpHeaders httpHeaders) throws IOException, VersionException {
super(uriInfo, httpServletRequest, httpHeaders);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/echo")
@ApiOperation(value = "echo json")
public Response formPost(@ApiParam(value = "json") Map<String, Object> json) {
// System.out.println("Received message " + message);
// for (String s : json.keySet()) {
// Object o = json.get(s);
// if (o instanceof Map) {
// System.out.println("It is a map");
// for (Object key : ((Map) o).keySet()) {
// System.out.println(key + " = " + json.get(key));
// }
// }
// System.out.println(s + " = " + json.get(s));
// }
return buildResponse(Response.ok("Hello, it worked"));
}
// @GET
// @Path("/{param}")
// @ApiOperation(defaultValue="just to test the sample api")
// public Response getMessage(@ApiParam(defaultValue="param",required=true)@PathParam("param") String msg ) {
// String output = "Hello : " + msg;
// return Response.status(200).entity(output).build();
// }
@GET
@Path("/echo/{message}")
@Produces("text/plain")
@ApiOperation(value = "Just to test the api")
public Response echoGet(@ApiParam(value = "message", required = true) @PathParam("message") String message) {
return buildResponse(Response.ok(message));
}
} | opencb/opencga | opencga-server/src/main/java/org/opencb/opencga/server/rest/TestWSServer.java | 801 | // Object o = json.get(s); | line_comment | nl | /*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.server.rest;
import org.opencb.opencga.core.tools.annotations.Api;
import org.opencb.opencga.core.tools.annotations.ApiOperation;
import org.opencb.opencga.core.tools.annotations.ApiParam;
import org.opencb.opencga.core.exceptions.VersionException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.util.Map;
@Path("/{apiVersion}/test")
@Api(value = "test", hidden = true, position = 12, description = "test web services")
public class TestWSServer extends OpenCGAWSServer {
public TestWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest, @Context HttpHeaders httpHeaders) throws IOException, VersionException {
super(uriInfo, httpServletRequest, httpHeaders);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/echo")
@ApiOperation(value = "echo json")
public Response formPost(@ApiParam(value = "json") Map<String, Object> json) {
// System.out.println("Received message " + message);
// for (String s : json.keySet()) {
// Object o<SUF>
// if (o instanceof Map) {
// System.out.println("It is a map");
// for (Object key : ((Map) o).keySet()) {
// System.out.println(key + " = " + json.get(key));
// }
// }
// System.out.println(s + " = " + json.get(s));
// }
return buildResponse(Response.ok("Hello, it worked"));
}
// @GET
// @Path("/{param}")
// @ApiOperation(defaultValue="just to test the sample api")
// public Response getMessage(@ApiParam(defaultValue="param",required=true)@PathParam("param") String msg ) {
// String output = "Hello : " + msg;
// return Response.status(200).entity(output).build();
// }
@GET
@Path("/echo/{message}")
@Produces("text/plain")
@ApiOperation(value = "Just to test the api")
public Response echoGet(@ApiParam(value = "message", required = true) @PathParam("message") String message) {
return buildResponse(Response.ok(message));
}
} |
167384_2 | /*
* Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.state;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.UnsignedInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPLlGracelfulRestartState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerMessagesState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiKey;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.BgpNeighborState.SessionState;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.bgp.neighbor.prefix.counters_state.PrefixesBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.GracefulRestart;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.GracefulRestartBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafis;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafisBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandling;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandlingBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.State;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.StateBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Timers;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TimersBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Transport;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TransportBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.NeighborBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Neighbors;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.NeighborsBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ADDPATHS;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ASN32;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.BgpCapability;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.GRACEFULRESTART;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.MPBGP;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ROUTEREFRESH;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Timeticks;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.BgpNeighborStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.BgpNeighborStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiGracefulRestartStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiGracefulRestartStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborErrorHandlingStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborErrorHandlingStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborGracefulRestartStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborGracefulRestartStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborTimersStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborTransportStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.MessagesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.Received;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.ReceivedBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.Sent;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.SentBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
import org.opendaylight.yangtools.yang.binding.util.BindingMap;
import org.opendaylight.yangtools.yang.common.Decimal64;
import org.opendaylight.yangtools.yang.common.Uint16;
import org.opendaylight.yangtools.yang.common.Uint32;
import org.opendaylight.yangtools.yang.common.Uint64;
/**
* Util for create OpenConfig Neighbor with corresponding openConfig state.
*/
public final class NeighborUtil {
private static final long TIMETICK_ROLLOVER_VALUE = UnsignedInteger.MAX_VALUE.longValue() + 1;
private NeighborUtil() {
// Hidden on purpose
}
/**
* Build a Openconfig Neighbors container with all Neighbors Stats from a list of
* BGPPeerGroupState.
*
* @param peerStats List of BGPPeerState containing Neighbor state counters
* @param bgpTableTypeRegistry BGP TableType Registry
* @return Openconfig Neighbors Stats
*/
public static @Nullable Neighbors buildNeighbors(final @NonNull List<BGPPeerState> peerStats,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
if (peerStats.isEmpty()) {
return null;
}
return new NeighborsBuilder().setNeighbor(peerStats.stream()
.filter(Objects::nonNull)
.map(neighbor -> buildNeighbor(neighbor, bgpTableTypeRegistry))
.collect(BindingMap.toMap())).build();
}
/**
* Build a list of neighbors containing Operational State from a list of BGPPeerState.
*
* @param neighbor containing Neighbor state counters
* @return neighbor containing Neighbor State
*/
public static @NonNull Neighbor buildNeighbor(final @NonNull BGPPeerState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
return new NeighborBuilder()
.setNeighborAddress(convertIpAddress(neighbor.getNeighborAddress()))
.setState(buildNeighborState(neighbor.getBGPSessionState(), neighbor.getBGPPeerMessagesState()))
.setTimers(buildTimer(neighbor.getBGPTimersState()))
.setTransport(buildTransport(neighbor.getBGPTransportState()))
.setErrorHandling(buildErrorHandling(neighbor.getBGPErrorHandlingState()))
.setGracefulRestart(buildGracefulRestart(neighbor.getBGPGracelfulRestart()))
.setAfiSafis(buildAfisSafis(neighbor, bgpTableTypeRegistry))
.build();
}
private static IpAddress convertIpAddress(final IpAddressNoZone addr) {
if (addr == null) {
return null;
}
final Ipv4AddressNoZone ipv4 = addr.getIpv4AddressNoZone();
if (ipv4 != null) {
return new IpAddress(ipv4);
}
return new IpAddress(addr.getIpv6AddressNoZone());
}
/**
* Builds Neighbor State from BGPPeerState counters.
*
* @param sessionState BGPPeerState containing Operational state counters
* @param bgpPeerMessagesState message state
* @return Neighbor State
*/
public static @Nullable State buildNeighborState(final @Nullable BGPSessionState sessionState,
final BGPPeerMessagesState bgpPeerMessagesState) {
if (sessionState == null && bgpPeerMessagesState == null) {
return null;
}
final StateBuilder builder = new StateBuilder();
if (sessionState != null) {
builder.addAugmentation(buildCapabilityState(sessionState));
}
if (bgpPeerMessagesState != null) {
builder.addAugmentation(buildMessageState(bgpPeerMessagesState));
}
return builder.build();
}
/**
* Builds Neighbor State from BGPPeerState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Timer State
*/
public static @Nullable Timers buildTimer(final @Nullable BGPTimersState neighbor) {
if (neighbor == null) {
return null;
}
// convert neighbor uptime which is in milliseconds to time-ticks which is
// hundredth of a second, and handle roll-over scenario
final long uptimeTicks = neighbor.getUpTime() / 10 % TIMETICK_ROLLOVER_VALUE;
return new TimersBuilder()
.setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
.timers.StateBuilder()
.addAugmentation(new NeighborTimersStateAugmentationBuilder()
.setNegotiatedHoldTime(Decimal64.valueOf(2, neighbor.getNegotiatedHoldTime()))
.setUptime(new Timeticks(Uint32.valueOf(uptimeTicks))).build())
.build())
.build();
}
/**
* Builds Transport State from BGPTransportState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Transport State
*/
public static @Nullable Transport buildTransport(final @Nullable BGPTransportState neighbor) {
if (neighbor == null) {
return null;
}
return new TransportBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009
.bgp.neighbor.group.transport.StateBuilder()
.addAugmentation(new NeighborTransportStateAugmentationBuilder()
.setLocalPort(neighbor.getLocalPort())
.setRemoteAddress(convertIpAddress(neighbor.getRemoteAddress()))
.setRemotePort(neighbor.getRemotePort())
.build())
.build())
.build();
}
/**
* Builds Error Handling State from BGPPeerState counters.
*
* @param errorHandlingState BGPErrorHandlingState containing ErrorHandlingState Operational state counters
* @return Error Handling State
*/
public static ErrorHandling buildErrorHandling(final @Nullable BGPErrorHandlingState errorHandlingState) {
if (errorHandlingState == null) {
return null;
}
return new ErrorHandlingBuilder()
.setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
.error.handling.StateBuilder()
.addAugmentation(buildErrorHandlingState(errorHandlingState.getErroneousUpdateReceivedCount()))
.build())
.build();
}
/**
* Builds Graceful Restart containing Graceful Restart State from BGPGracelfulRestartState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Graceful Restart
*/
public static @NonNull GracefulRestart buildGracefulRestart(final @NonNull BGPGracelfulRestartState neighbor) {
final NeighborGracefulRestartStateAugmentation gracefulRestartState =
new NeighborGracefulRestartStateAugmentationBuilder()
.setLocalRestarting(neighbor.isLocalRestarting())
.setPeerRestartTime(Uint16.valueOf(neighbor.getPeerRestartTime()))
.setMode(neighbor.getMode())
.setPeerRestarting(neighbor.isPeerRestarting()).build();
return new GracefulRestartBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp
.rev151009.bgp.graceful.restart.graceful.restart.StateBuilder()
.addAugmentation(gracefulRestartState).build()).build();
}
/**
* Builds Neighbor Afi Safi containing AfiSafi State.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Afi Safis
*/
public static AfiSafis buildAfisSafis(final @NonNull BGPPeerState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
return new AfiSafisBuilder().setAfiSafi(buildAfisSafisState(neighbor.getBGPAfiSafiState(),
bgpTableTypeRegistry)).build();
}
/**
* Builds Neighbor State containing Capabilities State, session State.
*
* @return Neighbor State
*/
public static NeighborStateAugmentation buildCapabilityState(final @NonNull BGPSessionState neighbor) {
final var state = switch (neighbor.getSessionState()) {
case IDLE -> SessionState.IDLE;
case UP -> SessionState.ESTABLISHED;
case OPEN_CONFIRM -> SessionState.OPENCONFIRM;
};
return new NeighborStateAugmentationBuilder()
.setSupportedCapabilities(buildSupportedCapabilities(neighbor))
.setSessionState(state)
.build();
}
/**
* Builds Bgp Neighbor State containing Message State.
*
* @return BgpNeighborState containing Message State
*/
public static @NonNull BgpNeighborStateAugmentation buildMessageState(
final @NonNull BGPPeerMessagesState neighbor) {
return new BgpNeighborStateAugmentationBuilder()
.setMessages(new MessagesBuilder()
.setReceived(buildMessagesReceived(neighbor))
.setSent(buildMessagesSent(neighbor)).build()).build();
}
private static Received buildMessagesReceived(final @NonNull BGPPeerMessagesState neighbor) {
return new ReceivedBuilder()
.setUPDATE(Uint64.valueOf(neighbor.getUpdateMessagesReceivedCount()))
.setNOTIFICATION(Uint64.valueOf(neighbor.getNotificationMessagesReceivedCount()))
.build();
}
private static Sent buildMessagesSent(final @NonNull BGPPeerMessagesState neighbor) {
return new SentBuilder()
.setUPDATE(Uint64.valueOf(neighbor.getUpdateMessagesSentCount()))
.setNOTIFICATION(Uint64.valueOf(neighbor.getNotificationMessagesSentCount()))
.build();
}
/**
* Builds Neighbor Error Handling State.
*
* @param erroneousUpdateCount erroneous Update Count
* @return Error Handling State
*/
public static @NonNull NeighborErrorHandlingStateAugmentation buildErrorHandlingState(
final long erroneousUpdateCount) {
return new NeighborErrorHandlingStateAugmentationBuilder()
.setErroneousUpdateMessages(Uint32.saturatedOf(erroneousUpdateCount))
.build();
}
/**
* Build List of afi safi containing State per Afi Safi.
*
* @return AfiSafi List
*/
public static @NonNull Map<AfiSafiKey, AfiSafi> buildAfisSafisState(final @NonNull BGPAfiSafiState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
final Set<TablesKey> afiSafiJoin = new HashSet<>(neighbor.getAfiSafisAdvertized());
afiSafiJoin.addAll(neighbor.getAfiSafisReceived());
return afiSafiJoin.stream().map(tableKey -> buildAfiSafi(neighbor, tableKey, bgpTableTypeRegistry))
.filter(Objects::nonNull)
.collect(BindingMap.toMap());
}
private static @Nullable AfiSafi buildAfiSafi(final @NonNull BGPAfiSafiState neighbor,
final @NonNull TablesKey tablesKey, final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
final AfiSafiType afiSafi = bgpTableTypeRegistry.getAfiSafiType(tablesKey);
return afiSafi == null ? null : new AfiSafiBuilder()
.setAfiSafiName(afiSafi)
.setState(buildAfiSafiState(neighbor, tablesKey, neighbor.isAfiSafiSupported(tablesKey)))
.setGracefulRestart(buildAfiSafiGracefulRestartState(neighbor, tablesKey))
.build();
}
private static org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.State buildAfiSafiState(final @NonNull BGPAfiSafiState neighbor,
final @NonNull TablesKey tablesKey, final boolean afiSafiSupported) {
final NeighborAfiSafiStateAugmentationBuilder builder = new NeighborAfiSafiStateAugmentationBuilder();
builder.setActive(afiSafiSupported);
if (afiSafiSupported) {
builder.setPrefixes(new PrefixesBuilder()
.setInstalled(Uint32.saturatedOf(neighbor.getPrefixesInstalledCount(tablesKey)))
.setReceived(Uint32.saturatedOf(neighbor.getPrefixesReceivedCount(tablesKey)))
.setSent(Uint32.saturatedOf(neighbor.getPrefixesSentCount(tablesKey))).build());
}
return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.StateBuilder().addAugmentation(builder.build()).build();
}
private static org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.GracefulRestart buildAfiSafiGracefulRestartState(
final @NonNull BGPLlGracelfulRestartState neighbor, final @NonNull TablesKey tablesKey) {
final NeighborAfiSafiGracefulRestartStateAugmentation builder =
new NeighborAfiSafiGracefulRestartStateAugmentationBuilder()
.setAdvertised(neighbor.isGracefulRestartAdvertized(tablesKey))
.setReceived(neighbor.isGracefulRestartReceived(tablesKey))
.setLlAdvertised(neighbor.isLlGracefulRestartAdvertised(tablesKey))
.setLlReceived(neighbor.isLlGracefulRestartReceived(tablesKey))
.setLlStaleTimer(Uint32.valueOf(neighbor.getLlGracefulRestartTimer(tablesKey))).build();
return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.GracefulRestartBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig
.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.afi.safi.graceful.restart.StateBuilder()
.addAugmentation(builder).build()).build();
}
/**
* Builds List of BgpCapability supported capabilities.
*
* @return List containing supported capabilities
*/
public static @NonNull Set<BgpCapability> buildSupportedCapabilities(final @NonNull BGPSessionState neighbor) {
final var supportedCapabilities = ImmutableSet.<BgpCapability>builder();
if (neighbor.isAddPathCapabilitySupported()) {
supportedCapabilities.add(ADDPATHS.VALUE);
}
if (neighbor.isAsn32CapabilitySupported()) {
supportedCapabilities.add(ASN32.VALUE);
}
if (neighbor.isGracefulRestartCapabilitySupported()) {
supportedCapabilities.add(GRACEFULRESTART.VALUE);
}
if (neighbor.isMultiProtocolCapabilitySupported()) {
supportedCapabilities.add(MPBGP.VALUE);
}
if (neighbor.isRouterRefreshCapabilitySupported()) {
supportedCapabilities.add(ROUTEREFRESH.VALUE);
}
return supportedCapabilities.build();
}
}
| opendaylight/bgpcep | bgp/openconfig-state/src/main/java/org/opendaylight/protocol/bgp/state/NeighborUtil.java | 7,723 | // Hidden on purpose | line_comment | nl | /*
* Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.state;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.UnsignedInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPLlGracelfulRestartState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerMessagesState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiKey;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.BgpNeighborState.SessionState;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.bgp.neighbor.prefix.counters_state.PrefixesBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.GracefulRestart;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.GracefulRestartBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafis;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafisBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandling;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandlingBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.State;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.StateBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Timers;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TimersBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Transport;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TransportBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.NeighborBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Neighbors;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.NeighborsBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ADDPATHS;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ASN32;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.BgpCapability;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.GRACEFULRESTART;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.MPBGP;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ROUTEREFRESH;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Timeticks;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.BgpNeighborStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.BgpNeighborStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiGracefulRestartStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiGracefulRestartStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborAfiSafiStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborErrorHandlingStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborErrorHandlingStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborGracefulRestartStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborGracefulRestartStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborStateAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborTimersStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.NeighborTransportStateAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.MessagesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.Received;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.ReceivedBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.Sent;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instance.protocol.bgp.neighbor_state.augmentation.messages.SentBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
import org.opendaylight.yangtools.yang.binding.util.BindingMap;
import org.opendaylight.yangtools.yang.common.Decimal64;
import org.opendaylight.yangtools.yang.common.Uint16;
import org.opendaylight.yangtools.yang.common.Uint32;
import org.opendaylight.yangtools.yang.common.Uint64;
/**
* Util for create OpenConfig Neighbor with corresponding openConfig state.
*/
public final class NeighborUtil {
private static final long TIMETICK_ROLLOVER_VALUE = UnsignedInteger.MAX_VALUE.longValue() + 1;
private NeighborUtil() {
// Hidden on<SUF>
}
/**
* Build a Openconfig Neighbors container with all Neighbors Stats from a list of
* BGPPeerGroupState.
*
* @param peerStats List of BGPPeerState containing Neighbor state counters
* @param bgpTableTypeRegistry BGP TableType Registry
* @return Openconfig Neighbors Stats
*/
public static @Nullable Neighbors buildNeighbors(final @NonNull List<BGPPeerState> peerStats,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
if (peerStats.isEmpty()) {
return null;
}
return new NeighborsBuilder().setNeighbor(peerStats.stream()
.filter(Objects::nonNull)
.map(neighbor -> buildNeighbor(neighbor, bgpTableTypeRegistry))
.collect(BindingMap.toMap())).build();
}
/**
* Build a list of neighbors containing Operational State from a list of BGPPeerState.
*
* @param neighbor containing Neighbor state counters
* @return neighbor containing Neighbor State
*/
public static @NonNull Neighbor buildNeighbor(final @NonNull BGPPeerState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
return new NeighborBuilder()
.setNeighborAddress(convertIpAddress(neighbor.getNeighborAddress()))
.setState(buildNeighborState(neighbor.getBGPSessionState(), neighbor.getBGPPeerMessagesState()))
.setTimers(buildTimer(neighbor.getBGPTimersState()))
.setTransport(buildTransport(neighbor.getBGPTransportState()))
.setErrorHandling(buildErrorHandling(neighbor.getBGPErrorHandlingState()))
.setGracefulRestart(buildGracefulRestart(neighbor.getBGPGracelfulRestart()))
.setAfiSafis(buildAfisSafis(neighbor, bgpTableTypeRegistry))
.build();
}
private static IpAddress convertIpAddress(final IpAddressNoZone addr) {
if (addr == null) {
return null;
}
final Ipv4AddressNoZone ipv4 = addr.getIpv4AddressNoZone();
if (ipv4 != null) {
return new IpAddress(ipv4);
}
return new IpAddress(addr.getIpv6AddressNoZone());
}
/**
* Builds Neighbor State from BGPPeerState counters.
*
* @param sessionState BGPPeerState containing Operational state counters
* @param bgpPeerMessagesState message state
* @return Neighbor State
*/
public static @Nullable State buildNeighborState(final @Nullable BGPSessionState sessionState,
final BGPPeerMessagesState bgpPeerMessagesState) {
if (sessionState == null && bgpPeerMessagesState == null) {
return null;
}
final StateBuilder builder = new StateBuilder();
if (sessionState != null) {
builder.addAugmentation(buildCapabilityState(sessionState));
}
if (bgpPeerMessagesState != null) {
builder.addAugmentation(buildMessageState(bgpPeerMessagesState));
}
return builder.build();
}
/**
* Builds Neighbor State from BGPPeerState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Timer State
*/
public static @Nullable Timers buildTimer(final @Nullable BGPTimersState neighbor) {
if (neighbor == null) {
return null;
}
// convert neighbor uptime which is in milliseconds to time-ticks which is
// hundredth of a second, and handle roll-over scenario
final long uptimeTicks = neighbor.getUpTime() / 10 % TIMETICK_ROLLOVER_VALUE;
return new TimersBuilder()
.setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
.timers.StateBuilder()
.addAugmentation(new NeighborTimersStateAugmentationBuilder()
.setNegotiatedHoldTime(Decimal64.valueOf(2, neighbor.getNegotiatedHoldTime()))
.setUptime(new Timeticks(Uint32.valueOf(uptimeTicks))).build())
.build())
.build();
}
/**
* Builds Transport State from BGPTransportState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Transport State
*/
public static @Nullable Transport buildTransport(final @Nullable BGPTransportState neighbor) {
if (neighbor == null) {
return null;
}
return new TransportBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009
.bgp.neighbor.group.transport.StateBuilder()
.addAugmentation(new NeighborTransportStateAugmentationBuilder()
.setLocalPort(neighbor.getLocalPort())
.setRemoteAddress(convertIpAddress(neighbor.getRemoteAddress()))
.setRemotePort(neighbor.getRemotePort())
.build())
.build())
.build();
}
/**
* Builds Error Handling State from BGPPeerState counters.
*
* @param errorHandlingState BGPErrorHandlingState containing ErrorHandlingState Operational state counters
* @return Error Handling State
*/
public static ErrorHandling buildErrorHandling(final @Nullable BGPErrorHandlingState errorHandlingState) {
if (errorHandlingState == null) {
return null;
}
return new ErrorHandlingBuilder()
.setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
.error.handling.StateBuilder()
.addAugmentation(buildErrorHandlingState(errorHandlingState.getErroneousUpdateReceivedCount()))
.build())
.build();
}
/**
* Builds Graceful Restart containing Graceful Restart State from BGPGracelfulRestartState counters.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Graceful Restart
*/
public static @NonNull GracefulRestart buildGracefulRestart(final @NonNull BGPGracelfulRestartState neighbor) {
final NeighborGracefulRestartStateAugmentation gracefulRestartState =
new NeighborGracefulRestartStateAugmentationBuilder()
.setLocalRestarting(neighbor.isLocalRestarting())
.setPeerRestartTime(Uint16.valueOf(neighbor.getPeerRestartTime()))
.setMode(neighbor.getMode())
.setPeerRestarting(neighbor.isPeerRestarting()).build();
return new GracefulRestartBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp
.rev151009.bgp.graceful.restart.graceful.restart.StateBuilder()
.addAugmentation(gracefulRestartState).build()).build();
}
/**
* Builds Neighbor Afi Safi containing AfiSafi State.
*
* @param neighbor BGPPeerState containing Operational state counters
* @return Afi Safis
*/
public static AfiSafis buildAfisSafis(final @NonNull BGPPeerState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
return new AfiSafisBuilder().setAfiSafi(buildAfisSafisState(neighbor.getBGPAfiSafiState(),
bgpTableTypeRegistry)).build();
}
/**
* Builds Neighbor State containing Capabilities State, session State.
*
* @return Neighbor State
*/
public static NeighborStateAugmentation buildCapabilityState(final @NonNull BGPSessionState neighbor) {
final var state = switch (neighbor.getSessionState()) {
case IDLE -> SessionState.IDLE;
case UP -> SessionState.ESTABLISHED;
case OPEN_CONFIRM -> SessionState.OPENCONFIRM;
};
return new NeighborStateAugmentationBuilder()
.setSupportedCapabilities(buildSupportedCapabilities(neighbor))
.setSessionState(state)
.build();
}
/**
* Builds Bgp Neighbor State containing Message State.
*
* @return BgpNeighborState containing Message State
*/
public static @NonNull BgpNeighborStateAugmentation buildMessageState(
final @NonNull BGPPeerMessagesState neighbor) {
return new BgpNeighborStateAugmentationBuilder()
.setMessages(new MessagesBuilder()
.setReceived(buildMessagesReceived(neighbor))
.setSent(buildMessagesSent(neighbor)).build()).build();
}
private static Received buildMessagesReceived(final @NonNull BGPPeerMessagesState neighbor) {
return new ReceivedBuilder()
.setUPDATE(Uint64.valueOf(neighbor.getUpdateMessagesReceivedCount()))
.setNOTIFICATION(Uint64.valueOf(neighbor.getNotificationMessagesReceivedCount()))
.build();
}
private static Sent buildMessagesSent(final @NonNull BGPPeerMessagesState neighbor) {
return new SentBuilder()
.setUPDATE(Uint64.valueOf(neighbor.getUpdateMessagesSentCount()))
.setNOTIFICATION(Uint64.valueOf(neighbor.getNotificationMessagesSentCount()))
.build();
}
/**
* Builds Neighbor Error Handling State.
*
* @param erroneousUpdateCount erroneous Update Count
* @return Error Handling State
*/
public static @NonNull NeighborErrorHandlingStateAugmentation buildErrorHandlingState(
final long erroneousUpdateCount) {
return new NeighborErrorHandlingStateAugmentationBuilder()
.setErroneousUpdateMessages(Uint32.saturatedOf(erroneousUpdateCount))
.build();
}
/**
* Build List of afi safi containing State per Afi Safi.
*
* @return AfiSafi List
*/
public static @NonNull Map<AfiSafiKey, AfiSafi> buildAfisSafisState(final @NonNull BGPAfiSafiState neighbor,
final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
final Set<TablesKey> afiSafiJoin = new HashSet<>(neighbor.getAfiSafisAdvertized());
afiSafiJoin.addAll(neighbor.getAfiSafisReceived());
return afiSafiJoin.stream().map(tableKey -> buildAfiSafi(neighbor, tableKey, bgpTableTypeRegistry))
.filter(Objects::nonNull)
.collect(BindingMap.toMap());
}
private static @Nullable AfiSafi buildAfiSafi(final @NonNull BGPAfiSafiState neighbor,
final @NonNull TablesKey tablesKey, final @NonNull BGPTableTypeRegistryConsumer bgpTableTypeRegistry) {
final AfiSafiType afiSafi = bgpTableTypeRegistry.getAfiSafiType(tablesKey);
return afiSafi == null ? null : new AfiSafiBuilder()
.setAfiSafiName(afiSafi)
.setState(buildAfiSafiState(neighbor, tablesKey, neighbor.isAfiSafiSupported(tablesKey)))
.setGracefulRestart(buildAfiSafiGracefulRestartState(neighbor, tablesKey))
.build();
}
private static org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.State buildAfiSafiState(final @NonNull BGPAfiSafiState neighbor,
final @NonNull TablesKey tablesKey, final boolean afiSafiSupported) {
final NeighborAfiSafiStateAugmentationBuilder builder = new NeighborAfiSafiStateAugmentationBuilder();
builder.setActive(afiSafiSupported);
if (afiSafiSupported) {
builder.setPrefixes(new PrefixesBuilder()
.setInstalled(Uint32.saturatedOf(neighbor.getPrefixesInstalledCount(tablesKey)))
.setReceived(Uint32.saturatedOf(neighbor.getPrefixesReceivedCount(tablesKey)))
.setSent(Uint32.saturatedOf(neighbor.getPrefixesSentCount(tablesKey))).build());
}
return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.StateBuilder().addAugmentation(builder.build()).build();
}
private static org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.GracefulRestart buildAfiSafiGracefulRestartState(
final @NonNull BGPLlGracelfulRestartState neighbor, final @NonNull TablesKey tablesKey) {
final NeighborAfiSafiGracefulRestartStateAugmentation builder =
new NeighborAfiSafiGracefulRestartStateAugmentationBuilder()
.setAdvertised(neighbor.isGracefulRestartAdvertized(tablesKey))
.setReceived(neighbor.isGracefulRestartReceived(tablesKey))
.setLlAdvertised(neighbor.isLlGracefulRestartAdvertised(tablesKey))
.setLlReceived(neighbor.isLlGracefulRestartReceived(tablesKey))
.setLlStaleTimer(Uint32.valueOf(neighbor.getLlGracefulRestartTimer(tablesKey))).build();
return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi
.safi.list.afi.safi.GracefulRestartBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig
.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.afi.safi.graceful.restart.StateBuilder()
.addAugmentation(builder).build()).build();
}
/**
* Builds List of BgpCapability supported capabilities.
*
* @return List containing supported capabilities
*/
public static @NonNull Set<BgpCapability> buildSupportedCapabilities(final @NonNull BGPSessionState neighbor) {
final var supportedCapabilities = ImmutableSet.<BgpCapability>builder();
if (neighbor.isAddPathCapabilitySupported()) {
supportedCapabilities.add(ADDPATHS.VALUE);
}
if (neighbor.isAsn32CapabilitySupported()) {
supportedCapabilities.add(ASN32.VALUE);
}
if (neighbor.isGracefulRestartCapabilitySupported()) {
supportedCapabilities.add(GRACEFULRESTART.VALUE);
}
if (neighbor.isMultiProtocolCapabilitySupported()) {
supportedCapabilities.add(MPBGP.VALUE);
}
if (neighbor.isRouterRefreshCapabilitySupported()) {
supportedCapabilities.add(ROUTEREFRESH.VALUE);
}
return supportedCapabilities.build();
}
}
|
118613_3 | package nl.openehr;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class ZibConverter {
private static final String ZIB_HEADER = "ZIB_Id,ZIB_Naam,ZIB_Type,ZIB_Card,ZIB_DefCode,ZIB_Verwijzing,openEHR_Path,openEHR_Naam,openEHR_Type,openEHR_Card,openEHR_Term,Commentaar";
private static final int ZIB_Id_COL = 11;
private static final int ZIB_Naam_COL_MIN = 1;
private static final int ZIB_Naam_COL_MAX = 6;
private static final int ZIB_Type_COL = 8;
private static final int ZIB_Type_COL_ALT = 10;
private static final int ZIB_Card_COL = 9;
private static final int ZIB_DefCode_COL = 13;
private static final int ZIB_Verwijzing_COL = 14;
private static final String VALUESET_HEADER = "ZIB_Conceptnaam,ZIB_Conceptcode,ZIB_Conceptwaarde,ZIB_Codestelselnaam,ZIB_Codesysteem_OID,ZIB_Omschrijving,openEHR_Code,openEHR_Text,Commentaar";
private Workbook workbook;
public static void main(String[] args) throws Exception {
if(args.length != 2) {
throw new IllegalArgumentException("Requires two arguments: inputdir outputdir");
}
String inputdir = args[0];
String outputdir = args[1];
File dir = new File(inputdir);
for(File file : dir.listFiles((dirx, filename) -> filename.startsWith("nl.zorg") && filename.endsWith(".xlsx"))) {
System.out.println(file.getName());
ZibConverter importer = new ZibConverter();
importer.open(file);
importer.convertZibToCsv(outputdir);
importer.convertValuesets(outputdir);
importer.close();
}
}
private void open(File file) throws IOException {
workbook = WorkbookFactory.create(file, null, true);
}
private void close() throws IOException {
workbook.close();
workbook = null;
}
private void convertZibToCsv(String outputdir) throws FileNotFoundException {
Sheet sheet = workbook.getSheet("Data");
Objects.requireNonNull(sheet);
int rownum = 2;
String zibnaam = getCellValue(sheet.getRow(rownum), ZIB_Naam_COL_MIN).toLowerCase(Locale.ROOT);
try(PrintStream out = new PrintStream(new FileOutputStream(outputdir + "/mappings/" + zibnaam + ".csv"))) {
out.println(ZIB_HEADER);
while (true) {
Row row = sheet.getRow(rownum);
if (row == null) {
break;
}
int mergeHeight = getMergeHeight(row.getCell(1));
List<Row> rows = new ArrayList<>(mergeHeight);
for(int i = 0; i < mergeHeight; i++) {
Row subRow = sheet.getRow(rownum + i);
Objects.requireNonNull(subRow, "Row " + (rownum + i) + " is null");
rows.add(subRow);
}
String ZIB_Id = getCellValue(row, ZIB_Id_COL);
String ZIB_Naam = getZIB_Naam(row);
String ZIB_Type = getCellValue(rows, ZIB_Type_COL);
if (ZIB_Type == null || ZIB_Type.isEmpty()) {
ZIB_Type = getCellValue(rows, ZIB_Type_COL_ALT);
}
String ZIB_Card = getCellValue(rows, ZIB_Card_COL);
String ZIB_DefCode = getCellValue(rows, ZIB_DefCode_COL);
String ZIB_Verwijzing = getCellValue(rows, ZIB_Verwijzing_COL);
out.println(ZIB_Id + "," + ZIB_Naam + "," + escape(ZIB_Type) + "," + ZIB_Card + "," + ZIB_DefCode + "," + ZIB_Verwijzing + ",,,,,,");
rownum += mergeHeight;
}
}
}
private void convertValuesets(String outputdir) throws FileNotFoundException {
// Start after Data sheet, skip last sheet (Gebruiksvoorwaarden).
for(int i = workbook.getSheetIndex("Data") + 1; i < workbook.getNumberOfSheets() - 1; i++) {
Sheet sheet = workbook.getSheetAt(i);
if(sheet.getSheetName().equals("Assigning Authorities")) {
continue;
}
convertValueset(outputdir, sheet);
}
}
private void convertValueset(String outputdir, Sheet sheet) throws FileNotFoundException {
Objects.requireNonNull(sheet);
String valuesetName = getCellValue(sheet.getRow(2), 2).toLowerCase(Locale.ROOT);
Row headerRow = sheet.getRow(3);
final Integer VALUESET_Conceptnaam = findValue(headerRow, "Conceptnaam");
final Integer VALUESET_Conceptcode = findValue(headerRow, "Conceptcode");
final Integer VALUESET_Conceptwaarde = findValue(headerRow, "Conceptwaarde");
final Integer VALUESET_Codestelselnaam = findValue(headerRow, "Codestelselnaam");
final Integer VALUESET_Codesysteem_OID = findValue(headerRow, "Codesysteem OID");
final Integer VALUESET_Omschrijving = findValue(headerRow, "Omschrijving");
final Integer VALUESET_Extra = findValue(headerRow, "");
int rownum = 4;
try(PrintStream out = new PrintStream(new FileOutputStream(outputdir + "/valuesets/" + valuesetName + ".csv"))) {
out.println(VALUESET_HEADER);
while (true) {
Row row = sheet.getRow(rownum);
if (row == null) {
break;
}
if(getMergeRegion(row.getCell(2)) != null) {
// Comment, skip this.
rownum++;
continue;
}
String conceptnaam = escape(getOptionalCellValue(row, VALUESET_Conceptnaam));
String conceptcode = escape(getOptionalCellValue(row, VALUESET_Conceptcode));
String conceptwaarde = escape(getOptionalCellValue(row, VALUESET_Conceptwaarde));
String codestelselnaam = escape(getOptionalCellValue(row, VALUESET_Codestelselnaam));
String codesysteem_OID = escape(getOptionalCellValue(row, VALUESET_Codesysteem_OID));
String omschrijving = escape(getOptionalCellValue(row, VALUESET_Omschrijving));
// Because of a bug some rows have a value split over two columns.
// This affects:
// nl.zorg.ApgarScore-v1.0.1(2020NL).xlsx: AdemhalingScoreCodelijst, SpierspanningScoreCodelijst
// nl.zorg.ComfortScore-v1.1(2020NL).xlsx: SpierspanningCodelijst
// nl.zorg.FLACCpijnScore-v1.1(2020NL).xlsx: HuilenCodelijst, TroostbaarCodelijst
String extra = escape(getOptionalCellValue(row, VALUESET_Extra));
out.println(conceptnaam + "," + conceptcode + "," + conceptwaarde + "," + codestelselnaam + "," + codesysteem_OID + "," + omschrijving + (extra.equals("") ? "" : "," + extra) + ",,,");
rownum += 1;
}
}
}
private CellRangeAddress getMergeRegion(Cell cell) {
for(CellRangeAddress region : cell.getSheet().getMergedRegions()) {
if(region.isInRange(cell)) {
return region;
}
}
return null;
}
private int getMergeHeight(Cell cell) {
CellRangeAddress mergeRegion = getMergeRegion(cell);
if(mergeRegion != null) {
return mergeRegion.getLastRow() - mergeRegion.getFirstRow() + 1;
}
return 1;
}
private String getZIB_Naam(Row row) {
String ZIB_Naam = null;
int cellnum = ZIB_Naam_COL_MIN;
while((ZIB_Naam == null || ZIB_Naam.isEmpty()) && cellnum <= ZIB_Naam_COL_MAX) {
ZIB_Naam = getCellValue(row, cellnum);
cellnum++;
}
return ZIB_Naam;
}
private String getCellValue(List<Row> rows, int cellnum) {
return rows.stream().map(row -> getCellValue(row, cellnum)).filter(value -> value != null && !value.isEmpty()).collect(Collectors.joining("; "));
}
private String getCellValue(Row row, int cellnum) {
Cell cell = row.getCell(cellnum);
Objects.requireNonNull(cell, "Cell " + cellnum + " of row " + row.getRowNum() + " is null");
return cell.getStringCellValue();
}
private String getOptionalCellValue(Row row, Integer cellnum) {
if(cellnum == null) {
return "";
}
Cell cell = row.getCell(cellnum);
if(cell == null) {
return "";
}
return cell.getStringCellValue();
}
private Integer findValue(Row row, String value) {
for (Iterator<Cell> it = row.cellIterator(); it.hasNext(); ) {
Cell cell = it.next();
if(value.equals(cell.getStringCellValue())) {
return cell.getColumnIndex();
}
}
return null;
}
private String escape(String value) {
if(value.contains(",")) {
return "\"" + value + "\"";
} else {
return value;
}
}
}
| openehr-nl/ZIBs-on-openEHR | scripts/ZibConverter.java | 2,752 | // nl.zorg.ApgarScore-v1.0.1(2020NL).xlsx: AdemhalingScoreCodelijst, SpierspanningScoreCodelijst | line_comment | nl | package nl.openehr;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class ZibConverter {
private static final String ZIB_HEADER = "ZIB_Id,ZIB_Naam,ZIB_Type,ZIB_Card,ZIB_DefCode,ZIB_Verwijzing,openEHR_Path,openEHR_Naam,openEHR_Type,openEHR_Card,openEHR_Term,Commentaar";
private static final int ZIB_Id_COL = 11;
private static final int ZIB_Naam_COL_MIN = 1;
private static final int ZIB_Naam_COL_MAX = 6;
private static final int ZIB_Type_COL = 8;
private static final int ZIB_Type_COL_ALT = 10;
private static final int ZIB_Card_COL = 9;
private static final int ZIB_DefCode_COL = 13;
private static final int ZIB_Verwijzing_COL = 14;
private static final String VALUESET_HEADER = "ZIB_Conceptnaam,ZIB_Conceptcode,ZIB_Conceptwaarde,ZIB_Codestelselnaam,ZIB_Codesysteem_OID,ZIB_Omschrijving,openEHR_Code,openEHR_Text,Commentaar";
private Workbook workbook;
public static void main(String[] args) throws Exception {
if(args.length != 2) {
throw new IllegalArgumentException("Requires two arguments: inputdir outputdir");
}
String inputdir = args[0];
String outputdir = args[1];
File dir = new File(inputdir);
for(File file : dir.listFiles((dirx, filename) -> filename.startsWith("nl.zorg") && filename.endsWith(".xlsx"))) {
System.out.println(file.getName());
ZibConverter importer = new ZibConverter();
importer.open(file);
importer.convertZibToCsv(outputdir);
importer.convertValuesets(outputdir);
importer.close();
}
}
private void open(File file) throws IOException {
workbook = WorkbookFactory.create(file, null, true);
}
private void close() throws IOException {
workbook.close();
workbook = null;
}
private void convertZibToCsv(String outputdir) throws FileNotFoundException {
Sheet sheet = workbook.getSheet("Data");
Objects.requireNonNull(sheet);
int rownum = 2;
String zibnaam = getCellValue(sheet.getRow(rownum), ZIB_Naam_COL_MIN).toLowerCase(Locale.ROOT);
try(PrintStream out = new PrintStream(new FileOutputStream(outputdir + "/mappings/" + zibnaam + ".csv"))) {
out.println(ZIB_HEADER);
while (true) {
Row row = sheet.getRow(rownum);
if (row == null) {
break;
}
int mergeHeight = getMergeHeight(row.getCell(1));
List<Row> rows = new ArrayList<>(mergeHeight);
for(int i = 0; i < mergeHeight; i++) {
Row subRow = sheet.getRow(rownum + i);
Objects.requireNonNull(subRow, "Row " + (rownum + i) + " is null");
rows.add(subRow);
}
String ZIB_Id = getCellValue(row, ZIB_Id_COL);
String ZIB_Naam = getZIB_Naam(row);
String ZIB_Type = getCellValue(rows, ZIB_Type_COL);
if (ZIB_Type == null || ZIB_Type.isEmpty()) {
ZIB_Type = getCellValue(rows, ZIB_Type_COL_ALT);
}
String ZIB_Card = getCellValue(rows, ZIB_Card_COL);
String ZIB_DefCode = getCellValue(rows, ZIB_DefCode_COL);
String ZIB_Verwijzing = getCellValue(rows, ZIB_Verwijzing_COL);
out.println(ZIB_Id + "," + ZIB_Naam + "," + escape(ZIB_Type) + "," + ZIB_Card + "," + ZIB_DefCode + "," + ZIB_Verwijzing + ",,,,,,");
rownum += mergeHeight;
}
}
}
private void convertValuesets(String outputdir) throws FileNotFoundException {
// Start after Data sheet, skip last sheet (Gebruiksvoorwaarden).
for(int i = workbook.getSheetIndex("Data") + 1; i < workbook.getNumberOfSheets() - 1; i++) {
Sheet sheet = workbook.getSheetAt(i);
if(sheet.getSheetName().equals("Assigning Authorities")) {
continue;
}
convertValueset(outputdir, sheet);
}
}
private void convertValueset(String outputdir, Sheet sheet) throws FileNotFoundException {
Objects.requireNonNull(sheet);
String valuesetName = getCellValue(sheet.getRow(2), 2).toLowerCase(Locale.ROOT);
Row headerRow = sheet.getRow(3);
final Integer VALUESET_Conceptnaam = findValue(headerRow, "Conceptnaam");
final Integer VALUESET_Conceptcode = findValue(headerRow, "Conceptcode");
final Integer VALUESET_Conceptwaarde = findValue(headerRow, "Conceptwaarde");
final Integer VALUESET_Codestelselnaam = findValue(headerRow, "Codestelselnaam");
final Integer VALUESET_Codesysteem_OID = findValue(headerRow, "Codesysteem OID");
final Integer VALUESET_Omschrijving = findValue(headerRow, "Omschrijving");
final Integer VALUESET_Extra = findValue(headerRow, "");
int rownum = 4;
try(PrintStream out = new PrintStream(new FileOutputStream(outputdir + "/valuesets/" + valuesetName + ".csv"))) {
out.println(VALUESET_HEADER);
while (true) {
Row row = sheet.getRow(rownum);
if (row == null) {
break;
}
if(getMergeRegion(row.getCell(2)) != null) {
// Comment, skip this.
rownum++;
continue;
}
String conceptnaam = escape(getOptionalCellValue(row, VALUESET_Conceptnaam));
String conceptcode = escape(getOptionalCellValue(row, VALUESET_Conceptcode));
String conceptwaarde = escape(getOptionalCellValue(row, VALUESET_Conceptwaarde));
String codestelselnaam = escape(getOptionalCellValue(row, VALUESET_Codestelselnaam));
String codesysteem_OID = escape(getOptionalCellValue(row, VALUESET_Codesysteem_OID));
String omschrijving = escape(getOptionalCellValue(row, VALUESET_Omschrijving));
// Because of a bug some rows have a value split over two columns.
// This affects:
// nl.zorg.ApgarScore-v1.0.1(2020NL).xlsx: AdemhalingScoreCodelijst,<SUF>
// nl.zorg.ComfortScore-v1.1(2020NL).xlsx: SpierspanningCodelijst
// nl.zorg.FLACCpijnScore-v1.1(2020NL).xlsx: HuilenCodelijst, TroostbaarCodelijst
String extra = escape(getOptionalCellValue(row, VALUESET_Extra));
out.println(conceptnaam + "," + conceptcode + "," + conceptwaarde + "," + codestelselnaam + "," + codesysteem_OID + "," + omschrijving + (extra.equals("") ? "" : "," + extra) + ",,,");
rownum += 1;
}
}
}
private CellRangeAddress getMergeRegion(Cell cell) {
for(CellRangeAddress region : cell.getSheet().getMergedRegions()) {
if(region.isInRange(cell)) {
return region;
}
}
return null;
}
private int getMergeHeight(Cell cell) {
CellRangeAddress mergeRegion = getMergeRegion(cell);
if(mergeRegion != null) {
return mergeRegion.getLastRow() - mergeRegion.getFirstRow() + 1;
}
return 1;
}
private String getZIB_Naam(Row row) {
String ZIB_Naam = null;
int cellnum = ZIB_Naam_COL_MIN;
while((ZIB_Naam == null || ZIB_Naam.isEmpty()) && cellnum <= ZIB_Naam_COL_MAX) {
ZIB_Naam = getCellValue(row, cellnum);
cellnum++;
}
return ZIB_Naam;
}
private String getCellValue(List<Row> rows, int cellnum) {
return rows.stream().map(row -> getCellValue(row, cellnum)).filter(value -> value != null && !value.isEmpty()).collect(Collectors.joining("; "));
}
private String getCellValue(Row row, int cellnum) {
Cell cell = row.getCell(cellnum);
Objects.requireNonNull(cell, "Cell " + cellnum + " of row " + row.getRowNum() + " is null");
return cell.getStringCellValue();
}
private String getOptionalCellValue(Row row, Integer cellnum) {
if(cellnum == null) {
return "";
}
Cell cell = row.getCell(cellnum);
if(cell == null) {
return "";
}
return cell.getStringCellValue();
}
private Integer findValue(Row row, String value) {
for (Iterator<Cell> it = row.cellIterator(); it.hasNext(); ) {
Cell cell = it.next();
if(value.equals(cell.getStringCellValue())) {
return cell.getColumnIndex();
}
}
return null;
}
private String escape(String value) {
if(value.contains(",")) {
return "\"" + value + "\"";
} else {
return value;
}
}
}
|
121895_20 | /**
*
*/
package org.sharks.service.producer;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sharks.service.dto.EntityDetails;
import org.sharks.service.dto.EntityDocument;
import org.sharks.service.dto.EntityEntry;
import org.sharks.service.dto.FaoLexDocument;
import org.sharks.service.dto.GroupEntry;
import org.sharks.service.dto.InformationSourceEntry;
import org.sharks.service.dto.MeasureEntry;
import org.sharks.service.dto.PoAEntry;
import org.sharks.service.moniker.dto.FaoLexFiDocument;
import org.sharks.storage.domain.CustomSpeciesGrp;
import org.sharks.storage.domain.InformationSource;
import org.sharks.storage.domain.Measure;
import org.sharks.storage.domain.MgmtEntity;
import org.sharks.storage.domain.PoA;
/**
* @author "Federico De Faveri [email protected]"
*
*/
public class EntryProducers {
public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) {
return input.stream().map(converter).collect(Collectors.toList());
}
public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() {
@Override
public EntityDocument produce(EntityDetails item) {
// private final long id;
// private final String acronym;
// private final String name;
// private final Long type;
// private final String logoUrl;
// private final String webSite;
// private final String factsheetUrl;
// private final List<EntityMember> members;
// private final List<MeasureEntry> measures;
// private final List<EntityDocument> others;
// private final String title;
// private final Integer year;
// private final String type;
// private final String url;
// private final String symbol;
return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null);
}
};
public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() {
@Override
public MeasureEntry produce(Measure measure) {
String replacedMeasureSourceUrl = null;
if (measure.getReplaces() != null) {
Measure replaced = measure.getReplaces();
List<InformationSource> replacedSources = replaced.getInformationSources();
replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null;
}
return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(),
measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null,
measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(),
convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl);
}
// private String findEntityAcronym(List<InformationSource> sources) {
// for (InformationSource source : sources) {
// for (MgmtEntity mgmtEntity : source.getMgmtEntities()) {
// if (mgmtEntity != null && mgmtEntity.getAcronym() != null)
// return mgmtEntity.getAcronym();
// }
// }
// // return "werkelijk niks";
// return null;
// }
};
public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() {
@Override
public InformationSourceEntry produce(InformationSource source) {
return new InformationSourceEntry(source.getUrl());
}
};
public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() {
@Override
public GroupEntry produce(CustomSpeciesGrp group) {
return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp());
}
};
public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() {
@Override
public PoAEntry produce(PoA poa) {
return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(),
poa.getPoAType() != null ? poa.getPoAType().getDescription() : null,
poa.getStatus() != null ? poa.getStatus().getDescription() : null,
convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY));
}
};
public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() {
@Override
public EntityEntry produce(MgmtEntity entity) {
return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(),
entity.getMgmtEntityType().getCode());
}
};
public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() {
@Override
public EntityDocument produce(InformationSource source) {
return new EntityDocument(source.getTitle(), source.getInfoSrcYear(),
source.getInformationType().getDescription(), source.getUrl(), source.getSymbol());
}
};
public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() {
@Override
public FaoLexDocument produce(FaoLexFiDocument doc) {
return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(),
doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri());
}
};
public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> {
@Override
public O apply(I t) {
return produce(t);
}
}
public interface EntryProducer<I, O> extends Function<I, O> {
public O produce(I item);
}
}
| openfigis/sharks | sharks-server/sharks-service/src/main/java/org/sharks/service/producer/EntryProducers.java | 1,761 | // // return "werkelijk niks"; | line_comment | nl | /**
*
*/
package org.sharks.service.producer;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sharks.service.dto.EntityDetails;
import org.sharks.service.dto.EntityDocument;
import org.sharks.service.dto.EntityEntry;
import org.sharks.service.dto.FaoLexDocument;
import org.sharks.service.dto.GroupEntry;
import org.sharks.service.dto.InformationSourceEntry;
import org.sharks.service.dto.MeasureEntry;
import org.sharks.service.dto.PoAEntry;
import org.sharks.service.moniker.dto.FaoLexFiDocument;
import org.sharks.storage.domain.CustomSpeciesGrp;
import org.sharks.storage.domain.InformationSource;
import org.sharks.storage.domain.Measure;
import org.sharks.storage.domain.MgmtEntity;
import org.sharks.storage.domain.PoA;
/**
* @author "Federico De Faveri [email protected]"
*
*/
public class EntryProducers {
public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) {
return input.stream().map(converter).collect(Collectors.toList());
}
public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() {
@Override
public EntityDocument produce(EntityDetails item) {
// private final long id;
// private final String acronym;
// private final String name;
// private final Long type;
// private final String logoUrl;
// private final String webSite;
// private final String factsheetUrl;
// private final List<EntityMember> members;
// private final List<MeasureEntry> measures;
// private final List<EntityDocument> others;
// private final String title;
// private final Integer year;
// private final String type;
// private final String url;
// private final String symbol;
return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null);
}
};
public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() {
@Override
public MeasureEntry produce(Measure measure) {
String replacedMeasureSourceUrl = null;
if (measure.getReplaces() != null) {
Measure replaced = measure.getReplaces();
List<InformationSource> replacedSources = replaced.getInformationSources();
replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null;
}
return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(),
measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null,
measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(),
convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl);
}
// private String findEntityAcronym(List<InformationSource> sources) {
// for (InformationSource source : sources) {
// for (MgmtEntity mgmtEntity : source.getMgmtEntities()) {
// if (mgmtEntity != null && mgmtEntity.getAcronym() != null)
// return mgmtEntity.getAcronym();
// }
// }
// // return "werkelijk<SUF>
// return null;
// }
};
public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() {
@Override
public InformationSourceEntry produce(InformationSource source) {
return new InformationSourceEntry(source.getUrl());
}
};
public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() {
@Override
public GroupEntry produce(CustomSpeciesGrp group) {
return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp());
}
};
public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() {
@Override
public PoAEntry produce(PoA poa) {
return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(),
poa.getPoAType() != null ? poa.getPoAType().getDescription() : null,
poa.getStatus() != null ? poa.getStatus().getDescription() : null,
convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY));
}
};
public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() {
@Override
public EntityEntry produce(MgmtEntity entity) {
return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(),
entity.getMgmtEntityType().getCode());
}
};
public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() {
@Override
public EntityDocument produce(InformationSource source) {
return new EntityDocument(source.getTitle(), source.getInfoSrcYear(),
source.getInformationType().getDescription(), source.getUrl(), source.getSymbol());
}
};
public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() {
@Override
public FaoLexDocument produce(FaoLexFiDocument doc) {
return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(),
doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri());
}
};
public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> {
@Override
public O apply(I t) {
return produce(t);
}
}
public interface EntryProducer<I, O> extends Function<I, O> {
public O produce(I item);
}
}
|
138253_15 | /*
* Copyright (C) 2021 B3Partners B.V.
*/
package nl.b3p.brmo.loader.xml;
import nl.b3p.brmo.loader.BrmoFramework;
import nl.b3p.brmo.loader.StagingProxy;
import nl.b3p.brmo.loader.entity.Bericht;
import nl.b3p.brmo.loader.entity.WozBericht;
import nl.b3p.brmo.loader.util.RsgbTransformer;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WozXMLReader extends BrmoXMLReader {
public static final String PREFIX_PRS = "WOZ.NPS.";
public static final String PREFIX_NNP = "WOZ.NNP.";
public static final String PREFIX_WOZ = "WOZ.WOZ.";
public static final String PREFIX_VES = "WOZ.VES.";
private static final Log LOG = LogFactory.getLog(WozXMLReader.class);
private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl";
private final StagingProxy staging;
private final XPathFactory xPathfactory = XPathFactory.newInstance();
private InputStream in;
private Templates template;
private NodeList objectNodes = null;
private int index;
private String brOrigXML = null;
public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception {
this.in = in;
this.staging = staging;
setBestandsDatum(d);
init();
}
@Override
public void init() throws Exception {
soort = BrmoFramework.BR_WOZ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in = new TeeInputStream(in, bos, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
brOrigXML = bos.toString(StandardCharsets.UTF_8);
LOG.trace("Originele WOZ xml is: \n" + brOrigXML);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setURIResolver((href, base) -> {
LOG.debug("looking for: " + href + " base: " + base);
return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href));
});
Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl));
this.template = tf.newTemplates(xsl);
XPath xpath = xPathfactory.newXPath();
if (this.getBestandsDatum() == null) {
// probeer datum nog uit doc te halen..
LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht.");
XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']");
Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE);
setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS");
LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum());
}
// woz:object nodes
XPathExpression objectNode = xpath.compile("//*[local-name()='object']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
// mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01)
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NPS omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NNP omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente VES omhangbericht");
}
}
index = 0;
}
@Override
public boolean hasNext() throws Exception {
return index < objectNodes.getLength();
}
@Override
public WozBericht next() throws Exception {
Node n = objectNodes.item(index);
index++;
String object_ref = getObjectRef(n);
StringWriter sw = new StringWriter();
// kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone.
Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder());
Transformer t;
if (old != null) {
LOG.debug("gebruik preprocessor xsl");
t = this.template.newTransformer();
} else {
LOG.debug("gebruik extractie xsl");
t = TransformerFactory.newInstance().newTransformer();
}
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "no");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.transform(new DOMSource(n), new StreamResult(sw));
Map<String, String> bsns = extractBSN(n);
String el = getXML(bsns);
String origXML = sw.toString();
String brXML = "<root>" + origXML;
brXML += el + "</root>";
WozBericht b = new WozBericht(brXML);
b.setDatum(getBestandsDatum());
if (index == 1) {
// alleen op 1e brmo bericht van mogelijk meer uit originele bericht
b.setBrOrgineelXml(brOrigXML);
}
// TODO volgorde nummer:
// bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere
// object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS"
// bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref
// van een NPS, maar met een hoger volgordenummer...
// vooralsnog halen we niet de geneste entiteiten uit het bericht
b.setVolgordeNummer(index);
if (index > 1) {
// om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken
b.setDatum(new Date(getBestandsDatum().getTime() + 10));
}
b.setObjectRef(object_ref);
if (StringUtils.isEmpty(b.getObjectRef())) {
// geen object_ref kunnen vaststellen; dan ook niet transformeren
b.setStatus(Bericht.STATUS.STAGING_NOK);
b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht.");
}
LOG.trace("bericht: " + b);
return b;
}
private String getObjectRef(Node wozObjectNode) throws XPathExpressionException {
// WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer
XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']");
NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn
XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']");
obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_PRS + getHash(obRefs.item(0).getTextContent());
}
// WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId
XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld...
// WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer
nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id.");
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer
XPathExpression wrd = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']");
obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer
XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']");
obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_VES + obRefs.item(0).getTextContent();
}
return null;
}
/**
* maakt een map met bsn,bsnhash.
*
* @param n document node met bsn-nummer
* @return hashmap met bsn,bsnhash
* @throws XPathExpressionException if any
*/
public Map<String, String> extractBSN(Node n) throws XPathExpressionException {
Map<String, String> hashes = new HashMap<>();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']");
NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
for (int i = 0; i < nodelist.getLength(); i++) {
Node bsn = nodelist.item(i);
String bsnString = bsn.getTextContent();
String hash = getHash(bsnString);
hashes.put(bsnString, hash);
}
return hashes;
}
public String getXML(Map<String, String> map) throws ParserConfigurationException {
if (map.isEmpty()) {
// als in bericht geen personen zitten
return "";
}
String root = "<bsnhashes>";
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) {
String hash = entry.getValue();
String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">";
root += el;
}
}
root += "</bsnhashes>";
return root;
}
}
| opengeogroep/brmo | brmo-loader/src/main/java/nl/b3p/brmo/loader/xml/WozXMLReader.java | 4,086 | /*[local-name()='inn.nnpId']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld...
// WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer
nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id.");
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer
XPathExpression wrd = xPathfactory.newXPath().compile("./*/ | block_comment | nl | /*
* Copyright (C) 2021 B3Partners B.V.
*/
package nl.b3p.brmo.loader.xml;
import nl.b3p.brmo.loader.BrmoFramework;
import nl.b3p.brmo.loader.StagingProxy;
import nl.b3p.brmo.loader.entity.Bericht;
import nl.b3p.brmo.loader.entity.WozBericht;
import nl.b3p.brmo.loader.util.RsgbTransformer;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WozXMLReader extends BrmoXMLReader {
public static final String PREFIX_PRS = "WOZ.NPS.";
public static final String PREFIX_NNP = "WOZ.NNP.";
public static final String PREFIX_WOZ = "WOZ.WOZ.";
public static final String PREFIX_VES = "WOZ.VES.";
private static final Log LOG = LogFactory.getLog(WozXMLReader.class);
private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl";
private final StagingProxy staging;
private final XPathFactory xPathfactory = XPathFactory.newInstance();
private InputStream in;
private Templates template;
private NodeList objectNodes = null;
private int index;
private String brOrigXML = null;
public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception {
this.in = in;
this.staging = staging;
setBestandsDatum(d);
init();
}
@Override
public void init() throws Exception {
soort = BrmoFramework.BR_WOZ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in = new TeeInputStream(in, bos, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
brOrigXML = bos.toString(StandardCharsets.UTF_8);
LOG.trace("Originele WOZ xml is: \n" + brOrigXML);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setURIResolver((href, base) -> {
LOG.debug("looking for: " + href + " base: " + base);
return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href));
});
Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl));
this.template = tf.newTemplates(xsl);
XPath xpath = xPathfactory.newXPath();
if (this.getBestandsDatum() == null) {
// probeer datum nog uit doc te halen..
LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht.");
XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']");
Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE);
setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS");
LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum());
}
// woz:object nodes
XPathExpression objectNode = xpath.compile("//*[local-name()='object']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
// mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01)
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NPS omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NNP omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente VES omhangbericht");
}
}
index = 0;
}
@Override
public boolean hasNext() throws Exception {
return index < objectNodes.getLength();
}
@Override
public WozBericht next() throws Exception {
Node n = objectNodes.item(index);
index++;
String object_ref = getObjectRef(n);
StringWriter sw = new StringWriter();
// kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone.
Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder());
Transformer t;
if (old != null) {
LOG.debug("gebruik preprocessor xsl");
t = this.template.newTransformer();
} else {
LOG.debug("gebruik extractie xsl");
t = TransformerFactory.newInstance().newTransformer();
}
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "no");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.transform(new DOMSource(n), new StreamResult(sw));
Map<String, String> bsns = extractBSN(n);
String el = getXML(bsns);
String origXML = sw.toString();
String brXML = "<root>" + origXML;
brXML += el + "</root>";
WozBericht b = new WozBericht(brXML);
b.setDatum(getBestandsDatum());
if (index == 1) {
// alleen op 1e brmo bericht van mogelijk meer uit originele bericht
b.setBrOrgineelXml(brOrigXML);
}
// TODO volgorde nummer:
// bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere
// object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS"
// bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref
// van een NPS, maar met een hoger volgordenummer...
// vooralsnog halen we niet de geneste entiteiten uit het bericht
b.setVolgordeNummer(index);
if (index > 1) {
// om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken
b.setDatum(new Date(getBestandsDatum().getTime() + 10));
}
b.setObjectRef(object_ref);
if (StringUtils.isEmpty(b.getObjectRef())) {
// geen object_ref kunnen vaststellen; dan ook niet transformeren
b.setStatus(Bericht.STATUS.STAGING_NOK);
b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht.");
}
LOG.trace("bericht: " + b);
return b;
}
private String getObjectRef(Node wozObjectNode) throws XPathExpressionException {
// WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer
XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']");
NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn
XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']");
obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_PRS + getHash(obRefs.item(0).getTextContent());
}
// WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId
XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']");
<SUF>*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']");
obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer
XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']");
obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_VES + obRefs.item(0).getTextContent();
}
return null;
}
/**
* maakt een map met bsn,bsnhash.
*
* @param n document node met bsn-nummer
* @return hashmap met bsn,bsnhash
* @throws XPathExpressionException if any
*/
public Map<String, String> extractBSN(Node n) throws XPathExpressionException {
Map<String, String> hashes = new HashMap<>();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']");
NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
for (int i = 0; i < nodelist.getLength(); i++) {
Node bsn = nodelist.item(i);
String bsnString = bsn.getTextContent();
String hash = getHash(bsnString);
hashes.put(bsnString, hash);
}
return hashes;
}
public String getXML(Map<String, String> map) throws ParserConfigurationException {
if (map.isEmpty()) {
// als in bericht geen personen zitten
return "";
}
String root = "<bsnhashes>";
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) {
String hash = entry.getValue();
String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">";
root += el;
}
}
root += "</bsnhashes>";
return root;
}
}
|
195993_4 | package nl.opengeogroep.safetymaps.viewer;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static nl.opengeogroep.safetymaps.server.db.JSONUtils.rowToJson;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Class to export object data for safetymaps-viewer, meant for both online use
* within safetymaps-server and for exporting to filesystem for offline viewers.
*
* @author Matthijs Laan
*/
public class ViewerDataExporter {
// TODO LogFactory use, so errors get logged both online and when exporting
private Connection c;
public ViewerDataExporter(Connection c) {
this.c = c;
}
/**
* Get a tag with the latest date an object was modified and total object
* count, to use as caching ETag.
*/
public String getObjectsETag() throws Exception {
String key = new QueryRunner().query(c, "select max(datum_actualisatie) || '_' || count(*) from viewer.viewer_object", new ScalarHandler<String>());
key += "_v" + new QueryRunner().query(c, "select max(value) from viewer.schema_version", new ScalarHandler<>());
if(key == null) {
return "empty_db";
} else {
return key;
}
}
/**
* @return All the objects that should be visible in the viewer with all object
* properties needed by the viewer as a JSON array, without properties that are
* null or empty strings.
*/
public JSONArray getViewerObjectMapOverview() throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_map", new MapListHandler());
// Not efficient in PostgreSQL: selectieadressen and verdiepingen
Set<Integer> verdiepingenIds = new HashSet(new QueryRunner().query(c, "select hoofdobject_id from viewer.viewer_object where hoofdobject_id is not null", new ColumnListHandler<>()));
Map selectieadressen = new QueryRunner().query(c, "select * from viewer.viewer_object_selectieadressen", new KeyedHandler<>("id"));
JSONArray a = new JSONArray();
for(Map<String, Object> row: rows) {
Integer id = (Integer)row.get("id");
String name = (String)row.get("formele_naam");
try {
JSONObject o = rowToJson(row, true, true);
if(verdiepingenIds.contains(id)) {
o.put("heeft_verdiepingen", true);
}
Map sa = (Map)selectieadressen.get(id);
if(sa != null) {
o.put("selectieadressen", new JSONArray(sa.get("selectieadressen").toString()));
}
a.put(o);
} catch(Exception e) {
throw new Exception(String.format("Error processing object id=%d, name \"%s\"", id, name), e);
}
}
return a;
}
/**
* @return All details for the viewer of an objector null
* if the object is not found or visible in the viewer
*/
public JSONObject getViewerObjectDetails(long id) throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details where id = ?", new MapListHandler(), id);
if(rows.isEmpty()) {
return null;
}
try {
return rowToJson(rows.get(0), true, true);
} catch(Exception e) {
throw new Exception(String.format("Error getting object details for id " + id), e);
}
}
/**
* Get all ids of objects that should be visible in the viewer.
*/
public List<Integer> getViewerObjectIds() throws Exception {
return new QueryRunner().query(c, "select id from viewer.viewer_object_map", new ColumnListHandler<Integer>());
}
/**
* @return All details for viewer objects using a single query
*/
public List<JSONObject> getAllViewerObjectDetails() throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details", new MapListHandler());
List<JSONObject> result = new ArrayList();
for(Map<String,Object> row: rows) {
Object id = row.get("id");
Object name = row.get("name");
try {
result.add(rowToJson(row, true, true));
} catch(Exception e) {
throw new Exception(String.format("Error converting object details to JSON for id " + id + ", name " + name), e);
}
}
return result;
}
/**
* Get styling information
*/
public JSONObject getStyles() throws Exception {
JSONObject o = new JSONObject();
JSONObject compartments = new JSONObject();
o.put("compartments", compartments);
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from wfs.type_compartment", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject compartment = rowToJson(row, false, false);
compartments.put(code, compartment);
}
JSONObject lines = new JSONObject();
o.put("custom_lines", lines);
rows = new QueryRunner().query(c, "select * from wfs.type_custom_line", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject line = rowToJson(row, false, false);
lines.put(code, line);
}
JSONObject polygons = new JSONObject();
o.put("custom_polygons", polygons);
rows = new QueryRunner().query(c, "select * from wfs.type_custom_polygon", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject polygon = rowToJson(row, false, false);
polygons.put(code, polygon);
}
return o;
}
}
| opengeogroep/safetymaps-server | src/main/java/nl/opengeogroep/safetymaps/viewer/ViewerDataExporter.java | 1,811 | // Not efficient in PostgreSQL: selectieadressen and verdiepingen | line_comment | nl | package nl.opengeogroep.safetymaps.viewer;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static nl.opengeogroep.safetymaps.server.db.JSONUtils.rowToJson;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Class to export object data for safetymaps-viewer, meant for both online use
* within safetymaps-server and for exporting to filesystem for offline viewers.
*
* @author Matthijs Laan
*/
public class ViewerDataExporter {
// TODO LogFactory use, so errors get logged both online and when exporting
private Connection c;
public ViewerDataExporter(Connection c) {
this.c = c;
}
/**
* Get a tag with the latest date an object was modified and total object
* count, to use as caching ETag.
*/
public String getObjectsETag() throws Exception {
String key = new QueryRunner().query(c, "select max(datum_actualisatie) || '_' || count(*) from viewer.viewer_object", new ScalarHandler<String>());
key += "_v" + new QueryRunner().query(c, "select max(value) from viewer.schema_version", new ScalarHandler<>());
if(key == null) {
return "empty_db";
} else {
return key;
}
}
/**
* @return All the objects that should be visible in the viewer with all object
* properties needed by the viewer as a JSON array, without properties that are
* null or empty strings.
*/
public JSONArray getViewerObjectMapOverview() throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_map", new MapListHandler());
// Not efficient<SUF>
Set<Integer> verdiepingenIds = new HashSet(new QueryRunner().query(c, "select hoofdobject_id from viewer.viewer_object where hoofdobject_id is not null", new ColumnListHandler<>()));
Map selectieadressen = new QueryRunner().query(c, "select * from viewer.viewer_object_selectieadressen", new KeyedHandler<>("id"));
JSONArray a = new JSONArray();
for(Map<String, Object> row: rows) {
Integer id = (Integer)row.get("id");
String name = (String)row.get("formele_naam");
try {
JSONObject o = rowToJson(row, true, true);
if(verdiepingenIds.contains(id)) {
o.put("heeft_verdiepingen", true);
}
Map sa = (Map)selectieadressen.get(id);
if(sa != null) {
o.put("selectieadressen", new JSONArray(sa.get("selectieadressen").toString()));
}
a.put(o);
} catch(Exception e) {
throw new Exception(String.format("Error processing object id=%d, name \"%s\"", id, name), e);
}
}
return a;
}
/**
* @return All details for the viewer of an objector null
* if the object is not found or visible in the viewer
*/
public JSONObject getViewerObjectDetails(long id) throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details where id = ?", new MapListHandler(), id);
if(rows.isEmpty()) {
return null;
}
try {
return rowToJson(rows.get(0), true, true);
} catch(Exception e) {
throw new Exception(String.format("Error getting object details for id " + id), e);
}
}
/**
* Get all ids of objects that should be visible in the viewer.
*/
public List<Integer> getViewerObjectIds() throws Exception {
return new QueryRunner().query(c, "select id from viewer.viewer_object_map", new ColumnListHandler<Integer>());
}
/**
* @return All details for viewer objects using a single query
*/
public List<JSONObject> getAllViewerObjectDetails() throws Exception {
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details", new MapListHandler());
List<JSONObject> result = new ArrayList();
for(Map<String,Object> row: rows) {
Object id = row.get("id");
Object name = row.get("name");
try {
result.add(rowToJson(row, true, true));
} catch(Exception e) {
throw new Exception(String.format("Error converting object details to JSON for id " + id + ", name " + name), e);
}
}
return result;
}
/**
* Get styling information
*/
public JSONObject getStyles() throws Exception {
JSONObject o = new JSONObject();
JSONObject compartments = new JSONObject();
o.put("compartments", compartments);
List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from wfs.type_compartment", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject compartment = rowToJson(row, false, false);
compartments.put(code, compartment);
}
JSONObject lines = new JSONObject();
o.put("custom_lines", lines);
rows = new QueryRunner().query(c, "select * from wfs.type_custom_line", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject line = rowToJson(row, false, false);
lines.put(code, line);
}
JSONObject polygons = new JSONObject();
o.put("custom_polygons", polygons);
rows = new QueryRunner().query(c, "select * from wfs.type_custom_polygon", new MapListHandler());
for(Map<String,Object> row: rows) {
String code = (String)row.get("code");
JSONObject polygon = rowToJson(row, false, false);
polygons.put(code, polygon);
}
return o;
}
}
|
85026_1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.extension.enums;
/**
* Del enum.
*/
public enum DelEnum {
/**
* Normal state
*/
NORMAL("0"),
/**
* Deleted state
*/
DELETE("1");
private final String statusCode;
DelEnum(String statusCode) {
this.statusCode = statusCode;
}
public String getCode() {
return this.statusCode;
}
public Integer getIntCode() {
return Integer.parseInt(this.statusCode);
}
@Override
public String toString() {
return statusCode;
}
}
| opengoofy/hippo4j | infra/common/src/main/java/cn/hippo4j/common/extension/enums/DelEnum.java | 354 | /**
* Del enum.
*/ | block_comment | nl | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.extension.enums;
/**
* Del enum.
<SUF>*/
public enum DelEnum {
/**
* Normal state
*/
NORMAL("0"),
/**
* Deleted state
*/
DELETE("1");
private final String statusCode;
DelEnum(String statusCode) {
this.statusCode = statusCode;
}
public String getCode() {
return this.statusCode;
}
public Integer getIntCode() {
return Integer.parseInt(this.statusCode);
}
@Override
public String toString() {
return statusCode;
}
}
|
200236_42 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
// in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
// in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
// in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SIMPLE_STATE {
{
command = "simple_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SIMPLE_STATE_NUM {
{
command = "simple_state_num";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SWITCHOFF_REASON_0 {
{
command = "switchoff_reason_0";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SWITCHOFF_CODE_0 {
{
command = "switchoff_code_0";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
// in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
// in german Solltemp MK1
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
// in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
// in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
},
// in german AV (Abtauventil)
TYPE_OUTPUT_AV {
{
command = "output_av";
itemClass = SwitchItem.class;
}
},
// in german BUP (Brauchwasserpumpe/Umstellventil)
TYPE_OUTPUT_BUP {
{
command = "output_bup";
itemClass = SwitchItem.class;
}
},
// in german HUP (Heizungsumwälzpumpe)
TYPE_OUTPUT_HUP {
{
command = "output_hup";
itemClass = SwitchItem.class;
}
},
// in german MA1 (Mischkreis 1 auf)
TYPE_OUTPUT_MA1 {
{
command = "output_ma1";
itemClass = SwitchItem.class;
}
},
// in german MZ1 (Mischkreis 1 zu)
TYPE_OUTPUT_MZ1 {
{
command = "output_mz1";
itemClass = SwitchItem.class;
}
},
// in german VEN (Ventilation/Lüftung)
TYPE_OUTPUT_VEN {
{
command = "output_ven";
itemClass = SwitchItem.class;
}
},
// in german VBO (Solepumpe/Ventilator)
TYPE_OUTPUT_VBO {
{
command = "output_vbo";
itemClass = SwitchItem.class;
}
},
// in german VD1 (Verdichter 1)
TYPE_OUTPUT_VD1 {
{
command = "output_vd1";
itemClass = SwitchItem.class;
}
},
// in german VD2 (Verdichter 2)
TYPE_OUTPUT_VD2 {
{
command = "output_vd2";
itemClass = SwitchItem.class;
}
},
// in german ZIP (Zirkulationspumpe)
TYPE_OUTPUT_ZIP {
{
command = "output_zip";
itemClass = SwitchItem.class;
}
},
// in german ZUP (Zusatzumwälzpumpe)
TYPE_OUTPUT_ZUP {
{
command = "output_zup";
itemClass = SwitchItem.class;
}
},
// in german ZW1 (Steuersignal Zusatzheizung v. Heizung)
TYPE_OUTPUT_ZW1 {
{
command = "output_zw1";
itemClass = SwitchItem.class;
}
},
// in german ZW2 (Steuersignal Zusatzheizung/Störsignal)
TYPE_OUTPUT_ZW2SST {
{
command = "output_zw2sst";
itemClass = SwitchItem.class;
}
},
// in german ZW3 (Zusatzheizung 3)
TYPE_OUTPUT_ZW3SST {
{
command = "output_zw3sst";
itemClass = SwitchItem.class;
}
},
// in german FP2 (Pumpe Mischkreis 2)
TYPE_OUTPUT_FP2 {
{
command = "output_fp2";
itemClass = SwitchItem.class;
}
},
// in german SLP (Solarladepumpe)
TYPE_OUTPUT_SLP {
{
command = "output_slp";
itemClass = SwitchItem.class;
}
},
// in german SUP (Schwimmbadpumpe)
TYPE_OUTPUT_SUP {
{
command = "output_sup";
itemClass = SwitchItem.class;
}
},
// in german MA2 (Mischkreis 2 auf)
TYPE_OUTPUT_MA2 {
{
command = "output_ma2";
itemClass = SwitchItem.class;
}
},
// in german MZ2 (Mischkreis 2 zu)
TYPE_OUTPUT_MZ2 {
{
command = "output_mz2";
itemClass = SwitchItem.class;
}
},
// in german MA3 (Mischkreis 3 auf)
TYPE_OUTPUT_MA3 {
{
command = "output_ma3";
itemClass = SwitchItem.class;
}
},
// in german MZ3 (Mischkreis 3 zu)
TYPE_OUTPUT_MZ3 {
{
command = "output_mz3";
itemClass = SwitchItem.class;
}
},
// in german FP3 (Pumpe Mischkreis 3)
TYPE_OUTPUT_FP3 {
{
command = "output_fp3";
itemClass = SwitchItem.class;
}
},
// in german VSK
TYPE_OUTPUT_VSK {
{
command = "output_vsk";
itemClass = SwitchItem.class;
}
},
// in german FRH
TYPE_OUTPUT_FRH {
{
command = "output_frh";
itemClass = SwitchItem.class;
}
},
// in german VDH (Verdichterheizung)
TYPE_OUTPUT_VDH {
{
command = "output_vdh";
itemClass = SwitchItem.class;
}
},
// in german AV2 (Abtauventil 2)
TYPE_OUTPUT_AV2 {
{
command = "output_av2";
itemClass = SwitchItem.class;
}
},
// in german VBO2 (Solepumpe/Ventilator)
TYPE_OUTPUT_VBO2 {
{
command = "output_vbo2";
itemClass = SwitchItem.class;
}
},
// in german VD12 (Verdichter 1/2)
TYPE_OUTPUT_VD12 {
{
command = "output_vd12";
itemClass = SwitchItem.class;
}
},
// in german VDH2 (Verdichterheizung 2)
TYPE_OUTPUT_VDH2 {
{
command = "output_vdh2";
itemClass = SwitchItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'");
}
}
| openhab-sandbox/openhab1-addons | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 5,097 | // in german AV (Abtauventil) | line_comment | nl | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
// in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
// in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
// in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
// in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SIMPLE_STATE {
{
command = "simple_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SIMPLE_STATE_NUM {
{
command = "simple_state_num";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SWITCHOFF_REASON_0 {
{
command = "switchoff_reason_0";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SWITCHOFF_CODE_0 {
{
command = "switchoff_code_0";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
// in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperature";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperature";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung Betriebsart
TYPE_COOLING_OPERATION_MODE {
{
command = "cooling_operation_mode";
itemClass = NumberItem.class;
}
},
// in german Comfort Kühlung AT-Freigabe
TYPE_COOLING_RELEASE_TEMPERATURE {
{
command = "cooling_release_temperature";
itemClass = NumberItem.class;
}
},
// in german Solltemp MK1
TYPE_COOLING_INLET_TEMP {
{
command = "cooling_inlet_temperature";
itemClass = NumberItem.class;
}
},
// in german AT-Überschreitung
TYPE_COOLING_START_AFTER_HOURS {
{
command = "cooling_start_hours";
itemClass = NumberItem.class;
}
},
// in german AT-Unterschreitung
TYPE_COOLING_STOP_AFTER_HOURS {
{
command = "cooling_stop_hours";
itemClass = NumberItem.class;
}
},
// in german<SUF>
TYPE_OUTPUT_AV {
{
command = "output_av";
itemClass = SwitchItem.class;
}
},
// in german BUP (Brauchwasserpumpe/Umstellventil)
TYPE_OUTPUT_BUP {
{
command = "output_bup";
itemClass = SwitchItem.class;
}
},
// in german HUP (Heizungsumwälzpumpe)
TYPE_OUTPUT_HUP {
{
command = "output_hup";
itemClass = SwitchItem.class;
}
},
// in german MA1 (Mischkreis 1 auf)
TYPE_OUTPUT_MA1 {
{
command = "output_ma1";
itemClass = SwitchItem.class;
}
},
// in german MZ1 (Mischkreis 1 zu)
TYPE_OUTPUT_MZ1 {
{
command = "output_mz1";
itemClass = SwitchItem.class;
}
},
// in german VEN (Ventilation/Lüftung)
TYPE_OUTPUT_VEN {
{
command = "output_ven";
itemClass = SwitchItem.class;
}
},
// in german VBO (Solepumpe/Ventilator)
TYPE_OUTPUT_VBO {
{
command = "output_vbo";
itemClass = SwitchItem.class;
}
},
// in german VD1 (Verdichter 1)
TYPE_OUTPUT_VD1 {
{
command = "output_vd1";
itemClass = SwitchItem.class;
}
},
// in german VD2 (Verdichter 2)
TYPE_OUTPUT_VD2 {
{
command = "output_vd2";
itemClass = SwitchItem.class;
}
},
// in german ZIP (Zirkulationspumpe)
TYPE_OUTPUT_ZIP {
{
command = "output_zip";
itemClass = SwitchItem.class;
}
},
// in german ZUP (Zusatzumwälzpumpe)
TYPE_OUTPUT_ZUP {
{
command = "output_zup";
itemClass = SwitchItem.class;
}
},
// in german ZW1 (Steuersignal Zusatzheizung v. Heizung)
TYPE_OUTPUT_ZW1 {
{
command = "output_zw1";
itemClass = SwitchItem.class;
}
},
// in german ZW2 (Steuersignal Zusatzheizung/Störsignal)
TYPE_OUTPUT_ZW2SST {
{
command = "output_zw2sst";
itemClass = SwitchItem.class;
}
},
// in german ZW3 (Zusatzheizung 3)
TYPE_OUTPUT_ZW3SST {
{
command = "output_zw3sst";
itemClass = SwitchItem.class;
}
},
// in german FP2 (Pumpe Mischkreis 2)
TYPE_OUTPUT_FP2 {
{
command = "output_fp2";
itemClass = SwitchItem.class;
}
},
// in german SLP (Solarladepumpe)
TYPE_OUTPUT_SLP {
{
command = "output_slp";
itemClass = SwitchItem.class;
}
},
// in german SUP (Schwimmbadpumpe)
TYPE_OUTPUT_SUP {
{
command = "output_sup";
itemClass = SwitchItem.class;
}
},
// in german MA2 (Mischkreis 2 auf)
TYPE_OUTPUT_MA2 {
{
command = "output_ma2";
itemClass = SwitchItem.class;
}
},
// in german MZ2 (Mischkreis 2 zu)
TYPE_OUTPUT_MZ2 {
{
command = "output_mz2";
itemClass = SwitchItem.class;
}
},
// in german MA3 (Mischkreis 3 auf)
TYPE_OUTPUT_MA3 {
{
command = "output_ma3";
itemClass = SwitchItem.class;
}
},
// in german MZ3 (Mischkreis 3 zu)
TYPE_OUTPUT_MZ3 {
{
command = "output_mz3";
itemClass = SwitchItem.class;
}
},
// in german FP3 (Pumpe Mischkreis 3)
TYPE_OUTPUT_FP3 {
{
command = "output_fp3";
itemClass = SwitchItem.class;
}
},
// in german VSK
TYPE_OUTPUT_VSK {
{
command = "output_vsk";
itemClass = SwitchItem.class;
}
},
// in german FRH
TYPE_OUTPUT_FRH {
{
command = "output_frh";
itemClass = SwitchItem.class;
}
},
// in german VDH (Verdichterheizung)
TYPE_OUTPUT_VDH {
{
command = "output_vdh";
itemClass = SwitchItem.class;
}
},
// in german AV2 (Abtauventil 2)
TYPE_OUTPUT_AV2 {
{
command = "output_av2";
itemClass = SwitchItem.class;
}
},
// in german VBO2 (Solepumpe/Ventilator)
TYPE_OUTPUT_VBO2 {
{
command = "output_vbo2";
itemClass = SwitchItem.class;
}
},
// in german VD12 (Verdichter 1/2)
TYPE_OUTPUT_VD12 {
{
command = "output_vd12";
itemClass = SwitchItem.class;
}
},
// in german VDH2 (Verdichterheizung 2)
TYPE_OUTPUT_VDH2 {
{
command = "output_vdh2";
itemClass = SwitchItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'");
}
}
|
177071_18 | /**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.tapocontrol.internal.api.protocol.klap;
import static org.openhab.binding.tapocontrol.internal.TapoControlHandlerFactory.GSON;
import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*;
import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorCode.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.ByteUtils.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.JsonUtils.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.TapoUtils.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpResponse;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.BufferingResponseListener;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.openhab.binding.tapocontrol.internal.api.TapoConnectorInterface;
import org.openhab.binding.tapocontrol.internal.dto.TapoBaseRequestInterface;
import org.openhab.binding.tapocontrol.internal.dto.TapoRequest;
import org.openhab.binding.tapocontrol.internal.dto.TapoResponse;
import org.openhab.binding.tapocontrol.internal.helpers.TapoCredentials;
import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handler class for TAPO-KLAP-Protocol
*
* @author Christian Wild - Initial contribution
*/
@NonNullByDefault
public class KlapProtocol implements org.openhab.binding.tapocontrol.internal.api.protocol.TapoProtocolInterface {
private final Logger logger = LoggerFactory.getLogger(KlapProtocol.class);
protected final TapoConnectorInterface httpDelegator;
private KlapSession session;
private String uid;
/***********************
* Init Class
**********************/
public KlapProtocol(TapoConnectorInterface httpDelegator) {
this.httpDelegator = httpDelegator;
session = new KlapSession(this);
uid = httpDelegator.getThingUID() + " / HTTP-KLAP";
}
@Override
public boolean login(TapoCredentials tapoCredentials) throws TapoErrorHandler {
logger.trace("({}) login to device", uid);
session.reset();
session.login(tapoCredentials);
return isLoggedIn();
}
@Override
public void logout() {
session.reset();
}
@Override
public boolean isLoggedIn() {
return session.isHandshakeComplete() && session.seedIsOkay() && !session.isExpired();
}
/***********************
* Request Sender
**********************/
/*
* send synchron request - response will be handled in [responseReceived()] function
*/
@Override
public void sendRequest(TapoRequest tapoRequest) throws TapoErrorHandler {
String url = getUrl();
String command = tapoRequest.method();
logger.trace("({}) sending unencrypted request: '{}' to '{}' ", uid, tapoRequest, url);
Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
/* set header */
httpRequest = setHeaders(httpRequest);
httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
/* add request body */
httpRequest.content(new StringContentProvider(tapoRequest.toString(), CONTENT_CHARSET), CONTENT_TYPE_JSON);
try {
responseReceived(httpRequest.send(), command);
} catch (Exception e) {
throw new TapoErrorHandler(e, "error sending content");
}
}
/**
* handle asynchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void sendAsyncRequest(TapoBaseRequestInterface tapoRequest) throws TapoErrorHandler {
String url = getUrl();
String command = tapoRequest.method();
logger.trace("({}) sendAsync unencrypted request: '{}' to '{}' ", uid, tapoRequest, url);
/* encrypt request */
byte[] encodedBytes = session.encryptRequest(tapoRequest);
String encrypteString = byteArrayToHex(encodedBytes);
Integer ivSequence = session.getIvSequence();
logger.trace("({}) encrypted request is '{}' with sequence '{}'", uid, encrypteString, ivSequence);
Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
/* set header and params */
httpRequest = setHeaders(httpRequest);
httpRequest.param("seq", ivSequence.toString());
/* add request body */
httpRequest.content(new BytesContentProvider(encodedBytes));
httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() {
@NonNullByDefault({})
@Override
public void onComplete(Result result) {
final HttpResponse response = (HttpResponse) result.getResponse();
if (result.getFailure() != null) {
/* handle result errors */
Throwable e = result.getFailure();
String errorMessage = getValueOrDefault(e.getMessage(), "");
/* throw errors to delegator */
if (e instanceof TimeoutException) {
logger.debug("({}) sendAsyncRequest timeout'{}'", uid, errorMessage);
httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_CONNECT_TIMEOUT, errorMessage));
} else {
logger.debug("({}) sendAsyncRequest failed'{}'", uid, errorMessage);
httpDelegator.handleError(new TapoErrorHandler(new Exception(e), errorMessage));
}
} else if (response.getStatus() != 200) {
logger.debug("({}) sendAsyncRequest response error'{}'", uid, response.getStatus());
httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString()));
} else {
/* request successful */
byte[] responseBytes = getContent();
try {
encryptedResponseReceived(responseBytes, ivSequence, command);
} catch (TapoErrorHandler tapoError) {
httpDelegator.handleError(tapoError);
}
}
}
});
}
/************************
* RESPONSE HANDLERS
************************/
/**
* handle synchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void responseReceived(ContentResponse response, String command) throws TapoErrorHandler {
logger.trace("({}) received response content: '{}'", uid, response.getContentAsString());
TapoResponse tapoResponse = getTapoResponse(response);
httpDelegator.handleResponse(tapoResponse, command);
httpDelegator.responsePasstrough(response.getContentAsString(), command);
}
/**
* handle asynchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void asyncResponseReceived(String content, String command) throws TapoErrorHandler {
try {
TapoResponse tapoResponse = getTapoResponse(content);
httpDelegator.handleResponse(tapoResponse, command);
} catch (TapoErrorHandler tapoError) {
httpDelegator.handleError(tapoError);
}
}
/**
* handle encrypted response. decrypt it and pass to asyncRequestReceived
*
* @param content bytearray with encrypted payload
* @param ivSeq ivSequence-Number which is incremented each request
* @param command command was sent to device
* @throws TapoErrorHandler
*/
public void encryptedResponseReceived(byte[] content, Integer ivSeq, String command) throws TapoErrorHandler {
String stringContent = byteArrayToHex(content);
logger.trace("({}) receivedRespose '{}'", uid, stringContent);
String decryptedResponse = session.decryptResponse(content, ivSeq);
logger.trace("({}) decrypted response: '{}'", uid, decryptedResponse);
asyncResponseReceived(decryptedResponse, command);
}
/**
* Get Tapo-Response from Contentresponse
* decrypt if is encrypted
*/
protected TapoResponse getTapoResponse(ContentResponse response) throws TapoErrorHandler {
if (response.getStatus() == 200) {
return getTapoResponse(response.getContentAsString());
} else {
logger.debug("({}) invalid response received", uid);
throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved");
}
}
/**
* Get Tapo-Response from responsestring
* decrypt if is encrypted
*/
protected TapoResponse getTapoResponse(String responseString) throws TapoErrorHandler {
if (isValidJson(responseString)) {
TapoResponse tapoResponse = Objects.requireNonNull(GSON.fromJson(responseString, TapoResponse.class));
if (tapoResponse.hasError()) {
throw new TapoErrorHandler(tapoResponse.errorCode(), tapoResponse.message());
}
return tapoResponse;
} else {
logger.debug("({}) invalid response received", uid);
throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved");
}
}
/************************
* PRIVATE HELPERS
************************/
protected String getUrl() {
String baseUrl = String.format(TAPO_DEVICE_URL, httpDelegator.getBaseUrl());
if (session.isHandshakeComplete()) {
return baseUrl + "/request";
} else {
return baseUrl;
}
}
/*
* Set HTTP-Headers
*/
protected Request setHeaders(Request httpRequest) {
if (!session.isHandshakeComplete()) {
httpRequest.header("content-type", CONTENT_TYPE_JSON);
httpRequest.header("Accept", CONTENT_TYPE_JSON);
}
if (!session.getCookie().isBlank()) {
httpRequest.header(HTTP_AUTH_TYPE_COOKIE, session.getCookie());
}
return httpRequest;
}
}
| openhab/openhab-addons | bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/api/protocol/klap/KlapProtocol.java | 3,075 | /*
* Set HTTP-Headers
*/ | block_comment | nl | /**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.tapocontrol.internal.api.protocol.klap;
import static org.openhab.binding.tapocontrol.internal.TapoControlHandlerFactory.GSON;
import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*;
import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorCode.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.ByteUtils.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.JsonUtils.*;
import static org.openhab.binding.tapocontrol.internal.helpers.utils.TapoUtils.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpResponse;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.BufferingResponseListener;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.openhab.binding.tapocontrol.internal.api.TapoConnectorInterface;
import org.openhab.binding.tapocontrol.internal.dto.TapoBaseRequestInterface;
import org.openhab.binding.tapocontrol.internal.dto.TapoRequest;
import org.openhab.binding.tapocontrol.internal.dto.TapoResponse;
import org.openhab.binding.tapocontrol.internal.helpers.TapoCredentials;
import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handler class for TAPO-KLAP-Protocol
*
* @author Christian Wild - Initial contribution
*/
@NonNullByDefault
public class KlapProtocol implements org.openhab.binding.tapocontrol.internal.api.protocol.TapoProtocolInterface {
private final Logger logger = LoggerFactory.getLogger(KlapProtocol.class);
protected final TapoConnectorInterface httpDelegator;
private KlapSession session;
private String uid;
/***********************
* Init Class
**********************/
public KlapProtocol(TapoConnectorInterface httpDelegator) {
this.httpDelegator = httpDelegator;
session = new KlapSession(this);
uid = httpDelegator.getThingUID() + " / HTTP-KLAP";
}
@Override
public boolean login(TapoCredentials tapoCredentials) throws TapoErrorHandler {
logger.trace("({}) login to device", uid);
session.reset();
session.login(tapoCredentials);
return isLoggedIn();
}
@Override
public void logout() {
session.reset();
}
@Override
public boolean isLoggedIn() {
return session.isHandshakeComplete() && session.seedIsOkay() && !session.isExpired();
}
/***********************
* Request Sender
**********************/
/*
* send synchron request - response will be handled in [responseReceived()] function
*/
@Override
public void sendRequest(TapoRequest tapoRequest) throws TapoErrorHandler {
String url = getUrl();
String command = tapoRequest.method();
logger.trace("({}) sending unencrypted request: '{}' to '{}' ", uid, tapoRequest, url);
Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
/* set header */
httpRequest = setHeaders(httpRequest);
httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
/* add request body */
httpRequest.content(new StringContentProvider(tapoRequest.toString(), CONTENT_CHARSET), CONTENT_TYPE_JSON);
try {
responseReceived(httpRequest.send(), command);
} catch (Exception e) {
throw new TapoErrorHandler(e, "error sending content");
}
}
/**
* handle asynchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void sendAsyncRequest(TapoBaseRequestInterface tapoRequest) throws TapoErrorHandler {
String url = getUrl();
String command = tapoRequest.method();
logger.trace("({}) sendAsync unencrypted request: '{}' to '{}' ", uid, tapoRequest, url);
/* encrypt request */
byte[] encodedBytes = session.encryptRequest(tapoRequest);
String encrypteString = byteArrayToHex(encodedBytes);
Integer ivSequence = session.getIvSequence();
logger.trace("({}) encrypted request is '{}' with sequence '{}'", uid, encrypteString, ivSequence);
Request httpRequest = httpDelegator.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
/* set header and params */
httpRequest = setHeaders(httpRequest);
httpRequest.param("seq", ivSequence.toString());
/* add request body */
httpRequest.content(new BytesContentProvider(encodedBytes));
httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() {
@NonNullByDefault({})
@Override
public void onComplete(Result result) {
final HttpResponse response = (HttpResponse) result.getResponse();
if (result.getFailure() != null) {
/* handle result errors */
Throwable e = result.getFailure();
String errorMessage = getValueOrDefault(e.getMessage(), "");
/* throw errors to delegator */
if (e instanceof TimeoutException) {
logger.debug("({}) sendAsyncRequest timeout'{}'", uid, errorMessage);
httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_CONNECT_TIMEOUT, errorMessage));
} else {
logger.debug("({}) sendAsyncRequest failed'{}'", uid, errorMessage);
httpDelegator.handleError(new TapoErrorHandler(new Exception(e), errorMessage));
}
} else if (response.getStatus() != 200) {
logger.debug("({}) sendAsyncRequest response error'{}'", uid, response.getStatus());
httpDelegator.handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, getContentAsString()));
} else {
/* request successful */
byte[] responseBytes = getContent();
try {
encryptedResponseReceived(responseBytes, ivSequence, command);
} catch (TapoErrorHandler tapoError) {
httpDelegator.handleError(tapoError);
}
}
}
});
}
/************************
* RESPONSE HANDLERS
************************/
/**
* handle synchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void responseReceived(ContentResponse response, String command) throws TapoErrorHandler {
logger.trace("({}) received response content: '{}'", uid, response.getContentAsString());
TapoResponse tapoResponse = getTapoResponse(response);
httpDelegator.handleResponse(tapoResponse, command);
httpDelegator.responsePasstrough(response.getContentAsString(), command);
}
/**
* handle asynchron request-response
* pushes (decrypted) TapoResponse to [httpDelegator.handleResponse()]-function
*/
@Override
public void asyncResponseReceived(String content, String command) throws TapoErrorHandler {
try {
TapoResponse tapoResponse = getTapoResponse(content);
httpDelegator.handleResponse(tapoResponse, command);
} catch (TapoErrorHandler tapoError) {
httpDelegator.handleError(tapoError);
}
}
/**
* handle encrypted response. decrypt it and pass to asyncRequestReceived
*
* @param content bytearray with encrypted payload
* @param ivSeq ivSequence-Number which is incremented each request
* @param command command was sent to device
* @throws TapoErrorHandler
*/
public void encryptedResponseReceived(byte[] content, Integer ivSeq, String command) throws TapoErrorHandler {
String stringContent = byteArrayToHex(content);
logger.trace("({}) receivedRespose '{}'", uid, stringContent);
String decryptedResponse = session.decryptResponse(content, ivSeq);
logger.trace("({}) decrypted response: '{}'", uid, decryptedResponse);
asyncResponseReceived(decryptedResponse, command);
}
/**
* Get Tapo-Response from Contentresponse
* decrypt if is encrypted
*/
protected TapoResponse getTapoResponse(ContentResponse response) throws TapoErrorHandler {
if (response.getStatus() == 200) {
return getTapoResponse(response.getContentAsString());
} else {
logger.debug("({}) invalid response received", uid);
throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved");
}
}
/**
* Get Tapo-Response from responsestring
* decrypt if is encrypted
*/
protected TapoResponse getTapoResponse(String responseString) throws TapoErrorHandler {
if (isValidJson(responseString)) {
TapoResponse tapoResponse = Objects.requireNonNull(GSON.fromJson(responseString, TapoResponse.class));
if (tapoResponse.hasError()) {
throw new TapoErrorHandler(tapoResponse.errorCode(), tapoResponse.message());
}
return tapoResponse;
} else {
logger.debug("({}) invalid response received", uid);
throw new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE, "invalid response receicved");
}
}
/************************
* PRIVATE HELPERS
************************/
protected String getUrl() {
String baseUrl = String.format(TAPO_DEVICE_URL, httpDelegator.getBaseUrl());
if (session.isHandshakeComplete()) {
return baseUrl + "/request";
} else {
return baseUrl;
}
}
/*
* Set HTTP-Headers
<SUF>*/
protected Request setHeaders(Request httpRequest) {
if (!session.isHandshakeComplete()) {
httpRequest.header("content-type", CONTENT_TYPE_JSON);
httpRequest.header("Accept", CONTENT_TYPE_JSON);
}
if (!session.getCookie().isBlank()) {
httpRequest.header(HTTP_AUTH_TYPE_COOKIE, session.getCookie());
}
return httpRequest;
}
}
|
97450_8 | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.tools.localfeature.options;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.CmdLineOptionsProvider;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.ProxyOptionHandler;
import org.openimaj.feature.local.LocalFeature;
import org.openimaj.feature.local.LocalFeatureExtractor;
import org.openimaj.feature.local.list.LocalFeatureList;
import org.openimaj.image.FImage;
import org.openimaj.image.Image;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.ColourSpace;
import org.openimaj.image.colour.Transforms;
import org.openimaj.image.feature.dense.gradient.dsift.ApproximateDenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.ByteDSIFTKeypoint;
import org.openimaj.image.feature.dense.gradient.dsift.ColourDenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.DenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.FloatDSIFTKeypoint;
import org.openimaj.image.feature.dense.gradient.dsift.PyramidDenseSIFT;
import org.openimaj.image.feature.local.affine.AffineSimulationKeypoint;
import org.openimaj.image.feature.local.affine.BasicASIFT;
import org.openimaj.image.feature.local.affine.ColourASIFT;
import org.openimaj.image.feature.local.engine.DoGColourSIFTEngine;
import org.openimaj.image.feature.local.engine.DoGSIFTEngine;
import org.openimaj.image.feature.local.engine.MinMaxDoGSIFTEngine;
import org.openimaj.image.feature.local.engine.asift.ASIFTEngine;
import org.openimaj.image.feature.local.engine.asift.ColourASIFTEngine;
import org.openimaj.image.feature.local.keypoints.Keypoint;
import org.openimaj.image.feature.local.keypoints.MinMaxKeypoint;
import org.openimaj.tools.localfeature.options.ColourMode.ColourModeOp;
import org.openimaj.tools.localfeature.options.ImageTransform.ImageTransformOp;
/**
* Types of local feature
*
* @author Jonathon Hare ([email protected])
*/
public enum LocalFeatureMode implements CmdLineOptionsProvider {
/**
* Difference-of-Gaussian SIFT
*/
SIFT {
@Override
public AbstractDoGSIFTModeOp getOptions() {
return new SiftMode(SIFT);
}
},
/**
* Min/Max Difference-of-Gaussian SIFT
*/
MIN_MAX_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new MinMaxSiftMode(MIN_MAX_SIFT);
}
},
/**
* Affine simulated Difference-of-Gaussian SIFT (ASIFT). Outputs x, y,
* scale, ori + feature
*/
ASIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new AsiftMode(ASIFT);
}
},
/**
* Enhanced output affine simulated Difference-of-Gaussian SIFT (ASIFT).
* Outputs x, y, scale, ori , tilt, theta, simulation index
*/
ASIFTENRICHED {
@Override
public LocalFeatureModeOp getOptions() {
return new AsiftEnrichedMode(ASIFTENRICHED);
}
},
/**
* Dense SIFT
*/
DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new DenseSiftMode(DENSE_SIFT);
}
},
/**
* Colour Dense SIFT
*/
COLOUR_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new ColourDenseSiftMode(COLOUR_DENSE_SIFT);
}
},
/**
* Dense SIFT in a pyramid
*/
PYRAMID_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new PyramidDenseSiftMode(DENSE_SIFT);
}
},
/**
* Dense colour SIFT in a pyramid
*/
PYRAMID_COLOUR_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new PyramidColourDenseSiftMode(COLOUR_DENSE_SIFT);
}
};
@Override
public abstract LocalFeatureModeOp getOptions();
/**
* Associated options for each {@link LocalFeatureMode}.
*
* @author Jonathon Hare ([email protected])
*/
public static abstract class LocalFeatureModeOp
implements
LocalFeatureExtractor<LocalFeature<?, ?>, MBFImage>
{
private LocalFeatureMode mode;
@Option(
name = "--image-transform",
aliases = "-it",
required = false,
usage = "Optionally perform a image transform before keypoint calculation",
handler = ProxyOptionHandler.class)
protected ImageTransform it = ImageTransform.NOTHING;
protected ImageTransformOp itOp = ImageTransform.NOTHING.getOptions();
/**
* Extract features based on the options.
*
* @param image
* the image
* @return the features
* @throws IOException
*/
public abstract LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException;
private LocalFeatureModeOp(LocalFeatureMode mode) {
this.mode = mode;
}
/**
* @return the name of the mode
*/
public String name() {
return mode.name();
}
/**
* @return the mode
*/
public LocalFeatureMode getMode() {
return mode;
}
}
/**
* Associated options for things built on a {@link DoGSIFTEngine}.
*
* @author Jonathon Hare ([email protected])
*/
public static abstract class AbstractDoGSIFTModeOp extends LocalFeatureModeOp {
@Option(
name = "--colour-mode",
aliases = "-cm",
required = false,
usage = "Optionally perform sift using the colour of the image in some mode",
handler = ProxyOptionHandler.class)
protected ColourMode cm = ColourMode.INTENSITY;
protected ColourModeOp cmOp = (ColourModeOp) ColourMode.INTENSITY.getOptions();
@Option(
name = "--no-double-size",
aliases = "-nds",
required = false,
usage = "Double the image sizes for the first iteration")
protected boolean noDoubleImageSize = false;
protected AbstractDoGSIFTModeOp(LocalFeatureMode mode) {
super(mode);
}
}
private static class SiftMode extends AbstractDoGSIFTModeOp {
private SiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<Keypoint> extract(byte[] img) throws IOException {
return extract(cmOp.process(img));
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return Keypoint.class;
}
@Override
public LocalFeatureList<Keypoint> extractFeature(MBFImage img) {
return extract(cmOp.process(img));
}
private LocalFeatureList<Keypoint> extract(Image<?, ?> image) {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY: {
final DoGSIFTEngine engine = new DoGSIFTEngine();
engine.getOptions().setDoubleInitialImage(!noDoubleImageSize);
image = itOp.transform(image);
keys = engine.findFeatures((FImage) image);
break;
}
case INTENSITY_COLOUR: {
final DoGColourSIFTEngine engine = new DoGColourSIFTEngine();
engine.getOptions().setDoubleInitialImage(!noDoubleImageSize);
image = itOp.transform(image);
keys = engine.findFeatures((MBFImage) image);
break;
}
}
return keys;
}
}
private static class MinMaxSiftMode extends AbstractDoGSIFTModeOp {
private MinMaxSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends Keypoint> extract(byte[] img) throws IOException {
final MinMaxDoGSIFTEngine engine = new MinMaxDoGSIFTEngine();
LocalFeatureList<MinMaxKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
keys = engine.findFeatures((FImage) itOp.transform(cmOp.process(img)));
break;
case INTENSITY_COLOUR:
throw new UnsupportedOperationException();
}
return keys;
}
@Override
public LocalFeatureList<? extends Keypoint> extractFeature(MBFImage img) {
img = (MBFImage) this.itOp.transform(img);
final MinMaxDoGSIFTEngine engine = new MinMaxDoGSIFTEngine();
LocalFeatureList<MinMaxKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
keys = engine.findFeatures((FImage) cmOp.process(img));
break;
case INTENSITY_COLOUR:
throw new UnsupportedOperationException();
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return MinMaxKeypoint.class;
}
}
private static class AsiftMode extends AbstractDoGSIFTModeOp {
private AsiftMode(LocalFeatureMode mode) {
super(mode);
}
@Option(
name = "--n-tilts",
required = false,
usage = "The number of tilts for the affine simulation")
public int ntilts = 5;
@Override
public LocalFeatureList<Keypoint> extract(byte[] image) throws IOException {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
final BasicASIFT basic = new BasicASIFT(!noDoubleImageSize);
basic.detectFeatures((FImage) itOp.transform(cmOp.process(image)), ntilts);
keys = basic.getFeatures();
break;
case INTENSITY_COLOUR:
final ColourASIFT colour = new ColourASIFT(!noDoubleImageSize);
colour.detectFeatures((MBFImage) itOp.transform(cmOp.process(image)), ntilts);
}
return keys;
}
@Override
public LocalFeatureList<Keypoint> extractFeature(MBFImage image) {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
final BasicASIFT basic = new BasicASIFT(!noDoubleImageSize);
basic.detectFeatures((FImage) itOp.transform(cmOp.process(image)), ntilts);
keys = basic.getFeatures();
break;
case INTENSITY_COLOUR:
final ColourASIFT colour = new ColourASIFT(!noDoubleImageSize);
colour.detectFeatures((MBFImage) itOp.transform(cmOp.process(image)), ntilts);
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return Keypoint.class;
}
}
private static class AsiftEnrichedMode extends AbstractDoGSIFTModeOp {
private AsiftEnrichedMode(LocalFeatureMode mode) {
super(mode);
}
@Option(
name = "--n-tilts",
required = false,
usage = "The number of tilts for the affine simulation")
public int ntilts = 5;
@Override
public LocalFeatureList<AffineSimulationKeypoint> extract(byte[] image) throws IOException {
final ASIFTEngine engine = new ASIFTEngine(!noDoubleImageSize, ntilts);
LocalFeatureList<AffineSimulationKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
FImage img = (FImage) cmOp.process(image);
img = (FImage) itOp.transform(img);
keys = engine.findFeatures(img);
break;
case INTENSITY_COLOUR:
final ColourASIFTEngine colourengine = new ColourASIFTEngine(!noDoubleImageSize, ntilts);
MBFImage colourimg = (MBFImage) cmOp.process(image);
colourimg = (MBFImage) itOp.transform(colourimg);
keys = colourengine.findFeatures(colourimg);
}
return keys;
}
@Override
public LocalFeatureList<AffineSimulationKeypoint> extractFeature(MBFImage image) {
final ASIFTEngine engine = new ASIFTEngine(!noDoubleImageSize, ntilts);
LocalFeatureList<AffineSimulationKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
FImage img = (FImage) cmOp.process(image);
img = (FImage) itOp.transform(img);
keys = engine.findFeatures(img);
break;
case INTENSITY_COLOUR:
final ColourASIFTEngine colourengine = new ColourASIFTEngine(!noDoubleImageSize, ntilts);
MBFImage colourimg = (MBFImage) cmOp.process(image);
colourimg = (MBFImage) itOp.transform(colourimg);
keys = colourengine.findFeatures(colourimg);
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return AffineSimulationKeypoint.class;
}
}
private static abstract class AbstractDenseSiftMode extends LocalFeatureModeOp {
@Option(
name = "--approximate",
aliases = "-ap",
required = false,
usage = "Enable approximate mode (much faster)")
boolean approximate;
@Option(
name = "--step-x",
aliases = "-sx",
required = false,
usage = "Step size of sampling window in x-direction (in pixels)")
protected int stepX = 5;
@Option(
name = "--step-y",
aliases = "-sy",
required = false,
usage = "Step size of sampling window in y-direction (in pixels)")
protected int stepY = 5;
@Option(
name = "--num-bins-x",
aliases = "-nx",
required = false,
usage = "Number of spatial bins in the X direction")
protected int numBinsX = 4;
@Option(
name = "--num-bins-y",
aliases = "-ny",
required = false,
usage = "Number of spatial bins in the Y direction")
protected int numBinsY = 4;
@Option(name = "--num-ori-bins", aliases = "-no", required = false, usage = "The number of orientation bins")
protected int numOriBins = 8;
@Option(
name = "--gaussian-window-size",
aliases = "-gws",
required = false,
usage = "Size of the Gaussian window (in relative to of the size of a bin)")
protected float gaussianWindowSize = 2f;
@Option(name = "--clipping-threshold", required = false, usage = "Threshold for clipping the SIFT features")
protected float valueThreshold = 0.2f;
@Option(
name = "--contrast-threshold",
required = false,
usage = "Threshold on the contrast of the returned features (-ve values disable this)")
protected float contrastThreshold = -1;
@Option(
name = "--byte-features",
required = false,
usage = "Output features scaled to bytes rather than floats")
protected boolean byteFeatures = false;
private AbstractDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
}
private static class DenseSiftMode extends AbstractDenseSiftMode {
@Option(
name = "--bin-width",
aliases = "-bw",
required = false,
usage = "Width of a single bin of the sampling window (in pixels). Sampling window width is this multiplied by #numBinX.")
protected int binWidth = 5;
@Option(
name = "--bin-height",
aliases = "-bh",
required = false,
usage = "Height of a single bin of the sampling window (in pixels). Sampling window height is this multiplied by #numBinY.")
protected int binHeight = 5;
private DenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extract(ImageUtilities.readF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
return extract(Transforms.calculateIntensityNTSC_LUT(image));
}
LocalFeatureList<? extends LocalFeature<?, ?>> extract(FImage image) {
image = (FImage) this.itOp.transform(image);
final DenseSIFT dsift;
if (approximate)
dsift = new ApproximateDenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold);
else
dsift = new DenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold);
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
if (byteFeatures)
return ByteDSIFTKeypoint.class;
return FloatDSIFTKeypoint.class;
}
}
private static class ColourDenseSiftMode extends DenseSiftMode {
@Option(name = "--colour-space", aliases = "-cs", required = false, usage = "Specify the colour space")
private ColourSpace colourspace = ColourSpace.RGB;
ColourDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readMBF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
image = (MBFImage) this.itOp.transform(image);
final ColourDenseSIFT dsift;
if (approximate)
dsift = new ColourDenseSIFT(new ApproximateDenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX,
numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), colourspace);
else
dsift = new ColourDenseSIFT(new DenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), colourspace);
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
}
private static class PyramidDenseSiftMode extends AbstractDenseSiftMode {
@Option(
name = "--sizes",
aliases = "-s",
required = true,
usage = "Scales at which the dense SIFT features are extracted. Each value is used as bin size for the DenseSIFT.")
List<Integer> sizes = new ArrayList<Integer>();
@Option(
name = "--magnification-factor",
aliases = "-mf",
usage = "The amount to smooth the image by at each level relative to the bin size (sigma = size/magnification).")
float magnificationFactor = 6;
PyramidDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
return extractFeature(Transforms.calculateIntensityNTSC_LUT(image));
}
protected int[] toArray(List<Integer> in) {
final int[] out = new int[in.size()];
for (int i = 0; i < out.length; i++) {
out[i] = in.get(i);
}
return out;
}
LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(FImage image) {
image = (FImage) this.itOp.transform(image);
final PyramidDenseSIFT<FImage> dsift;
if (approximate)
dsift = new PyramidDenseSIFT<FImage>(new ApproximateDenseSIFT(stepX, stepY, 1, 1, numBinsX, numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), magnificationFactor, toArray(sizes));
else
dsift = new PyramidDenseSIFT<FImage>(new DenseSIFT(stepX, stepY, 1, 1, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), magnificationFactor, toArray(sizes));
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
if (byteFeatures)
return ByteDSIFTKeypoint.class;
return FloatDSIFTKeypoint.class;
}
}
private static class PyramidColourDenseSiftMode extends PyramidDenseSiftMode {
@Option(name = "--colour-space", aliases = "-cs", required = false, usage = "Specify the colour space")
private ColourSpace colourspace = ColourSpace.RGB;
PyramidColourDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readMBF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
image = (MBFImage) this.itOp.transform(image);
final PyramidDenseSIFT<MBFImage> dsift;
if (approximate)
dsift = new PyramidDenseSIFT<MBFImage>(new ColourDenseSIFT(new ApproximateDenseSIFT(stepX, stepY, 1, 1,
numBinsX,
numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), colourspace), magnificationFactor, toArray(sizes));
else
dsift = new PyramidDenseSIFT<MBFImage>(new ColourDenseSIFT(new DenseSIFT(stepX, stepY, 1, 1, numBinsX,
numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), colourspace), magnificationFactor, toArray(sizes));
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
}
}
| openimaj/openimaj | tools/LocalFeaturesTool/src/main/java/org/openimaj/tools/localfeature/options/LocalFeatureMode.java | 7,406 | /**
* Dense SIFT in a pyramid
*/ | block_comment | nl | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.tools.localfeature.options;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.CmdLineOptionsProvider;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.ProxyOptionHandler;
import org.openimaj.feature.local.LocalFeature;
import org.openimaj.feature.local.LocalFeatureExtractor;
import org.openimaj.feature.local.list.LocalFeatureList;
import org.openimaj.image.FImage;
import org.openimaj.image.Image;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.ColourSpace;
import org.openimaj.image.colour.Transforms;
import org.openimaj.image.feature.dense.gradient.dsift.ApproximateDenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.ByteDSIFTKeypoint;
import org.openimaj.image.feature.dense.gradient.dsift.ColourDenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.DenseSIFT;
import org.openimaj.image.feature.dense.gradient.dsift.FloatDSIFTKeypoint;
import org.openimaj.image.feature.dense.gradient.dsift.PyramidDenseSIFT;
import org.openimaj.image.feature.local.affine.AffineSimulationKeypoint;
import org.openimaj.image.feature.local.affine.BasicASIFT;
import org.openimaj.image.feature.local.affine.ColourASIFT;
import org.openimaj.image.feature.local.engine.DoGColourSIFTEngine;
import org.openimaj.image.feature.local.engine.DoGSIFTEngine;
import org.openimaj.image.feature.local.engine.MinMaxDoGSIFTEngine;
import org.openimaj.image.feature.local.engine.asift.ASIFTEngine;
import org.openimaj.image.feature.local.engine.asift.ColourASIFTEngine;
import org.openimaj.image.feature.local.keypoints.Keypoint;
import org.openimaj.image.feature.local.keypoints.MinMaxKeypoint;
import org.openimaj.tools.localfeature.options.ColourMode.ColourModeOp;
import org.openimaj.tools.localfeature.options.ImageTransform.ImageTransformOp;
/**
* Types of local feature
*
* @author Jonathon Hare ([email protected])
*/
public enum LocalFeatureMode implements CmdLineOptionsProvider {
/**
* Difference-of-Gaussian SIFT
*/
SIFT {
@Override
public AbstractDoGSIFTModeOp getOptions() {
return new SiftMode(SIFT);
}
},
/**
* Min/Max Difference-of-Gaussian SIFT
*/
MIN_MAX_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new MinMaxSiftMode(MIN_MAX_SIFT);
}
},
/**
* Affine simulated Difference-of-Gaussian SIFT (ASIFT). Outputs x, y,
* scale, ori + feature
*/
ASIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new AsiftMode(ASIFT);
}
},
/**
* Enhanced output affine simulated Difference-of-Gaussian SIFT (ASIFT).
* Outputs x, y, scale, ori , tilt, theta, simulation index
*/
ASIFTENRICHED {
@Override
public LocalFeatureModeOp getOptions() {
return new AsiftEnrichedMode(ASIFTENRICHED);
}
},
/**
* Dense SIFT
*/
DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new DenseSiftMode(DENSE_SIFT);
}
},
/**
* Colour Dense SIFT
*/
COLOUR_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new ColourDenseSiftMode(COLOUR_DENSE_SIFT);
}
},
/**
* Dense SIFT in<SUF>*/
PYRAMID_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new PyramidDenseSiftMode(DENSE_SIFT);
}
},
/**
* Dense colour SIFT in a pyramid
*/
PYRAMID_COLOUR_DENSE_SIFT {
@Override
public LocalFeatureModeOp getOptions() {
return new PyramidColourDenseSiftMode(COLOUR_DENSE_SIFT);
}
};
@Override
public abstract LocalFeatureModeOp getOptions();
/**
* Associated options for each {@link LocalFeatureMode}.
*
* @author Jonathon Hare ([email protected])
*/
public static abstract class LocalFeatureModeOp
implements
LocalFeatureExtractor<LocalFeature<?, ?>, MBFImage>
{
private LocalFeatureMode mode;
@Option(
name = "--image-transform",
aliases = "-it",
required = false,
usage = "Optionally perform a image transform before keypoint calculation",
handler = ProxyOptionHandler.class)
protected ImageTransform it = ImageTransform.NOTHING;
protected ImageTransformOp itOp = ImageTransform.NOTHING.getOptions();
/**
* Extract features based on the options.
*
* @param image
* the image
* @return the features
* @throws IOException
*/
public abstract LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException;
private LocalFeatureModeOp(LocalFeatureMode mode) {
this.mode = mode;
}
/**
* @return the name of the mode
*/
public String name() {
return mode.name();
}
/**
* @return the mode
*/
public LocalFeatureMode getMode() {
return mode;
}
}
/**
* Associated options for things built on a {@link DoGSIFTEngine}.
*
* @author Jonathon Hare ([email protected])
*/
public static abstract class AbstractDoGSIFTModeOp extends LocalFeatureModeOp {
@Option(
name = "--colour-mode",
aliases = "-cm",
required = false,
usage = "Optionally perform sift using the colour of the image in some mode",
handler = ProxyOptionHandler.class)
protected ColourMode cm = ColourMode.INTENSITY;
protected ColourModeOp cmOp = (ColourModeOp) ColourMode.INTENSITY.getOptions();
@Option(
name = "--no-double-size",
aliases = "-nds",
required = false,
usage = "Double the image sizes for the first iteration")
protected boolean noDoubleImageSize = false;
protected AbstractDoGSIFTModeOp(LocalFeatureMode mode) {
super(mode);
}
}
private static class SiftMode extends AbstractDoGSIFTModeOp {
private SiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<Keypoint> extract(byte[] img) throws IOException {
return extract(cmOp.process(img));
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return Keypoint.class;
}
@Override
public LocalFeatureList<Keypoint> extractFeature(MBFImage img) {
return extract(cmOp.process(img));
}
private LocalFeatureList<Keypoint> extract(Image<?, ?> image) {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY: {
final DoGSIFTEngine engine = new DoGSIFTEngine();
engine.getOptions().setDoubleInitialImage(!noDoubleImageSize);
image = itOp.transform(image);
keys = engine.findFeatures((FImage) image);
break;
}
case INTENSITY_COLOUR: {
final DoGColourSIFTEngine engine = new DoGColourSIFTEngine();
engine.getOptions().setDoubleInitialImage(!noDoubleImageSize);
image = itOp.transform(image);
keys = engine.findFeatures((MBFImage) image);
break;
}
}
return keys;
}
}
private static class MinMaxSiftMode extends AbstractDoGSIFTModeOp {
private MinMaxSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends Keypoint> extract(byte[] img) throws IOException {
final MinMaxDoGSIFTEngine engine = new MinMaxDoGSIFTEngine();
LocalFeatureList<MinMaxKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
keys = engine.findFeatures((FImage) itOp.transform(cmOp.process(img)));
break;
case INTENSITY_COLOUR:
throw new UnsupportedOperationException();
}
return keys;
}
@Override
public LocalFeatureList<? extends Keypoint> extractFeature(MBFImage img) {
img = (MBFImage) this.itOp.transform(img);
final MinMaxDoGSIFTEngine engine = new MinMaxDoGSIFTEngine();
LocalFeatureList<MinMaxKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
keys = engine.findFeatures((FImage) cmOp.process(img));
break;
case INTENSITY_COLOUR:
throw new UnsupportedOperationException();
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return MinMaxKeypoint.class;
}
}
private static class AsiftMode extends AbstractDoGSIFTModeOp {
private AsiftMode(LocalFeatureMode mode) {
super(mode);
}
@Option(
name = "--n-tilts",
required = false,
usage = "The number of tilts for the affine simulation")
public int ntilts = 5;
@Override
public LocalFeatureList<Keypoint> extract(byte[] image) throws IOException {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
final BasicASIFT basic = new BasicASIFT(!noDoubleImageSize);
basic.detectFeatures((FImage) itOp.transform(cmOp.process(image)), ntilts);
keys = basic.getFeatures();
break;
case INTENSITY_COLOUR:
final ColourASIFT colour = new ColourASIFT(!noDoubleImageSize);
colour.detectFeatures((MBFImage) itOp.transform(cmOp.process(image)), ntilts);
}
return keys;
}
@Override
public LocalFeatureList<Keypoint> extractFeature(MBFImage image) {
LocalFeatureList<Keypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
final BasicASIFT basic = new BasicASIFT(!noDoubleImageSize);
basic.detectFeatures((FImage) itOp.transform(cmOp.process(image)), ntilts);
keys = basic.getFeatures();
break;
case INTENSITY_COLOUR:
final ColourASIFT colour = new ColourASIFT(!noDoubleImageSize);
colour.detectFeatures((MBFImage) itOp.transform(cmOp.process(image)), ntilts);
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return Keypoint.class;
}
}
private static class AsiftEnrichedMode extends AbstractDoGSIFTModeOp {
private AsiftEnrichedMode(LocalFeatureMode mode) {
super(mode);
}
@Option(
name = "--n-tilts",
required = false,
usage = "The number of tilts for the affine simulation")
public int ntilts = 5;
@Override
public LocalFeatureList<AffineSimulationKeypoint> extract(byte[] image) throws IOException {
final ASIFTEngine engine = new ASIFTEngine(!noDoubleImageSize, ntilts);
LocalFeatureList<AffineSimulationKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
FImage img = (FImage) cmOp.process(image);
img = (FImage) itOp.transform(img);
keys = engine.findFeatures(img);
break;
case INTENSITY_COLOUR:
final ColourASIFTEngine colourengine = new ColourASIFTEngine(!noDoubleImageSize, ntilts);
MBFImage colourimg = (MBFImage) cmOp.process(image);
colourimg = (MBFImage) itOp.transform(colourimg);
keys = colourengine.findFeatures(colourimg);
}
return keys;
}
@Override
public LocalFeatureList<AffineSimulationKeypoint> extractFeature(MBFImage image) {
final ASIFTEngine engine = new ASIFTEngine(!noDoubleImageSize, ntilts);
LocalFeatureList<AffineSimulationKeypoint> keys = null;
switch (this.cm) {
case SINGLE_COLOUR:
case INTENSITY:
FImage img = (FImage) cmOp.process(image);
img = (FImage) itOp.transform(img);
keys = engine.findFeatures(img);
break;
case INTENSITY_COLOUR:
final ColourASIFTEngine colourengine = new ColourASIFTEngine(!noDoubleImageSize, ntilts);
MBFImage colourimg = (MBFImage) cmOp.process(image);
colourimg = (MBFImage) itOp.transform(colourimg);
keys = colourengine.findFeatures(colourimg);
}
return keys;
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
return AffineSimulationKeypoint.class;
}
}
private static abstract class AbstractDenseSiftMode extends LocalFeatureModeOp {
@Option(
name = "--approximate",
aliases = "-ap",
required = false,
usage = "Enable approximate mode (much faster)")
boolean approximate;
@Option(
name = "--step-x",
aliases = "-sx",
required = false,
usage = "Step size of sampling window in x-direction (in pixels)")
protected int stepX = 5;
@Option(
name = "--step-y",
aliases = "-sy",
required = false,
usage = "Step size of sampling window in y-direction (in pixels)")
protected int stepY = 5;
@Option(
name = "--num-bins-x",
aliases = "-nx",
required = false,
usage = "Number of spatial bins in the X direction")
protected int numBinsX = 4;
@Option(
name = "--num-bins-y",
aliases = "-ny",
required = false,
usage = "Number of spatial bins in the Y direction")
protected int numBinsY = 4;
@Option(name = "--num-ori-bins", aliases = "-no", required = false, usage = "The number of orientation bins")
protected int numOriBins = 8;
@Option(
name = "--gaussian-window-size",
aliases = "-gws",
required = false,
usage = "Size of the Gaussian window (in relative to of the size of a bin)")
protected float gaussianWindowSize = 2f;
@Option(name = "--clipping-threshold", required = false, usage = "Threshold for clipping the SIFT features")
protected float valueThreshold = 0.2f;
@Option(
name = "--contrast-threshold",
required = false,
usage = "Threshold on the contrast of the returned features (-ve values disable this)")
protected float contrastThreshold = -1;
@Option(
name = "--byte-features",
required = false,
usage = "Output features scaled to bytes rather than floats")
protected boolean byteFeatures = false;
private AbstractDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
}
private static class DenseSiftMode extends AbstractDenseSiftMode {
@Option(
name = "--bin-width",
aliases = "-bw",
required = false,
usage = "Width of a single bin of the sampling window (in pixels). Sampling window width is this multiplied by #numBinX.")
protected int binWidth = 5;
@Option(
name = "--bin-height",
aliases = "-bh",
required = false,
usage = "Height of a single bin of the sampling window (in pixels). Sampling window height is this multiplied by #numBinY.")
protected int binHeight = 5;
private DenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extract(ImageUtilities.readF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
return extract(Transforms.calculateIntensityNTSC_LUT(image));
}
LocalFeatureList<? extends LocalFeature<?, ?>> extract(FImage image) {
image = (FImage) this.itOp.transform(image);
final DenseSIFT dsift;
if (approximate)
dsift = new ApproximateDenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold);
else
dsift = new DenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold);
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
if (byteFeatures)
return ByteDSIFTKeypoint.class;
return FloatDSIFTKeypoint.class;
}
}
private static class ColourDenseSiftMode extends DenseSiftMode {
@Option(name = "--colour-space", aliases = "-cs", required = false, usage = "Specify the colour space")
private ColourSpace colourspace = ColourSpace.RGB;
ColourDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readMBF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
image = (MBFImage) this.itOp.transform(image);
final ColourDenseSIFT dsift;
if (approximate)
dsift = new ColourDenseSIFT(new ApproximateDenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX,
numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), colourspace);
else
dsift = new ColourDenseSIFT(new DenseSIFT(stepX, stepY, binWidth, binHeight, numBinsX, numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), colourspace);
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
}
private static class PyramidDenseSiftMode extends AbstractDenseSiftMode {
@Option(
name = "--sizes",
aliases = "-s",
required = true,
usage = "Scales at which the dense SIFT features are extracted. Each value is used as bin size for the DenseSIFT.")
List<Integer> sizes = new ArrayList<Integer>();
@Option(
name = "--magnification-factor",
aliases = "-mf",
usage = "The amount to smooth the image by at each level relative to the bin size (sigma = size/magnification).")
float magnificationFactor = 6;
PyramidDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
return extractFeature(Transforms.calculateIntensityNTSC_LUT(image));
}
protected int[] toArray(List<Integer> in) {
final int[] out = new int[in.size()];
for (int i = 0; i < out.length; i++) {
out[i] = in.get(i);
}
return out;
}
LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(FImage image) {
image = (FImage) this.itOp.transform(image);
final PyramidDenseSIFT<FImage> dsift;
if (approximate)
dsift = new PyramidDenseSIFT<FImage>(new ApproximateDenseSIFT(stepX, stepY, 1, 1, numBinsX, numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), magnificationFactor, toArray(sizes));
else
dsift = new PyramidDenseSIFT<FImage>(new DenseSIFT(stepX, stepY, 1, 1, numBinsX, numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), magnificationFactor, toArray(sizes));
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
@Override
public Class<? extends LocalFeature<?, ?>> getFeatureClass() {
if (byteFeatures)
return ByteDSIFTKeypoint.class;
return FloatDSIFTKeypoint.class;
}
}
private static class PyramidColourDenseSiftMode extends PyramidDenseSiftMode {
@Option(name = "--colour-space", aliases = "-cs", required = false, usage = "Specify the colour space")
private ColourSpace colourspace = ColourSpace.RGB;
PyramidColourDenseSiftMode(LocalFeatureMode mode) {
super(mode);
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extract(byte[] image) throws IOException {
return extractFeature(ImageUtilities.readMBF(new ByteArrayInputStream(image)));
}
@Override
public LocalFeatureList<? extends LocalFeature<?, ?>> extractFeature(MBFImage image) {
image = (MBFImage) this.itOp.transform(image);
final PyramidDenseSIFT<MBFImage> dsift;
if (approximate)
dsift = new PyramidDenseSIFT<MBFImage>(new ColourDenseSIFT(new ApproximateDenseSIFT(stepX, stepY, 1, 1,
numBinsX,
numBinsY, numOriBins,
gaussianWindowSize, valueThreshold), colourspace), magnificationFactor, toArray(sizes));
else
dsift = new PyramidDenseSIFT<MBFImage>(new ColourDenseSIFT(new DenseSIFT(stepX, stepY, 1, 1, numBinsX,
numBinsY,
numOriBins,
gaussianWindowSize, valueThreshold), colourspace), magnificationFactor, toArray(sizes));
dsift.analyseImage(image);
if (contrastThreshold <= 0) {
if (byteFeatures)
return dsift.getByteKeypoints();
return dsift.getFloatKeypoints();
} else {
if (byteFeatures)
return dsift.getByteKeypoints(contrastThreshold);
return dsift.getFloatKeypoints(contrastThreshold);
}
}
}
}
|
50831_3 | package org.apache.minibase;
import java.io.IOException;
import java.util.Comparator;
public class KeyValue implements Comparable<KeyValue> {
public static final int RAW_KEY_LEN_SIZE = 4;
public static final int VAL_LEN_SIZE = 4;
public static final int OP_SIZE = 1;
public static final int SEQ_ID_SIZE = 8;
public static final KeyValueComparator KV_CMP = new KeyValueComparator();
private byte[] key;
private byte[] value;
private Op op;
private long sequenceId;
public enum Op {
Put((byte) 0),
Delete((byte) 1);
private byte code;
Op(byte code) {
this.code = code;
}
public static Op code2Op(byte code) {
switch (code) {
case 0:
return Put;
case 1:
return Delete;
default:
throw new IllegalArgumentException("Unknown code: " + code);
}
}
public byte getCode() {
return this.code;
}
}
public static KeyValue create(byte[] key, byte[] value, Op op, long sequenceId) {
return new KeyValue(key, value, op, sequenceId);
}
public static KeyValue createPut(byte[] key, byte[] value, long sequenceId) {
return KeyValue.create(key, value, Op.Put, sequenceId);
}
public static KeyValue createDelete(byte[] key, long sequenceId) {
return KeyValue.create(key, Bytes.EMPTY_BYTES, Op.Delete, sequenceId);
}
private KeyValue(byte[] key, byte[] value, Op op, long sequenceId) {
assert key != null;
assert value != null;
assert op != null;
assert sequenceId >= 0;
this.key = key;
this.value = value;
this.op = op;
this.sequenceId = sequenceId;
}
public byte[] getKey() {
return key;
}
public byte[] getValue() {
return value;
}
public Op getOp() {
return this.op;
}
public long getSequenceId() {
return this.sequenceId;
}
private int getRawKeyLen() {
return key.length + OP_SIZE + SEQ_ID_SIZE;
}
public byte[] toBytes() throws IOException {
int rawKeyLen = getRawKeyLen();
int pos = 0;
byte[] bytes = new byte[getSerializeSize()];
// Encode raw key length
byte[] rawKeyLenBytes = Bytes.toBytes(rawKeyLen);
System.arraycopy(rawKeyLenBytes, 0, bytes, pos, RAW_KEY_LEN_SIZE);
pos += RAW_KEY_LEN_SIZE;
// Encode value length.
byte[] valLen = Bytes.toBytes(value.length);
System.arraycopy(valLen, 0, bytes, pos, VAL_LEN_SIZE);
pos += VAL_LEN_SIZE;
// Encode key
System.arraycopy(key, 0, bytes, pos, key.length);
pos += key.length;
// Encode Op
bytes[pos] = op.getCode();
pos += 1;
// Encode sequenceId
byte[] seqIdBytes = Bytes.toBytes(sequenceId);
System.arraycopy(seqIdBytes, 0, bytes, pos, seqIdBytes.length);
pos += seqIdBytes.length;
// Encode value
System.arraycopy(value, 0, bytes, pos, value.length);
return bytes;
}
@Override
public int compareTo(KeyValue kv) {
if (kv == null) {
throw new IllegalArgumentException("kv to compare should be null");
}
int ret = Bytes.compare(this.key, kv.key);
if (ret != 0) {
return ret;
}
if (this.sequenceId != kv.sequenceId) {
return this.sequenceId > kv.sequenceId ? -1 : 1;
}
if (this.op != kv.op) {
return this.op.getCode() > kv.op.getCode() ? -1 : 1;
}
return 0;
}
@Override
public boolean equals(Object kv) {
if (kv == null) return false;
if (!(kv instanceof KeyValue)) return false;
KeyValue that = (KeyValue) kv;
return this.compareTo(that) == 0;
}
public int getSerializeSize() {
return RAW_KEY_LEN_SIZE + VAL_LEN_SIZE + getRawKeyLen() + value.length;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("key=").append(Bytes.toHex(this.key)).append("/op=").append(op).append
("/sequenceId=").append(this.sequenceId).append("/value=").append(Bytes.toHex(this
.value));
return sb.toString();
}
public static KeyValue parseFrom(byte[] bytes, int offset) throws IOException {
if (bytes == null) {
throw new IOException("buffer is null");
}
if (offset + RAW_KEY_LEN_SIZE + VAL_LEN_SIZE >= bytes.length) {
throw new IOException("Invalid offset or len. offset: " + offset + ", len: " + bytes.length);
}
// Decode raw key length
int pos = offset;
int rawKeyLen = Bytes.toInt(Bytes.slice(bytes, pos, RAW_KEY_LEN_SIZE));
pos += RAW_KEY_LEN_SIZE;
// Decode value length
int valLen = Bytes.toInt(Bytes.slice(bytes, pos, VAL_LEN_SIZE));
pos += VAL_LEN_SIZE;
// Decode key
int keyLen = rawKeyLen - OP_SIZE - SEQ_ID_SIZE;
byte[] key = Bytes.slice(bytes, pos, keyLen);
pos += keyLen;
// Decode Op
Op op = Op.code2Op(bytes[pos]);
pos += 1;
// Decode sequenceId
long sequenceId = Bytes.toLong(Bytes.slice(bytes, pos, SEQ_ID_SIZE));
pos += SEQ_ID_SIZE;
// Decode value.
byte[] val = Bytes.slice(bytes, pos, valLen);
return create(key, val, op, sequenceId);
}
public static KeyValue parseFrom(byte[] bytes) throws IOException {
return parseFrom(bytes, 0);
}
private static class KeyValueComparator implements Comparator<KeyValue> {
@Override
public int compare(KeyValue a, KeyValue b) {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
return a.compareTo(b);
}
}
}
| openinx/minibase | src/main/java/org/apache/minibase/KeyValue.java | 1,825 | // Decode value length | line_comment | nl | package org.apache.minibase;
import java.io.IOException;
import java.util.Comparator;
public class KeyValue implements Comparable<KeyValue> {
public static final int RAW_KEY_LEN_SIZE = 4;
public static final int VAL_LEN_SIZE = 4;
public static final int OP_SIZE = 1;
public static final int SEQ_ID_SIZE = 8;
public static final KeyValueComparator KV_CMP = new KeyValueComparator();
private byte[] key;
private byte[] value;
private Op op;
private long sequenceId;
public enum Op {
Put((byte) 0),
Delete((byte) 1);
private byte code;
Op(byte code) {
this.code = code;
}
public static Op code2Op(byte code) {
switch (code) {
case 0:
return Put;
case 1:
return Delete;
default:
throw new IllegalArgumentException("Unknown code: " + code);
}
}
public byte getCode() {
return this.code;
}
}
public static KeyValue create(byte[] key, byte[] value, Op op, long sequenceId) {
return new KeyValue(key, value, op, sequenceId);
}
public static KeyValue createPut(byte[] key, byte[] value, long sequenceId) {
return KeyValue.create(key, value, Op.Put, sequenceId);
}
public static KeyValue createDelete(byte[] key, long sequenceId) {
return KeyValue.create(key, Bytes.EMPTY_BYTES, Op.Delete, sequenceId);
}
private KeyValue(byte[] key, byte[] value, Op op, long sequenceId) {
assert key != null;
assert value != null;
assert op != null;
assert sequenceId >= 0;
this.key = key;
this.value = value;
this.op = op;
this.sequenceId = sequenceId;
}
public byte[] getKey() {
return key;
}
public byte[] getValue() {
return value;
}
public Op getOp() {
return this.op;
}
public long getSequenceId() {
return this.sequenceId;
}
private int getRawKeyLen() {
return key.length + OP_SIZE + SEQ_ID_SIZE;
}
public byte[] toBytes() throws IOException {
int rawKeyLen = getRawKeyLen();
int pos = 0;
byte[] bytes = new byte[getSerializeSize()];
// Encode raw key length
byte[] rawKeyLenBytes = Bytes.toBytes(rawKeyLen);
System.arraycopy(rawKeyLenBytes, 0, bytes, pos, RAW_KEY_LEN_SIZE);
pos += RAW_KEY_LEN_SIZE;
// Encode value length.
byte[] valLen = Bytes.toBytes(value.length);
System.arraycopy(valLen, 0, bytes, pos, VAL_LEN_SIZE);
pos += VAL_LEN_SIZE;
// Encode key
System.arraycopy(key, 0, bytes, pos, key.length);
pos += key.length;
// Encode Op
bytes[pos] = op.getCode();
pos += 1;
// Encode sequenceId
byte[] seqIdBytes = Bytes.toBytes(sequenceId);
System.arraycopy(seqIdBytes, 0, bytes, pos, seqIdBytes.length);
pos += seqIdBytes.length;
// Encode value
System.arraycopy(value, 0, bytes, pos, value.length);
return bytes;
}
@Override
public int compareTo(KeyValue kv) {
if (kv == null) {
throw new IllegalArgumentException("kv to compare should be null");
}
int ret = Bytes.compare(this.key, kv.key);
if (ret != 0) {
return ret;
}
if (this.sequenceId != kv.sequenceId) {
return this.sequenceId > kv.sequenceId ? -1 : 1;
}
if (this.op != kv.op) {
return this.op.getCode() > kv.op.getCode() ? -1 : 1;
}
return 0;
}
@Override
public boolean equals(Object kv) {
if (kv == null) return false;
if (!(kv instanceof KeyValue)) return false;
KeyValue that = (KeyValue) kv;
return this.compareTo(that) == 0;
}
public int getSerializeSize() {
return RAW_KEY_LEN_SIZE + VAL_LEN_SIZE + getRawKeyLen() + value.length;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("key=").append(Bytes.toHex(this.key)).append("/op=").append(op).append
("/sequenceId=").append(this.sequenceId).append("/value=").append(Bytes.toHex(this
.value));
return sb.toString();
}
public static KeyValue parseFrom(byte[] bytes, int offset) throws IOException {
if (bytes == null) {
throw new IOException("buffer is null");
}
if (offset + RAW_KEY_LEN_SIZE + VAL_LEN_SIZE >= bytes.length) {
throw new IOException("Invalid offset or len. offset: " + offset + ", len: " + bytes.length);
}
// Decode raw key length
int pos = offset;
int rawKeyLen = Bytes.toInt(Bytes.slice(bytes, pos, RAW_KEY_LEN_SIZE));
pos += RAW_KEY_LEN_SIZE;
// Decode value<SUF>
int valLen = Bytes.toInt(Bytes.slice(bytes, pos, VAL_LEN_SIZE));
pos += VAL_LEN_SIZE;
// Decode key
int keyLen = rawKeyLen - OP_SIZE - SEQ_ID_SIZE;
byte[] key = Bytes.slice(bytes, pos, keyLen);
pos += keyLen;
// Decode Op
Op op = Op.code2Op(bytes[pos]);
pos += 1;
// Decode sequenceId
long sequenceId = Bytes.toLong(Bytes.slice(bytes, pos, SEQ_ID_SIZE));
pos += SEQ_ID_SIZE;
// Decode value.
byte[] val = Bytes.slice(bytes, pos, valLen);
return create(key, val, op, sequenceId);
}
public static KeyValue parseFrom(byte[] bytes) throws IOException {
return parseFrom(bytes, 0);
}
private static class KeyValueComparator implements Comparator<KeyValue> {
@Override
public int compare(KeyValue a, KeyValue b) {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
return a.compareTo(b);
}
}
}
|
198063_11 | /*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if ((jeventType == MouseEvent.MOUSE_PRESSED) && (jbuttonNumber > MouseEvent.NOBUTTON)) {
// 8294426: NSEvent.nsToJavaModifiers returns 0 on M2 MacBooks if the event is generated
// via tapping (not pressing) on a trackpad
// (System Preferences -> Trackpad -> Tap to click must be turned on).
// So let's set the modifiers manually.
jmodifiers |= MouseEvent.getMaskForButton(jbuttonNumber);
}
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSEventTypeFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jextendedkeyCode = -1;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation, jkeyType]
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode};
int[] out = new int[4]; // [jkeyCode, jkeyLocation, deadChar, extendedKeyCode]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
if(testChar == 0){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
(LWCToolkit.isLocaleUSInternationalPC(lwcToolkit.getDefaultKeyboardLocale()) &&
LWCToolkit.isCharModifierKeyInUSInternationalPC(testChar) &&
(testChar != testCharIgnoringModifiers))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jextendedkeyCode = out[3];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation, jextendedkeyCode);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
}
}
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
| openjdk/jdk | src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java | 3,870 | // [jkeyCode, jkeyLocation, jkeyType] | line_comment | nl | /*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if ((jeventType == MouseEvent.MOUSE_PRESSED) && (jbuttonNumber > MouseEvent.NOBUTTON)) {
// 8294426: NSEvent.nsToJavaModifiers returns 0 on M2 MacBooks if the event is generated
// via tapping (not pressing) on a trackpad
// (System Preferences -> Trackpad -> Tap to click must be turned on).
// So let's set the modifiers manually.
jmodifiers |= MouseEvent.getMaskForButton(jbuttonNumber);
}
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSEventTypeFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jextendedkeyCode = -1;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation,<SUF>
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode};
int[] out = new int[4]; // [jkeyCode, jkeyLocation, deadChar, extendedKeyCode]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
if(testChar == 0){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
(LWCToolkit.isLocaleUSInternationalPC(lwcToolkit.getDefaultKeyboardLocale()) &&
LWCToolkit.isCharModifierKeyInUSInternationalPC(testChar) &&
(testChar != testCharIgnoringModifiers))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jextendedkeyCode = out[3];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation, jextendedkeyCode);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
}
}
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
|