repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
AfriGIS-South-Africa/afrigis-services-java | addresssubmission/src/main/java/com/afrigis/services/addresssubmission/AddressSubmissionResponse.java | 506 | package com.afrigis.services.addresssubmission;
import com.afrigis.services.Response;
/**
*
* @author Pieterv
*/
public interface AddressSubmissionResponse extends Response {
/**
*
* @return Client ID your AfriGIS key.
*/
String getClientID();
/**
*
* @return Ticket number the reference number in the internal AfriGIS
* ticketing system with which you can track the progress of the Address
* Submission.
*/
String getTicketNumber();
}
| gpl-2.0 |
tectronics/reformationofeurope | src/net/sf/freecol/common/model/ModelMessage.java | 16955 | /**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.Arrays;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.Reformation;
import net.sf.freecol.client.gui.i18n.Messages;
/**
* Contains a message about a change in the model.
*/
public class ModelMessage extends FreeColObject {
/** Constants describing the type of message. */
public static enum MessageType {
DEFAULT,
WARNING,
SONS_OF_LIBERTY,
GOVERNMENT_EFFICIENCY,
WAREHOUSE_CAPACITY,
UNIT_IMPROVED,
UNIT_DEMOTED,
UNIT_LOST,
UNIT_ADDED,
BUILDING_COMPLETED,
FOREIGN_DIPLOMACY,
MARKET_PRICES,
LOST_CITY_RUMOUR,
GIFT_GOODS,
MISSING_GOODS,
TUTORIAL,
COMBAT_RESULT,
ACCEPTED_DEMANDS,
REJECTED_DEMANDS
}
private Player owner;
private FreeColGameObject source;
private Location sourceLocation;
private FreeColObject display;
private MessageType type;
private String[] data;
private boolean beenDisplayed = false;
public ModelMessage() {
}
private static String[] convertData(String[][] data) {
if (data == null) {
return null;
}
String[] strings = new String[data.length * 2];
for (int index = 0; index < data.length; index++) {
strings[index * 2] = data[index][0];
strings[index * 2 + 1] = data[index][1];
}
return strings;
}
/**
* Creates a new <code>ModelMessage</code>.
*
* @param source The source of the message. This is what the message should be
* associated with. In addition, the owner of the source is the
* player getting the message.
* @param id The ID of the message to display.
* @param data Contains data to be displayed in the message or <i>null</i>.
* @param type The type of this model message.
* @param display The Object to display.
*/
@Deprecated
public ModelMessage(FreeColGameObject source, String id, String[][] data, MessageType type, FreeColObject display) {
this(source, type, display, id, convertData(data));
}
/**
* Creates a new <code>ModelMessage</code>.
*
* @param source The source of the message. This is what the message should be
* associated with. In addition, the owner of the source is the
* player getting the message.
* @param type The type of this model message.
* @param display The Object to display.
* @param id The ID of the message to display.
* @param data Contains data to be displayed in the message or <i>null</i>.
*/
public ModelMessage(FreeColGameObject source, MessageType type, FreeColObject display,
String id, String... data) {
this.source = source;
this.sourceLocation = null;
if (source instanceof Unit) {
Unit u = (Unit) source;
this.owner = u.getOwner();
if (u.getTile() != null) {
this.sourceLocation = u.getTile();
} else if (u.getColony() != null) {
this.sourceLocation = u.getColony().getTile();
} else if (u.getIndianSettlement() != null) {
this.sourceLocation = u.getIndianSettlement().getTile();
} else if (u.isInEurope()) {
this.sourceLocation = u.getOwner().getEurope();
}
} else if (source instanceof Settlement) {
this.owner = ((Settlement) source).getOwner();
this.sourceLocation = ((Settlement) source).getTile();
} else if (source instanceof Europe) {
this.owner = ((Europe) source).getOwner();
} else if (source instanceof Player) {
this.owner = (Player) source;
} else if (source instanceof Ownable) {
this.owner = ((Ownable) source).getOwner();
}
setId(id);
this.data = data;
this.type = type;
if (display == null) {
this.display = getDefaultDisplay(type, source);
} else {
this.display = display;
}
verifyFields();
}
/**
* Checks that all the fields as they are set in the constructor are valid.
*/
private void verifyFields() {
if (getId() == null) {
throw new IllegalArgumentException("ModelMessage should not have a null id.");
}
if (source == null) {
throw new IllegalArgumentException("ModelMessage with ID " + this.toString() + " should not have a null source.");
}
if (owner == null) {
throw new IllegalArgumentException("ModelMessage with ID " + this.getId() + " should not have a null owner.");
}
if (!(display == null ||
display instanceof FreeColGameObject ||
display instanceof FreeColGameObjectType)) {
throw new IllegalArgumentException("The display must be a FreeColGameObject or FreeColGameObjectType!");
}
if (data != null && data.length % 2 != 0) {
throw new IllegalArgumentException("Data length must be multiple of 2.");
}
}
/**
* Creates a new <code>ModelMessage</code>.
*
* @param source The source of the message. This is what the message should be
* associated with. In addition, the owner of the source is the
* player getting the message.
* @param id The ID of the message to display.
* @param data Contains data to be displayed in the message or <i>null</i>.
* @param type The type of this model message.
*/
public ModelMessage(FreeColGameObject source, String id, String[][] data, MessageType type) {
this(source, type, getDefaultDisplay(type, source), id, convertData(data));
}
/**
* Creates a new <code>ModelMessage</code>.
*
* @param source The source of the message. This is what the message should be
* associated with. In addition, the owner of the source is the
* player getting the message.
* @param id The ID of the message to display.
* @param data Contains data to be displayed in the message or <i>null</i>.
*/
public ModelMessage(FreeColGameObject source, String id, String[][] data) {
this(source, MessageType.DEFAULT, getDefaultDisplay(MessageType.DEFAULT, source), id, convertData(data));
}
/**
* Returns the default display object for the given type.
* @param type the type for which to find the default display object.
* @param source the source object
* @return an object to be displayed for the message.
*/
static private FreeColObject getDefaultDisplay(MessageType type, FreeColGameObject source) {
FreeColObject newDisplay = null;
switch(type) {
case SONS_OF_LIBERTY:
case GOVERNMENT_EFFICIENCY:
newDisplay = Reformation.getSpecification().getGoodsType("model.goods.bells");
break;
case LOST_CITY_RUMOUR:
case UNIT_IMPROVED:
case UNIT_DEMOTED:
case UNIT_LOST:
case UNIT_ADDED:
case COMBAT_RESULT:
newDisplay = source;
break;
case BUILDING_COMPLETED:
newDisplay = Reformation.getSpecification().getGoodsType("model.goods.hammers");
break;
case TUTORIAL:
case DEFAULT:
case WARNING:
case WAREHOUSE_CAPACITY:
case FOREIGN_DIPLOMACY:
case MARKET_PRICES:
case GIFT_GOODS:
case MISSING_GOODS:
default:
if (source instanceof Player) {
newDisplay = source;
}
}
return newDisplay;
}
/**
* Checks if this <code>ModelMessage</code> has been displayed.
* @return <i>true</i> if this <code>ModelMessage</code> has been displayed.
* @see #setBeenDisplayed
*/
public boolean hasBeenDisplayed() {
return beenDisplayed;
}
/**
* Sets the <code>beenDisplayed</code> value of this <code>ModelMessage</code>.
* This is used to avoid showing the same message twice.
*
* @param beenDisplayed Should be set to <code>true</code> after the
* message has been displayed.
*/
public void setBeenDisplayed(boolean beenDisplayed) {
this.beenDisplayed = beenDisplayed;
}
/**
* Gets the source of the message. This is what the message
* should be associated with. In addition, the owner of the source is the
* player getting the message.
*
* @return The source of the message.
* @see #getOwner
*/
public FreeColGameObject getSource() {
return source;
}
/**
* Sets the source of the message.
* @param newSource a new source for this message
*/
public void setSource(FreeColGameObject newSource) {
source = newSource;
}
/**
* Returns the data to be displayed in the message.
* @return The data as a <code>String[]</code> or <i>null</i>
* if no data applies.
*/
public String[] getData() {
return data;
}
/**
* Gets the type of the message to display.
* @return The type.
*/
public MessageType getType() {
return type;
}
public String getTypeName() {
return Messages.message("model.message." + type.toString());
}
/**
* Gets the Object to display.
* @return The Object to display.
*/
public FreeColObject getDisplay() {
return display;
}
/**
* Sets the Object to display.
* @param newDisplay the new object to display
*/
public void setDisplay(FreeColGameObject newDisplay) {
display = newDisplay;
}
/**
* Returns the owner of this message. The owner of this method
* is the owner of the {@link #getSource source}.
*
* @return The owner of the message. This is the <code>Player</code>
* who should receive the message.
*/
public Player getOwner() {
return owner;
}
/**
* Set the owner of this message.
*
* @param newOwner A <code>Player</code> to own this message.
*/
public void setOwner(Player newOwner) {
newOwner = owner;
}
/**
* Checks if this <code>ModelMessage</code> is equal to another <code>ModelMessage</code>.
* @return <i>true</i> if the sources, message IDs and data are equal.
*/
@Override
public boolean equals(Object o) {
if ( ! (o instanceof ModelMessage) ) { return false; }
ModelMessage m = (ModelMessage) o;
// Check that the content of the data array is equal
if (!Arrays.equals(data, m.data)) {
return false;
}
return ( source.equals(m.source)
&& getId().equals(m.getId())
&& type == m.type );
}
@Override
public int hashCode() {
int value = 1;
value = 37 * value + ((source == null) ? 0 : source.hashCode());
value = 37 * value + getId().hashCode();
if (data != null) {
for (String s : data) {
value = 37 * value + s.hashCode();
}
}
value = 37 * value + type.ordinal();
return value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ModelMessage<");
sb.append(hashCode() + ", " + ((source == null) ? "null" : source.getId()) + ", " + getId() + ", " + ((display==null) ? "null" : display.getId()) + ", ");
if (data != null) {
for (String s : data) {
sb.append(s + "/");
}
}
sb.append(", " + type + " >");
return sb.toString();
}
public static String getXMLElementTagName() {
return "modelMessage";
}
@Override
public void toXMLImpl(XMLStreamWriter out) throws XMLStreamException {
out.writeStartElement(getXMLElementTagName());
out.writeAttribute("owner", owner.getId());
if (source!=null) {
if ((source instanceof Unit && ((Unit)source).isDisposed())
||(source instanceof Settlement && ((Settlement)source).isDisposed())) {
if (sourceLocation==null) {
logger.warning("sourceLocation==null for source "+source.getId());
out.writeAttribute("source", owner.getId());
} else {
out.writeAttribute("source", sourceLocation.getId());
}
} else {
out.writeAttribute("source", source.getId());
}
}
if (display != null) {
out.writeAttribute("display", display.getId());
}
out.writeAttribute("type", type.toString());
out.writeAttribute("ID", getId());
out.writeAttribute("hasBeenDisplayed", String.valueOf(beenDisplayed));
if (data != null) {
toArrayElement("data", data, out);
}
out.writeEndElement();
}
/**
* Initialize this object from an XML-representation of this object.
* @param in The input stream with the XML.
* @throws XMLStreamException if a problem was encountered
* during parsing.
*/
@Override
public void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException {
setId(in.getAttributeValue(null, "ID"));
type = Enum.valueOf(MessageType.class, getAttribute(in, "type", MessageType.DEFAULT.toString()));
beenDisplayed = Boolean.parseBoolean(in.getAttributeValue(null, "hasBeenDisplayed"));
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals("data")) {
data = readFromArrayElement("data", in, new String[0]);
}
}
}
/**
* Initialize this object from an XML-representation of this object.
* @param in The input stream with the XML.
* @param game a <code>Game</code> value
* @exception XMLStreamException if a problem was encountered
* during parsing.
*/
public void readFromXML(XMLStreamReader in, Game game) throws XMLStreamException {
setId(in.getAttributeValue(null, "ID"));
String ownerPlayer = in.getAttributeValue(null, "owner");
owner = (Player)game.getFreeColGameObject(ownerPlayer);
type = Enum.valueOf(MessageType.class, getAttribute(in, "type", MessageType.DEFAULT.toString()));
beenDisplayed = Boolean.parseBoolean(in.getAttributeValue(null, "hasBeenDisplayed"));
String sourceString = in.getAttributeValue(null, "source");
source = game.getFreeColGameObject(sourceString);
if (source == null) {
logger.warning("source null from string " + sourceString);
source = owner;
}
String displayString = in.getAttributeValue(null, "display");
if (displayString != null) {
// usually referring to a unit, colony or player
display = game.getFreeColGameObject(displayString);
if (display==null) {
// either the unit, colony has been killed/destroyed
// or the message refers to goods or building type
try {
display = Reformation.getSpecification().getType(displayString);
} catch (IllegalArgumentException e) {
// do nothing
display = owner;
logger.warning("display null from string " + displayString);
}
}
}
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals("data")) {
data = readFromArrayElement("data", in, new String[0]);
}
}
verifyFields();
owner.addModelMessage(this);
}
}
| gpl-2.0 |
SkidJava/BaseClient | new_1.8.8/optfine/CustomSkyLayer.java | 10956 | package optfine;
import java.util.Properties;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
public class CustomSkyLayer
{
public String source = null;
private int startFadeIn = -1;
private int endFadeIn = -1;
private int startFadeOut = -1;
private int endFadeOut = -1;
private int blend = 1;
private boolean rotate = false;
private float speed = 1.0F;
private float[] axis;
public int textureId;
public static final float[] DEFAULT_AXIS = new float[] {1.0F, 0.0F, 0.0F};
public CustomSkyLayer(Properties p_i31_1_, String p_i31_2_)
{
this.axis = DEFAULT_AXIS;
this.textureId = -1;
this.source = p_i31_1_.getProperty("source", p_i31_2_);
this.startFadeIn = this.parseTime(p_i31_1_.getProperty("startFadeIn"));
this.endFadeIn = this.parseTime(p_i31_1_.getProperty("endFadeIn"));
this.startFadeOut = this.parseTime(p_i31_1_.getProperty("startFadeOut"));
this.endFadeOut = this.parseTime(p_i31_1_.getProperty("endFadeOut"));
this.blend = Blender.parseBlend(p_i31_1_.getProperty("blend"));
this.rotate = this.parseBoolean(p_i31_1_.getProperty("rotate"), true);
this.speed = this.parseFloat(p_i31_1_.getProperty("speed"), 1.0F);
this.axis = this.parseAxis(p_i31_1_.getProperty("axis"), DEFAULT_AXIS);
}
private int parseTime(String p_parseTime_1_)
{
if (p_parseTime_1_ == null)
{
return -1;
}
else
{
String[] astring = Config.tokenize(p_parseTime_1_, ":");
if (astring.length != 2)
{
Config.warn("Invalid time: " + p_parseTime_1_);
return -1;
}
else
{
String s = astring[0];
String s1 = astring[1];
int i = Config.parseInt(s, -1);
int j = Config.parseInt(s1, -1);
if (i >= 0 && i <= 23 && j >= 0 && j <= 59)
{
i = i - 6;
if (i < 0)
{
i += 24;
}
int k = i * 1000 + (int)((double)j / 60.0D * 1000.0D);
return k;
}
else
{
Config.warn("Invalid time: " + p_parseTime_1_);
return -1;
}
}
}
}
private boolean parseBoolean(String p_parseBoolean_1_, boolean p_parseBoolean_2_)
{
if (p_parseBoolean_1_ == null)
{
return p_parseBoolean_2_;
}
else if (p_parseBoolean_1_.toLowerCase().equals("true"))
{
return true;
}
else if (p_parseBoolean_1_.toLowerCase().equals("false"))
{
return false;
}
else
{
Config.warn("Unknown boolean: " + p_parseBoolean_1_);
return p_parseBoolean_2_;
}
}
private float parseFloat(String p_parseFloat_1_, float p_parseFloat_2_)
{
if (p_parseFloat_1_ == null)
{
return p_parseFloat_2_;
}
else
{
float f = Config.parseFloat(p_parseFloat_1_, Float.MIN_VALUE);
if (f == Float.MIN_VALUE)
{
Config.warn("Invalid value: " + p_parseFloat_1_);
return p_parseFloat_2_;
}
else
{
return f;
}
}
}
private float[] parseAxis(String p_parseAxis_1_, float[] p_parseAxis_2_)
{
if (p_parseAxis_1_ == null)
{
return p_parseAxis_2_;
}
else
{
String[] astring = Config.tokenize(p_parseAxis_1_, " ");
if (astring.length != 3)
{
Config.warn("Invalid axis: " + p_parseAxis_1_);
return p_parseAxis_2_;
}
else
{
float[] afloat = new float[3];
for (int i = 0; i < astring.length; ++i)
{
afloat[i] = Config.parseFloat(astring[i], Float.MIN_VALUE);
if (afloat[i] == Float.MIN_VALUE)
{
Config.warn("Invalid axis: " + p_parseAxis_1_);
return p_parseAxis_2_;
}
if (afloat[i] < -1.0F || afloat[i] > 1.0F)
{
Config.warn("Invalid axis values: " + p_parseAxis_1_);
return p_parseAxis_2_;
}
}
float f2 = afloat[0];
float f = afloat[1];
float f1 = afloat[2];
if (f2 * f2 + f * f + f1 * f1 < 1.0E-5F)
{
Config.warn("Invalid axis values: " + p_parseAxis_1_);
return p_parseAxis_2_;
}
else
{
float[] afloat1 = new float[] {f1, f, -f2};
return afloat1;
}
}
}
}
public boolean isValid(String p_isValid_1_)
{
if (this.source == null)
{
Config.warn("No source texture: " + p_isValid_1_);
return false;
}
else
{
this.source = TextureUtils.fixResourcePath(this.source, TextureUtils.getBasePath(p_isValid_1_));
if (this.startFadeIn >= 0 && this.endFadeIn >= 0 && this.endFadeOut >= 0)
{
int i = this.normalizeTime(this.endFadeIn - this.startFadeIn);
if (this.startFadeOut < 0)
{
this.startFadeOut = this.normalizeTime(this.endFadeOut - i);
}
int j = this.normalizeTime(this.startFadeOut - this.endFadeIn);
int k = this.normalizeTime(this.endFadeOut - this.startFadeOut);
int l = this.normalizeTime(this.startFadeIn - this.endFadeOut);
int i1 = i + j + k + l;
if (i1 != 24000)
{
Config.warn("Invalid fadeIn/fadeOut times, sum is more than 24h: " + i1);
return false;
}
else if (this.speed < 0.0F)
{
Config.warn("Invalid speed: " + this.speed);
return false;
}
else
{
return true;
}
}
else
{
Config.warn("Invalid times, required are: startFadeIn, endFadeIn and endFadeOut.");
return false;
}
}
}
private int normalizeTime(int p_normalizeTime_1_)
{
while (p_normalizeTime_1_ >= 24000)
{
p_normalizeTime_1_ -= 24000;
}
while (p_normalizeTime_1_ < 0)
{
p_normalizeTime_1_ += 24000;
}
return p_normalizeTime_1_;
}
public void render(int p_render_1_, float p_render_2_, float p_render_3_)
{
float f = p_render_3_ * this.getFadeBrightness(p_render_1_);
f = Config.limit(f, 0.0F, 1.0F);
if (f >= 1.0E-4F)
{
GlStateManager.bindTexture(this.textureId);
Blender.setupBlend(this.blend, f);
GlStateManager.pushMatrix();
if (this.rotate)
{
GlStateManager.rotate(p_render_2_ * 360.0F * this.speed, this.axis[0], this.axis[1], this.axis[2]);
}
Tessellator tessellator = Tessellator.getInstance();
GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F);
this.renderSide(tessellator, 4);
GlStateManager.pushMatrix();
GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F);
this.renderSide(tessellator, 1);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F);
this.renderSide(tessellator, 0);
GlStateManager.popMatrix();
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
this.renderSide(tessellator, 5);
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
this.renderSide(tessellator, 2);
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
this.renderSide(tessellator, 3);
GlStateManager.popMatrix();
}
}
private float getFadeBrightness(int p_getFadeBrightness_1_)
{
if (this.timeBetween(p_getFadeBrightness_1_, this.startFadeIn, this.endFadeIn))
{
int k = this.normalizeTime(this.endFadeIn - this.startFadeIn);
int l = this.normalizeTime(p_getFadeBrightness_1_ - this.startFadeIn);
return (float)l / (float)k;
}
else if (this.timeBetween(p_getFadeBrightness_1_, this.endFadeIn, this.startFadeOut))
{
return 1.0F;
}
else if (this.timeBetween(p_getFadeBrightness_1_, this.startFadeOut, this.endFadeOut))
{
int i = this.normalizeTime(this.endFadeOut - this.startFadeOut);
int j = this.normalizeTime(p_getFadeBrightness_1_ - this.startFadeOut);
return 1.0F - (float)j / (float)i;
}
else
{
return 0.0F;
}
}
private void renderSide(Tessellator p_renderSide_1_, int p_renderSide_2_)
{
WorldRenderer worldrenderer = p_renderSide_1_.getWorldRenderer();
double d0 = (double)(p_renderSide_2_ % 3) / 3.0D;
double d1 = (double)(p_renderSide_2_ / 3) / 2.0D;
worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX);
worldrenderer.pos(-100.0D, -100.0D, -100.0D).tex(d0, d1).endVertex();
worldrenderer.pos(-100.0D, -100.0D, 100.0D).tex(d0, d1 + 0.5D).endVertex();
worldrenderer.pos(100.0D, -100.0D, 100.0D).tex(d0 + 0.3333333333333333D, d1 + 0.5D).endVertex();
worldrenderer.pos(100.0D, -100.0D, -100.0D).tex(d0 + 0.3333333333333333D, d1).endVertex();
p_renderSide_1_.draw();
}
public boolean isActive(int p_isActive_1_)
{
return !this.timeBetween(p_isActive_1_, this.endFadeOut, this.startFadeIn);
}
private boolean timeBetween(int p_timeBetween_1_, int p_timeBetween_2_, int p_timeBetween_3_)
{
return p_timeBetween_2_ <= p_timeBetween_3_ ? p_timeBetween_1_ >= p_timeBetween_2_ && p_timeBetween_1_ <= p_timeBetween_3_ : p_timeBetween_1_ >= p_timeBetween_2_ || p_timeBetween_1_ <= p_timeBetween_3_;
}
}
| gpl-2.0 |
hankqin/device-manager | device-zjjs/src/com/yykj/micromsg/services/impl/NopaymetnRecordService.java | 4010 | package com.yykj.micromsg.services.impl;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;
import com.yykj.micromsg.services.INopaymetnRecordService;
import com.yykj.system.entity.hisentity.Billinfo5001;
import com.yykj.system.entity.hisentity.BilllDetail5001;
import com.yykj.system.entity.requestenity.BillInfo2015004;
import com.yykj.system.entity.requestenity.BilllDetail2015004;
import com.yykj.system.socket.socketclient4his.HandlerHis2006;
import com.yykj.system.socket.socketclient4his.HandlerHis5001;
@Service("nopaymetnRecordService")
public class NopaymetnRecordService implements INopaymetnRecordService {
public String getNopayMentRecord(String idcardNum, String wxappid) {
String returnval = null;
try {
Map<String, String> map_param = new HashMap<String, String>();
map_param.put("UserId", wxappid);
map_param.put("CardTypeID", "1");
Map<String, String> map_hisResponse_2006 = HandlerHis2006.handler2006(map_param);
if ((map_hisResponse_2006.get("ResultCode")).equals("1")){
return null;
}
String PatientID = (String) map_hisResponse_2006.get("PatientID");
map_param.put("PatientID", PatientID);
Billinfo5001 billinfo5001 = HandlerHis5001.handler5001(map_param);
if (billinfo5001.getResultCode().equals("1")) {
return null;
}
List<BilllDetail5001> billDetails = billinfo5001.getBillDetail5001s();
List<String> receiptNos = new ArrayList<String>();
for (BilllDetail5001 billlDetail5001 : billDetails) {
String receiptNo = billlDetail5001.getReceiptNo();
if (!receiptNos.contains(receiptNo)){
receiptNos.add(receiptNo);
}
}
List<BillInfo2015004> billInfo2015004s = new ArrayList<BillInfo2015004>();
for (String receiptNo : receiptNos) {
int count = 0;
double shouldMoney = 0.0D;
double actualMoney = 0.0D;
BillInfo2015004 billInfo2015004 = new BillInfo2015004();
List<BilllDetail2015004> billDetails2015004s = new ArrayList<BilllDetail2015004>();
for (BilllDetail5001 billlDetail5001 : billDetails) {
if (receiptNo.equals(billlDetail5001.getReceiptNo())) {
if (count == 0) {
billInfo2015004.setReceiptNo(receiptNo);
billInfo2015004.setReceiptTime(billlDetail5001.getReceiptTime());
billInfo2015004.setBillDept(billlDetail5001.getBillDept());
billInfo2015004.setDoctor(billlDetail5001.getDoctor());
}
shouldMoney += Double.valueOf(billlDetail5001.getShouldMoney()).doubleValue();
actualMoney += Double.valueOf(billlDetail5001.getActualMoney()).doubleValue();
BilllDetail2015004 billlDetail2015004 = new BilllDetail2015004();
billlDetail2015004.setExecDept(billlDetail5001.getExecDept());
billlDetail2015004.setFeesType(billlDetail5001.getFeesType());
billlDetail2015004.setFeesItem(billlDetail5001.getFeesItem());
billlDetail2015004.setItemID(billlDetail5001.getItemID());
billlDetail2015004.setItemName(billlDetail5001.getItemName());
billlDetail2015004.setItemUnit(billlDetail5001.getItemUnit());
billlDetail2015004.setNum(billlDetail5001.getNum());
billlDetail2015004.setPrice(billlDetail5001.getPrice());
billlDetail2015004.setShouldMoney(billlDetail5001.getShouldMoney());
billlDetail2015004.setActualMoney(billlDetail5001.getActualMoney());
billDetails2015004s.add(billlDetail2015004);
}
}
DecimalFormat df = new DecimalFormat("######0.00");
billInfo2015004.setShouldMoney(String.valueOf(df.format(shouldMoney)));
billInfo2015004.setActualMoney(String.valueOf(df.format(actualMoney)));
billInfo2015004.setDatails(billDetails2015004s);
billInfo2015004s.add(billInfo2015004);
}
JSONArray dataJson = JSONArray.fromObject(billInfo2015004s);
returnval = dataJson.toString();
} catch (Exception e) {
e.printStackTrace();
}
return returnval;
}
} | gpl-2.0 |
ZabinX/DuskRPG | DuskFiles/Dusk2.7.3src/DuskEngine.java | 78814 | /*
All code copyright Tom Weingarten (captaint@home.com) 2000
Tom Weingarten makes no assurances as to the reliability or
functionality of this code. Use at your own risk.
You are free to edit or redistribute this code or any portion
at your wish, under the condition that you do not edit or
remove this license, and accompany it with all redistributions.
*/
import java.io.*;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.util.Vector;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Date;
/**
*DuskEngine is the center of the Dusk game.
*
*@author Tom Weingarten
*/
public class DuskEngine implements Runnable
{
//Logger
Log log;
//Prefs:
int port=7400,
trackerport=7401,
maxconnections=0,
petcost=100,
merchantimage,
signimage,
battlesound=-1,
mobrespawnspeed,
viewrange=5,
oldviewrange=0,
mapsize=11,
titlecap=0,
noChannelMax=600, // defalut 600=10 minutes
namecap=20, //default 20
messagecap=120, //default 120
changeRaceCpLimit=100, //default 100cp
logLevel=Log.ERROR,
traincost=100,
expgainmod=10;
double gplosemod=1D/16D, //default 1/16
explosemod=1D/16D,
gpfleemod=1D/64D, //default 1/64
expfleemod=1D/64D;
long lngMobTicks=1000, //default 1000 milliseconds(1 second) per tick
lngPlayerTicks=250, //default 250 milliseconds(1/4 second) per tick
floodLimit=1000; //default 1000 milliseconds(1 second) btw messages
String trackername="Just Some World.",
site="none",
strRCAddress,
strRCName,
strLogFile=null,
strMusicAddress;
boolean blnMusic=false,
blnLineOfSight=false,
blnAI=false,
blnIPF=false,
tracker=true,
blnSavingGame=false,
blnShuttingDown=false;
Script scrCanSeeLivingThing=null,
scrCanMoveThroughLivingThing=null,
scrCanAttack=null,
scrOnStart=null,
scrOnDeath=null,
scrOnLogOut=null;
//End Prefs
static String version="2.6.2.W42";
Date datStart= new Date(System.currentTimeMillis());
protected int MapRows,
MapColumns;
protected short shrMap[][];
protected short shrMapOwnerPrivs[][];
protected int intMapOwnerID[][];
protected Config IDtoName;
protected DuskObject objEntities[][];
Vector vctSockets,
vctMerchants,
vctMobs,
vctItems,
vctBattles,
vctSigns,
vctPets,
vctProps,
vctTiles,
vctTileActions,
vctSeeTiles,
vctFactions,
vctSpellGroups,
vctBannedIP,
vctCheckConditions;
VariableSet varVariables;
VariableSet varIP;
private long ID=0;
boolean blnVariableListChanged=false,
blnMapHasChanged=false,
blnMobListChanged=false,
blnSignListChanged=false,
blnMerchantListChanged=false,
blnPropListChanged=false;
public DuskEngine()
{
RandomAccessFile rafFile = null;
vctSockets = new Vector(0,10);
vctItems = new Vector(0,10);
vctMobs = new Vector(0,10);
vctSigns = new Vector(0,10);
vctMerchants = new Vector(0,10);
vctBattles = new Vector(0,10);
vctPets = new Vector(0,10);
vctProps = new Vector(0,10);
vctTiles = new Vector(0,1);
vctTileActions = new Vector(0,1);
vctSeeTiles = new Vector(0,1);
vctFactions = new Vector(0,5);
vctSpellGroups = new Vector(0,1);
vctBannedIP = new Vector(0,1);
vctCheckConditions = new Vector(0,5);
varVariables = new VariableSet();
varIP = new VariableSet();
log = new Log(System.out);
try
{
int i=0,
i2=0;
String strStore;
loadPrefs();
// Load Map
File newmap = new File("shortmap");
if (newmap.exists())
{
rafFile = new RandomAccessFile("shortmap", "r");
log.printMessage(Log.INFO,"Loading Map...");
MapColumns = rafFile.readInt();
MapRows = rafFile.readInt();
log.printMessage(Log.VERBOSE,MapColumns + "/" + MapRows);
shrMap = new short[MapColumns][MapRows];
objEntities = new DuskObject[MapColumns][MapRows];
for (i=0;i<MapColumns;i++)
{
for (i2=0;i2<MapRows;i2++)
{
shrMap[i][i2] = rafFile.readShort();
}
}
rafFile.close();
}else
{
rafFile = new RandomAccessFile("map", "r");
log.printMessage(Log.INFO,"Converting old map to new short format...");
MapColumns = rafFile.readInt();
MapRows = rafFile.readInt();
log.printMessage(Log.VERBOSE,"Map size: "+MapColumns + "/" + MapRows);
shrMap = new short[MapColumns][MapRows];
objEntities = new DuskObject[MapColumns][MapRows];
for (i=0;i<MapColumns;i++)
{
for (i2=0;i2<MapRows;i2++)
{
shrMap[i][i2] = rafFile.readByte();
}
}
rafFile.close();
}
log.printMessage(Log.INFO,"Map Loaded...");
// Loading Map tile priviledges
File mapprivs = new File("shortmap.privs");
if (mapprivs.exists())
{
rafFile = new RandomAccessFile("shortmap.privs", "r");
log.printMessage(Log.INFO,"Loading Map Tile Privs...");
int PrivsColumns = rafFile.readInt();
int PrivsRows = rafFile.readInt();
if (PrivsColumns != MapColumns || PrivsRows != MapRows)
{
log.printMessage(Log.ERROR,"Map privs array size ("+PrivsColumns + "/" + PrivsRows+") does not match map size ("+MapColumns + "/" + MapRows+")");
}
log.printMessage(Log.ALWAYS,PrivsColumns + "/" + PrivsRows);
shrMapOwnerPrivs = new short[PrivsColumns][PrivsRows];
for (i=0;i<PrivsColumns;i++)
{
for (i2=0;i2<PrivsRows;i2++)
{
shrMapOwnerPrivs[i][i2] = rafFile.readShort();
}
}
rafFile.close();
}
// Loading Map tile ownership
File mapowners = new File("shortmap.owner");
File ownerlist = new File("tile_owner_list");
if (mapowners.exists() && ownerlist.exists())
{
IDtoName = new Config(this, "tile_owner_list");
rafFile = new RandomAccessFile("shortmap.owner", "r");
log.printMessage(Log.INFO,"Loading Map Tile Ownership...");
int OwnColumns = rafFile.readInt();
int OwnRows = rafFile.readInt();
if (OwnColumns != MapColumns || OwnRows != MapRows)
{
log.printMessage(Log.ERROR,"Map ownership array size ("+OwnColumns + "/" + OwnRows+") does not match map size ("+MapColumns + "/" + MapRows+")");
}
log.printMessage(Log.ALWAYS,OwnColumns + "/" + OwnRows);
intMapOwnerID = new int[OwnColumns][OwnRows];
for (i=0;i<OwnColumns;i++)
{
for (i2=0;i2<OwnRows;i2++)
{
intMapOwnerID[i][i2] = rafFile.readInt();
}
}
rafFile.close();
}
// Load Merchants
try
{
rafFile = new RandomAccessFile("merchants", "r");
Merchant mrcStore;
log.printMessage(Log.INFO,"Loading Merchants...");
strStore = rafFile.readLine();
while (!(strStore == null || strStore.equals("")))
{
mrcStore = new Merchant(this);
mrcStore.vctItems = new Vector(0);
mrcStore.intLocX = Integer.parseInt(strStore);
mrcStore.intLocY = Integer.parseInt(rafFile.readLine());
log.printMessage(Log.VERBOSE,"Merchant("+mrcStore.intLocX+","+mrcStore.intLocY+")");
strStore = rafFile.readLine();
while (strStore != null && !strStore.equals("") && !strStore.equalsIgnoreCase("end"))
{
log.printMessage(Log.DEBUG,"\t"+strStore);
mrcStore.vctItems.addElement(strStore);
strStore = rafFile.readLine();
}
if (mrcStore.intLocX > MapColumns || mrcStore.intLocY > MapRows
|| mrcStore.intLocX < 0 || mrcStore.intLocY < 0)
{
log.printMessage(Log.VERBOSE,"Previous merchant is off of the map, ignoring");
blnMerchantListChanged = true;
} else {
vctMerchants.addElement(mrcStore);
addDuskObject(mrcStore);
}
strStore = rafFile.readLine();
}
}catch (Exception e)
{
log.printError("DuskEngine():While loading merchants", e);
}
rafFile.close();
// Load Mobs
LivingThing thnStore;
rafFile = new RandomAccessFile("mobs", "r");
log.printMessage(Log.INFO,"Loading Mobs...");
strStore = rafFile.readLine();
while (strStore !=null)
{
if (strStore.equals(""))
{
break;
}
if (strStore.equals("mob2.3"))
{
strStore = rafFile.readLine();
log.printMessage(Log.VERBOSE,strStore);
try
{
thnStore = new Mob(strStore,
Integer.parseInt(rafFile.readLine()),
Integer.parseInt(rafFile.readLine()),
this
);
if (thnStore.intLocX > MapColumns || thnStore.intLocY > MapRows
|| thnStore.intLocX < 0 || thnStore.intLocY < 0)
{
log.printMessage(Log.VERBOSE,"Previous mob is off of the map, ignoring");
blnMobListChanged = true;
} else {
vctMobs.addElement(thnStore);
addDuskObject(thnStore);
}
}catch(Exception e)
{
log.printError("DuskEngine():While loading mobs", e);
}
}else
{
log.printMessage(Log.VERBOSE,strStore);
try
{
thnStore = new Mob(strStore,
Integer.parseInt(rafFile.readLine()),
Integer.parseInt(rafFile.readLine()),
Integer.parseInt(rafFile.readLine()),
this
);
if (thnStore.intLocX > MapColumns || thnStore.intLocY > MapRows
|| thnStore.intLocX < 0 || thnStore.intLocY < 0)
{
log.printMessage(Log.VERBOSE,"Previous mob is off of the map, ignoring");
blnMobListChanged = true;
} else {
vctMobs.addElement(thnStore);
addDuskObject(thnStore);
}
}catch(Exception e)
{
log.printError("DuskEngine():While loading mobs", e);
}
}
strStore = rafFile.readLine();
}
rafFile.close();
// Load signs
Sign sgnStore;
rafFile = new RandomAccessFile("signs", "r");
log.printMessage(Log.INFO,"Loading Signs...");
strStore = rafFile.readLine();
while (!(strStore == null || strStore.equals("")))
{
log.printMessage(Log.VERBOSE,strStore);
sgnStore = new Sign("sign",strStore,Integer.parseInt(rafFile.readLine()),Integer.parseInt(rafFile.readLine()),getID());
if (sgnStore.intLocX > MapColumns || sgnStore.intLocY > MapRows
|| sgnStore.intLocX < 0 || sgnStore.intLocY < 0)
{
log.printMessage(Log.VERBOSE,"Previous sign is off of the map, ignoring");
blnSignListChanged = true;
} else {
vctSigns.addElement(sgnStore);
addDuskObject(sgnStore);
}
strStore = rafFile.readLine();
}
rafFile.close();
// Load props
Prop prpStore;
rafFile = new RandomAccessFile("props","r");
log.printMessage(Log.INFO,"Loading Props...");
strStore = rafFile.readLine();
while (!(strStore == null || strStore.equals("")))
{
log.printMessage(Log.VERBOSE,strStore);
prpStore = getProp(strStore);
if (prpStore != null)
{
prpStore.intLocX = Integer.parseInt(rafFile.readLine());
prpStore.intLocY = Integer.parseInt(rafFile.readLine());
if (prpStore.intLocX > MapColumns || prpStore.intLocY > MapRows
|| prpStore.intLocX < 0 || prpStore.intLocY < 0)
{
log.printMessage(Log.VERBOSE,"Previous prop is off of the map, ignoring");
blnPropListChanged = true;
} else {
vctProps.addElement(prpStore);
addDuskObject(prpStore);
}
}
strStore = rafFile.readLine();
}
rafFile.close();
// Load global variables
String strVarName;
int intType;
String strObject;
double dblObject;
rafFile = new RandomAccessFile("globals", "r");
log.printMessage(Log.INFO,"Loading Global Variables...");
strVarName = rafFile.readLine();
while (!(strVarName == null || strVarName.equals("")))
{
intType = Integer.parseInt(rafFile.readLine());
switch (intType)
{
case 0:
{
dblObject = (double)Double.parseDouble(rafFile.readLine());
varVariables.addVariable(strVarName, dblObject);
log.printMessage(Log.VERBOSE,strVarName+" = "+dblObject);
break;
}
case 1:
{
strObject = rafFile.readLine();
varVariables.addVariable(strVarName, strObject);
log.printMessage(Log.VERBOSE,strVarName+" = '"+strObject+"'");
break;
}
}
strVarName = rafFile.readLine();
}
rafFile.close();
//Start onBoot script
try
{
Script scrOnBoot = new Script("conf/onBoot",this,true);
scrOnBoot.runScript();
scrOnBoot.close();
log.printMessage(Log.INFO,"Ran onBoot script.");
}catch(Exception e)
{
log.printError("DuskEngine():Failed to run onBoot script, maybe it doesn't exist? (Not a fatal error)", e);
log.printMessage(Log.ALWAYS, "To create an onBoot script, type \"view conf onBoot\" in game as a high or master god.");
}
}catch(Exception e)
{
log.printError("DuskEngine()", e);
}
}
boolean isGoodIP(String strIP)
{
RandomAccessFile rafFile = null;
try
{
String strBlockedIP;
String strLowerCaseIP = strIP.toLowerCase();
rafFile = new RandomAccessFile("conf/blockedIP", "r");
strBlockedIP = rafFile.readLine();
while (strBlockedIP != null)
{
if (strLowerCaseIP.indexOf(strBlockedIP) != -1)
{
rafFile.close();
return false;
}
strBlockedIP = rafFile.readLine();
}
rafFile.close();
for (int i=0; i < vctBannedIP.size(); i++)
{
strBlockedIP = (String)vctBannedIP.elementAt(i);
if (strLowerCaseIP.indexOf(strBlockedIP) != -1)
{
return false;
}
}
}catch (Exception e)
{
log.printError("isGoodIP():Checking for bad IP address", e);
return false;
}
return true;
}
boolean isGoodName(String strName)
{
if (strName == null)
return false;
if (strName.equals("")
|| strName.length() > namecap
|| strName.toLowerCase().equals("god")
|| strName.toLowerCase().equals("default"))
return false;
String strValid = "0123456789][_'#";
char[] letters = strName.toCharArray();
char[] validChars = strValid.toCharArray();
boolean blnValid = true;
for(int n=0; n<letters.length;n++)
{
if (!Character.isLetter(letters[n]))
{
blnValid = false;
for(int i=0; i<validChars.length;i++)
{
if (letters[n] == validChars[i])
{
blnValid = true;
}
}
}
}
if (!blnValid)
{
return false;
}
RandomAccessFile rafFile = null;
try
{
String strDirtyWord;
String strLowerCaseName = strName.toLowerCase();
rafFile = new RandomAccessFile("conf/dirtyWordFile", "r");
strDirtyWord = rafFile.readLine();
while (strDirtyWord != null)
{
if (strLowerCaseName.indexOf(strDirtyWord) != -1)
{
rafFile.close();
return false;
}
strDirtyWord = rafFile.readLine();
}
rafFile.close();
}catch (Exception e)
{
log.printError("isGoodName():"+strName + " had an error checking for bad name", e);
return false;
}
return true;
}
synchronized void loadPrefs()
{
Config settings = new Config(this, "conf/prefs");
//Load Prefs
strLogFile = settings.getString("LogFileName",strLogFile);
if (strLogFile != null)
{
try
{
log = new Log(new PrintStream(new FileOutputStream(strLogFile, true),true));
} catch (Exception e)
{
log = new Log(System.out);
log.printError("loadPrefs():Opening log file \""+strLogFile+"\"", e);
}
} else
{
log = new Log(System.out);
}
log.printMessage(Log.INFO, "Loading Preferences...");
logLevel = settings.getInt("LoggingLevel",logLevel);
log.setLogLevel(logLevel);
port = settings.getInt("Port",port);
tracker = settings.getBoolean("Tracker",tracker);
trackerport = settings.getInt("TrackerPort",trackerport);
trackername = settings.getString("TrackerName",trackername);
site = settings.getString("TrackerSite",site);
strRCAddress = settings.getString("RCAddress",strRCAddress);
strRCName = settings.getString("RCName",strRCName);
maxconnections = settings.getInt("MaxConnections",maxconnections);
blnMusic = settings.getBoolean("Music",blnMusic);
blnAI = settings.getBoolean("Ai",blnAI);
blnLineOfSight = settings.getBoolean("LineOfSight",blnLineOfSight);
blnIPF = settings.getBoolean("UniqueIPFilter",blnIPF);
changeRaceCpLimit = settings.getInt("ChangeRaceCPLimit",changeRaceCpLimit);
petcost = settings.getInt("PetCost",petcost);
messagecap = settings.getInt("MessageCap",messagecap);
namecap = settings.getInt("NameCap",namecap);
titlecap = settings.getInt("TitleCap",titlecap);
noChannelMax = settings.getInt("NoChannelMax",noChannelMax);
merchantimage = settings.getInt("MerchantImage",merchantimage);
signimage = settings.getInt("SignImage",signimage);
battlesound = settings.getInt("BattleSound",battlesound);
mobrespawnspeed = -1*settings.getInt("MobReSpawnSpeed",mobrespawnspeed);
traincost = settings.getInt("TrainCost",traincost);
expgainmod = settings.getInt("ExpGainMod",expgainmod);
gplosemod = settings.getDouble("GpLoseMod",gplosemod);
explosemod = settings.getDouble("ExpLoseMod",explosemod);
gpfleemod = settings.getDouble("GpFleeMod",gpfleemod);
expfleemod = settings.getDouble("ExpFleeMod",expfleemod);
viewrange = settings.getInt("ViewRange",viewrange);
lngMobTicks = settings.getLong("MobTicks",lngMobTicks);
lngPlayerTicks = settings.getLong("PlayerTicks",lngPlayerTicks);
if (viewrange != oldviewrange)
{
oldviewrange = viewrange;
mapsize = 1+(2*viewrange);
LivingThing thnStore;
for (int i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
thnStore.resizeMap();
}
}
//Load Triggered Scripts
try
{
if (scrCanSeeLivingThing != null)
{
synchronized(scrCanSeeLivingThing)
{
scrCanSeeLivingThing.close();
scrCanSeeLivingThing = new Script("conf/canSeeLivingThing",this,true);
}
} else
{
scrCanSeeLivingThing = new Script("conf/canSeeLivingThing",this,true);
}
}catch(Exception e)
{
scrCanSeeLivingThing = null;
}
try
{
if (scrCanMoveThroughLivingThing != null)
{
synchronized(scrCanMoveThroughLivingThing)
{
scrCanMoveThroughLivingThing.close();
scrCanMoveThroughLivingThing= new Script("conf/canMoveThroughLivingThing",this,true);
}
}else
{
scrCanMoveThroughLivingThing= new Script("conf/canMoveThroughLivingThing",this,true);
}
}catch(Exception e)
{
scrCanMoveThroughLivingThing = null;
}
try
{
if (scrCanAttack != null)
{
synchronized(scrCanAttack)
{
scrCanAttack.close();
scrCanAttack = new Script("conf/canAttack",this,true);
}
} else
{
scrCanAttack = new Script("conf/canAttack",this,true);
}
}catch(Exception e)
{
scrCanAttack = null;
}
try
{
if (scrOnStart != null)
{
synchronized(scrOnStart)
{
scrOnStart.close();
scrOnStart = new Script("conf/onStart",this,true);
}
} else
{
scrOnStart = new Script("conf/onStart",this,true);
}
}catch(Exception e)
{
scrOnStart = null;
}
try
{
if (scrOnDeath != null)
{
synchronized(scrOnDeath)
{
scrOnDeath.close();
scrOnDeath = new Script("conf/onDeath",this,true);
}
} else
{
scrOnDeath = new Script("conf/onDeath",this,true);
}
}catch(Exception e)
{
scrOnDeath = null;
}
try
{
if (scrOnLogOut != null)
{
synchronized(scrOnLogOut)
{
scrOnLogOut.close();
scrOnLogOut = new Script("conf/onLogOut",this,true);
}
} else
{
scrOnLogOut = new Script("conf/onLogOut",this,true);
}
}catch(Exception e)
{
scrOnLogOut = null;
}
// Load Tile Scripts
synchronized(vctTiles)
{
try
{
int i;
for (i=0;i<vctTiles.size();i++)
{
((Script)vctTiles.elementAt(i)).close();
}
vctTiles = new Vector(0);
for (i=0;true;i++)
{
try
{
vctTiles.addElement(new Script("defTileScripts/"+i,this,true));
}catch(Exception e)
{
break;
}
}
}catch (Exception e) { }
}
synchronized(vctTileActions)
{
try
{
int i;
for (i=0;i<vctTileActions.size();i++)
{
((Script)vctTileActions.elementAt(i)).close();
}
vctTileActions = new Vector(0);
for (i=0;true;i++)
{
try
{
vctTileActions.addElement(new Script("defTileActions/"+i,this,true));
}catch(Exception e)
{
break;
}
}
}catch (Exception e) { }
}
synchronized(vctSeeTiles)
{
try
{
int i;
for (i=0;i<vctSeeTiles.size();i++)
{
((Script)vctSeeTiles.elementAt(i)).close();
}
vctSeeTiles = new Vector(0);
for (i=0;true;i++)
{
try
{
vctSeeTiles.addElement(new Script("defTileSeeScripts/"+i,this,true));
}catch(Exception e)
{
break;
}
}
}catch (Exception e) { }
}
}
synchronized long getID()
{
ID++;
return ID;
}
void chatMessage(String inMessage, String strFrom)
{
int i;
strFrom = strFrom.toLowerCase();
LivingThing thnStore;
log.printMessage(Log.ALWAYS,inMessage);
for (i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
if (!thnStore.vctIgnore.contains(strFrom))
{
thnStore.chatMessage(inMessage);
}
}
}
void chatMessage(String inMessage, int intLocX, int intLocY, String strFrom)
{
strFrom = strFrom.toLowerCase();
LivingThing thnStore;
log.printMessage(Log.ALWAYS,inMessage);
int i,
i2,
i3;
DuskObject objStore;
i=0;
if (intLocX-viewrange<0)
{
i = -1*(intLocX-viewrange);
}
i2=0;
if (intLocY-viewrange<0)
{
i2 = -1*(intLocY-viewrange);
}
for (;i<mapsize;i++)
{
if (intLocX+i-viewrange<MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (intLocY+i3-viewrange<MapRows)
{
objStore = objEntities[intLocX+i-viewrange][intLocY+i3-viewrange];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer()
&& !thnStore.vctIgnore.contains(strFrom))
{
thnStore.chatMessage(inMessage);
}
}
objStore = objStore.objNext;
}
}
}
}
}
}
void chatMessage(String inMessage, String strClan, String strFrom)
{
int i;
strFrom = strFrom.toLowerCase();
LivingThing thnStore;
log.printMessage(Log.ALWAYS,inMessage);
for (i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
if (thnStore.strClan.equals(strClan)
&& !thnStore.vctIgnore.contains(strFrom))
{
thnStore.chatMessage(inMessage);
}
}
}
synchronized void refreshEntities(LivingThing thnRefresh)
{
int i,
i2,
i3,
i4;
DuskObject objStore,
objStore2;
LivingThing thnStore;
Prop prpStore;
Item itmStore;
Sign sgnStore;
Merchant mrcStore;
Vector vctNewEntities=new Vector(0,10);
String strResult=null,
strStore=null;
boolean blnCanSee;
i=0;
if (thnRefresh.intLocX-viewrange<0)
{
i = -1*(thnRefresh.intLocX-viewrange);
}
i2=0;
if (thnRefresh.intLocY-viewrange<0)
{
i2 = -1*(thnRefresh.intLocY-viewrange);
}
for (;i<mapsize;i++)
{
if (thnRefresh.intLocX+i-viewrange < MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (thnRefresh.intLocY+i3-viewrange < MapRows)
{
objStore = objEntities[thnRefresh.intLocX+i-viewrange][thnRefresh.intLocY+i3-viewrange];
if (objStore != null)
{
if (canSeeTo(thnRefresh,thnRefresh.intLocX+i-viewrange,thnRefresh.intLocY+i3-viewrange))
{
do
{
vctNewEntities.addElement(objStore);
for (i4=0;i4<thnRefresh.vctEntities.size();i4++)
{
objStore2 = (DuskObject)thnRefresh.vctEntities.elementAt(i4);
if (objStore2 == objStore)
{
thnRefresh.vctEntities.removeElementAt(i4);
i4 = -1;
break;
}
}
if (objStore.isPlayerMerchant())
{
PlayerMerchant pmrStore = (PlayerMerchant)objStore;
if (thnRefresh.intLocX == pmrStore.intLocX && thnRefresh.intLocY == pmrStore.intLocY)
{
strResult = (char)17+"";
Iterator iter = pmrStore.vctItems.keySet().iterator();
Vector vctStore;
while(iter.hasNext())
{
vctStore = (Vector)pmrStore.vctItems.get(iter.next());
itmStore = (Item)vctStore.firstElement();
int intCost = (itmStore.intCost * 3) / 4;
if (thnRefresh.strName.equalsIgnoreCase(pmrStore.strOwner))
{
intCost = 0;
}
strResult += intCost+"gp)" +strStore+"\n";
}
thnRefresh.send(strResult+".\n");
thnRefresh.updateSell();
}
}
if (objStore.isMerchant())
{
mrcStore = (Merchant)objStore;
if (thnRefresh.intLocX == mrcStore.intLocX && thnRefresh.intLocY == mrcStore.intLocY)
{
strResult = (char)17+"";
if (thnRefresh.thnFollowing != null && thnRefresh.thnFollowing.isPet())
{
for (int i5=0;i5<mrcStore.vctItems.size();i5++)
{
strStore = (String)mrcStore.vctItems.elementAt(i5);
itmStore = getItem(strStore);
if (itmStore != null)
{
strResult += itmStore.intCost+"gp)" +strStore+"\n";
}else if (strStore.equals("pet"))
{
strResult += petcost+"gp)" +strStore+"\n";
}else
{
strResult += traincost+"exp)"+strStore+"\n";
strResult += traincost+"exp)"+thnRefresh.thnFollowing.strName+":"+strStore+"\n";
}
}
}else
{
for (int i5=0;i5<mrcStore.vctItems.size();i5++)
{
strStore = (String)mrcStore.vctItems.elementAt(i5);
itmStore = getItem(strStore);
if (itmStore != null)
{
strResult += itmStore.intCost+"gp)" +strStore+"\n";
}else if (strStore.equals("pet"))
{
strResult += +petcost+"gp)" +strStore+"\n";
}else
{
strResult += traincost+"exp)"+strStore+"\n";
}
}
}
thnRefresh.send(strResult+".\n");
thnRefresh.updateSell();
}
}
if (i4 != -1)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (scrCanSeeLivingThing != null)
{
synchronized(scrCanSeeLivingThing)
{
scrCanSeeLivingThing.varVariables.clearVariables();
scrCanSeeLivingThing.varVariables.addVariable("seeing",thnRefresh);
scrCanSeeLivingThing.varVariables.addVariable("seen",thnStore);
blnCanSee = scrCanSeeLivingThing.rewindAndParseScript();
}
}else
blnCanSee=true;
if (blnCanSee)
{
if (thnStore.isPlayer())
{
strResult=(char)4+"";
if (thnStore.blnSleep)
{
strResult += "<sleeping>";
}
if (!thnStore.strClan.equals("none"))
{
strResult += "<" + thnStore.strClan + ">";
}
for (i4=0;i4<thnStore.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore.strName+"\n";
strResult += 0+"\n";
strResult += thnStore.ID+"\n";
strResult += thnStore.intLocX+"\n";
strResult += thnStore.intLocY+"\n";
strResult += thnStore.intImage+"\n";
strResult += thnStore.intStep+"\n";
thnRefresh.send(strResult);
}else if (thnStore.isMob())
{
strResult=(char)4+"";
if (thnStore.blnSleep)
{
strResult += "<sleeping>";
}
for (i4=0;i4<thnStore.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore.strName+"\n";
strResult += 4+"\n";
strResult += thnStore.ID+"\n";
strResult += thnStore.intLocX+"\n";
strResult += thnStore.intLocY+"\n";
strResult += thnStore.intImage+"\n";
thnRefresh.send(strResult);
}else if (thnStore.isPet())
{
strResult=(char)4+"";
if (thnStore.blnSleep)
{
strResult += "<sleeping>";
}
if (thnStore.hp < 0)
{
strResult += "<wounded>";
}
for (i4=0;i4<thnStore.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore.strName+"\n";
strResult += 4+"\n";
strResult += thnStore.ID+"\n";
strResult += thnStore.intLocX+"\n";
strResult += thnStore.intLocY+"\n";
strResult += thnStore.intImage+"\n";
thnRefresh.send(strResult);
}
}
}else if (objStore.isItem())
{
strResult=(char)4+"";
itmStore = (Item)objStore;
strResult += itmStore.strName+"\n";
strResult += 1+"\n";
strResult += itmStore.ID+"\n";
strResult += itmStore.intLocX+"\n";
strResult += itmStore.intLocY+"\n";
strResult += itmStore.intImage+"\n";
thnRefresh.send(strResult);
}else if (objStore.isProp())
{
strResult=(char)4+"";
prpStore = (Prop)objStore;
strResult += prpStore.strName+"\n";
strResult += 3+"\n";
strResult += prpStore.ID+"\n";
strResult += prpStore.intLocX+"\n";
strResult += prpStore.intLocY+"\n";
strResult += prpStore.intImage+"\n";
thnRefresh.send(strResult);
}else if (objStore.isSign())
{
strResult=(char)4+"";
sgnStore = (Sign)objStore;
strResult += sgnStore.strName+"\n";
strResult += 3+"\n";
strResult += sgnStore.ID+"\n";
strResult += sgnStore.intLocX+"\n";
strResult += sgnStore.intLocY+"\n";
strResult += signimage+"\n";
thnRefresh.send(strResult);
}else if (objStore.isMerchant())
{
strResult=(char)4+"";
mrcStore = (Merchant)objStore;
strResult += "Merchant\n";
strResult += 2+"\n";
strResult += mrcStore.ID+"\n";
strResult += mrcStore.intLocX+"\n";
strResult += mrcStore.intLocY+"\n";
strResult += merchantimage+"\n";
thnRefresh.send(strResult);
}else if (objStore.isPlayerMerchant())
{
strResult=(char)4+"";
PlayerMerchant pmrStore = (PlayerMerchant)objStore;
strResult += pmrStore.strOwner+"'s Merchant\n";
strResult += 2+"\n";
strResult += pmrStore.ID+"\n";
strResult += pmrStore.intLocX+"\n";
strResult += pmrStore.intLocY+"\n";
strResult += merchantimage+"\n";
thnRefresh.send(strResult);
}
}
objStore = objStore.objNext;
}while(objStore != null);
}
}
}
}
}
}
for (i=0;i<thnRefresh.vctEntities.size();i++)
{
objStore = (DuskObject)thnRefresh.vctEntities.elementAt(i);
strResult=(char)16+""+objStore.ID+"\n";
thnRefresh.send(strResult);
}
thnRefresh.vctEntities = vctNewEntities;
}
synchronized void addEntity(DuskObject objRefresh)
{
int i,
i2,
i3,
i4;
DuskObject objStore;
LivingThing thnStore,
thnStore2;
Prop prpStore;
Item itmStore;
Sign sgnStore;
Merchant mrcStore;
String strResult,
strStore;
boolean blnCanSee;
i=0;
if (objRefresh.intLocX-viewrange<0)
{
i = -1*(objRefresh.intLocX-viewrange);
}
i2=0;
if (objRefresh.intLocY-viewrange<0)
{
i2 = -1*(objRefresh.intLocY-viewrange);
}
for (;i<mapsize;i++)
{
if (objRefresh.intLocX+i-viewrange < MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (objRefresh.intLocY+i3-viewrange < MapRows)
{
objStore = objEntities[objRefresh.intLocX+i-viewrange][objRefresh.intLocY+i3-viewrange];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer())
{
if (canSeeTo(thnStore,objRefresh.intLocX,objRefresh.intLocY))
{
if (objRefresh.isLivingThing() && scrCanSeeLivingThing != null)
{
synchronized(scrCanSeeLivingThing)
{
scrCanSeeLivingThing.varVariables.clearVariables();
scrCanSeeLivingThing.varVariables.addVariable("seeing",thnStore);
scrCanSeeLivingThing.varVariables.addVariable("seen",(LivingThing)objRefresh);
blnCanSee = scrCanSeeLivingThing.rewindAndParseScript();
}
}else
blnCanSee=true;
if (blnCanSee)
{
if (!thnStore.vctEntities.contains(objRefresh))
{
strResult=(char)4+"";
thnStore.vctEntities.addElement(objRefresh);
if (objRefresh.isLivingThing())
{
thnStore2 = (LivingThing)objRefresh;
if (thnStore2.isPlayer())
{
if (thnStore2.blnSleep)
{
strResult += "<sleeping>";
}
if (!thnStore2.strClan.equals("none"))
{
strResult += "<" + thnStore2.strClan + ">";
}
for (i4=0;i4<thnStore2.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore2.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore2.strName+"\n";
strResult += 0+"\n";
strResult += thnStore2.ID+"\n";
strResult += thnStore2.intLocX+"\n";
strResult += thnStore2.intLocY+"\n";
strResult += thnStore2.intImage+"\n";
strResult += thnStore2.intStep+"\n";
}else if (thnStore2.isMob())
{
if (thnStore2.blnSleep)
{
strResult += "<sleeping>";
}
for (i4=0;i4<thnStore2.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore2.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore2.strName+"\n";
strResult += 4+"\n";
strResult += thnStore2.ID+"\n";
strResult += thnStore2.intLocX+"\n";
strResult += thnStore2.intLocY+"\n";
strResult += thnStore2.intImage+"\n";
}else if (thnStore2.isPet())
{
if (thnStore2.blnSleep)
{
strResult += "<sleeping>";
}
if (thnStore2.hp<0)
{
strResult += "<wounded>";
}
for (i4=0;i4<thnStore2.vctFlags.size();i4++)
{
strResult += "<" + (String)thnStore2.vctFlags.elementAt(i4) + ">";
}
strResult += thnStore2.strName+"\n";
strResult += 4+"\n";
strResult += thnStore2.ID+"\n";
strResult += thnStore2.intLocX+"\n";
strResult += thnStore2.intLocY+"\n";
strResult += thnStore2.intImage+"\n";
}
}else if (objRefresh.isItem())
{
itmStore = (Item)objRefresh;
strResult += itmStore.strName+"\n";
strResult += 1+"\n";
strResult += itmStore.ID+"\n";
strResult += itmStore.intLocX+"\n";
strResult += itmStore.intLocY+"\n";
strResult += itmStore.intImage+"\n";
}else if (objRefresh.isProp())
{
prpStore = (Prop)objRefresh;
strResult += prpStore.strName+"\n";
strResult += 3+"\n";
strResult += prpStore.ID+"\n";
strResult += prpStore.intLocX+"\n";
strResult += prpStore.intLocY+"\n";
strResult += prpStore.intImage+"\n";
}else if (objRefresh.isSign())
{
sgnStore = (Sign)objRefresh;
strResult += sgnStore.strName+"\n";
strResult += 3+"\n";
strResult += sgnStore.ID+"\n";
strResult += sgnStore.intLocX+"\n";
strResult += sgnStore.intLocY+"\n";
strResult += signimage+"\n";
}else if (objRefresh.isMerchant())
{
mrcStore = (Merchant)objRefresh;
strResult += "Merchant\n";
strResult += 2+"\n";
strResult += mrcStore.ID+"\n";
strResult += mrcStore.intLocX+"\n";
strResult += mrcStore.intLocY+"\n";
strResult += merchantimage+"\n";
}else if (objRefresh.isPlayerMerchant())
{
PlayerMerchant pmrStore = (PlayerMerchant)objRefresh;
strResult += pmrStore.strOwner+"'s Merchant\n";
strResult += 2+"\n";
strResult += pmrStore.ID+"\n";
strResult += pmrStore.intLocX+"\n";
strResult += pmrStore.intLocY+"\n";
strResult += merchantimage+"\n";
}
thnStore.send(strResult);
}
}
}
}
}
objStore = objStore.objNext;
}
}
}
}
}
}
synchronized void removeEntity(DuskObject objRefresh)
{
int i,
i2,
i3;
DuskObject objStore;
LivingThing thnStore;
String strResult;
i=0;
if (objRefresh.intLocX-viewrange<0)
{
i = -1*(objRefresh.intLocX-viewrange);
}
i2=0;
if (objRefresh.intLocY-viewrange<0)
{
i2 = -1*(objRefresh.intLocY-viewrange);
}
for (;i<mapsize;i++)
{
if (objRefresh.intLocX+i-viewrange < MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (objRefresh.intLocY+i3-viewrange < MapRows)
{
objStore = objEntities[objRefresh.intLocX+i-viewrange][objRefresh.intLocY+i3-viewrange];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer())
{
if (canSeeTo(thnStore,objRefresh.intLocX,objRefresh.intLocY))
{
thnStore.vctEntities.removeElement(objRefresh);
strResult=(char)16+""+objRefresh.ID+"\n";
thnStore.send(strResult);
}
}
}
objStore = objStore.objNext;
}
}
}
}
}
}
void newBattle(LivingThing pla1, LivingThing pla2)
{
if (pla2 == null)
{
return;
}
if (pla1.isPet())
{
pla1.chatMessage("Pets cannot lead battles.");
return;
}
if (pla1.batBattle != null)
{
pla1.chatMessage("You're already fighting!");
return;
}
if (pla1 == pla2)
{
pla1.chatMessage("You can't fight yourself!");
return;
}
if (pla2.isPet())
{
pla1.chatMessage("You can't attack pets.");
return;
}
// if (Math.abs(pla1.intLocX - pla2.intLocX) + Math.abs(pla1.intLocY - pla2.intLocY) > 1)
if (Math.abs(pla1.intLocX - pla2.intLocX) + Math.abs(pla1.intLocY - pla2.intLocY) > pla1.getRangeWithBonus())
{
System.out.println("mob range = "+Math.abs(pla1.intLocX - pla2.intLocX) + Math.abs(pla1.intLocY - pla2.intLocY));
System.out.println("player range = "+pla1.getRangeWithBonus());
pla1.chatMessage("They're too far away.");
return;
}
if (scrCanAttack != null)
{
synchronized(scrCanAttack)
{
scrCanAttack.varVariables.clearVariables();
scrCanAttack.varVariables.addVariable("attacking",pla1);
scrCanAttack.varVariables.addVariable("attacked",pla2);
if (!scrCanAttack.rewindAndParseScript())
{
pla1.chatMessage("You can't attack them.");
return;
}
}
}
// Check if the attacked is following the attacker
LivingThing thnStore = pla2;
while (thnStore != null)
{
if (pla1 == thnStore)
{
pla1.chatMessage("You can't attack a member of your group.");
return;
}
if (thnStore.isPlayer() && !pla1.isMob())
{
if (thnStore.strClan == null || thnStore.strClan.equalsIgnoreCase("none"))
{
pla1.chatMessage("You can't fight them.");
return;
}
}
thnStore = thnStore.thnMaster;
}
// Check if the attacker is following the attacked
thnStore = pla2;
while (thnStore != null)
{
if (pla1 == thnStore)
{
pla1.chatMessage("You can't attack a member of your group.");
return;
}
if (thnStore.isPlayer() && !pla1.isMob())
{
if (thnStore.strClan == null || thnStore.strClan.equalsIgnoreCase("none"))
{
pla1.chatMessage("You can't fight them.");
return;
}
}
thnStore = thnStore.thnFollowing;
}
if (pla2.batBattle == null)
{
if ((pla1.isPlayer() && pla2.isPlayer()) && (pla1.strClan.equals("none") || pla2.strClan.equals("none")))
{
pla1.chatMessage("Players who are not in clans cannot fight other players.");
return;
}
if (pla2.isPlayer() && overMerchant(pla2.intLocX,pla2.intLocY) != null)
{
pla1.chatMessage("You cannot attack players who are shopping.");
return;
}
if (pla2.isPlayer() && overPlayerMerchant(pla2.intLocX,pla2.intLocY) != null)
{
pla1.chatMessage("You cannot attack players who are shopping.");
return;
}
vctBattles.addElement(new Battle(pla1,pla2,this));
return;
}else
{
if (pla2.bytSide == 1)
{
thnStore = pla1;
while (thnStore != null)
{
if (thnStore.batBattle == null)
{
pla2.batBattle.addToBattle(thnStore,2);
}
thnStore = thnStore.thnFollowing;
}
thnStore = pla1.thnMaster;
while (thnStore != null)
{
if (thnStore.batBattle == null)
{
pla2.batBattle.addToBattle(thnStore,2);
}
thnStore = thnStore.thnMaster;
}
}else
{
thnStore = pla1;
while (thnStore != null)
{
if (thnStore.batBattle == null)
{
pla2.batBattle.addToBattle(thnStore,1);
}
thnStore = thnStore.thnFollowing;
}
thnStore = pla1.thnMaster;
while (thnStore != null)
{
if (thnStore.batBattle == null)
{
pla2.batBattle.addToBattle(thnStore,1);
}
thnStore = thnStore.thnMaster;
}
}
// pla2.batBattle.chatMessage("\t"+pla1.strName+" has joined the battle.");
return;
}
}
Sign getSign(String inName)
{
int i;
Sign sgnStore;
for (i=0;i<vctSigns.size();i++)
{
sgnStore = (Sign)vctSigns.elementAt(i);
if (inName.equals(sgnStore.strName))
{
return sgnStore;
}
}
return null;
}
LivingThing getPet(String inName)
{
int i;
LivingThing thnStore;
for (i=0;i<vctPets.size();i++)
{
thnStore = (LivingThing)vctPets.elementAt(i);
if (inName.equalsIgnoreCase(thnStore.strName))
{
return thnStore;
}
}
return null;
}
LivingThing getPlayer(String inName)
{
int i;
LivingThing thnStore;
for (i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
if (inName.equalsIgnoreCase(thnStore.strName))
{
return thnStore;
}
}
return null;
}
Faction getFaction(String strName)
{
int i;
Faction fctStore;
for (i=0;i<vctFactions.size();i++)
{
fctStore = (Faction)vctFactions.elementAt(i);
if (fctStore.strName.equals(strName))
return fctStore;
}
fctStore = new Faction(strName,this);
vctFactions.addElement(fctStore);
return fctStore;
}
LivingThing getMobFromVct(String inName)
{
int i=0;
LivingThing thnStore;
while (i < vctMobs.size())
{
thnStore = (LivingThing)vctMobs.elementAt(i);
if (thnStore.strName.equals(inName))
{
return thnStore;
}
i++;
}
return null;
}
Prop getProp(String strName)
{
Prop prpStore=null;
try
{
RandomAccessFile rafPropDef = new RandomAccessFile("defProps/"+strName, "r");
prpStore = new Prop(getID());
prpStore.strName = strName;
String strStore = rafPropDef.readLine();
while (!(strStore == null || strStore.equals(".")))
{
if (strStore.equalsIgnoreCase("description"))
{
prpStore.strDescription = rafPropDef.readLine();
}else if (strStore.equalsIgnoreCase("image"))
{
prpStore.intImage = Integer.parseInt(rafPropDef.readLine());
}
strStore = rafPropDef.readLine();
}
rafPropDef.close();
}catch (Exception e)
{
log.printError("getProp():While trying to get prop \""+strName+"\"", e);
}
return prpStore;
}
Prop getPropFromVct(String inName)
{
try
{
int i=0;
Prop prpStore;
while (true)
{
prpStore = (Prop)vctProps.elementAt(i);
if (prpStore.strName.equals(inName))
{
return prpStore;
}
i++;
}
}catch (Exception e)
{
log.printError("getPropFromVct():While trying to get prop \""+inName+"\"", e);
}
return null;
}
Prop getPropFromVctAndRemove(String inName)
{
try
{
int i=0;
Prop prpStore;
while (true)
{
prpStore = (Prop)vctProps.elementAt(i);
if (prpStore.strName.equals(inName))
{
vctProps.removeElementAt(i);
removeDuskObject(prpStore);
return prpStore;
}
i++;
}
}catch (Exception e)
{
log.printError("getPropFromVctAndRemove():While trying to get prop \""+inName+"\"", e);
}
return null;
}
Condition getCondition(String inName)
{
String strStore="Error opening file";
try
{
RandomAccessFile rafConditionDef = new RandomAccessFile("defConditions/"+inName.toLowerCase(), "r");
Condition cndStore = new Condition();
cndStore.strName = inName;
strStore = rafConditionDef.readLine();
while (!(strStore == null || strStore.equals(".")))
{
if (strStore.equalsIgnoreCase("duration"))
{
cndStore.intDuration = Integer.parseInt(rafConditionDef.readLine());
}else if (strStore.equalsIgnoreCase("occurance"))
{
cndStore.intOccurance = Integer.parseInt(rafConditionDef.readLine());
}else if (strStore.equalsIgnoreCase("onstart"))
{
cndStore.strOnStart = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("onoccurance"))
{
cndStore.strOnOccurance = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("onend"))
{
cndStore.strOnEnd = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("nodisplay"))
{
cndStore.blnDisplay = false;
}
strStore = rafConditionDef.readLine();
}
rafConditionDef.close();
return cndStore;
}catch (Exception e)
{
log.printError("getCondition():Parsing \""+strStore+"\" for condition \""+inName+"\"", e);
}
return null;
}
int getSpellPercent(String strName)
{
try
{
RandomAccessFile rafSpell = new RandomAccessFile("defSpells/"+strName,"r");
SpellGroup grpStore = getSpellGroup(rafSpell.readLine());
rafSpell.close();
return grpStore.getSpellPercent(strName);
}catch (Exception e)
{
log.printError("getSpellPercent():While trying to get info on spell \""+strName+"\"", e);
}
return -1;
}
SpellGroup getSpellGroup(String strName)
{
SpellGroup grpStore;
for (int i=0;i<vctSpellGroups.size();i++)
{
grpStore = (SpellGroup)vctSpellGroups.elementAt(i);
if (strName.equalsIgnoreCase(grpStore.strName))
{
return grpStore;
}
}
try
{
grpStore = new SpellGroup(strName);
RandomAccessFile rafSpellGroup = new RandomAccessFile("defSpellGroups/"+strName,"r");
try
{
String strStore = rafSpellGroup.readLine();
while (strStore != null && !strStore.equals("") && !strStore.equals("."))
{
grpStore.vctSpells.addElement(strStore);
strStore = rafSpellGroup.readLine();
}
}catch (Exception e)
{
log.printError("getSpellGroup():While trying to read spell group file for \""+strName+"\"", e);
}
rafSpellGroup.close();
vctSpellGroups.addElement(grpStore);
return grpStore;
}catch(Exception e)
{
log.printError("getSpellGroup():While trying to get spell group info for \""+strName+"\"", e);
}
return null;
}
Item getItem(String inName)
{
Item itmStore=null;
RandomAccessFile rafItemDef=null;
String strStore = "Error reading file";
try
{
File fileTest = new File("defItems/"+inName.toLowerCase());
if (!fileTest.exists())
{
return null;
}
rafItemDef = new RandomAccessFile("defItems/"+inName.toLowerCase(), "r");
//itmStore = new Item(this);
itmStore = new Item(getID());
itmStore.strName = inName;
itmStore.strDescription = "a "+inName; //default description is name
strStore = rafItemDef.readLine();
while (!(strStore == null || strStore.equals(".")))
{
if (strStore.equalsIgnoreCase("type"))
{
strStore = rafItemDef.readLine();
if (strStore.equalsIgnoreCase("item"))
{
itmStore.intType = 0;
}else if (strStore.equalsIgnoreCase("weapon"))
{
itmStore.intType = 1;
}else if (strStore.equalsIgnoreCase("armor"))
{
itmStore.intType = 2;
}else if (strStore.equalsIgnoreCase("food"))
{
itmStore.intType = 3;
}else if (strStore.equalsIgnoreCase("drink"))
{
itmStore.intType = 4;
}
}else if (strStore.equalsIgnoreCase("kind"))
{
strStore = rafItemDef.readLine();
if (strStore.equalsIgnoreCase("arms"))
{
itmStore.intKind = 0;
}else if (strStore.equalsIgnoreCase("legs"))
{
itmStore.intKind = 1;
}else if (strStore.equalsIgnoreCase("torso"))
{
itmStore.intKind = 2;
}else if (strStore.equalsIgnoreCase("waist"))
{
itmStore.intKind = 3;
}else if (strStore.equalsIgnoreCase("neck"))
{
itmStore.intKind = 4;
}else if (strStore.equalsIgnoreCase("skull"))
{
itmStore.intKind = 5;
}else if (strStore.equalsIgnoreCase("eyes"))
{
itmStore.intKind = 6;
}else if (strStore.equalsIgnoreCase("hands"))
{
itmStore.intKind = 7;
}
}else if (strStore.equalsIgnoreCase("description"))
{
itmStore.strDescription = rafItemDef.readLine();
}else if (strStore.equalsIgnoreCase("cost"))
{
itmStore.intCost = Integer.parseInt(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("durability"))
{
itmStore.lngDurability = Long.parseLong(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("uses"))
{
itmStore.intUses = Integer.parseInt(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("mod"))
{
itmStore.intMod = Integer.parseInt(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("range"))
{
itmStore.intRange = Integer.parseInt(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("image"))
{
itmStore.intImage = Integer.parseInt(rafItemDef.readLine());
}else if (strStore.equalsIgnoreCase("onuse"))
{
itmStore.strOnUseScript = rafItemDef.readLine();
}else if (strStore.equalsIgnoreCase("onwear"))
{
itmStore.strOnWearScript = rafItemDef.readLine();
}else if (strStore.equalsIgnoreCase("onunwear"))
{
itmStore.strOnUnWearScript = rafItemDef.readLine();
}else if (strStore.equalsIgnoreCase("onget"))
{
itmStore.strOnGetScript = rafItemDef.readLine();
}else if (strStore.equalsIgnoreCase("ondrop"))
{
itmStore.strOnDropScript = rafItemDef.readLine();
}
strStore = rafItemDef.readLine();
}
rafItemDef.close();
}catch (Exception e)
{
log.printError("getItem():Parsing \""+strStore+"\" for item \""+inName+"\"", e);
try
{
if (rafItemDef != null)
rafItemDef.close();
}catch(Exception e2)
{
log.printError("getItem():Closing file for item \""+inName+"\" after failed parse", e2);
}
return null;
}
return itmStore;
}
Item getItemFromVct(String inName)
{
try
{
int i;
Item itmStore;
StringTokenizer tokName = new StringTokenizer(inName, " ");
String strStore = tokName.nextToken();
i = Integer.parseInt(strStore);
strStore = inName.substring(strStore.length()+1,inName.length());
itmStore = (Item)vctItems.elementAt(i);
if (itmStore.strName.equals(strStore))
{
return itmStore;
}
}catch (Exception e)
{
log.printError("getItemFromVct():For item \""+inName+"\"", e);
}
return null;
}
Item getItemFromVctAndRemove(String inName)
{
try
{
int i;
Item itmStore;
StringTokenizer tokName = new StringTokenizer(inName, " ");
String strStore = tokName.nextToken();
i = Integer.parseInt(strStore);
strStore = inName.substring(strStore.length()+1,inName.length());
itmStore = (Item)vctItems.elementAt(i);
if (itmStore.strName.equals(strStore))
{
vctItems.removeElementAt(i);
removeDuskObject(itmStore);
return itmStore;
}
}catch (Exception e)
{
log.printError("getItemFromVctAndRemove():For item \""+inName+"\"", e);
}
return null;
}
void playSound(int intSFX,int intLocX, int intLocY)
{
int i,
i2,
i3;
DuskObject objStore;
LivingThing thnStore;
i=0;
intLocX = intLocX-viewrange;
intLocY = intLocY-viewrange;
if (intLocX<0)
{
i = -1*(intLocX);
}
i2=0;
if (intLocY<0)
{
i2 = -1*(intLocY);
}
for (;i<mapsize;i++)
{
if (intLocX+i<MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (intLocY+i3<MapRows)
{
objStore = objEntities[intLocX+i][intLocY+i3];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer())
{
thnStore.playSFX(intSFX);
}
}
objStore = objStore.objNext;
}
}
}
}
}
}
boolean canMoveTo(int inLocX, int inLocY,LivingThing thnStore)
{
int i;
LivingThing thnStore2;
DuskObject objStore=null;
Script scrStore;
boolean blnStore;
try
{
objStore = objEntities[inLocX][inLocY];
}catch(Exception e) {}
if (scrCanMoveThroughLivingThing != null)
{
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore2 = (LivingThing)objStore;
synchronized(scrCanMoveThroughLivingThing)
{
scrCanMoveThroughLivingThing.varVariables.clearVariables();
scrCanMoveThroughLivingThing.varVariables.addVariable("moving",thnStore);
scrCanMoveThroughLivingThing.varVariables.addVariable("blocking",thnStore2);
if (!scrCanMoveThroughLivingThing.rewindAndParseScript())
return false;
}
}
objStore = objStore.objNext;
}
}
try
{
scrStore = new Script("defCanMoveScripts/"+inLocX+"_"+inLocY,this,false);
scrStore.varVariables.addVariable("trigger",thnStore);
blnStore = scrStore.rewindAndParseScript();
scrStore.close();
return blnStore;
}catch (Exception e){}
try
{
scrStore = (Script)vctTiles.elementAt(shrMap[inLocX][inLocY]);
synchronized(scrStore)
{
scrStore.varVariables.clearVariables();
scrStore.varVariables.addVariable("trigger",thnStore);
blnStore = scrStore.rewindAndParseScript();
}
return blnStore;
}catch (Exception e){}
return false;
}
boolean canSee(int inLocX, int inLocY,LivingThing thnStore)
{
int i;
LivingThing thnStore2;
DuskObject objStore=null;
Script scrStore;
boolean blnStore;
try
{
scrStore = new Script("defCanSeeScripts/"+inLocX+"_"+inLocY,this,false);
scrStore.varVariables.addVariable("trigger",thnStore);
blnStore = scrStore.rewindAndParseScript();
scrStore.close();
return blnStore;
}catch (Exception e){}
try
{
scrStore = (Script)vctSeeTiles.elementAt(shrMap[inLocX][inLocY]);
synchronized(scrStore)
{
scrStore.varVariables.clearVariables();
scrStore.varVariables.addVariable("trigger",thnStore);
blnStore = scrStore.rewindAndParseScript();
}
return blnStore;
}catch (Exception e){}
return false;
}
//Following by Randall Leeds and Tom Weingarten
boolean canSeeTo(LivingThing thnStore,int destX, int destY)
{
if (Math.abs(thnStore.intLocX-destX)>viewrange || Math.abs(thnStore.intLocY-destY)>viewrange)
{
return false;
}
if (!blnLineOfSight)
return true;
int tempX = thnStore.intLocX;
int tempY = thnStore.intLocY;
while(!(Math.abs(tempX-destX)<2 && Math.abs(tempY-destY)<2))
{
if (Math.abs(tempX-destX) > Math.abs(tempY-destY))
{
if (tempX > destX)
{
try
{
if (!(canSee(tempX-1,tempY,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX--;
}else
{
try
{
if (!(canSee(tempX+1,tempY,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX++;
}
}else if (Math.abs(tempX-destX) < Math.abs(tempY-destY))
{
if (tempY > destY)
{
try
{
if (!(canSee(tempX,tempY-1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempY--;
}else
{
try
{
if (!(canSee(tempX,tempY+1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempY++;
}
}else
{
if (tempX > destX && tempY > destY)
{
try
{
if (!(canSee(tempX-1,tempY-1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX--;
tempY--;
}else if (tempX < destX && tempY < destY)
{
try
{
if (!(canSee(tempX+1,tempY+1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX++;
tempY++;
}else if (tempX > destX && tempY < destY)
{
try
{
if (!(canSee(tempX-1,tempY+1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX--;
tempY++;
}else
{
try
{
if (!(canSee(tempX+1,tempY-1,thnStore)))
return false;
}catch(Exception e)
{
return false;
}
tempX++;
tempY--;
}
}
}
return true;
}
//End contributed portion
Merchant overMerchant(int x, int y)
{
int i;
Merchant mrcStore;
DuskObject objStore;
try
{
objStore = objEntities[x][y];
}catch (Exception e)
{
return null;
}
while (objStore != null)
{
if (objStore.isMerchant())
return (Merchant)objStore;
objStore = objStore.objNext;
}
return null;
}
PlayerMerchant overPlayerMerchant(int x, int y)
{
int i;
PlayerMerchant mrcStore;
DuskObject objStore;
try
{
objStore = objEntities[x][y];
}catch (Exception e)
{
return null;
}
while (objStore != null)
{
if (objStore.isPlayerMerchant())
return (PlayerMerchant)objStore;
objStore = objStore.objNext;
}
return null;
}
synchronized void changeMap(int intLocX, int intLocY, short value)
{
if (value < 0 || value > vctTiles.size())
{
log.printMessage(Log.INFO, "Invalid value passed to changeMap("+intLocX+","+intLocY+","+value+")");
return;
}
if (intLocX < 0 || intLocX > MapColumns || intLocY < 0 || intLocY > MapRows)
{
log.printMessage(Log.INFO, "Invalid location to changeMap("+intLocX+","+intLocY+","+value+")");
return;
}
shrMap[intLocX][intLocY] = value;
blnMapHasChanged=true;
updateMap(intLocX,intLocY);
}
synchronized void resizeMap(int x, int y)
{
int i,
i2,
X,
Y;
short newMap[][]= new short[x][y];
X = MapColumns;
if (x < MapColumns)
{
X = x;
}
Y = MapRows;
if (y < MapRows)
{
Y = y;
}
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newMap[i][i2] = shrMap[i][i2];
}catch(Exception e)
{
}
}
}
shrMap = newMap;
DuskObject newEntities[][]= new DuskObject[x][y];
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newEntities[i][i2] = objEntities[i][i2];
}catch(Exception e)
{
}
}
}
objEntities = newEntities;
MapColumns = x;
MapRows = y;
LivingThing thnStore;
for (i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
thnStore.resizeMap();
}
blnMapHasChanged = true;
}
void saveMap()
{
if (blnSavingGame)
return;
try
{
blnSavingGame=true;
StringTokenizer tknStore;
Mob mobStore;
Item itmStore;
Sign sgnStore;
Merchant mrcStore;
Prop prpStore;
File deleteme;
RandomAccessFile rafFile;
int i,
i2;
if (blnMapHasChanged)
{
log.printMessage(Log.ALWAYS,"Saving map...");
synchronized(shrMap)
{
deleteme = new File("shortmap");
deleteme.delete();
rafFile = new RandomAccessFile("shortmap", "rw");
rafFile.writeInt(MapColumns);
rafFile.writeInt(MapRows);
for (i=0;i<MapColumns;i++)
{
for (i2=0;i2<MapRows;i2++)
{
rafFile.writeShort(shrMap[i][i2]);
}
}
rafFile.close();
}
String strMapLog = "shortmap_redraw";
PrintStream psMap = new PrintStream(new FileOutputStream(strMapLog, true),true);
psMap.println("# Map Saved");
psMap.close();
blnMapHasChanged=false;
}
if (blnMobListChanged)
{
log.printMessage(Log.ALWAYS,"Saving mobs...");
synchronized(vctMobs)
{
deleteme = new File("mobs");
deleteme.delete();
rafFile = new RandomAccessFile("mobs", "rw");
for (i=0;i<vctMobs.size();i++)
{
mobStore = (Mob)vctMobs.elementAt(i);
if (mobStore.blnOneUse == false)
{
if (mobStore.level == -1)
{
rafFile.writeBytes("mob2.3\n"+mobStore.strName+"\n"+mobStore.originalX+"\n"+mobStore.originalY+"\n");
}else
{
rafFile.writeBytes(mobStore.strName+"\n"+mobStore.level+"\n"+mobStore.originalX+"\n"+mobStore.originalY+"\n");
}
}
}
rafFile.close();
}
blnMobListChanged=false;
}
if (blnSignListChanged)
{
log.printMessage(Log.ALWAYS,"Saving signs...");
synchronized(vctSigns)
{
deleteme = new File("signs");
deleteme.delete();
rafFile = new RandomAccessFile("signs", "rw");
for (i=0;i<vctSigns.size();i++)
{
sgnStore = (Sign)vctSigns.elementAt(i);
rafFile.writeBytes(sgnStore.strMessage+"\n"+sgnStore.intLocX+"\n"+sgnStore.intLocY+"\n");
}
rafFile.close();
}
blnSignListChanged=false;
}
if (blnMerchantListChanged)
{
log.printMessage(Log.ALWAYS,"Saving merchants...");
synchronized(vctMerchants)
{
deleteme = new File("merchants");
deleteme.delete();
rafFile = new RandomAccessFile("merchants", "rw");
for (i=0;i<vctMerchants.size();i++)
{
mrcStore = (Merchant)vctMerchants.elementAt(i);
rafFile.writeBytes(mrcStore.intLocX+"\n"+mrcStore.intLocY+"\n");
for (i2=0;i2<mrcStore.vctItems.size();i2++)
{
rafFile.writeBytes((String)mrcStore.vctItems.elementAt(i2)+"\n");
}
rafFile.writeBytes("end\n");
}
rafFile.close();
}
blnMerchantListChanged=false;
}
if (blnPropListChanged)
{
log.printMessage(Log.ALWAYS,"Saving props...");
synchronized(vctProps)
{
deleteme = new File("props");
deleteme.delete();
rafFile = new RandomAccessFile("props", "rw");
for (i=0;i<vctProps.size();i++)
{
prpStore = (Prop)vctProps.elementAt(i);
rafFile.writeBytes(prpStore.strName+"\n"+prpStore.intLocX+"\n"+prpStore.intLocY+"\n");
}
rafFile.close();
}
blnPropListChanged=false;
}
if (blnVariableListChanged)
{
log.printMessage(Log.ALWAYS,"Saving global variables...");
synchronized(varVariables)
{
deleteme = new File("globals");
deleteme.delete();
rafFile = new RandomAccessFile("globals", "rw");
Variable varStore;
for (i=0;i<varVariables.vctVariables.size();i++)
{
varStore = (Variable)varVariables.vctVariables.elementAt(i);
if (varStore.isString() || varStore.isNumber())
{
rafFile.writeBytes(varStore.strName+"\n");
rafFile.writeBytes(varStore.bytType+"\n");
rafFile.writeBytes(varStore.objData+"\n");
}
}
rafFile.close();
}
blnVariableListChanged=false;
}
log.printMessage(Log.ALWAYS,"Saved game settings without error");
}catch (Exception e)
{
log.printError("saveMap():While saving game settings", e);
}
blnSavingGame=false;
}
void backupMap()
{
try
{
StringTokenizer tknStore;
Mob mobStore;
Item itmStore;
Sign sgnStore;
Merchant mrcStore;
Prop prpStore;
synchronized(shrMap)
{
File deleteme = new File("backup/shortmap.backup");
deleteme.delete();
RandomAccessFile rafFile = new RandomAccessFile("backup/shortmap.backup", "rw");
int i,
i2;
rafFile.writeInt(MapColumns);
rafFile.writeInt(MapRows);
for (i=0;i<MapColumns;i++)
{
for (i2=0;i2<MapRows;i2++)
{
rafFile.writeShort(shrMap[i][i2]);
}
}
rafFile.close();
deleteme = new File("backup/mobs.backup");
deleteme.delete();
rafFile = new RandomAccessFile("backup/mobs.backup", "rw");
for (i=0;i<vctMobs.size();i++)
{
mobStore = (Mob)vctMobs.elementAt(i);
if (mobStore.blnOneUse == false)
{
tknStore = new StringTokenizer(mobStore.strName," ");
rafFile.writeBytes(tknStore.nextToken()+"\n"+mobStore.level+"\n"+mobStore.originalX+"\n"+mobStore.originalY+"\n");
}
}
rafFile.close();
deleteme = new File("backup/signs.backup");
deleteme.delete();
rafFile = new RandomAccessFile("backup/signs.backup", "rw");
for (i=0;i<vctSigns.size();i++)
{
sgnStore = (Sign)vctSigns.elementAt(i);
rafFile.writeBytes(sgnStore.strMessage+"\n"+sgnStore.intLocX+"\n"+sgnStore.intLocY+"\n");
}
rafFile.close();
deleteme = new File("backup/merchants.backup");
deleteme.delete();
rafFile = new RandomAccessFile("backup/merchants.backup", "rw");
for (i=0;i<vctMerchants.size();i++)
{
mrcStore = (Merchant)vctMerchants.elementAt(i);
rafFile.writeBytes(mrcStore.intLocX+"\n"+mrcStore.intLocY+"\n");
for (i2=0;i2<mrcStore.vctItems.size();i2++)
{
rafFile.writeBytes((String)mrcStore.vctItems.elementAt(i2)+"\n");
}
rafFile.writeBytes("end\n");
}
rafFile.close();
deleteme = new File("backup/props.backup");
deleteme.delete();
rafFile = new RandomAccessFile("backup/props.backup", "rw");
for (i=0;i<vctProps.size();i++)
{
prpStore = (Prop)vctProps.elementAt(i);
rafFile.writeBytes(prpStore.strName+"\n"+prpStore.intLocX+"\n"+prpStore.intLocY+"\n");
}
rafFile.close();
}
log.printMessage(Log.ALWAYS,"Backed up game settings without error");
}catch (Exception e)
{
log.printError("backupMap():While backing up settings", e);
}
}
DuskObject getDuskObject(int x, int y, String strIn)
{
DuskObject objStore = objEntities[x][y];
while (objStore != null)
{
if (objStore.strName.equalsIgnoreCase(strIn))
{
return objStore;
}
objStore = objStore.objNext;
}
return null;
}
void pushDuskObject(DuskObject objIn)
{
synchronized(objEntities)
{
if (objIn.intLocX < 0 || objIn.intLocY < 0 || objIn.intLocX >= MapColumns || objIn.intLocY >= MapRows)
{
return;
}
DuskObject objStore;
objStore = objEntities[objIn.intLocX][objIn.intLocY];
if (objIn == objStore) // needed to add this check
{ // as the invis condition
return; // adds the mob to update the
} // the flags
if (objStore == null)
{
objEntities[objIn.intLocX][objIn.intLocY] = objIn;
}else
{
while (objStore.objNext != null)
{
if (objIn == objStore) // needed to add this check
{ // as the invis condition
return; // adds the mob to update the
} // the flags
objStore = objStore.objNext;
}
objStore.objNext = objIn;
}
}
}
void popDuskObject(DuskObject objIn)
{
synchronized(objEntities)
{
if (objIn.intLocX < 0 || objIn.intLocY < 0 || objIn.intLocX >= MapColumns || objIn.intLocY >= MapRows)
{
return;
}
if (objEntities[objIn.intLocX][objIn.intLocY] == null)
{
return;
}else
{
if (objEntities[objIn.intLocX][objIn.intLocY] == objIn)
{
objEntities[objIn.intLocX][objIn.intLocY] = objIn.objNext;
objIn.objNext = null;
}else
{
DuskObject objStore = objEntities[objIn.intLocX][objIn.intLocY];
while (objStore.objNext != null && objStore.objNext != objIn)
{
objStore = objStore.objNext;
}
if (objStore.objNext != null)
{
objStore.objNext = objStore.objNext.objNext;
}
objIn.objNext = null;
}
}
}
}
void addDuskObject(DuskObject objIn)
{
if (objIn.isLivingThing())
{
LivingThing thnStore = (LivingThing)objIn;
if (!thnStore.blnIsLoaded)
return;
}
synchronized(objEntities)
{
pushDuskObject(objIn);
addEntity(objIn);
}
}
void removeDuskObject(DuskObject objIn)
{
if (objIn.isLivingThing())
{
LivingThing thnStore = (LivingThing)objIn;
if (!thnStore.blnIsLoaded)
return;
}
synchronized(objEntities)
{
removeEntity(objIn);
popDuskObject(objIn);
}
}
void moveDuskObject(DuskObject objIn,int inLocX,int inLocY)
{
popDuskObject(objIn);
objIn.intLocX = inLocX;
objIn.intLocY = inLocY;
addDuskObject(objIn);
}
synchronized void updateMap(int intLocX, int intLocY)
{
DuskObject objStore;
LivingThing thnStore;
int i=0, i2=0, i3;
if (intLocX-viewrange<0) i = -1*(intLocX-viewrange);
if (intLocY-viewrange<0) i2 = -1*(intLocY-viewrange);
for (;i<mapsize;i++)
{
if (intLocX+i-viewrange<MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (intLocY+i3-viewrange<MapRows)
{
objStore = objEntities[intLocX+i-viewrange][intLocY+i3-viewrange];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer())
thnStore.updateMap();
}
objStore = objStore.objNext;
}
}
}
}
}
}
public void run()
{
log.printMessage(Log.ALWAYS,"Mob ticks = "+lngMobTicks);
log.printMessage(Log.ALWAYS,"Player ticks = "+lngPlayerTicks);
log.printMessage(Log.ALWAYS,"Starting Ticks");
int tick=0,
i;
LivingThing thnStore,
thnStore2;
Battle batStore;
long lngTime = System.currentTimeMillis(),
lngPause=0;
while(true)
{
try
{
//250 milliseconds per tick
lngPause = lngPlayerTicks-(System.currentTimeMillis()-lngTime);
if (lngPause > 0)
Thread.currentThread().sleep(lngPause);
lngTime = System.currentTimeMillis();
if (tick%73==0)
{
for (i=0;i<vctPets.size();i++)
{
thnStore = (LivingThing)vctPets.elementAt(i);
if (thnStore.batBattle == null)
{
if (thnStore.blnSleep)
{
thnStore.hp += 3+(thnStore.cons+thnStore.consbon);
if (thnStore.hp > (thnStore.maxhp+thnStore.hpbon))
{
thnStore.hp = (thnStore.maxhp+thnStore.hpbon);
}
thnStore.mp += 3+(thnStore.wisd+thnStore.wisdbon);
if (thnStore.mp > (thnStore.maxmp+thnStore.mpbon))
{
thnStore.mp = (thnStore.maxmp+thnStore.mpbon);
}
}else
{
thnStore.hp += 1+((thnStore.cons+thnStore.consbon)/2);
if (thnStore.hp > (thnStore.maxhp+thnStore.hpbon))
{
thnStore.hp = (thnStore.maxhp+thnStore.hpbon);
}
thnStore.mp += 1+((thnStore.wisd+thnStore.wisdbon)/2);
if (thnStore.mp > (thnStore.maxmp+thnStore.mpbon))
{
thnStore.mp = (thnStore.maxmp+thnStore.mpbon);
}
}
}
if (thnStore.thnMaster != null)
{
if (!thnStore.thnMaster.blnWorking) {
thnStore.close();
continue;
}
boolean blnTmpShouldSave = thnStore.blnShouldSave;
thnStore.thnMaster.updateStats();
thnStore.blnShouldSave = blnTmpShouldSave;
} else {
thnStore.close();
continue;
}
thnStore.savePlayer();
}
}
for (i=0;i<vctPets.size();i++)
{
thnStore = (LivingThing)vctPets.elementAt(i);
synchronized(thnStore.vctMovement)
{
if(thnStore.vctMovement.size() > 0)
{
try
{
String strStore = (String)thnStore.vctMovement.elementAt(0);
char charStore = strStore.charAt(0);
switch(charStore)
{
case 'n':
thnStore.moveN();
break;
case 's':
thnStore.moveS();
break;
case 'w':
thnStore.moveW();
break;
case 'e':
thnStore.moveE();
break;
}
thnStore.vctMovement.removeElement(thnStore.vctMovement.elementAt(0));
}catch(Exception e)
{
log.printError("DuskEngine.run():At movement tick for players", e);
}
}
}
}
//Following code submitted by Randall Leeds, revised by Tom Weingarten:
for(i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
if (!thnStore.blnWorking) {
//thnStore.closeNoMsgPlayer();
continue;
}
if (!thnStore.blnCanSave)
{
continue;
}
if (thnStore.noChannel > 0 && tick%4 == 0)
{
thnStore.noChannel--;
}
synchronized(thnStore.vctMovement)
{
if(thnStore.vctMovement.size() > 0)
{
try
{
String strStore = (String)thnStore.vctMovement.elementAt(0);
char charStore = strStore.charAt(0);
switch(charStore)
{
case 'n':
thnStore.moveN();
break;
case 's':
thnStore.moveS();
break;
case 'w':
thnStore.moveW();
break;
case 'e':
thnStore.moveE();
break;
}
thnStore.vctMovement.removeElement(thnStore.vctMovement.elementAt(0));
}catch(Exception e)
{
log.printError("DuskEngine.run():At movement tick for players", e);
}
}
}
if (tick%73 == 0)
{
if (thnStore.batBattle == null)
{
if (thnStore.blnSleep)
{
thnStore.hp += 3+(thnStore.cons+thnStore.consbon);
if (thnStore.hp > (thnStore.maxhp+thnStore.hpbon))
{
thnStore.hp = (thnStore.maxhp+thnStore.hpbon);
}
thnStore.mp += 3+(thnStore.wisd+thnStore.wisdbon);
if (thnStore.mp > (thnStore.maxmp+thnStore.mpbon))
{
thnStore.mp = (thnStore.maxmp+thnStore.mpbon);
}
}else
{
thnStore.hp += 1+((thnStore.cons+thnStore.consbon)/2);
if (thnStore.hp > (thnStore.maxhp+thnStore.hpbon))
{
thnStore.hp = (thnStore.maxhp+thnStore.hpbon);
}
thnStore.mp += 1+((thnStore.wisd+thnStore.wisdbon)/2);
if (thnStore.mp > (thnStore.maxmp+thnStore.mpbon))
{
thnStore.mp = (thnStore.maxmp+thnStore.mpbon);
}
}
thnStore.updateInfo();
thnStore.savePlayer();
}
}
}
//End of code submitted by Randall Leeds
if (tick%10 == 0)
{
for (i=0;i<vctBattles.size();i++)
{
batStore = (Battle)vctBattles.elementAt(i);
if (batStore.blnRunning == false)
{
vctBattles.removeElementAt(i);
i--;
}else
{
batStore.run();
}
}
}
if (tick>72)
{
tick = 0;
for (i=0;i<vctMobs.size();i++)
{
thnStore = (LivingThing)vctMobs.elementAt(i);
if (thnStore.batBattle == null)
{
if (thnStore.intLocX != -6)
{
thnStore.hp += 1+(thnStore.cons/2);
if (thnStore.hp > thnStore.maxhp)
{
thnStore.hp = thnStore.maxhp;
}
thnStore.mp += 1+(thnStore.wisd/2);
if (thnStore.mp > thnStore.maxmp)
{
thnStore.mp = thnStore.maxmp;
}
}else
{
thnStore.hp++;
if (thnStore.hp > 0)
{
thnStore.hp = thnStore.maxhp;
thnStore.mp = thnStore.maxmp;
thnStore.changeLocBypass(thnStore.originalX,thnStore.originalY);
}
}
}
}
for (i=0;i<vctFactions.size();i++)
{
((Faction)(vctFactions.elementAt(i))).saveFactionData();
}
}
tick++;
}catch (Exception e)
{
log.printError("DuskEngine.run():at ticks", e);
}
}
}
}
| gpl-2.0 |
Sixstring982/gastastic | src/com/lunagameserve/decarbonator/statistics/StatisticSet.java | 2009 | package com.lunagameserve.decarbonator.statistics;
import android.content.Context;
import android.graphics.Canvas;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sixstring982 on 2/23/15.
*/
public class StatisticSet {
@NotNull
private List<PolaroidSet> sets = new ArrayList<PolaroidSet>();
public StatisticSet(Context ctx, StatisticType type) {
initStatistics(ctx, type);
}
private void initStatistics(Context ctx, StatisticType type) {
for (Statistics s : Statistics.suitableStatistics(type)) {
sets.add(new PolaroidSet(ctx, s));
}
}
public byte[] getStatisticOrdinals() {
byte[] ordinals = new byte[sets.size()];
int i = 0;
for (PolaroidSet p : sets) {
ordinals[i++] = (byte)p.getStatistic().ordinal();
}
return ordinals;
}
public boolean canUpdate() {
for (PolaroidSet set : sets) {
if (set.canUpdate()) {
return true;
}
}
return false;
}
public void updatePolaroids(double totalGallons,
int maxX, int maxY) {
for (PolaroidSet set : sets) {
set.updatePolaroids(totalGallons, maxX, maxY);
}
}
public void updatePolaroids() {
for (PolaroidSet set : sets) {
set.updatePolaroids();
}
}
public void renderStoppedPolaroids(@NotNull Canvas c) {
for (PolaroidSet set : sets) {
set.renderStoppedPolaroids(c);
}
}
public void renderMovingPolaroids(@NotNull Canvas c) {
for (PolaroidSet set : sets) {
set.renderMovingPolaroids(c);
}
}
public void setOnSingleFinishMoving(
PolaroidSet.SingleFinishMovingListener onSingleFinishMoving) {
for (PolaroidSet set : sets) {
set.setOnSingleFinishMoving(onSingleFinishMoving);
}
}
}
| gpl-2.0 |
flaviomarcheni/feuc_caminho_virtual | caminhoVirtual/src/br/com/fmarcheni/feuc/controller/IndexController.java | 521 | package br.com.fmarcheni.feuc.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/pages/index.jsp").forward(req, resp);
}
} | gpl-2.0 |
dlitz/resin | modules/quercus/src/com/caucho/quercus/program/JavaClassDef.java | 44069 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.program;
import com.caucho.quercus.QuercusContext;
import com.caucho.quercus.QuercusModuleException;
import com.caucho.quercus.QuercusException;
import com.caucho.quercus.QuercusRuntimeException;
import com.caucho.quercus.annotation.*;
import com.caucho.quercus.env.*;
import com.caucho.quercus.expr.Expr;
import com.caucho.quercus.expr.LiteralExpr;
import com.caucho.quercus.function.AbstractFunction;
import com.caucho.quercus.marshal.JavaMarshal;
import com.caucho.quercus.marshal.Marshal;
import com.caucho.quercus.marshal.MarshalFactory;
import com.caucho.quercus.module.ModuleContext;
import com.caucho.util.L10N;
import com.caucho.vfs.WriteStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents an introspected Java class.
*/
public class JavaClassDef extends ClassDef {
private final static Logger log
= Logger.getLogger(JavaClassDef.class.getName());
private final static L10N L = new L10N(JavaClassDef.class);
private final ModuleContext _moduleContext;
private final String _name;
private final Class _type;
private QuercusClass _quercusClass;
private HashSet<String> _instanceOfSet;
private HashSet<String> _instanceOfSetLowerCase;
private final boolean _isAbstract;
private final boolean _isInterface;
private final boolean _isDelegate;
private boolean _isPhpClass;
private String _resourceType;
private JavaClassDef _componentDef;
protected volatile boolean _isInit;
private final HashMap<String, Value> _constMap
= new HashMap<String, Value>();
private final HashMap<String, Object> _constJavaMap
= new HashMap<String, Object>();
private final MethodMap<AbstractJavaMethod> _functionMap
= new MethodMap<AbstractJavaMethod>(null, this);
private final HashMap<StringValue, AbstractJavaMethod> _getMap
= new HashMap<StringValue, AbstractJavaMethod>();
private final HashMap<StringValue, AbstractJavaMethod> _setMap
= new HashMap<StringValue, AbstractJavaMethod>();
// _fieldMap stores all public non-static fields
// used by getField and setField
private final HashMap<StringValue, FieldMarshalPair> _fieldMap
= new HashMap<StringValue, FieldMarshalPair> ();
private AbstractJavaMethod _cons;
private AbstractJavaMethod __construct;
private JavaMethod __fieldGet;
private JavaMethod __fieldSet;
private FunctionArrayDelegate _funArrayDelegate;
private ArrayDelegate _arrayDelegate;
private JavaMethod __call;
private JavaMethod __toString;
private Method _printRImpl;
private Method _varDumpImpl;
private Method _jsonEncode;
private Method _entrySet;
private TraversableDelegate _traversableDelegate;
private CountDelegate _countDelegate;
private Method _iteratorMethod;
private Marshal _marshal;
private String _extension;
public JavaClassDef(ModuleContext moduleContext, String name, Class type)
{
super(null, name, null, new String[] {});
_moduleContext = moduleContext;
_name = name;
_type = type;
_isAbstract = Modifier.isAbstract(type.getModifiers());
_isInterface = type.isInterface();
_isDelegate = type.isAnnotationPresent(ClassImplementation.class);
if (type.isArray() && ! isArray())
throw new IllegalStateException(
L.l("'{0}' needs to be called with JavaArrayClassDef", type));
}
public JavaClassDef(ModuleContext moduleContext,
String name,
Class type,
String extension)
{
this(moduleContext, name, type);
_extension = extension;
moduleContext.addExtensionClass(extension, name);
}
private void fillInstanceOfSet(Class type, boolean isTop)
{
if (type == null)
return;
if (isTop && _isDelegate) {
_instanceOfSet.add(_name);
_instanceOfSetLowerCase.add(_name.toLowerCase(Locale.ENGLISH));
}
else {
String name = type.getSimpleName();
_instanceOfSet.add(name);
_instanceOfSetLowerCase.add(name.toLowerCase(Locale.ENGLISH));
}
fillInstanceOfSet(type.getSuperclass(), false);
Class []ifaceList = type.getInterfaces();
if (ifaceList != null) {
for (Class iface : ifaceList)
fillInstanceOfSet(iface, false);
}
}
public static JavaClassDef create(ModuleContext moduleContext,
String name, Class<?> type)
{
if (Double.class.isAssignableFrom(type)
|| Float.class.isAssignableFrom(type))
return new DoubleClassDef(moduleContext);
else if (Long.class.isAssignableFrom(type)
|| Integer.class.isAssignableFrom(type)
|| Short.class.isAssignableFrom(type)
|| Byte.class.isAssignableFrom(type))
return new LongClassDef(moduleContext);
else if (BigDecimal.class.isAssignableFrom(type))
return new BigDecimalClassDef(moduleContext);
else if (BigInteger.class.isAssignableFrom(type))
return new BigIntegerClassDef(moduleContext);
else if (String.class.isAssignableFrom(type)
|| Character.class.isAssignableFrom(type))
return new StringClassDef(moduleContext);
else if (Boolean.class.isAssignableFrom(type))
return new BooleanClassDef(moduleContext);
else if (Calendar.class.isAssignableFrom(type))
return new CalendarClassDef(moduleContext);
else if (Date.class.isAssignableFrom(type))
return new DateClassDef(moduleContext);
else if (URL.class.isAssignableFrom(type))
return new URLClassDef(moduleContext);
else if (Map.class.isAssignableFrom(type))
return new JavaMapClassDef(moduleContext, name, type);
else if (List.class.isAssignableFrom(type))
return new JavaListClassDef(moduleContext, name, type);
else if (Collection.class.isAssignableFrom(type)
&& ! Queue.class.isAssignableFrom(type))
return new JavaCollectionClassDef(moduleContext, name, type);
else
return null;
}
/**
* Returns the class name.
*/
@Override
public String getName()
{
return _name;
}
/**
* Returns the class name.
*/
public String getSimpleName()
{
return _type.getSimpleName();
}
public Class getType()
{
return _type;
}
/*
* Returns the type of this resource.
*/
public String getResourceType()
{
return _resourceType;
}
protected ModuleContext getModuleContext()
{
return _moduleContext;
}
/*
* Returns the name of the extension that this class is part of.
*/
@Override
public String getExtension()
{
return _extension;
}
@Override
public boolean isA(String name)
{
if (_instanceOfSet == null) {
_instanceOfSet = new HashSet<String>();
_instanceOfSetLowerCase = new HashSet<String>();
fillInstanceOfSet(_type, true);
}
return (_instanceOfSet.contains(name)
|| _instanceOfSetLowerCase.contains(name.toLowerCase(Locale.ENGLISH)));
}
/**
* Adds the interfaces to the set
*/
@Override
public void addInterfaces(HashSet<String> interfaceSet)
{
addInterfaces(interfaceSet, _type, true);
}
protected void addInterfaces(HashSet<String> interfaceSet,
Class type,
boolean isTop)
{
if (type == null)
return;
interfaceSet.add(_name.toLowerCase(Locale.ENGLISH));
interfaceSet.add(type.getSimpleName().toLowerCase(Locale.ENGLISH));
if (type.getInterfaces() != null) {
for (Class iface : type.getInterfaces()) {
addInterfaces(interfaceSet, iface, false);
}
}
// php/1z21
addInterfaces(interfaceSet, type.getSuperclass(), false);
}
private boolean hasInterface(String name, Class type)
{
Class[] interfaces = type.getInterfaces();
if (interfaces != null) {
for (Class intfc : interfaces) {
if (intfc.getSimpleName().equalsIgnoreCase(name))
return true;
if (hasInterface(name, intfc))
return true;
}
}
return false;
}
@Override
public boolean isAbstract()
{
return _isAbstract;
}
public boolean isArray()
{
return false;
}
@Override
public boolean isInterface()
{
return _isInterface;
}
public boolean isDelegate()
{
return _isDelegate;
}
public void setPhpClass(boolean isPhpClass)
{
_isPhpClass = isPhpClass;
}
public boolean isPhpClass()
{
return _isPhpClass;
}
public JavaClassDef getComponentDef()
{
if (_componentDef == null) {
Class compType = getType().getComponentType();
_componentDef = _moduleContext.getJavaClassDefinition(compType.getName());
}
return _componentDef;
}
public Value wrap(Env env, Object obj)
{
if (! _isInit)
init();
if (_resourceType != null)
return new JavaResourceValue(env, obj, this);
else
return new JavaValue(env, obj, this);
}
private int cmpObject(Object lValue, Object rValue)
{
if (lValue == rValue)
return 0;
if (lValue == null)
return -1;
if (rValue == null)
return 1;
if (lValue instanceof Comparable) {
if (!(rValue instanceof Comparable))
return -1;
return ((Comparable) lValue).compareTo(rValue);
}
else if (rValue instanceof Comparable) {
return 1;
}
if (lValue.equals(rValue))
return 0;
String lName = lValue.getClass().getName();
String rName = rValue.getClass().getName();
return lName.compareTo(rName);
}
public int cmpObject(Object lValue, Object rValue, JavaClassDef rClassDef)
{
int cmp = cmpObject(lValue, rValue);
if (cmp != 0)
return cmp;
// attributes
// XX: not sure how to do this, to imitate PHP objects,
// should getters be involved as well?
for (
Map.Entry<StringValue, FieldMarshalPair> lEntry : _fieldMap.entrySet()
) {
StringValue lFieldName = lEntry.getKey();
FieldMarshalPair rFieldPair = rClassDef._fieldMap.get(lFieldName);
if (rFieldPair == null)
return 1;
FieldMarshalPair lFieldPair = lEntry.getValue();
try {
Object lResult = lFieldPair._field.get(lValue);
Object rResult = rFieldPair._field.get(lValue);
int resultCmp = cmpObject(lResult, rResult);
if (resultCmp != 0)
return resultCmp;
}
catch (IllegalAccessException e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return 0;
}
}
return 0;
}
/**
* Returns the field getter.
*
* @param name
* @return Value attained through invoking getter
*/
public Value getField(Env env, Value qThis, StringValue name)
{
AbstractJavaMethod get = _getMap.get(name);
if (get != null) {
try {
return get.callMethod(env, getQuercusClass(), qThis);
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return null;
}
}
FieldMarshalPair fieldPair = _fieldMap.get(name);
if (fieldPair != null) {
try {
Object result = fieldPair._field.get(qThis.toJavaObject());
return fieldPair._marshal.unmarshal(env, result);
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return null;
}
}
AbstractFunction phpGet = qThis.getQuercusClass().getFieldGet();
if (phpGet != null) {
return phpGet.callMethod(env, getQuercusClass(), qThis, name);
}
if (__fieldGet != null) {
try {
return __fieldGet.callMethod(env, getQuercusClass(), qThis, name);
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return null;
}
}
return null;
}
public Value putField(Env env,
Value qThis,
StringValue name,
Value value)
{
AbstractJavaMethod setter = _setMap.get(name);
if (setter != null) {
try {
return setter.callMethod(env, getQuercusClass(), qThis, value);
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return NullValue.NULL;
}
}
FieldMarshalPair fieldPair = _fieldMap.get(name);
if (fieldPair != null) {
try {
Class type = fieldPair._field.getType();
Object marshaledValue = fieldPair._marshal.marshal(env, value, type);
fieldPair._field.set(qThis.toJavaObject(), marshaledValue);
return value;
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return NullValue.NULL;
}
}
if (! qThis.isFieldInit()) {
AbstractFunction phpSet = qThis.getQuercusClass().getFieldSet();
if (phpSet != null) {
qThis.setFieldInit(true);
try {
return phpSet.callMethod(env, getQuercusClass(), qThis, name, value);
} finally {
qThis.setFieldInit(false);
}
}
}
if (__fieldSet != null) {
try {
return __fieldSet.callMethod(env,
getQuercusClass(),
qThis,
name,
value);
} catch (Exception e) {
log.log(Level.FINE, L.l(e.getMessage()), e);
return NullValue.NULL;
}
}
return null;
}
/**
* Returns the marshal instance.
*/
public Marshal getMarshal()
{
return _marshal;
}
/**
* Creates a new instance.
*/
@Override
public ObjectValue newInstance(Env env, QuercusClass qClass)
{
// return newInstance();
return null;
}
public Value newInstance()
{
return null;
/*
try {
//Object obj = _type.newInstance();
return new JavaValue(null, _type.newInstance(), this);
} catch (Exception e) {
throw new QuercusRuntimeException(e);
}
*/
}
/**
* Eval new
*/
@Override
public Value callNew(Env env, Value []args)
{
if (_cons != null) {
if (__construct != null) {
Value value = _cons.call(env, Value.NULL_ARGS);
__construct.callMethod(env, __construct.getQuercusClass(), value, args);
return value;
}
else {
return _cons.call(env, args);
}
}
else if (__construct != null)
return __construct.call(env, args);
else
return NullValue.NULL;
}
/**
* Returns the __call.
*/
public AbstractFunction getCallMethod()
{
return __call;
}
@Override
public AbstractFunction getCall()
{
return __call;
}
/**
* Eval a method
*/
public AbstractFunction findFunction(StringValue methodName)
{
return _functionMap.getRaw(methodName);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value []args)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, args);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value a1)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, a1);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value a1, Value a2)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, a1, a2);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value a1, Value a2, Value a3)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, a1, a2, a3);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value a1, Value a2, Value a3, Value a4)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, a1, a2, a3, a4);
}
/**
* Eval a method
*/
public Value callMethod(Env env, Value qThis,
StringValue methodName, int hash,
Value a1, Value a2, Value a3, Value a4, Value a5)
{
AbstractFunction fun = _functionMap.get(methodName, hash);
return fun.callMethod(env, getQuercusClass(), qThis, a1, a2, a3, a4, a5);
}
public Set<? extends Map.Entry<Value,Value>> entrySet(Object obj)
{
try {
if (_entrySet == null) {
return null;
}
return (Set) _entrySet.invoke(obj);
} catch (Exception e) {
throw new QuercusException(e);
}
}
/**
* Initialize the quercus class.
*/
@Override
public void initClass(QuercusClass cl)
{
init();
if (_cons != null) {
cl.setConstructor(_cons);
cl.addMethod(new StringBuilderValue("__construct"), _cons);
}
if (__construct != null) {
cl.setConstructor(__construct);
cl.addMethod(new StringBuilderValue("__construct"), __construct);
}
for (AbstractJavaMethod value : _functionMap.values()) {
cl.addMethod(new StringBuilderValue(value.getName()), value);
}
if (__fieldGet != null)
cl.setFieldGet(__fieldGet);
if (__fieldSet != null)
cl.setFieldSet(__fieldSet);
if (__call != null)
cl.setCall(__call);
if (__toString != null) {
cl.addMethod(new StringBuilderValue("__toString"), __toString);
}
if (_arrayDelegate != null)
cl.setArrayDelegate(_arrayDelegate);
else if (_funArrayDelegate != null)
cl.setArrayDelegate(_funArrayDelegate);
if (_traversableDelegate != null)
cl.setTraversableDelegate(_traversableDelegate);
else if (cl.getTraversableDelegate() == null
&& _iteratorMethod != null) {
// adds support for Java classes implementing iterator()
// php/
cl.setTraversableDelegate(new JavaTraversableDelegate(_iteratorMethod));
}
if (_countDelegate != null)
cl.setCountDelegate(_countDelegate);
for (Map.Entry<String,Value> entry : _constMap.entrySet()) {
cl.addConstant(entry.getKey(), new LiteralExpr(entry.getValue()));
}
for (Map.Entry<String,Object> entry : _constJavaMap.entrySet()) {
cl.addJavaConstant(entry.getKey(), entry.getValue());
}
}
/**
* Finds the matching constant
*/
public Value findConstant(Env env, String name)
{
return _constMap.get(name);
}
/**
* Creates a new instance.
*/
public void initInstance(Env env, Value value)
{
}
/**
* Returns the quercus class
*/
public QuercusClass getQuercusClass()
{
if (_quercusClass == null) {
init();
_quercusClass = new QuercusClass(_moduleContext, this, null);
}
return _quercusClass;
}
/**
* Returns the constructor
*/
@Override
public AbstractFunction findConstructor()
{
return null;
}
@Override
public final void init()
{
if (_isInit)
return;
synchronized (this) {
if (_isInit)
return;
super.init();
try {
initInterfaceList(_type);
introspect();
}
finally {
_isInit = true;
}
}
}
private void initInterfaceList(Class type)
{
Class[] ifaces = type.getInterfaces();
if (ifaces == null)
return;
for (Class iface : ifaces) {
JavaClassDef javaClassDef = _moduleContext.getJavaClassDefinition(iface);
if (javaClassDef != null)
addInterface(javaClassDef.getName());
// recurse for parent interfaces
initInterfaceList(iface);
}
}
/**
* Introspects the Java class.
*/
private void introspect()
{
introspectConstants(_type);
introspectMethods(_moduleContext, _type);
introspectFields(_moduleContext, _type);
_marshal = new JavaMarshal(this, false);
AbstractJavaMethod consMethod = getConsMethod();
if (consMethod != null) {
if (consMethod.isStatic())
_cons = consMethod;
else
__construct = consMethod;
}
//Method consMethod = getConsMethod(_type);
/*
if (consMethod != null) {
if (Modifier.isStatic(consMethod.getModifiers()))
_cons = new JavaMethod(_moduleContext, consMethod);
else
__construct = new JavaMethod(_moduleContext, consMethod);
}
*/
if (_cons == null) {
Constructor []cons = _type.getConstructors();
if (cons.length > 0) {
int i;
for (i = 0; i < cons.length; i++) {
if (cons[i].isAnnotationPresent(Construct.class))
break;
}
if (i < cons.length) {
_cons = new JavaConstructor(_moduleContext, cons[i]);
}
else {
_cons = new JavaConstructor(_moduleContext, cons[0]);
for (i = 1; i < cons.length; i++) {
_cons = _cons.overload(new JavaConstructor(_moduleContext,
cons[i]));
}
}
} else
_cons = null;
}
if (_cons != null)
_cons.setConstructor(true);
if (__construct != null)
__construct.setConstructor(true);
introspectAnnotations(_type);
}
private void introspectAnnotations(Class type)
{
try {
if (type == null)
return;
// interfaces
for (Class<?> iface : type.getInterfaces())
introspectAnnotations(iface);
// super-class
introspectAnnotations(type.getSuperclass());
// this
for (Annotation annotation : type.getAnnotations()) {
if (annotation.annotationType() == Delegates.class) {
Class[] delegateClasses = ((Delegates) annotation).value();
for (Class cl : delegateClasses) {
boolean isDelegate = addDelegate(cl);
if (! isDelegate)
throw new IllegalArgumentException(
L.l("unknown @Delegate class '{0}'", cl));
}
}
else if (annotation.annotationType() == ResourceType.class) {
_resourceType = ((ResourceType) annotation).value();
}
}
} catch (RuntimeException e) {
throw e;
} catch (InstantiationException e) {
throw new QuercusModuleException(e.getCause());
} catch (Exception e) {
throw new QuercusModuleException(e);
}
}
private boolean addDelegate(Class cl)
throws InstantiationException, IllegalAccessException
{
boolean isDelegate = false;
if (TraversableDelegate.class.isAssignableFrom(cl)) {
_traversableDelegate = (TraversableDelegate) cl.newInstance();
isDelegate = true;
}
if (ArrayDelegate.class.isAssignableFrom(cl)) {
_arrayDelegate = (ArrayDelegate) cl.newInstance();
isDelegate = true;
}
if (CountDelegate.class.isAssignableFrom(cl)) {
_countDelegate = (CountDelegate) cl.newInstance();
isDelegate = true;
}
return isDelegate;
}
private <T> boolean addDelegate(Class<T> cl,
ArrayList<T> delegates,
Class<? extends Object> delegateClass)
{
if (!cl.isAssignableFrom(delegateClass))
return false;
for (T delegate : delegates) {
if (delegate.getClass() == delegateClass) {
return true;
}
}
try {
delegates.add((T) delegateClass.newInstance());
}
catch (InstantiationException e) {
throw new QuercusModuleException(e);
}
catch (IllegalAccessException e) {
throw new QuercusModuleException(e);
}
return true;
}
/*
private Method getConsMethod(Class type)
{
Method []methods = type.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (! method.getName().equals("__construct"))
continue;
if (! Modifier.isPublic(method.getModifiers()))
continue;
return method;
}
return null;
}
*/
private AbstractJavaMethod getConsMethod()
{
for (AbstractJavaMethod method : _functionMap.values()) {
if (method.getName().equals("__construct"))
return method;
}
return null;
}
/**
* Introspects the Java class.
*/
private void introspectFields(ModuleContext moduleContext, Class type)
{
if (type == null)
return;
if (! Modifier.isPublic(type.getModifiers()))
return;
// Introspect getXXX and setXXX
// also register whether __get, __getField, __set, __setField exists
Method[] methods = type.getMethods();
for (Method method : methods) {
if (Modifier.isStatic(method.getModifiers()))
continue;
if (method.isAnnotationPresent(Hide.class))
continue;
String methodName = method.getName();
int length = methodName.length();
if (length > 3) {
if (methodName.startsWith("get")) {
StringValue quercusName
= javaToQuercusConvert(methodName.substring(3, length));
AbstractJavaMethod existingGetter = _getMap.get(quercusName);
AbstractJavaMethod newGetter = new JavaMethod(moduleContext, method);
if (existingGetter != null) {
newGetter = existingGetter.overload(newGetter);
}
_getMap.put(quercusName, newGetter);
}
else if (methodName.startsWith("is")) {
StringValue quercusName
= javaToQuercusConvert(methodName.substring(2, length));
AbstractJavaMethod existingGetter = _getMap.get(quercusName);
AbstractJavaMethod newGetter = new JavaMethod(moduleContext, method);
if (existingGetter != null) {
newGetter = existingGetter.overload(newGetter);
}
_getMap.put(quercusName, newGetter);
}
else if (methodName.startsWith("set")) {
StringValue quercusName
= javaToQuercusConvert(methodName.substring(3, length));
AbstractJavaMethod existingSetter = _setMap.get(quercusName);
AbstractJavaMethod newSetter = new JavaMethod(moduleContext, method);
if (existingSetter != null)
newSetter = existingSetter.overload(newSetter);
_setMap.put(quercusName, newSetter);
} else if ("__get".equals(methodName)) {
if (_funArrayDelegate == null)
_funArrayDelegate = new FunctionArrayDelegate();
_funArrayDelegate.setArrayGet(new JavaMethod(moduleContext, method));
} else if ("__set".equals(methodName)) {
if (_funArrayDelegate == null)
_funArrayDelegate = new FunctionArrayDelegate();
_funArrayDelegate.setArrayPut(new JavaMethod(moduleContext, method));
} else if ("__count".equals(methodName)) {
FunctionCountDelegate delegate = new FunctionCountDelegate();
delegate.setCount(new JavaMethod(moduleContext, method));
_countDelegate = delegate;
} else if ("__getField".equals(methodName)) {
__fieldGet = new JavaMethod(moduleContext, method);
} else if ("__setField".equals(methodName)) {
__fieldSet = new JavaMethod(moduleContext, method);
} else if ("__fieldGet".equals(methodName)) {
__fieldGet = new JavaMethod(moduleContext, method);
} else if ("__fieldSet".equals(methodName)) {
__fieldSet = new JavaMethod(moduleContext, method);
}
}
}
// server/2v00
/*
if (__fieldGet != null)
_getMap.clear();
if (__fieldSet != null)
_setMap.clear();
*/
// Introspect public non-static fields
Field[] fields = type.getFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()))
continue;
else if (field.isAnnotationPresent(Hide.class))
continue;
MarshalFactory factory = moduleContext.getMarshalFactory();
Marshal marshal = factory.create(field.getType(), false);
_fieldMap.put(new ConstStringValue(field.getName()),
new FieldMarshalPair(field, marshal));
}
// introspectFields(quercus, type.getSuperclass());
}
/**
* helper for introspectFields
*
* @param s (eg: Foo, URL)
* @return (foo, URL)
*/
private StringValue javaToQuercusConvert(String s)
{
if (s.length() == 1) {
return new ConstStringValue(
new char[]{ Character.toLowerCase(s.charAt(0)) });
}
if (Character.isUpperCase(s.charAt(1)))
return new ConstStringValue(s);
else {
StringBuilderValue sb = new StringBuilderValue();
sb.append(Character.toLowerCase(s.charAt(0)));
int length = s.length();
for (int i = 1; i < length; i++) {
sb.append(s.charAt(i));
}
return sb;
}
}
/**
* Introspects the Java class.
*/
private void introspectConstants(Class type)
{
if (type == null)
return;
if (! Modifier.isPublic(type.getModifiers()))
return;
/* not needed because Class.getFields() is recursive
Class []ifcs = type.getInterfaces();
for (Class ifc : ifcs) {
introspectConstants(ifc);
}
*/
Field []fields = type.getFields();
for (Field field : fields) {
if (_constMap.get(field.getName()) != null)
continue;
else if (_constJavaMap.get(field.getName()) != null)
continue;
else if (! Modifier.isPublic(field.getModifiers()))
continue;
else if (! Modifier.isStatic(field.getModifiers()))
continue;
else if (! Modifier.isFinal(field.getModifiers()))
continue;
else if (field.isAnnotationPresent(Hide.class))
continue;
try {
Object obj = field.get(null);
Value value = QuercusContext.objectToValue(obj);
if (value != null)
_constMap.put(field.getName().intern(), value);
else
_constJavaMap.put(field.getName().intern(), obj);
} catch (Throwable e) {
log.log(Level.FINEST, e.toString(), e);
}
}
//introspectConstants(type.getSuperclass());
}
/**
* Introspects the Java class.
*/
private void introspectMethods(ModuleContext moduleContext,
Class<?> type)
{
if (type == null)
return;
Method []methods = type.getMethods();
for (Method method : methods) {
if (! Modifier.isPublic(method.getModifiers()))
continue;
if (method.isAnnotationPresent(Hide.class))
continue;
if (_isPhpClass && method.getDeclaringClass() == Object.class)
continue;
if ("iterator".equals(method.getName())
&& method.getParameterTypes().length == 0
&& Iterator.class.isAssignableFrom(method.getReturnType())) {
_iteratorMethod = method;
}
if ("printRImpl".equals(method.getName())) {
_printRImpl = method;
} else if ("varDumpImpl".equals(method.getName())) {
_varDumpImpl = method;
} else if (method.isAnnotationPresent(JsonEncode.class)) {
_jsonEncode = method;
} else if (method.isAnnotationPresent(EntrySet.class)) {
_entrySet = method;
} else if ("__call".equals(method.getName())) {
__call = new JavaMethod(moduleContext, method);
} else if ("__toString".equals(method.getName())) {
__toString = new JavaMethod(moduleContext, method);
} else {
if (method.getName().startsWith("quercus_"))
throw new UnsupportedOperationException(
L.l("{0}: use @Name instead", method.getName()));
JavaMethod newFun = new JavaMethod(moduleContext, method);
StringValue funName = new StringBuilderValue(newFun.getName());
AbstractJavaMethod fun = _functionMap.getRaw(funName);
if (fun != null)
fun = fun.overload(newFun);
else
fun = newFun;
_functionMap.put(funName.toString(), fun);
}
}
/* Class.getMethods() is recursive
introspectMethods(moduleContext, type.getSuperclass());
Class []ifcs = type.getInterfaces();
for (Class ifc : ifcs) {
introspectMethods(moduleContext, ifc);
}
*/
}
public JavaMethod getToString()
{
return __toString;
}
public StringValue toString(Env env,
JavaValue value)
{
if (__toString == null)
return null;
return __toString.callMethod(
env, getQuercusClass(), value, new Expr[0]).toStringValue();
}
public boolean jsonEncode(Env env, Object obj, StringValue sb)
{
if (_jsonEncode == null)
return false;
try {
_jsonEncode.invoke(obj, env, sb);
return true;
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
/**
*
* @return false if printRImpl not implemented
* @throws IOException
*/
public boolean printRImpl(Env env,
Object obj,
WriteStream out,
int depth,
IdentityHashMap<Value, String> valueSet)
throws IOException
{
try {
if (_printRImpl == null) {
return false;
}
_printRImpl.invoke(obj, env, out, depth, valueSet);
return true;
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
public boolean varDumpImpl(Env env,
Value obj,
Object javaObj,
WriteStream out,
int depth,
IdentityHashMap<Value, String> valueSet)
throws IOException
{
try {
if (_varDumpImpl == null)
return false;
_varDumpImpl.invoke(javaObj, env, obj, out, depth, valueSet);
return true;
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
private class JavaTraversableDelegate
implements TraversableDelegate
{
private Method _iteratorMethod;
public JavaTraversableDelegate(Method iterator)
{
_iteratorMethod = iterator;
}
public Iterator<Map.Entry<Value, Value>>
getIterator(Env env, ObjectValue qThis)
{
try {
Iterator iterator
= (Iterator) _iteratorMethod.invoke(qThis.toJavaObject());
return new JavaIterator(env, iterator);
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
public Iterator<Value> getKeyIterator(Env env, ObjectValue qThis)
{
try {
Iterator iterator =
(Iterator) _iteratorMethod.invoke(qThis.toJavaObject());
return new JavaKeyIterator(iterator);
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
public Iterator<Value> getValueIterator(Env env, ObjectValue qThis)
{
try {
Iterator iterator =
(Iterator) _iteratorMethod.invoke(qThis.toJavaObject());
return new JavaValueIterator(env, iterator);
} catch (InvocationTargetException e) {
throw new QuercusRuntimeException(e);
} catch (IllegalAccessException e) {
throw new QuercusRuntimeException(e);
}
}
}
private class JavaKeyIterator
implements Iterator<Value>
{
private Iterator _iterator;
private int _index;
public JavaKeyIterator(Iterator iterator)
{
_iterator = iterator;
}
public Value next()
{
_iterator.next();
return LongValue.create(_index++);
}
public boolean hasNext()
{
return _iterator.hasNext();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
private class JavaValueIterator
implements Iterator<Value>
{
private Env _env;
private Iterator _iterator;
public JavaValueIterator(Env env, Iterator iterator)
{
_env = env;
_iterator = iterator;
}
public Value next()
{
return _env.wrapJava(_iterator.next());
}
public boolean hasNext()
{
if (_iterator != null)
return _iterator.hasNext();
else
return false;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
private class JavaIterator
implements Iterator<Map.Entry<Value, Value>>
{
private Env _env;
private Iterator _iterator;
private int _index;
public JavaIterator(Env env, Iterator iterator)
{
_env = env;
_iterator = iterator;
}
public Map.Entry<Value, Value> next()
{
Object next = _iterator.next();
int index = _index++;
if (next instanceof Map.Entry) {
Map.Entry entry = (Map.Entry) next;
if (entry.getKey() instanceof Value
&& entry.getValue() instanceof Value)
{
return (Map.Entry<Value, Value>) entry;
}
else {
Value key = _env.wrapJava(entry.getKey());
Value val = _env.wrapJava(entry.getValue());
return new JavaEntry(key, val);
}
}
else {
return new JavaEntry(LongValue.create(index), _env.wrapJava(next));
}
}
public boolean hasNext()
{
if (_iterator != null)
return _iterator.hasNext();
else
return false;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
private class JavaEntry
implements Map.Entry<Value, Value>
{
private Value _key;
private Value _value;
public JavaEntry(Value key, Value value)
{
_key = key;
_value = value;
}
public Value getKey()
{
return _key;
}
public Value getValue()
{
return _value;
}
public Value setValue(Value value)
{
throw new UnsupportedOperationException();
}
}
private class MethodMarshalPair {
public Method _method;
public Marshal _marshal;
public MethodMarshalPair(Method method,
Marshal marshal)
{
_method = method;
_marshal = marshal;
}
}
private class FieldMarshalPair {
public Field _field;
public Marshal _marshal;
public FieldMarshalPair(Field field,
Marshal marshal)
{
_field = field;
_marshal = marshal;
}
}
private static class LongClassDef extends JavaClassDef {
LongClassDef(ModuleContext module)
{
super(module, "Long", Long.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return LongValue.create(((Number) obj).longValue());
}
}
private static class DoubleClassDef extends JavaClassDef {
DoubleClassDef(ModuleContext module)
{
super(module, "Double", Double.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new DoubleValue(((Number) obj).doubleValue());
}
}
private static class BigIntegerClassDef extends JavaClassDef {
BigIntegerClassDef(ModuleContext module)
{
super(module, "BigInteger", BigInteger.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new BigIntegerValue(env, (BigInteger) obj, this);
}
}
private static class BigDecimalClassDef extends JavaClassDef {
BigDecimalClassDef(ModuleContext module)
{
super(module, "BigDecimal", BigDecimal.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new BigDecimalValue(env, (BigDecimal) obj, this);
}
}
private static class StringClassDef extends JavaClassDef {
StringClassDef(ModuleContext module)
{
super(module, "String", String.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return env.createString((String) obj);
}
}
private static class BooleanClassDef extends JavaClassDef {
BooleanClassDef(ModuleContext module)
{
super(module, "Boolean", Boolean.class);
}
@Override
public Value wrap(Env env, Object obj)
{
if (Boolean.TRUE.equals(obj))
return BooleanValue.TRUE;
else
return BooleanValue.FALSE;
}
}
private static class CalendarClassDef extends JavaClassDef {
CalendarClassDef(ModuleContext module)
{
super(module, "Calendar", Calendar.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new JavaCalendarValue(env, (Calendar)obj, this);
}
}
private static class DateClassDef extends JavaClassDef {
DateClassDef(ModuleContext module)
{
super(module, "Date", Date.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new JavaDateValue(env, (Date)obj, this);
}
}
private static class URLClassDef extends JavaClassDef {
URLClassDef(ModuleContext module)
{
super(module, "URL", URL.class);
}
@Override
public Value wrap(Env env, Object obj)
{
return new JavaURLValue(env, (URL)obj, this);
}
}
}
| gpl-2.0 |
CvO-Theory/apt | src/lib/uniol/apt/util/equations/EquationSystem.java | 10250 | /*-
* APT - Analysis of Petri Nets and labeled Transition systems
* Copyright (C) 2014 Uli Schlachter
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package uniol.apt.util.equations;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import uniol.apt.util.interrupt.InterrupterRegistry;
import static uniol.apt.util.DebugUtil.debug;
import static uniol.apt.util.DebugUtil.debugFormat;
/**
* Representation of an equation system.
* @author Uli Schlachter
*/
public class EquationSystem {
private final int numVariables;
private final Collection<List<BigInteger>> equations = new HashSet<>();
private static class EquationSystemSolver {
// Algorithm 4 from "Petri Net Synthesis" by Badouel, Bernardinello and Darondeau, page 190
// The invariant of the algorithm is:
// There exists some y so that x = equations1 * y and equations2 * y = 0.
// So each equation in the equations has variables y_0 to y_{n-1}
private final List<List<BigInteger>> equations1 = new ArrayList<>();
private final List<List<BigInteger>> equations2 = new ArrayList<>();
private final int numVariables;
EquationSystemSolver(int numVariables, Collection<List<BigInteger>> equations) {
this.numVariables = numVariables;
// Input equations, but x_i is substituted with y_i
equations2.addAll(equations);
for (int i = 0; i < numVariables; i++) {
// Set x_i = y_i in equations1
List<BigInteger> equation = new ArrayList<>(numVariables);
for (int j = 0; j < numVariables; j++) {
equation.add(j == i ? BigInteger.ONE : BigInteger.ZERO);
}
equations1.add(equation);
}
}
public List<List<BigInteger>> solve() {
debug("solve called");
debug("============");
while (!equations2.isEmpty()) {
InterrupterRegistry.throwIfInterruptRequestedForCurrentThread();
debug("New round");
debug(equations1);
debug(equations2);
debug();
// Get an equation and ensure it only has non-negative coefficients
List<BigInteger> equation = equations2.get(0);
for (int i = 0; i < numVariables; i++) {
if (equation.get(i).compareTo(BigInteger.ZERO) < 0)
invertVariableY(i);
}
// "Reduce" the equation to a single, non-zero coefficient
// TODO: Baaaaad performance
while (true) {
InterrupterRegistry.throwIfInterruptRequestedForCurrentThread();
boolean restart = false;
// Find two coefficients with 0 < lambda_i <= lambda_j
for (int i = 0; i < numVariables; i++) {
BigInteger lambdai = equation.get(i);
if (lambdai.equals(BigInteger.ZERO))
continue;
for (int j = i + 1; j < numVariables; j++) {
BigInteger lambdaj = equation.get(j);
if (lambdaj.equals(BigInteger.ZERO))
continue;
// Swap the two equations if necessary
if (lambdaj.compareTo(lambdai) < 0) {
int tmp1 = i;
i = j;
j = tmp1;
BigInteger tmp2 = lambdai;
lambdai = lambdaj;
lambdaj = tmp2;
}
// Substitute y_j -> y_j - floor(lambda_j / lambda_i) * y_i
BigDecimal a = new BigDecimal(lambdaj);
BigDecimal b = new BigDecimal(lambdai);
BigDecimal result = a.divide(b, RoundingMode.FLOOR);
substituteVariable(j, result.toBigIntegerExact().negate(), i);
restart = true;
break;
}
if (restart)
break;
}
// We didn't find two non-zero coefficients, so at most a single one is left
if (!restart)
break;
}
debug(equations1);
debug(equations2);
debug();
removeRedundancy();
}
debug("Result:");
debug(equations1);
return Collections.unmodifiableList(equations1);
}
/**
* Simplify equations2 by removing simple forms of redundancy.
* This handles equations of the form k*y_i = 0 and 0 = 0.
*/
private void removeRedundancy() {
// For all equations k*y_i = 0 with k!=0 in equations2, remove this equation and remove
// variable y_i (since it must be zero)
for (int i = 0; i < equations2.size(); i++) {
Integer nonZeroIndex = null;
List<BigInteger> equation = equations2.get(i);
for (int j = 0; j < numVariables; j++) {
if (equation.get(j).equals(BigInteger.ZERO))
continue;
if (nonZeroIndex == null) {
nonZeroIndex = j;
} else {
nonZeroIndex = null;
break;
}
}
if (nonZeroIndex != null) {
equations2.remove(i--);
removeVariable(nonZeroIndex);
}
}
// Eliminate redundant equations or the trivial equation 0=0 from E2
for (int i = 0; i < equations2.size(); i++) {
List<BigInteger> equation = equations2.get(i);
boolean found = false;
for (int j = 0; j < numVariables; j++)
if (!equation.get(j).equals(BigInteger.ZERO)) {
found = true;
break;
}
if (!found)
equations2.remove(i--);
}
}
// Invert variable y_j in all equations.
private void invertVariableY(int j) {
debugFormat("Inverting variable y_%d", j);
for (int i = 0; i < equations1.size(); i++) {
List<BigInteger> equation = equations1.get(i);
equation.set(j, equation.get(j).negate());
}
for (int i = 0; i < equations2.size(); i++) {
List<BigInteger> equation = equations2.get(i);
equation.set(j, equation.get(j).negate());
}
}
// Remove variable y_j from all equations.
private void removeVariable(int j) {
debugFormat("Removing variable y_%d", j);
for (int i = 0; i < equations1.size(); i++)
equations1.get(i).set(j, BigInteger.ZERO);
for (int i = 0; i < equations2.size(); i++)
equations2.get(i).set(j, BigInteger.ZERO);
}
// Substitute variable y_variableIndex with y_variableIndex + factor * y_addendIndex in all equations.
private void substituteVariable(int variableIndex, BigInteger factor, int addendIndex) {
debugFormat("Substituting variable y_%d with y_%d + %d * y_%d",
variableIndex, variableIndex, factor, addendIndex);
for (int i = 0; i < equations1.size(); i++)
substituteVariable(equations1.get(i), variableIndex, factor, addendIndex);
for (int i = 0; i < equations2.size(); i++)
substituteVariable(equations2.get(i), variableIndex, factor, addendIndex);
}
// Substitute variable y_variableIndex with y_variableIndex + factor * y_addendIndex in the given
// equation.
private static void substituteVariable(List<BigInteger> equation, int variableIndex, BigInteger factor,
int addendIndex) {
BigInteger addend = equation.get(addendIndex);
BigInteger variableValue = equation.get(variableIndex);
// newValue = variableValue + factor * addend
BigInteger newValue = variableValue.add(factor.multiply(addend));
equation.set(variableIndex, newValue);
}
}
/**
* Construct a new equation system.
* @param numVariables The number of variables in the equation system.
*/
public EquationSystem(int numVariables) {
assert numVariables >= 0;
this.numVariables = numVariables;
}
/**
* Add an equation to the equation system.
* @param coefficients List of coefficients for the equation. This must have exactly one entry for each variable
* in the equation system.
*/
public void addEquation(int... coefficients) {
assert coefficients.length == numVariables;
ArrayList<BigInteger> row = new ArrayList<>(numVariables);
for (int i = 0; i < coefficients.length; i++)
row.add(BigInteger.valueOf(coefficients[i]));
equations.add(row);
}
/**
* Add an equation to the equation system.
* @param coefficients List of coefficients for the equation. This must have exactly one entry for each variable
* in the equation system.
*/
public void addEquation(Collection<BigInteger> coefficients) {
assert coefficients.size() == numVariables;
ArrayList<BigInteger> row = new ArrayList<>(coefficients);
equations.add(row);
}
/**
* Calculate a basis of the equation system.
* @return The set of basis vectors
*/
public Set<List<BigInteger>> findBasis() {
Set<List<BigInteger>> result = new HashSet<>();
EquationSystemSolver solver = new EquationSystemSolver(numVariables, equations);
// The *columns* of the matrix provide a basis of the solution
List<List<BigInteger>> solution = solver.solve();
assert solution.size() == numVariables;
for (int i = 0; i < numVariables; i++) {
boolean allZero = true;
List<BigInteger> row = new ArrayList<>(numVariables);
for (int j = 0; j < numVariables; j++) {
BigInteger value = solution.get(j).get(i);
if (!value.equals(BigInteger.ZERO))
allZero = false;
row.add(value);
}
if (!allZero)
result.add(Collections.unmodifiableList(row));
}
debug("Basis found: ", result);
debug("");
return Collections.unmodifiableSet(result);
}
@Override
public String toString() {
StringWriter buffer = new StringWriter();
buffer.write("[\n");
for (List<BigInteger> equation : equations) {
boolean first = true;
for (int j = 0; j < numVariables; j++) {
if (equation.get(j).equals(BigInteger.ZERO))
continue;
if (!first)
buffer.write(" + ");
buffer.write("" + equation.get(j));
buffer.write("*x[");
buffer.write("" + j);
buffer.write("]");
first = false;
}
if (first)
buffer.write("0");
buffer.write(" = 0\n");
}
buffer.write("]");
return buffer.toString();
}
}
// vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
| gpl-2.0 |
christopherfebles/magicdbwebapp | src/main/java/com/christopherfebles/magic/controller/MagicController.java | 7809 | package com.christopherfebles.magic.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.christopherfebles.magic.dao.ExpansionDAO;
import com.christopherfebles.magic.dao.MagicCardDAO;
import com.christopherfebles.magic.dao.SubTypeDAO;
import com.christopherfebles.magic.enums.Color;
import com.christopherfebles.magic.enums.SubType;
import com.christopherfebles.magic.enums.Type;
import com.christopherfebles.magic.form.model.DisplayMagicCard;
import com.christopherfebles.magic.form.model.SearchFormModel;
import com.christopherfebles.magic.service.MagicCardSearchService;
@Controller
public class MagicController {
private static final Logger LOG = LoggerFactory.getLogger( MagicController.class );
@Autowired
private MagicCardSearchService searchService;
@Autowired
private MagicCardDAO cardDAO;
@Autowired
private SubTypeDAO subTypeDAO;
@Autowired
private ExpansionDAO expansionDAO;
//Data caching
private static List<SubType> subTypeList;
/**
* Get the list of colors for display in the UI
*
* @return A list of displayable colors for a dropdown
*/
private List<Color> getCardColors() {
List<Color> colorList = new ArrayList<>( Arrays.asList( Color.values() ) );
colorList.remove( Color.VARIABLE_COLORLESS );
return colorList;
}
/**
* Get a list of subtypes for display in the UI
*
* @return A list of displayable SubTypes for a dropdown
*/
private List<SubType> getSubTypes() {
if ( subTypeList == null ) {
subTypeList = subTypeDAO.getAllSubTypes();
}
return subTypeList;
}
@RequestMapping( value = "", method = RequestMethod.GET )
public String main() {
LOG.trace( "Redirecting from main url to search form." );
return "redirect:search.form";
}
@RequestMapping( value = "/search.form", method = RequestMethod.GET )
public String searchForm( Model model, HttpServletRequest request ) {
LOG.trace( "Search form loaded" );
request.getSession().invalidate();
return this.prepareSearchModel( model );
}
@RequestMapping( value = "/search.do", method = { RequestMethod.GET, RequestMethod.POST } )
public String searchDo( @ModelAttribute( "searchObj" ) SearchFormModel searchFormParm, Model model,
@RequestParam( value = "page", required = false ) String page,
HttpServletRequest request ) {
LOG.trace( "Search form loaded." );
SearchFormModel searchForm = searchFormParm;
if ( searchForm.isEmpty() ) {
searchForm = ( SearchFormModel ) request.getSession().getAttribute( "MagicController_searchForm" );
if ( searchForm == null || searchForm.isEmpty() ) {
return "redirect:search.form";
}
}
List<DisplayMagicCard> resultList = null;
Integer pageNumber = ( Integer ) request.getSession().getAttribute( "MagicController_pageNumber" );
if ( StringUtils.isEmpty( page ) ) {
request.getSession().setAttribute( "MagicController_searchForm", searchForm );
pageNumber = 1;
Integer numPages = searchService.numberOfPagesForSearch( searchForm );
request.getSession().setAttribute( "MagicController_numPages", numPages );
Integer numResults = searchService.numberOfResultsForSearch( searchForm );
request.getSession().setAttribute( "MagicController_numResults", numResults );
} else {
switch (page) {
case "next":
pageNumber++;
break;
case "previous":
pageNumber--;
break;
default:
try {
pageNumber = Integer.parseInt(page);
} catch (NumberFormatException e) {
//Unknown page value
LOG.error("Unknown value for page: {}", page);
}
break;
}
}
resultList = searchService.searchDatabaseByPage( searchForm, pageNumber );
request.getSession().setAttribute( "MagicController_pageNumber", pageNumber );
model.addAttribute( "cards", resultList );
model.addAttribute( "searchObj", searchForm );
model.addAttribute( "currentPage", pageNumber );
model.addAttribute( "numPages", request.getSession().getAttribute( "MagicController_numPages" ) );
model.addAttribute( "numResults", request.getSession().getAttribute( "MagicController_numResults" ) );
return this.prepareSearchModel( model );
}
private String prepareSearchModel( Model model ) {
if ( !model.containsAttribute( "searchObj" ) ) {
model.addAttribute( "searchObj", new SearchFormModel() );
}
if ( !model.containsAttribute( "colors" ) ) {
model.addAttribute( "colors", getCardColors() );
}
if ( !model.containsAttribute( "types" ) ) {
model.addAttribute( "types", Type.values() );
}
if ( !model.containsAttribute( "subTypes" ) ) {
model.addAttribute( "subTypes", getSubTypes() );
}
if ( !model.containsAttribute( "expansions" ) ) {
model.addAttribute( "expansions", expansionDAO.getAllExpansions() );
}
return "search";
}
@RequestMapping( value = "/image.do", method = RequestMethod.GET, produces = "image/jpeg" )
@ResponseBody
public byte[] getCardImage( @RequestParam( "id" ) String id ) {
LOG.trace( "Loading image for multiverse id {}", id );
return cardDAO.getCardImageById( Integer.parseInt( id ) );
}
@RequestMapping( value = "/isCardOwned.do", method = RequestMethod.GET )
@ResponseBody
public String isOwned( @RequestParam( "id" ) String id ) {
LOG.trace( "Checking if card owned for multiverse id {}", id );
return String.valueOf( cardDAO.isCardOwned( Integer.parseInt( id ) ) );
}
@RequestMapping( value = "/numberOfCardsOwned.do", method = RequestMethod.GET )
@ResponseBody
public String numberOwned( @RequestParam( "id" ) String id ) {
LOG.trace( "Loading number of cards owned for multiverse id {}", id );
return String.valueOf( cardDAO.numberOfOwnedCard( Integer.parseInt( id ) ) );
}
@RequestMapping( value = "/setNumberOfCardsOwned.do", method = RequestMethod.POST )
@ResponseBody
public String updateNumberOwned( @RequestParam( "id" ) String id, @RequestParam( "number" ) String number ) {
LOG.trace( "Updating number of cards owned to {} for multiverse id {}", number, id );
int idInt = Integer.parseInt( id );
int numberInt = Integer.parseInt( number );
cardDAO.updateOwnedCardCount( idInt, numberInt );
return String.valueOf( cardDAO.numberOfOwnedCard( idInt ) );
}
} | gpl-2.0 |
MarginallyClever/Makelangelo-software | src/main/java/com/marginallyclever/convenience/LineCollection.java | 2897 | package com.marginallyclever.convenience;
import java.util.ArrayList;
public class LineCollection extends ArrayList<LineSegment2D> {
private static final long serialVersionUID = 1L;
private boolean[] usePt;
public LineCollection() {
super();
}
public LineCollection(ArrayList<LineSegment2D> list) {
super();
addAll(list);
}
/**
* Splits this collection by color. Does not affect the original list. Does not deep copy.
* @return the list of collections separated by color
*/
public ArrayList<LineCollection> splitByColor() {
ArrayList<LineCollection> result = new ArrayList<LineCollection> ();
if(this.size()>0) {
LineSegment2D head = get(0);
LineCollection c = new LineCollection();
result.add(c);
c.add(head);
for(int i=1;i<size();++i) {
LineSegment2D next = get(i);
if(next.c.isEqualTo(head.c)) {
c.add(next);
} else {
head = next;
c = new LineCollection();
result.add(c);
c.add(head);
}
}
}
return result;
}
/**
* Splits this collection by travel moves. Does not affect the original list. Does not deep copy.
* A travel move is any moment in the collection where element (N).b != (N+1).a
* @return the list of collections separated by color
*/
public ArrayList<LineCollection> splitByTravel() {
ArrayList<LineCollection> result = new ArrayList<LineCollection> ();
if(this.size()>0) {
LineSegment2D head = get(0);
LineCollection c = new LineCollection();
result.add(c);
c.add(head);
for(int i=1;i<size();++i) {
LineSegment2D next = get(i);
if(next.b.distanceSquared(head.a)<1e-6) {
c.add(next);
} else {
head = next;
c = new LineCollection();
result.add(c);
c.add(head);
}
}
}
return result;
}
public LineCollection simplify(double distanceTolerance) {
usePt = new boolean[size()];
for (int i = 0; i < size(); i++) {
usePt[i] = true;
}
simplifySection(0, size() - 1,distanceTolerance);
LineCollection result = new LineCollection();
Point2D head = get(0).a;
for (int i = 0; i < size(); i++) {
if (usePt[i]) {
Point2D next = get(i).b;
result.add(new LineSegment2D(head,next,get(i).c));
head=next;
}
}
return result;
}
private void simplifySection(int i, int j,double distanceTolerance) {
if ((i + 1) == j) return;
LineSegment2D seg = new LineSegment2D(
get(i).a,
get(j).b,
get(i).c);
double maxDistance = -1.0;
int maxIndex = i;
for (int k = i + 1; k < j; k++) {
double distance = seg.ptLineDistSq(get(k).b);
if (distance > maxDistance) {
maxDistance = distance;
maxIndex = k;
}
}
if (maxDistance <= distanceTolerance) {
for (int k = i + 1; k < j; k++) {
usePt[k] = false;
}
} else {
simplifySection(i, maxIndex,distanceTolerance);
simplifySection(maxIndex, j,distanceTolerance);
}
}
}; | gpl-2.0 |
geoff-addepar/heap-dump | src/com/addepar/heapdump/inspect/inferior/NoSuchSymbolException.java | 319 | package com.addepar.heapdump.inspect.inferior;
/**
* Thrown when an attempt is made to look up a symbol that cannot be found in the inferior
*/
@SuppressWarnings("serial")
public class NoSuchSymbolException extends RuntimeException {
public NoSuchSymbolException(String symbolName) {
super(symbolName);
}
}
| gpl-2.0 |
mohamedkettouch/MovieCollectionManager | src/Projet/Mediateur/main.java | 2004 | package Projet.Mediateur;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import javax.swing.UIManager;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.jena.atlas.logging.Log;
import org.apache.jena.atlas.logging.LogCtl;
import org.json.JSONException;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import Projet.GesionDeCollectionPersonelle.GestionDeCollectionPersonelle;
public class main {
/**
* @param args
* @throws IOException
* @throws JSONException
* @throws NumberFormatException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws NumberFormatException, JSONException, IOException, ParserConfigurationException, SAXException {
/*final String authUser = "f.boug";
final String authPassword = "uvrt311";
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authUser, authPassword.toCharArray());
}
}
);
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "192.168.5.1");
System.getProperties().put("proxyPort", "8080");
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
*/
new GestionDeCollectionPersonelle();
}}
| gpl-2.0 |
sourceress-project/archestica | src/games/stendhal/client/textClient.java | 7772 | /* $Id: textClient.java,v 1.34 2013/04/22 21:51:39 kiheru Exp $ */
/***************************************************************************
* (C) Copyright 2003 - Marauroa *
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
package games.stendhal.client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import marauroa.client.net.IPerceptionListener;
import marauroa.client.net.PerceptionHandler;
import marauroa.common.game.RPAction;
import marauroa.common.game.RPObject;
import marauroa.common.net.message.MessageS2CPerception;
import marauroa.common.net.message.TransferContent;
public class textClient extends Thread {
private final String host;
private final String username;
private final String password;
private final String character;
private final String port;
private static boolean showWorld;
private final Map<RPObject.ID, RPObject> world_objects;
private final marauroa.client.ClientFramework clientManager;
private final PerceptionHandler handler;
public textClient(final String h, final String u, final String p, final String c, final String P,
final boolean t) {
host = h;
username = u;
password = p;
character = c;
port = P;
world_objects = new HashMap<RPObject.ID, RPObject>();
handler = new PerceptionHandler(new IPerceptionListener() {
@Override
public boolean onAdded(final RPObject object) {
return false;
}
@Override
public boolean onClear() {
return false;
}
@Override
public boolean onDeleted(final RPObject object) {
return false;
}
@Override
public void onException(final Exception exception,
final MessageS2CPerception perception) {
exception.printStackTrace();
}
@Override
public boolean onModifiedAdded(final RPObject object, final RPObject changes) {
return false;
}
@Override
public boolean onModifiedDeleted(final RPObject object, final RPObject changes) {
return false;
}
@Override
public boolean onMyRPObject(final RPObject added, final RPObject deleted) {
return false;
}
@Override
public void onPerceptionBegin(final byte type, final int timestamp) {
}
@Override
public void onPerceptionEnd(final byte type, final int timestamp) {
}
@Override
public void onSynced() {
}
@Override
public void onUnsynced() {
}
});
clientManager = new marauroa.client.ClientFramework(
"games/stendhal/log4j.properties") {
@Override
protected String getGameName() {
return "stendhal";
}
@Override
protected String getVersionNumber() {
return stendhal.VERSION;
}
@Override
protected void onPerception(final MessageS2CPerception message) {
try {
System.out.println("Received perception "
+ message.getPerceptionTimestamp());
handler.apply(message, world_objects);
final int i = message.getPerceptionTimestamp();
final RPAction action = new RPAction();
if (i % 50 == 0) {
action.put("type", "move");
action.put("dy", "-1");
clientManager.send(action);
} else if (i % 50 == 20) {
action.put("type", "move");
action.put("dy", "1");
clientManager.send(action);
}
if (showWorld) {
System.out.println("<World contents ------------------------------------->");
int j = 0;
for (final RPObject object : world_objects.values()) {
j++;
System.out.println(j + ". " + object);
}
System.out.println("</World contents ------------------------------------->");
}
} catch (final Exception e) {
e.printStackTrace();
}
}
@Override
protected List<TransferContent> onTransferREQ(
final List<TransferContent> items) {
for (final TransferContent item : items) {
item.ack = true;
}
return items;
}
@Override
protected void onTransfer(final List<TransferContent> items) {
System.out.println("Transfering ----");
for (final TransferContent item : items) {
System.out.println(item);
}
}
@Override
protected void onAvailableCharacters(final String[] characters) {
System.out.println("Characters available");
for (final String characterAvail : characters) {
System.out.println(characterAvail);
}
try {
chooseCharacter(character);
} catch (final Exception e) {
e.printStackTrace();
}
}
@Override
protected void onServerInfo(final String[] info) {
System.out.println("Server info");
for (final String info_string : info) {
System.out.println(info_string);
}
}
@Override
protected void onPreviousLogins(final List<String> previousLogins) {
System.out.println("Previous logins");
for (final String info_string : previousLogins) {
System.out.println(info_string);
}
}
};
}
@Override
public void run() {
try {
clientManager.connect(host, Integer.parseInt(port));
clientManager.login(username, password);
} catch (final Exception e) {
e.printStackTrace();
return;
}
final boolean cond = true;
while (cond) {
clientManager.loop(0);
try {
sleep(100);
} catch (final InterruptedException e) {
}
}
}
public static void main(final String[] args) {
try {
if (args.length > 0) {
int i = 0;
String username = null;
String password = null;
String character = null;
String host = null;
String port = null;
boolean tcp = false;
while (i != args.length) {
if (args[i].equals("-u")) {
username = args[i + 1];
} else if (args[i].equals("-p")) {
password = args[i + 1];
} else if (args[i].equals("-c")) {
character = args[i + 1];
} else if (args[i].equals("-h")) {
host = args[i + 1];
} else if (args[i].equals("-P")) {
port = args[i + 1];
} else if (args[i].equals("-W")) {
if ("1".equals(args[i + 1])) {
showWorld = true;
}
} else if (args[i].equals("-t")) {
tcp = true;
}
i++;
}
if ((username != null) && (password != null)
&& (character != null) && (host != null)
&& (port != null)) {
System.out.println("Parameter operation");
new textClient(host, username, password, character, port,
tcp).start();
return;
}
}
System.out.println("Stendhal textClient");
System.out.println();
System.out.println(" games.stendhal.textClient -u username -p pass -h host -P port -c character");
System.out.println();
System.out.println("Required parameters");
System.out.println("* -h\tHost that is running Marauroa server");
System.out.println("* -P\tPort on which Marauroa server is running");
System.out.println("* -u\tUsername to log into Marauroa server");
System.out.println("* -p\tPassword to log into Marauroa server");
System.out.println("* -c\tCharacter used to log into Marauroa server");
System.out.println("Optional parameters");
System.out.println("* -W\tShow world content? 0 or 1");
} catch (final Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
| gpl-2.0 |
cesarvarela04/R_Pets_Land | src/main/java/co/petsland/model/control/ISucursalesLogic.java | 1458 | package co.petsland.model.control;
import co.petsland.model.Sucursales;
import co.petsland.model.dto.SucursalesDTO;
import java.math.BigDecimal;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* @author Zathura Code Generator http://code.google.com/p/zathura
* www.zathuracode.org
*
*/
public interface ISucursalesLogic {
public List<Sucursales> getSucursales() throws Exception;
/**
* Save an new Sucursales entity
*/
public void saveSucursales(Sucursales entity) throws Exception;
/**
* Delete an existing Sucursales entity
*
*/
public void deleteSucursales(Sucursales entity) throws Exception;
/**
* Update an existing Sucursales entity
*
*/
public void updateSucursales(Sucursales entity) throws Exception;
/**
* Load an existing Sucursales entity
*
*/
public Sucursales getSucursales(Long sucCodigo) throws Exception;
public List<Sucursales> findByCriteria(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Sucursales> findPageSucursales(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSucursales() throws Exception;
public List<SucursalesDTO> getDataSucursales() throws Exception;
}
| gpl-2.0 |
hjp4lucifer/lucifer_test | src/main/java/cn/lucifer/thread/ThreadTest2.java | 1066 | package cn.lucifer.thread;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadTest2 {
private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
10);
public static void main(String[] args) {
long start = System.currentTimeMillis();
Hello hello;
long delay;
for (int i = 0; i < 11; i++) {
hello = new Hello(i);
// executor.submit(hello);
if (i == 3) {
delay = 1000;
} else {
delay = 1;
}
executor.schedule(hello, delay, TimeUnit.MILLISECONDS);
}
System.out.println(System.currentTimeMillis() - start);
}
private static class Hello extends Thread {
int index;
public Hello(int index) {
this.index = index;
}
@Override
public void run() {
System.out.println("hello " + index);
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("bye " + index);
}
}
}
| gpl-2.0 |
jacobono/gradle-jaxb-plugin | examples/hello-world-bindings-schema/src/main/java/helloworld/sample/ibm/helloworld/HelloResponseType.java | 1801 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7-b41
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.03.30 at 03:47:44 PM EDT
//
package helloworld.sample.ibm.helloworld;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for helloResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="helloResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="response" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "helloResponseType", propOrder = {
"response"
})
public class HelloResponseType {
@XmlElement(required = true, nillable = true)
protected String response;
/**
* Gets the value of the response property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getResponse() {
return response;
}
/**
* Sets the value of the response property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setResponse(String value) {
this.response = value;
}
}
| gpl-2.0 |
ZooMMX/Omoikane | main/src/omoikane/producto/PrecioAlternoPK.java | 563 | package omoikane.producto;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: octavioruizcastillo
* Date: 13/04/14
* Time: 23:35
* To change this template use File | Settings | File Templates.
*/
public class PrecioAlternoPK implements Serializable {
private Articulo articulo;
private ListaDePrecios listaDePrecios;
public PrecioAlternoPK() {
}
public PrecioAlternoPK(Articulo articulo, ListaDePrecios listaDePrecios) {
this.articulo = articulo;
this.listaDePrecios = listaDePrecios;
}
}
| gpl-2.0 |
isaacl/openjdk-jdk | test/java/sql/test/sql/DateTests.java | 16424 | /*
* Copyright (c) 2014, 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.
*
* 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 test.sql;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DateTests {
public DateTests() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_year() throws Exception {
String expResult = "20009-11-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_year2() throws Exception {
String expResult = "09-11-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_year3() throws Exception {
String expResult = "-11-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_month() throws Exception {
String expResult = "2009-111-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_month3() throws Exception {
String expResult = "2009--01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_month4() throws Exception {
String expResult = "2009-13-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_day() throws Exception {
String expResult = "2009-11-011";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_day3() throws Exception {
String expResult = "2009-11-";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_day4() throws Exception {
String expResult = "2009-11-00";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_day5() throws Exception {
String expResult = "2009-11-33";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf() throws Exception {
String expResult = "--";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf2() throws Exception {
String expResult = "";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf3() throws Exception {
String expResult = null;
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf4() throws Exception {
String expResult = "-";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf5() throws Exception {
String expResult = "2009";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf6() throws Exception {
String expResult = "2009-01";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf7() throws Exception {
String expResult = "---";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf8() throws Exception {
String expResult = "2009-13--1";
Date.valueOf(expResult);
}
/**
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalid_valueOf10() {
String expResult = "1900-1-0";
Date.valueOf(expResult);
}
/**
* Test that a date created from a date string is equal to the value
* returned from toString()
*/
@Test
public void test_valueOf() {
String expResult = "2009-08-30";
Date d = Date.valueOf(expResult);
assertEquals(expResult, d.toString());
}
/**
* Test that two dates, one with lead 0s omitted for month are equal
*/
@Test
public void testValid_month_single_digit() {
String testDate = "2009-1-01";
String expResult = "2009-01-01";
Date d = Date.valueOf(testDate);
Date d2 = Date.valueOf(expResult);
assertEquals(d, d2);
}
/**
* Test that two dates, one with lead 0s omitted for day are equal
*/
@Test
public void testValid_day_single_digit() {
String testDate = "2009-11-1";
String expResult = "2009-11-01";
Date d = Date.valueOf(testDate);
Date d2 = Date.valueOf(expResult);
assertEquals(d, d2);
}
/**
* Test that two dates, one with lead 0s omitted for month and day are equal
*/
@Test
public void testValid_month_day_single_digit() {
String testDate = "2009-1-1";
String expResult = "2009-01-01";
Date d = Date.valueOf(testDate);
Date d2 = Date.valueOf(expResult);
assertEquals(d, d2);
}
/**
* Validate that a Date.after() returns false when same date is compared
*/
@Test
public void test1() {
Date d = Date.valueOf("1961-08-30");
assertFalse(d.after(d), "Error d.after(d) = true");
}
/**
* Validate that a Date.after() returns true when later date is compared to
* earlier date
*/
@Test
public void test2() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d2.after(d), "Error d2.after(d) = false");
}
/**
* Validate that a Date.after() returns false when earlier date is compared
* to later date
*/
@Test
public void test3() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.after(d2), "Error d.after(d2) = true");
}
/**
* Validate that a Date.after() returns false when date compared to another
* date created from the original date
*/
@Test
public void test4() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.after(d2), "Error d.after(d2) = true");
assertFalse(d2.after(d), "Error d2.after(d) = true");
}
/**
* Validate that a Date.before() returns false when same date is compared
*/
@Test
public void test5() {
Date d = Date.valueOf("1961-08-30");
assertFalse(d.before(d), "Error d.before(d) = true");
}
/**
* Validate that a Date.before() returns true when earlier date is compared
* to later date
*/
@Test
public void test6() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d.before(d2), "Error d.before(d2) = false");
}
/**
* Validate that a Date.before() returns false when later date is compared
* to earlier date
*/
@Test
public void test7() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d2.before(d), "Error d2.before(d) = true");
}
/**
* Validate that a Date.before() returns false when date compared to another
* date created from the original date
*/
@Test
public void test8() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.before(d2), "Error d.before(d2) = true");
assertFalse(d2.before(d), "Error d2.before(d) = true");
}
/**
* Validate that a Date.compareTo returns 0 when both Date objects are the
* same
*/
@Test
public void test9() {
Date d = Date.valueOf("1961-08-30");
assertTrue(d.compareTo(d) == 0, "Error d.compareTo(d) !=0");
}
/**
* Validate that a Date.compareTo returns 0 when both Date objects represent
* the same date
*/
@Test
public void test10() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertTrue(d.compareTo(d2) == 0, "Error d.compareTo(d2) !=0");
}
/**
* Validate that a Date.compareTo returns -1 when comparing a date to a
* later date
*/
@Test
public void test11() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d.compareTo(d2) == -1, "Error d.compareTo(d2) != -1");
}
/**
* Validate that a Date.compareTo returns 1 when comparing a date to an
* earlier date
*/
@Test
public void test12() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d2.compareTo(d) == 1, "Error d.compareTo(d2) != 1");
}
/**
* Validate that a Date made from a LocalDate are equal
*/
@Test
public void test13() {
Date d = Date.valueOf("1961-08-30");
LocalDate ldt = d.toLocalDate();
Date d2 = Date.valueOf(ldt);
assertTrue(d.equals(d2), "Error d != d2");
}
/**
* Validate that a Date LocalDate value, made from a LocalDate are equal
*/
@Test
public void test14() {
LocalDate ldt = LocalDate.now();
Date d = Date.valueOf(ldt);
assertTrue(ldt.equals(d.toLocalDate()),
"Error LocalDate values are not equal");
}
/**
* Validate an NPE occurs when a null LocalDate is passed to valueOf
*/
@Test(expectedExceptions = NullPointerException.class)
public void test15() throws Exception {
LocalDate ld = null;
Date.valueOf(ld);
}
/**
* Validate an UnsupportedOperationException occurs when toInstant() is
* called
*/
@Test(expectedExceptions = UnsupportedOperationException.class)
public void test16() throws Exception {
Date d = Date.valueOf("1961-08-30");
Instant instant = d.toInstant();
}
/**
* Validate that two Date objects are equal when one is created from the
* toString() of the other
*/
@Test
public void test17() {
Date d = Date.valueOf("1961-08-30");
Date d2 = Date.valueOf(d.toString());
assertTrue(d.equals(d2) && d2.equals(d), "Error d != d2");
}
/**
* Validate that two Date values one created using valueOf and another via a
* constructor are equal
*/
@Test
public void test18() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(61, 7, 30);
assertTrue(d.equals(d2), "Error d != d2");
}
/**
* Validate that two Date values one created using getTime() of the other
* are equal
*/
@Test
public void test19() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertTrue(d.equals(d2), "Error d != d2");
}
/**
* Validate that a Date value is equal to itself
*/
@Test
public void test20() {
Date d = Date.valueOf("1961-08-30");
assertTrue(d.equals(d), "Error d != d");
}
/**
* Validate an IllegalArgumentException is thrown for calling getHours
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test21() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getHours();
}
/**
* Validate an IllegalArgumentException is thrown for calling getMinutes
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test22() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getMinutes();
}
/**
* Validate an IllegalArgumentException is thrown for calling getSeconds
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test23() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getSeconds();
}
/**
* Validate an IllegalArgumentException is thrown for calling setHours
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test24() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setHours(8);
}
/**
* Validate an IllegalArgumentException is thrown for calling setMinutes
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test25() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setMinutes(0);
}
/**
* Validate an IllegalArgumentException is thrown for calling setSeconds
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test26() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setSeconds(0);
}
}
| gpl-2.0 |
fiji/SPIM_Registration | src/main/java/mpicbg/spim/registration/detection/AbstractDetection.java | 3550 | /*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2007 - 2021 Fiji developers.
* %%
* 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 mpicbg.spim.registration.detection;
import net.imglib2.util.Util;
import fiji.util.node.Leaf;
import mpicbg.models.Point;
public abstract class AbstractDetection< T extends AbstractDetection< T > > extends Point implements Leaf< T >
{
private static final long serialVersionUID = 1L;
final protected long id;
protected double weight;
protected boolean useW = false;
// used for display
protected double distance = -1;
// used for recursive parsing
protected boolean isUsed = false;
public AbstractDetection( final int id, final double[] location )
{
super( location );
this.id = id;
}
public AbstractDetection( final int id, final double[] location, final double weight )
{
super( location );
this.id = id;
this.weight = weight;
}
public void setWeight( final double weight ){ this.weight = weight; }
public double getWeight(){ return weight; }
public long getID() { return id; }
public void setDistance( double distance ) { this.distance = distance; }
public double getDistance() { return distance; }
public boolean isUsed() { return isUsed; }
public void setUsed( final boolean isUsed ) { this.isUsed = isUsed; }
public boolean equals( final AbstractDetection<?> otherDetection )
{
if ( useW )
{
for ( int d = 0; d < 3; ++d )
if ( w[ d ] != otherDetection.w[ d ] )
return false;
}
else
{
for ( int d = 0; d < 3; ++d )
if ( l[ d ] != otherDetection.l[ d ] )
return false;
}
return true;
}
public void setW( final double[] wn )
{
for ( int i = 0; i < w.length; ++i )
w[ i ] = wn[ i ];
}
public void resetW()
{
for ( int i = 0; i < w.length; ++i )
w[i] = l[i];
}
public double getDistance( final Point point2 )
{
double distance = 0;
final double[] a = getL();
final double[] b = point2.getW();
for ( int i = 0; i < getL().length; ++i )
{
final double tmp = a[ i ] - b[ i ];
distance += tmp * tmp;
}
return Math.sqrt( distance );
}
@Override
public boolean isLeaf() { return true; }
@Override
public float distanceTo( final T o )
{
final double x = o.get( 0 ) - get( 0 );
final double y = o.get( 1 ) - get( 1 );
final double z = o.get( 2 ) - get( 2 );
return (float)Math.sqrt(x*x + y*y + z*z);
}
public void setUseW( final boolean useW ) { this.useW = useW; }
public boolean getUseW() { return useW; }
@Override
public float get( final int k )
{
if ( useW )
return (float)w[ k ];
else
return (float)l[ k ];
}
@Override
public int getNumDimensions() { return 3; }
@Override
public String toString()
{
String desc = "Detection " + getID() + " l"+ Util.printCoordinates( getL() ) + "; w"+ Util.printCoordinates( getW() );
return desc;
}
}
| gpl-2.0 |
degandroid/HospitalLink | app/src/main/java/com/enjoyor/hospitallink/custom/CircularImage.java | 1117 | package com.enjoyor.hospitallink.custom;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
public class CircularImage extends MaskedImage {
public CircularImage(Context paramContext) {
super(paramContext);
}
public CircularImage(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
}
public CircularImage(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
}
public Bitmap createMask() {
int i = getWidth();
int j = getHeight();
Bitmap.Config localConfig = Bitmap.Config.ARGB_8888;
Bitmap localBitmap = Bitmap.createBitmap(i, j, localConfig);
Canvas localCanvas = new Canvas(localBitmap);
Paint localPaint = new Paint(1);
localPaint.setColor(-16777216);
float f1 = getWidth();
float f2 = getHeight();
RectF localRectF = new RectF(0.0F, 0.0F, f1, f2);
localCanvas.drawOval(localRectF, localPaint);
return localBitmap;
}
}
| gpl-2.0 |
Kaos1337/ProjectKitten | src/bytecode/VIRTUALCALL.java | 3103 | package bytecode;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import javaBytecodeGenerator.GeneralClassGenerator;
import org.apache.bcel.generic.InstructionList;
import types.ClassType;
import types.CodeSignature;
import types.MethodSignature;
/**
* A bytecode that calls a method of an object with dynamic lookup.
* That object is the <i>receiver</i> of the call. If the receiver is
* {@code nil}, the computation stops.
* <br><br>
* ..., receiver, par_1, ..., par_n -> ..., returned value<br>
* if the method return type is non-{@code void}<br><br>
* ..., receiver, par_1, ..., par_n -> ...<br>
* if the method's return type is {@code void}
*
* @author <A HREF="mailto:fausto.spoto@univr.it">Fausto Spoto</A>
*/
public class VIRTUALCALL extends CALL {
/**
* Constructs a bytecode that calls a method of an object with dynamic
* lookup. The set of runtime targets is assumed to be that obtained
* from every subclass of the static type of the receiver.
*
* @param receiverType the static type of the receiver of this call
* @param staticTarget the signature of the static target of the call
*/
public VIRTUALCALL(ClassType receiverType, MethodSignature staticTarget) {
// we compute the dynamic targets by assuming that the runtime
// type of the receiver is any subclass of its static type
super(receiverType, staticTarget, dynamicTargets(receiverType.getInstances(), staticTarget));
}
/**
* Yields the set of runtime receivers of this call. They are all
* methods with the same signature of the static target and that might
* be called from a given set of runtime classes for the receiver.
*
* @param possibleRunTimeClasses the set of runtime classes for the receiver
* @param staticTarget the static target of the call
* @return the set of method signatures that might be called
* with the given set of classes as receiver
*/
private static Set<CodeSignature> dynamicTargets(List<ClassType> possibleRunTimeClasses, CodeSignature staticTarget) {
Set<CodeSignature> dynamicTargets = new HashSet<CodeSignature>();
for (ClassType rec: possibleRunTimeClasses) {
// we look up for the method from the dynamic receiver
MethodSignature candidate = rec.methodLookup(staticTarget.getName(), staticTarget.getParameters());
// we add the dynamic target
if (candidate != null)
dynamicTargets.add(candidate);
}
return dynamicTargets;
}
/**
* Generates the Java bytecode corresponding to this Kitten bytecode. Namely, it generates an
* {@code invokevirtual staticTarget} Java bytecode. The Java {@code invokevirtual} bytecode
* calls a method by using the runtime class of the receiver to look up for the method's implementation.
*
* @param classGen the Java class generator to be used for this generation
* @return the Java {@code invokevirtual staticTarget} bytecode
*/
@Override
public InstructionList generateJavaBytecode(GeneralClassGenerator classGen) {
return new InstructionList(((MethodSignature) getStaticTarget()).createINVOKEVIRTUAL(classGen));
}
} | gpl-2.0 |
priya121/TicTacToe | src/main/java/ttt/board/BoardDisplay.java | 512 | package ttt.board;
import ttt.Symbol;
import java.util.List;
public class BoardDisplay {
List<Symbol> board;
String display = "";
public BoardDisplay(List<Symbol> board) {
this.board = board;
}
public String showBoard() {
for (int i = 0; i < board.size(); i++) {
display += " " + board.get(i).getSymbol() + " ";
if ((i + 1) % Math.sqrt(board.size()) == 0) {
display += "\n";
}
}
return display;
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.core.common/src/org/graalvm/compiler/core/common/type/AbstractObjectStamp.java | 15167 | /*
* Copyright (c) 2012, 2021, 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 org.graalvm.compiler.core.common.type;
import java.util.AbstractList;
import java.util.Objects;
import java.util.RandomAccess;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* Type describing all pointers to Java objects.
*/
public abstract class AbstractObjectStamp extends AbstractPointerStamp {
/**
* Note: the meaning of {@link #type} == null is unfortunately overloaded: it means
* "java.lang.Object" when {@link #exactType} == false; but it means {@link #isEmpty "empty"}
* when {@link #exactType} == true.
*/
private final ResolvedJavaType type;
private final boolean exactType;
private final boolean alwaysArray;
protected AbstractObjectStamp(ResolvedJavaType type, boolean exactType, boolean nonNull, boolean alwaysNull, boolean alwaysArray) {
super(nonNull, alwaysNull);
/*
* Canonicalize the non-exact java.lang.Object to null so that other places like equals do
* not need special handling.
*/
this.type = type == null || (!exactType && type.isJavaLangObject()) ? null : type;
this.exactType = exactType;
this.alwaysArray = alwaysArray || (type != null && type.isArray());
}
@Override
public void accept(Visitor v) {
super.accept(v);
v.visitObject(type);
v.visitBoolean(exactType);
v.visitBoolean(alwaysArray);
}
protected abstract AbstractObjectStamp copyWith(ResolvedJavaType newType, boolean newExactType, boolean newNonNull, boolean newAlwaysNull, boolean newAlwaysArray);
@Override
protected final AbstractPointerStamp copyWith(boolean newNonNull, boolean newAlwaysNull) {
return copyWith(type, exactType, newNonNull, newAlwaysNull, alwaysArray);
}
@Override
public Stamp unrestricted() {
return copyWith(null, false, false, false, false);
}
@Override
public Stamp empty() {
return copyWith(null, true, true, false, false);
}
@Override
public Stamp constant(Constant c, MetaAccessProvider meta) {
JavaConstant jc = (JavaConstant) c;
ResolvedJavaType constType = jc.isNull() ? null : meta.lookupJavaType(jc);
return copyWith(constType, jc.isNonNull(), jc.isNonNull(), jc.isNull(), false);
}
@Override
public boolean hasValues() {
return !exactType || (type != null && (isConcreteType(type)));
}
@Override
public JavaKind getStackKind() {
return JavaKind.Object;
}
@Override
public ResolvedJavaType javaType(MetaAccessProvider metaAccess) {
if (type != null) {
return type;
}
return metaAccess.lookupJavaType(Object.class);
}
public ResolvedJavaType type() {
return type;
}
public boolean isExactType() {
return exactType && type != null;
}
/**
* Returns true if the stamp represents a type that is always an array. While all object arrays
* have a common base class, there is no common base class for primitive arrays, so maintaining
* a separate flag is more precise than just using {@link AbstractObjectStamp#type
* type}.{@link ResolvedJavaType#isArray isArray}.
*/
public boolean isAlwaysArray() {
return alwaysArray;
}
public AbstractObjectStamp asAlwaysArray() {
return copyWith(type, exactType, nonNull(), alwaysNull(), true);
}
protected void appendString(StringBuilder str) {
if (this.isEmpty()) {
str.append(" empty");
} else {
// Append "[]" for arrays, but only if it's not included in the type.
boolean forceArrayNotation = alwaysArray && !(type != null && type.isArray());
str.append(nonNull() ? "!" : "").//
append(exactType ? "#" : "").//
append(' ').//
append(type == null ? "java.lang.Object" : type.toJavaName()).//
append(forceArrayNotation ? "[]" : "").//
append(alwaysNull() ? " NULL" : "");
}
}
@Override
public Stamp meet(Stamp otherStamp) {
if (this == otherStamp) {
return this;
}
AbstractObjectStamp other = (AbstractObjectStamp) otherStamp;
if (isEmpty()) {
return other;
} else if (other.isEmpty()) {
return this;
}
ResolvedJavaType meetType;
boolean meetExactType;
boolean meetNonNull;
boolean meetAlwaysNull;
boolean meetAlwaysArray;
if (other.alwaysNull()) {
meetType = type();
meetExactType = exactType;
meetNonNull = false;
meetAlwaysNull = alwaysNull();
meetAlwaysArray = alwaysArray;
} else if (alwaysNull()) {
meetType = other.type();
meetExactType = other.exactType;
meetNonNull = false;
meetAlwaysNull = other.alwaysNull();
meetAlwaysArray = other.alwaysArray;
} else {
meetType = meetTypes(type(), other.type());
meetExactType = exactType && other.exactType;
if (meetExactType && type != null && other.type != null) {
// meeting two valid exact types may result in a non-exact type
meetExactType = Objects.equals(meetType, type) && Objects.equals(meetType, other.type);
}
meetNonNull = nonNull() && other.nonNull();
meetAlwaysNull = false;
meetAlwaysArray = this.alwaysArray && other.alwaysArray;
}
if (Objects.equals(meetType, type) && meetExactType == exactType && meetNonNull == nonNull() && meetAlwaysNull == alwaysNull() && meetAlwaysArray == alwaysArray) {
return this;
} else if (Objects.equals(meetType, other.type) && meetExactType == other.exactType && meetNonNull == other.nonNull() && meetAlwaysNull == other.alwaysNull() &&
meetAlwaysArray == other.alwaysArray) {
return other;
} else {
return copyWith(meetType, meetExactType, meetNonNull, meetAlwaysNull, meetAlwaysArray);
}
}
@Override
public Stamp join(Stamp otherStamp) {
return join0(otherStamp, false);
}
/**
* Returns the stamp representing the type of this stamp after a cast to the type represented by
* the {@code to} stamp. While this is very similar to a {@link #join} operation, in the case
* where both types are not obviously related, the cast operation will prefer the type of the
* {@code to} stamp. This is necessary as long as ObjectStamps are not able to accurately
* represent intersection types.
*
* For example when joining the {@link RandomAccess} type with the {@link AbstractList} type,
* without intersection types, this would result in the most generic type ({@link Object} ). For
* this reason, in some cases a {@code castTo} operation is preferable in order to keep at least
* the {@link AbstractList} type.
*
* @param other the stamp this stamp should be casted to
* @return the new improved stamp or {@code null} if this stamp cannot be improved
*/
@Override
public Stamp improveWith(Stamp other) {
return join0(other, true);
}
private Stamp join0(Stamp otherStamp, boolean improve) {
if (this == otherStamp) {
return this;
}
AbstractObjectStamp other = (AbstractObjectStamp) otherStamp;
if (isEmpty()) {
return this;
} else if (other.isEmpty()) {
return other;
}
ResolvedJavaType joinType;
boolean joinAlwaysNull = alwaysNull() || other.alwaysNull();
boolean joinNonNull = nonNull() || other.nonNull();
boolean joinExactType = exactType || other.exactType;
boolean joinAlwaysArray = alwaysArray || other.alwaysArray;
if (Objects.equals(type, other.type)) {
joinType = type;
} else if (type == null) {
joinType = other.type;
} else if (other.type == null) {
joinType = type;
} else {
// both types are != null and different
if (type.isAssignableFrom(other.type)) {
joinType = other.type;
if (exactType) {
joinAlwaysNull = true;
}
} else if (other.type.isAssignableFrom(type)) {
joinType = type;
if (other.exactType) {
joinAlwaysNull = true;
}
} else {
if (improve) {
joinType = type;
joinExactType = exactType;
} else {
joinType = null;
}
if (joinExactType || (!isInterfaceOrArrayOfInterface(type) && !isInterfaceOrArrayOfInterface(other.type))) {
joinAlwaysNull = true;
}
}
}
if (joinAlwaysArray && joinType != null && !joinType.isArray() && (joinExactType || !joinType.isJavaLangObject())) {
joinAlwaysNull = true;
/* If we now have joinNonNull && joinAlwaysNull, it is converted to "empty" below. */
}
if (joinAlwaysNull) {
joinType = null;
joinExactType = false;
joinAlwaysArray = false;
}
if (joinExactType && joinType == null) {
return empty();
}
if (joinAlwaysNull && joinNonNull) {
return empty();
} else if (joinExactType && !isConcreteType(joinType)) {
return empty();
}
if (Objects.equals(joinType, type) && joinExactType == exactType && joinNonNull == nonNull() && joinAlwaysNull == alwaysNull() && joinAlwaysArray == alwaysArray) {
return this;
} else if (Objects.equals(joinType, other.type) && joinExactType == other.exactType && joinNonNull == other.nonNull() && joinAlwaysNull == other.alwaysNull() &&
joinAlwaysArray == other.alwaysArray) {
return other;
} else {
return copyWith(joinType, joinExactType, joinNonNull, joinAlwaysNull, joinAlwaysArray);
}
}
private static boolean isInterfaceOrArrayOfInterface(ResolvedJavaType t) {
return t.isInterface() || (t.isArray() && t.getElementalType().isInterface());
}
public static boolean isConcreteType(ResolvedJavaType type) {
return !(type.isAbstract() && !type.isArray());
}
private static ResolvedJavaType meetTypes(ResolvedJavaType a, ResolvedJavaType b) {
if (Objects.equals(a, b)) {
return a;
} else if (a == null || b == null) {
return null;
} else {
// The `meetTypes` operation must be commutative. One way to achieve this is to totally
// order the types and always call `meetOrderedNonNullTypes` in the same order. We
// establish the order by first comparing the hash-codes for performance reasons, and
// then comparing the internal names of the types.
int hashA = a.getName().hashCode();
int hashB = b.getName().hashCode();
if (hashA < hashB) {
return meetOrderedNonNullTypes(a, b);
} else if (hashB < hashA) {
return meetOrderedNonNullTypes(b, a);
} else {
int diff = a.getName().compareTo(b.getName());
if (diff <= 0) {
return meetOrderedNonNullTypes(a, b);
} else {
return meetOrderedNonNullTypes(b, a);
}
}
}
}
private static ResolvedJavaType meetOrderedNonNullTypes(ResolvedJavaType a, ResolvedJavaType b) {
ResolvedJavaType result = a.findLeastCommonAncestor(b);
if (result.isJavaLangObject() && a.isInterface() && b.isInterface()) {
// Both types are incompatible interfaces => search for first possible common
// ancestor match among super interfaces.
ResolvedJavaType[] interfacesA = a.getInterfaces();
ResolvedJavaType[] interfacesB = b.getInterfaces();
for (int i = 0; i < interfacesA.length; ++i) {
ResolvedJavaType interface1 = interfacesA[i];
for (int j = 0; j < interfacesB.length; ++j) {
ResolvedJavaType interface2 = interfacesB[j];
ResolvedJavaType leastCommon = meetTypes(interface1, interface2);
if (leastCommon.isInterface()) {
return leastCommon;
}
}
}
}
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + super.hashCode();
result = prime * result + (exactType ? 1231 : 1237);
result = prime * result + (alwaysArray ? 1231 : 1237);
result = prime * result + (type == null ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractObjectStamp other = (AbstractObjectStamp) obj;
if (exactType != other.exactType) {
return false;
}
if (alwaysArray != other.alwaysArray) {
return false;
}
if (!Objects.equals(type, other.type)) {
return false;
}
return super.equals(other);
}
}
| gpl-2.0 |
piaolinzhi/fight | dubbo/pay/pay-web-notify-receive/src/main/java/wusc/edu/pay/web/notify/receive/mail/biz/MailBiz.java | 1447 | package wusc.edu.pay.web.notify.receive.mail.biz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import wusc.edu.pay.common.param.MailParam;
/**
*
* @描述: 邮件发送业务逻辑类.
* @作者: LiLiqiong,WuShuicheng.
* @创建: 2014-6-4,下午3:34:41
* @版本: V1.0
*
*/
@Component("mailBiz")
public class MailBiz {
@Autowired
private JavaMailSender mailSender;// spring配置中定义
@Autowired
private SimpleMailMessage simpleMailMessage;// spring配置中定义
@Autowired
private ThreadPoolTaskExecutor threadPool;
/**
* 发送模板邮件
*
* @param mailParamTemp需要设置四个参数
* templateName,toMail,subject,mapModel
* @throws Exception
*
*/
public void mailSend(final MailParam mailParam) {
threadPool.execute(new Runnable() {
public void run() {
simpleMailMessage.setFrom(simpleMailMessage.getFrom()); // 发送人,从配置文件中取得
simpleMailMessage.setTo(mailParam.getTo()); // 接收人
simpleMailMessage.setSubject(mailParam.getSubject());
simpleMailMessage.setText(mailParam.getContent());
mailSender.send(simpleMailMessage);
}
});
}
}
| gpl-2.0 |
imagopole/omero-csv-tools | src/main/java/org/imagopole/omero/tools/impl/CsvAnnotator.java | 20257 | /**
*
*/
package org.imagopole.omero.tools.impl;
import static org.imagopole.omero.tools.util.AnnotationsUtil.getExportModeAnnotationInfo;
import static org.imagopole.omero.tools.util.AnnotationsUtil.getImportModeAnnotationInfo;
import static org.imagopole.omero.tools.util.ParseUtil.getFileBasename;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
import omero.ServerError;
import omero.api.ServiceFactoryPrx;
import org.imagopole.omero.tools.api.blitz.OmeroAnnotationService;
import org.imagopole.omero.tools.api.blitz.OmeroContainerService;
import org.imagopole.omero.tools.api.blitz.OmeroFileService;
import org.imagopole.omero.tools.api.blitz.OmeroQueryService;
import org.imagopole.omero.tools.api.blitz.OmeroUpdateService;
import org.imagopole.omero.tools.api.cli.Args.AnnotatedType;
import org.imagopole.omero.tools.api.cli.Args.AnnotationType;
import org.imagopole.omero.tools.api.cli.Args.ContainerType;
import org.imagopole.omero.tools.api.cli.Args.Defaults;
import org.imagopole.omero.tools.api.cli.Args.FileType;
import org.imagopole.omero.tools.api.cli.Args.RunMode;
import org.imagopole.omero.tools.api.cli.CsvAnnotationConfig;
import org.imagopole.omero.tools.api.ctrl.CsvAnnotationController;
import org.imagopole.omero.tools.api.ctrl.CsvExportController;
import org.imagopole.omero.tools.api.ctrl.FileReaderController;
import org.imagopole.omero.tools.api.ctrl.FileWriterController;
import org.imagopole.omero.tools.api.ctrl.MetadataController;
import org.imagopole.omero.tools.api.dto.AnnotationInfo;
import org.imagopole.omero.tools.api.dto.CsvData;
import org.imagopole.omero.tools.api.dto.LinksData;
import org.imagopole.omero.tools.api.dto.PojoData;
import org.imagopole.omero.tools.impl.blitz.AnnotationBlitzService;
import org.imagopole.omero.tools.impl.blitz.FileBlitzService;
import org.imagopole.omero.tools.impl.blitz.QueryBlitzService;
import org.imagopole.omero.tools.impl.blitz.ShimContainersBlitzService;
import org.imagopole.omero.tools.impl.blitz.UpdateBlitzService;
import org.imagopole.omero.tools.impl.ctrl.DefaultCsvAnnotationController;
import org.imagopole.omero.tools.impl.ctrl.DefaultCsvExportController;
import org.imagopole.omero.tools.impl.ctrl.DefaultFileReaderController;
import org.imagopole.omero.tools.impl.ctrl.DefaultFileWriterController;
import org.imagopole.omero.tools.impl.ctrl.DefaultMetadataController;
import org.imagopole.omero.tools.impl.logic.DefaultCsvAnnotationService;
import org.imagopole.omero.tools.impl.logic.DefaultCsvReaderService;
import org.imagopole.omero.tools.impl.logic.DefaultCsvWriterService;
import org.imagopole.omero.tools.impl.logic.DefaultFileReaderService;
import org.imagopole.omero.tools.impl.logic.DefaultFileWriterService;
import org.imagopole.omero.tools.impl.logic.DefaultMetadataService;
import org.imagopole.omero.tools.util.Check;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main application class for CSV and annotations processing.
*
* @author seb
*
*/
public class CsvAnnotator {
/** Application logs */
private final Logger log = LoggerFactory.getLogger(CsvAnnotator.class);
private CsvAnnotationConfig config;
private ServiceFactoryPrx session;
private CsvAnnotationController annotationController;
private MetadataController metadataController;
private CsvExportController exportController;
private FileReaderController fileReaderController;
private FileWriterController fileWriterController;
/**
* Parameterized constructor.
*
* @param config the CSV tool configuration settings
* @param session the OMERO Blitz session
*/
private CsvAnnotator(CsvAnnotationConfig config, ServiceFactoryPrx session) {
super();
Check.notNull(session, "session");
Check.notNull(config, "config");
this.config = config;
this.session = session;
}
/**
* Static factory method.
*
* @param config the CSV tool configuration settings
* @param session the OMERO Blitz session
* @return an initialized <code>CsvAnnotator</code>
* >
*/
public static final CsvAnnotator forSession(
CsvAnnotationConfig config,
ServiceFactoryPrx session) {
Check.notNull(config, "config");
Check.notNull(session, "session");
CsvAnnotator annotator = new CsvAnnotator(config, session);
annotator.wireDependencies();
return annotator;
}
/**
* Main entry point to the application logic.
*
* @param experimenterId the experimenter
* @throws ServerError OMERO client or server failure
* @throws IOException CSV file read failure
*/
public void runFromConfig(final Long experimenterId) throws ServerError, IOException {
Check.notNull(experimenterId, "experimenterId");
// config is expected to be valid at this point
log.debug("Config dump: {}", config.dump());
// convert cli arguments to valid enum values or fail
final String runModeArg = config.getRunModeArg();
final RunMode runMode = RunMode.valueOf(runModeArg);
log.debug("Requested run mode: {}", runMode);
switch (runMode) {
case annotate:
runAnnotateModeFromConfig(experimenterId);
break;
case export:
runExportModeFromConfig(experimenterId);
break;
case transfer:
runTransferModeFromConfig(experimenterId);
break;
case auto:
runAutoModeFromConfig(experimenterId);
break;
default:
throw new UnsupportedOperationException("Unsupported run mode parameter");
}
}
/**
* Main entry point to the "annotate mode" logic.
*
* @param experimenterId the experimenter
* @throws ServerError OMERO client or server failure
* @throws IOException CSV file read failure
*/
private void runAnnotateModeFromConfig(final Long experimenterId) throws ServerError, IOException {
Check.notNull(experimenterId, "experimenterId");
log.debug("annotate-mode:start");
final Long containerId = config.getContainerId();
final String csvFileName = config.getOrInferCsvFilename();
// convert cli arguments to valid enum values or fail
final String fileTypeArg = config.getCsvFileTypeArg();
final String containerTypeArg = config.getCsvContainerTypeArg();
final String annotationTypeArg = config.getAnnotationTypeArg();
final FileType fileType = FileType.valueOf(fileTypeArg);
final ContainerType containerType = ContainerType.valueOf(containerTypeArg);
final AnnotationType annotationType = AnnotationType.valueOf(annotationTypeArg);
final AnnotatedType annotatedType = config.getOrInferEffectiveAnnotatedType();
// read CSV content from input source (local file or remote file annotation)
// and decode into string data
final CsvData csvData =
fileReaderController.readByFileContainerType(
experimenterId,
containerId,
containerType,
fileType,
csvFileName);
// process CSV string to OMERO model object annotation links
LinksData linksData = annotationController.buildAnnotationsByTypes(
experimenterId,
containerId,
containerType,
annotationType,
annotatedType,
csvData);
// persist to database
log.info("Persisting changes to database");
annotationController.saveAllAnnotationLinks(linksData);
log.debug("annotate-mode:end");
}
/**
* Main entry point to the "export mode" logic.
*
* @param experimenterId the experimenter
* @throws ServerError OMERO client or server failure
* @throws IOException CSV file write failure
*/
private void runExportModeFromConfig(final Long experimenterId) throws ServerError, IOException {
Check.notNull(experimenterId, "experimenterId");
log.debug("export-mode:start");
final Long containerId = config.getContainerId();
final String csvFileName = config.getOrInferCsvFilename();
// convert cli arguments to valid enum values or fail
final String fileTypeArg = config.getCsvFileTypeArg();
final String containerTypeArg = config.getCsvContainerTypeArg();
final String annotationTypeArg = config.getAnnotationTypeArg();
final FileType fileType = FileType.valueOf(fileTypeArg);
final ContainerType containerType = ContainerType.valueOf(containerTypeArg);
final AnnotationType annotationType = AnnotationType.valueOf(annotationTypeArg);
final AnnotatedType annotatedType = config.getOrInferEffectiveAnnotatedType();
// lookup the (annotated) OMERO data hierarchy for export
Collection<PojoData> entitiesPlusAnnotations =
metadataController.listEntitiesPlusAnnotations(
experimenterId,
containerId,
containerType,
annotationType,
annotatedType);
// convert the OMERO data hierarchy into CSV content
String fileContent =
exportController.convertToCsv(annotationType, annotatedType, entitiesPlusAnnotations);
// get the file annotation metadata (ie. namespace & description)
AnnotationInfo annotationInfo = getExportModeAnnotationInfo(containerId, containerType);
// upload and attach the generated CSV to the OMERO container
fileWriterController.writeByFileContainerType(
experimenterId,
containerId,
containerType,
fileType,
csvFileName,
fileContent,
annotationInfo);
log.debug("export-mode:end");
}
/**
* Main entry point to the "import/transfer mode" (ie. upload + attach) logic.
*
* @param experimenterId the experimenter
* @throws ServerError OMERO client or server failure
* @throws IOException CSV file upload/attach failure
*/
private void runTransferModeFromConfig(final Long experimenterId) throws ServerError, IOException {
Check.notNull(experimenterId, "experimenterId");
log.debug("transfer-mode:start");
final Long containerId = config.getContainerId();
final String configCsvFileName = config.getOrInferCsvFilename();
// ignore the fileType in attach mode:
// always read from a local file and write to a remote file annotation
final String fileTypeArg = config.getCsvFileTypeArg();
if (null != fileTypeArg && !fileTypeArg.trim().isEmpty()) {
log.info("Transfer mode - ignoring/resetting configured fileType: {}", fileTypeArg);
config.setCsvFileTypeArg(null);
}
// convert cli arguments to valid enum values or fail
final String containerTypeArg = config.getCsvContainerTypeArg();
final ContainerType containerType = ContainerType.valueOf(containerTypeArg);
// read CSV content from local file
final CsvData csvData =
fileReaderController.readByFileContainerType(
experimenterId,
containerId,
containerType,
FileType.local,
configCsvFileName);
if (null != csvData) {
// get the file annotation data + metadata (ie. namespace & description)
String fileContent = csvData.getFileContent();
AnnotationInfo annotationInfo = getImportModeAnnotationInfo(containerId, containerType);
// strip the path information from the remote file annotation name
String remoteCsvFileName = getFileBasename(configCsvFileName);
// upload and attach the generated CSV to the OMERO container
fileWriterController.writeByFileContainerType(
experimenterId,
containerId,
containerType,
FileType.remote,
remoteCsvFileName,
fileContent,
annotationInfo);
} else {
log.warn("Failed to read local file content for transfer from: {}", configCsvFileName);
}
log.debug("transfer-mode:end");
}
/**
* Main entry point to the "auto-pilot mode" (transfer + annotate) logic.
*
* @param experimenterId the experimenter
* @throws ServerError OMERO client or server failure
* @throws IOException CSV file upload/attach failure
*/
private void runAutoModeFromConfig(final Long experimenterId) throws ServerError, IOException {
Check.notNull(experimenterId, "experimenterId");
//-- auto mode:
//-- (i) upload and attach local CSV file
runTransferModeFromConfig(experimenterId);
//-- (ii) re-configure cli parameters for next step (annotate)
String configCsvFileName = config.getOrInferCsvFilename();
String remoteCsvFileName = getFileBasename(configCsvFileName);
log.info("Auto mode - overriding configured fileType: {}->remote and fileName: {}->{}",
config.getCsvFileTypeArg(), configCsvFileName, remoteCsvFileName);
config.setCsvFileTypeArg(Defaults.FILE_TYPE_REMOTE);
config.setCsvFileName(remoteCsvFileName);
//-- (iii) process remote CSV file annotation
runAnnotateModeFromConfig(experimenterId);
}
/**
* Initialize required services.
*
* Calls sequence down "layers":
*
* CsvAnnotator -> controllers -> application logic ("business") services -> OMERO Blitz services
*/
private void wireDependencies() {
Charset charset = lookupCharsetOrFail(config.getCsvCharsetName());
//-- omero/blitz common "layer"
// note: ContainersBlitzService is replaced with an intercepting implementation until support
// for SPW data makes it into server-side OMERO implementations (QueryDefinitions and DataObject)
OmeroAnnotationService annotationService = new AnnotationBlitzService(session);
OmeroFileService fileService = new FileBlitzService(session);
OmeroUpdateService updateService = new UpdateBlitzService(session);
OmeroContainerService containerService = new ShimContainersBlitzService(session);
CsvAnnotationController annotationController =
buildAnnotationController(session, config, annotationService, containerService, updateService);
FileReaderController fileReaderController =
buildFileReaderController(session, config, charset, annotationService, fileService);
FileWriterController fileWriterController =
buildFileWriterController(session, config, charset, fileService, updateService);
MetadataController metadataController =
buildMetadataController(session, config, annotationService, containerService);
CsvExportController exportController =
buildExportController(session, config);
this.annotationController = annotationController;
this.fileReaderController = fileReaderController;
this.fileWriterController = fileWriterController;
this.metadataController = metadataController;
this.exportController = exportController;
}
private FileReaderController buildFileReaderController(
final ServiceFactoryPrx session,
final CsvAnnotationConfig config,
final Charset charset,
final OmeroAnnotationService annotationService,
final OmeroFileService fileService) {
//-- business logic "layer"
DefaultFileReaderService fileReaderService = new DefaultFileReaderService();
fileReaderService.setFileService(fileService);
fileReaderService.setAnnotationService(annotationService);
fileReaderService.setCharset(charset);
//-- controller "layer"
final DefaultFileReaderController fileReaderController = new DefaultFileReaderController();
fileReaderController.setFileReaderService(fileReaderService);
return fileReaderController;
}
private FileWriterController buildFileWriterController(
final ServiceFactoryPrx session,
final CsvAnnotationConfig config,
final Charset charset,
final OmeroFileService fileService,
final OmeroUpdateService updateService) {
//-- omero/blitz "layer"
OmeroQueryService queryService = new QueryBlitzService(session);
//-- business logic "layer"
DefaultFileWriterService fileWriterService = new DefaultFileWriterService();
fileWriterService.setFileService(fileService);
fileWriterService.setQueryService(queryService);
fileWriterService.setUpdateService(updateService);
fileWriterService.setCharset(charset);
//-- controller "layer"
final DefaultFileWriterController fileWriterController = new DefaultFileWriterController();
fileWriterController.setFileWriterService(fileWriterService);
return fileWriterController;
}
private CsvAnnotationController buildAnnotationController(
final ServiceFactoryPrx session,
final CsvAnnotationConfig config,
final OmeroAnnotationService annotationService,
final OmeroContainerService containerService,
final OmeroUpdateService updateService) {
//-- business logic "layer"
DefaultCsvReaderService csvReaderService = new DefaultCsvReaderService();
csvReaderService.setDelimiter(config.getCsvDelimiter());
csvReaderService.setSkipHeader(config.getCsvSkipHeader());
DefaultCsvAnnotationService csvAnnotationService = new DefaultCsvAnnotationService();
csvAnnotationService.setContainerService(containerService);
csvAnnotationService.setAnnotationService(annotationService);
csvAnnotationService.setUpdateService(updateService);
//-- controller "layer"
DefaultCsvAnnotationController annotationController = new DefaultCsvAnnotationController();
annotationController.setCsvReaderService(csvReaderService);
annotationController.setCsvAnnotationService(csvAnnotationService);
return annotationController;
}
private MetadataController buildMetadataController(
final ServiceFactoryPrx session,
final CsvAnnotationConfig config,
final OmeroAnnotationService annotationService,
final OmeroContainerService containerService) {
//-- business logic "layer"
DefaultMetadataService metadataService = new DefaultMetadataService();
metadataService.setAnnotationService(annotationService);
metadataService.setContainerService(containerService);
//-- controller "layer"
DefaultMetadataController metadataController = new DefaultMetadataController();
metadataController.setMetadataService(metadataService);
return metadataController;
}
private CsvExportController buildExportController(
final ServiceFactoryPrx session,
final CsvAnnotationConfig config) {
//-- business logic "layer"
DefaultCsvWriterService csvWriterService = new DefaultCsvWriterService();
csvWriterService.setDelimiter(config.getCsvDelimiter());
csvWriterService.setSkipHeader(config.getCsvSkipHeader());
//-- controller "layer"
DefaultCsvExportController exportController = new DefaultCsvExportController();
exportController.setCsvWriterService(csvWriterService);
return exportController;
}
private static Charset lookupCharsetOrFail(String charsetName) {
// maybe move this to a check to config.validate() first?
return Charset.forName(charsetName);
}
}
| gpl-2.0 |
Longri/CB_MAP | writer/src/test/java/de/cb_map/database/OSMDB/FileOSMDBTest.java | 7347 | package de.cb_map.database.OSMDB;
import de.cb_map.CONSTANTS;
import de.cb_map.database.IElementStreamReader;
import de.cb_map.io.utils.TimeFormat;
import de.cb_map.osm.low_memory.IntBoundingBox;
import de.cb_map.osm.low_memory.ReadOsm;
import org.junit.Test;
import org.mapsforge.map.writer.model.TDNode;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Longri on 30.03.2016.
*/
public class FileOSMDBTest {
static final String dbPath = CONSTANTS.RESOURCE;
static final String dbName = "testDatabase";
static final String dbName2 = "testDatabase2";
static final String dbName3 = "testDatabase3";
static final String dbName4 = "testDatabase4";
@Test
public void create() throws Exception {
//delete exist db file
FileOSMDB.delete(dbPath, dbName);
FileOSMDB db = new FileOSMDB(dbPath, dbName, AccessType.WRITE);
db.open();
FileOSMDB db2 = new FileOSMDB(dbPath, dbName, AccessType.READ);
db2.open();
//db2 must read default header settings
// assertEquals("Wrong NodeStore pointer", FileOSMDB.HEADER_LENGTH + 1, db2.POINTER.NodeStore);
}
@Test
public void addNodeAndSearch() throws Exception {
//delete exist db file
FileOSMDB.delete(dbPath, dbName2);
FileOSMDB db = new FileOSMDB(dbPath, dbName2, AccessType.READ_WRITE);
db.open();
TDNode node = new TDNode(1, 10, -11, (short) 1, (byte) 1, "Housenumber", "Name", new short[]{1, 2});
db.storeNode(node, true);
TDNode node2 = db.getNode(1);
TDNode node3 = new TDNode(2, 2, 2, (short) 2, (byte) 2, "Housenumber2", "Name2", new short[]{1, 2});
db.storeNode(node3, true);
TDNode node4 = db.getNode(2);
TDNode node5 = new TDNode(3, 3, 3, (short) 3, (byte) 3, "Housenumber3", "Name3", new short[]{1, 2});
db.storeNode(node5, true);
TDNode node6 = db.getNode(3);
TDNode node7 = new TDNode(4, 4, 4, (short) 5, (byte) 4, "Housenumber4", "Name4", new short[]{1, 2});
db.storeNode(node7, true);
TDNode node8 = db.getNode(4);
// Id equals
assertEquals("Nodes must by equals", node, node2);
assertEquals("Nodes must by equals", node3, node4);
assertEquals("Nodes must by equals", node5, node6);
assertEquals("Nodes must by equals", node7, node8);
// latitude equals
assertEquals("Nodes must by equals", node.getLatitude(), node2.getLatitude());
assertEquals("Nodes must by equals", node3.getLatitude(), node4.getLatitude());
assertEquals("Nodes must by equals", node5.getLatitude(), node6.getLatitude());
assertEquals("Nodes must by equals", node7.getLatitude(), node8.getLatitude());
// longitude equals
assertEquals("Nodes must by equals", node.getLongitude(), node2.getLongitude());
assertEquals("Nodes must by equals", node3.getLongitude(), node4.getLongitude());
assertEquals("Nodes must by equals", node5.getLongitude(), node6.getLongitude());
assertEquals("Nodes must by equals", node7.getLongitude(), node8.getLongitude());
}
@Test
public void writeBerlinNodesIntoOSMDB() throws IOException, SQLException {
boolean onlyRead = false;
boolean onlyWrite = false;
File nameFile = new File("src/test/resources/berlin-latest.osm");
//delete exist db file
if (!onlyRead) FileOSMDB.delete(dbPath, dbName3);
long start = System.currentTimeMillis();
if (!onlyRead) {
FileOSMDB db = new FileOSMDB(dbPath, dbName3, AccessType.WRITE);
db.open();
ReadOsm.setOsmFile(nameFile);
ReadOsm.writeToGeoDB(db, null);
long writeTime = System.currentTimeMillis() - start;
System.out.println("Nodes Write to DB after " + new TimeFormat(writeTime, TimeFormat.ROUND_TO_MILLISECOND));
System.out.println("Write " + db.count);
System.out.println("ReadOsmFoundedStartTags " + ReadOsm.nodeCount);
assertTrue(4323871 == db.count);
}
if (onlyWrite) return;
start = System.currentTimeMillis();
FileOSMDB DbReader = new FileOSMDB(dbPath, dbName3, AccessType.READ);
DbReader.open();
IntBoundingBox bb = new IntBoundingBox(CONSTANTS.BB_PANKOW);
IElementStreamReader reader = DbReader.getStreamReader(bb);
int count = 0;
while (reader.hasNextNode()) {
reader.getNode();
count++;
}
System.out.println("countAddNode = " + FileOSMDB.countAddNode);
System.out.println("countAddValues = " + FileOSMDB.countAddValues);
System.out.println("countAddInside = " + FileOSMDB.countAddInside);
System.out.println("countRead = " + FileOSMDB.countRead);
System.out.println("countReadLatLon = " + FileOSMDB.countReadLatLon);
System.out.println("countAll = " + FileOSMDB.countAll);
assertEquals("Must found 169 Nodes for PankowBB", 169, count);
long duration = System.currentTimeMillis() - start;
System.out.println(count + " Nodes Found in Pankow (" + CONSTANTS.BB_PANKOW + ") after " + new TimeFormat(duration, TimeFormat.ROUND_TO_MILLISECOND));
}
@Test
public void parselatLonTest() throws IOException, SQLException {
File nameFile = new File("src/test/resources/nodes.osm");
//delete exist db file
FileOSMDB.delete(dbPath, dbName4);
long start = System.currentTimeMillis();
FileOSMDB db = new FileOSMDB(dbPath, dbName4, AccessType.WRITE);
db.open();
ReadOsm.setOsmFile(nameFile);
ReadOsm.writeToGeoDB(db, null);
long writeTime = System.currentTimeMillis() - start;
System.out.println("Nodes Write to DB after " + new TimeFormat(writeTime, TimeFormat.ROUND_TO_MILLISECOND));
System.out.println("Write " + db.count);
System.out.println("ReadOsmFoundedStartTags " + ReadOsm.nodeCount);
assertTrue(10 == db.count);
start = System.currentTimeMillis();
FileOSMDB DbReader = new FileOSMDB(dbPath, dbName4, AccessType.READ);
DbReader.open();
IntBoundingBox bb = new IntBoundingBox(CONSTANTS.BB_PANKOW);
IElementStreamReader reader = DbReader.getStreamReader(bb);
int count = 0;
while (reader.hasNextNode()) {
reader.getNode();
count++;
}
System.out.println("countAddNode = " + FileOSMDB.countAddNode);
System.out.println("countAddValues = " + FileOSMDB.countAddValues);
System.out.println("countAddInside = " + FileOSMDB.countAddInside);
System.out.println("countRead = " + FileOSMDB.countRead);
System.out.println("countReadLatLon = " + FileOSMDB.countReadLatLon);
System.out.println("countAll = " + FileOSMDB.countAll);
assertEquals("Must found 0 Nodes for PankowBB", 0, count);
long duration = System.currentTimeMillis() - start;
System.out.println(count + " Nodes Found in Pankow (" + CONSTANTS.BB_PANKOW + ") after " + new TimeFormat(duration, TimeFormat.ROUND_TO_MILLISECOND));
}
} | gpl-2.0 |
rabbott99/dolphin | Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/ui/settings/viewholder/SingleChoiceViewHolder.java | 1479 | package org.dolphinemu.dolphinemu.ui.settings.viewholder;
import android.view.View;
import android.widget.TextView;
import org.dolphinemu.dolphinemu.R;
import org.dolphinemu.dolphinemu.model.settings.view.SettingsItem;
import org.dolphinemu.dolphinemu.model.settings.view.SingleChoiceSetting;
import org.dolphinemu.dolphinemu.model.settings.view.StringSingleChoiceSetting;
import org.dolphinemu.dolphinemu.ui.settings.SettingsAdapter;
public final class SingleChoiceViewHolder extends SettingViewHolder
{
private SettingsItem mItem;
private TextView mTextSettingName;
private TextView mTextSettingDescription;
public SingleChoiceViewHolder(View itemView, SettingsAdapter adapter)
{
super(itemView, adapter);
}
@Override
protected void findViews(View root)
{
mTextSettingName = (TextView) root.findViewById(R.id.text_setting_name);
mTextSettingDescription = (TextView) root.findViewById(R.id.text_setting_description);
}
@Override
public void bind(SettingsItem item)
{
mItem = item;
mTextSettingName.setText(item.getNameId());
if (item.getDescriptionId() > 0)
{
mTextSettingDescription.setText(item.getDescriptionId());
}
}
@Override
public void onClick(View clicked)
{
if (mItem instanceof SingleChoiceSetting)
{
getAdapter().onSingleChoiceClick((SingleChoiceSetting) mItem);
}
else if (mItem instanceof StringSingleChoiceSetting)
{
getAdapter().onStringSingleChoiceClick((StringSingleChoiceSetting) mItem);
}
}
}
| gpl-2.0 |
AubinMahe/dcrud | Java/test/tests/shapes/ShapesUI.java | 12985 | package tests.shapes;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.BiFunction;
import org.hpms.mw.dcrud.Arguments;
import org.hpms.mw.dcrud.ICRUD;
import org.hpms.mw.dcrud.ICache;
import org.hpms.mw.dcrud.IDispatcher;
import org.hpms.mw.dcrud.IParticipant;
import org.hpms.mw.dcrud.IRegistry;
import org.hpms.mw.dcrud.IRequired;
import org.hpms.mw.dcrud.Network;
import org.hpms.mw.dcrud.Shareable;
import org.hpms.util.Performance;
import javafx.application.Application.Parameters;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Menu;
import javafx.scene.control.TableView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Screen;
import javafx.stage.Stage;
import tests.App;
import tests.Controller;
import tests.QuadFunction;
import tests.StaticRegistry;
public class ShapesUI implements Controller {
private final Random _random = new Random();
private ICache _cache;
private int _rank;
private Node _dragged;
private double _nodeX;
private double _nodeY;
private double _fromX;
private double _fromY;
private boolean _periodic;
private boolean _moveThem;
private boolean _readonly;
private ICRUD _remoteEllipseFactory;
private ICRUD _remoteRectangleFactory;
private String _window;
private IRequired _iMonitor;
@FXML private Menu _publisherMnu;
@FXML private CheckMenuItem _periodicChkMnu;
@FXML private CheckMenuItem _moveChkMnu;
@FXML private TableView<FxShape> _shapesTbl;
@FXML private Pane _shapesArea;
@FXML private ColorPicker _strokeColor;
@FXML private ColorPicker _fillColor;
@FXML
private void onQuit() {
try {
Performance.saveToDisk();
_iMonitor.call( "exit" );
Thread.sleep( 40 );
}
catch( final Throwable t ) {
t.printStackTrace();
}
System.exit( 0 );
}
private void onShown( Stage stage ) {
final Rectangle2D screen = Screen.getPrimary().getBounds();
final double left = ( screen.getWidth () - stage.getWidth ()) + 4;
final double top = ( screen.getHeight() - stage.getHeight()) + 4;
Platform.runLater(() -> {
switch( _window ) {
default:
case "left-top":
stage.setX( -4 );
stage.setY( -4 );
break;
case "right-top":
stage.setX( left );
stage.setY( -4 );
break;
case "right-bottom":
stage.setX( left );
stage.setY( top );
break;
case "left-bottom":
stage.setX( -4 );
stage.setY( top );
break;
}
});
}
private void dcrudInitialize( Map<String, String> n ) throws IOException {
_window = n.getOrDefault( "window" , "left-top" );
_readonly = Boolean.parseBoolean( n.getOrDefault( "readonly" , "false" ));
final boolean ownership = Boolean.parseBoolean( n.getOrDefault( "ownership", "false" ));
final boolean periodic = Boolean.parseBoolean( n.getOrDefault( "periodic" , "false" ));
final boolean move = Boolean.parseBoolean( n.getOrDefault( "move" , "false" ));
Network.recordPerformance = Boolean.parseBoolean( n.getOrDefault( "perf" , "false" ));
final boolean remote = Boolean.parseBoolean( n.getOrDefault( "remote" , "false" ));
final String intrfcName = n.getOrDefault( "interface", "eth0" );
final short port = Short .parseShort( n.getOrDefault( "port" , "2416" ));
if( intrfcName == null ) {
throw new IllegalStateException( "--interface=<string> missing" );
}
final NetworkInterface intrfc = NetworkInterface.getByName( intrfcName );
final InetSocketAddress addr = new InetSocketAddress( "224.0.0.3", port );
final IRegistry registry = new StaticRegistry();
final IParticipant participant = Network.join( port - 2415, addr, intrfc );
participant.listen( intrfc, registry );
participant.registerLocalFactory( ShareableEllipse.CLASS_ID, ShareableEllipse::new );
participant.registerLocalFactory( ShareableRect .CLASS_ID, ShareableRect ::new );
_cache = participant.createCache();
_cache.setOwnership( ownership );
// _cache.subscribe( ShareableEllipse.CLASS_ID );
// _cache.subscribe( ShareableRect .CLASS_ID );
final IDispatcher dispatcher = participant.getDispatcher();
if( remote ) {
_remoteEllipseFactory = dispatcher.requireCRUD( ShareableEllipse.CLASS_ID );
_remoteRectangleFactory = dispatcher.requireCRUD( ShareableRect .CLASS_ID );
}
_iMonitor = dispatcher.require( "IMonitor" );
new Timer( "AnimationActivity", true ).schedule(
new TimerTask() { @Override public void run() { animationActivity(); }}, 0, 40L );
new Timer( "NetworkActivity", true ).schedule(
new TimerTask() { @Override public void run() { networkActivity(); }}, 0, 40L );
if( periodic ) {
_periodicChkMnu.setSelected( periodic );
_periodic = periodic;
}
if( move ) {
_moveChkMnu.setSelected( move );
_moveThem = move;
}
final String create = n.getOrDefault( "create", null );
if( create != null ) {
final String[] shapes = create.split( "," );
for( final String shape : shapes ) {
switch( shape ) {
default: throw new IllegalArgumentException( create );
case "Ellipse" : createEllipse(); break;
case "Rectangle": createRectangle(); break;
}
}
}
}
@Override
public void initialize( Stage stage, Parameters args ) throws Exception {
stage.setTitle( "Editeur de formes" );
stage.setOnShown ( e -> onShown( stage ));
stage.setOnCloseRequest( e -> onQuit());
stage.getIcons().add( new Image( getClass().getResource( "local.png" ).toExternalForm()));
final Map<String, String> n = args.getNamed();
final String fill = n.get( "fill" );
if( fill != null ) {
_fillColor.setValue( Color.web( fill ));
}
else {
_fillColor.setValue( Color.LIGHTSALMON );
}
final String stroke = n.get( "stroke" );
if( stroke != null ) {
_strokeColor.setValue( Color.web( stroke ));
}
else {
_strokeColor.setValue( Color.BLACK );
}
dcrudInitialize( n );
}
private double nextDouble( double min, double max ) {
return min + ( _random.nextDouble()*(max-min) );
}
private <S extends Shape, SS extends ShareableShape>
void createShape(
String name,
QuadFunction<Double,Double,Double,Double,S> sf,
BiFunction<String, S, SS> ssf )
{
final double x = nextDouble( 0, 540 );
final double y = nextDouble( 0, 400 );
final double w = nextDouble( 40, 100 );
final double h = nextDouble( 20, 80 );
final S shape = sf.apply( x, y, w, h );
final SS sshape = ssf.apply( String.format( name + " %03d", ++_rank ), shape );
shape.setStroke( _strokeColor.getValue());
shape.setFill( _fillColor.getValue());
_cache.create( sshape );
_shapesArea.getChildren().add( shape );
}
private void createEllipseRemotely() {
try {
final Arguments args = new Arguments();
args.put( "class", ShareableEllipse.CLASS_ID );
args.put( "x" , nextDouble( 0, 540 ));
args.put( "y" , nextDouble( 0, 400 ));
args.put( "w" , nextDouble( 40, 100 ));
args.put( "h" , nextDouble( 20, 80 ));
_remoteEllipseFactory.create( args );
}
catch( final Throwable t ) {
t.printStackTrace();
}
}
private void createRectangleRemotely() {
try {
final Arguments args = new Arguments();
args.put( "class", ShareableRect.CLASS_ID );
args.put( "x" , nextDouble( 0, 540 ));
args.put( "y" , nextDouble( 0, 400 ));
args.put( "w" , nextDouble( 40, 100 ));
args.put( "h" , nextDouble( 20, 80 ));
_remoteRectangleFactory.create( args );
}
catch( final Throwable t ) {
t.printStackTrace();
}
}
@FXML
private void createRectangle() {
if( _remoteRectangleFactory != null ) {
createRectangleRemotely();
}
else {
createShape(
"Rectangle",
( x, y, w, h ) -> new Rectangle( x, y, w, h ),
( name, shape ) -> new ShareableRect( name, shape ));
}
}
@FXML
private void createEllipse() {
if( _remoteEllipseFactory != null ) {
createEllipseRemotely();
}
else {
createShape(
"Ellipse",
( x, y, w, h ) -> new Ellipse( x, y, w, h ),
( name, shape ) -> new ShareableEllipse( name, shape ));
}
}
@FXML
private void periodic( ActionEvent event ) {
final CheckMenuItem periodic = (CheckMenuItem)event.getSource();
_periodic = periodic.isSelected();
}
@FXML
private void moveThem( ActionEvent event ) {
final CheckMenuItem moveThem = (CheckMenuItem)event.getSource();
_moveThem = moveThem.isSelected();
}
@FXML
private void publish() throws IOException {
_cache.publish();
}
private void refreshUI() {
_shapesArea.getChildren().clear();
for( final Shareable shareable : _cache.values()) {
final ShareableShape shape = (ShareableShape)shareable;
assert shape != null;
assert shape.getShape() != null;
_shapesArea.getChildren().add( shape.getShape());
search: {
for( final FxShape fxs : _shapesTbl.getItems()) {
if( fxs.idProperty().get().equals( shape._id )) {
fxs.setShape( shape );
break search;
}
}
_shapesTbl.getItems().add( new FxShape( shape ));
}
}
}
@FXML
private void refresh() {
_cache.refresh();
Platform.runLater( this::refreshUI );
}
void networkActivity() {
try {
if( _periodic ) {
if( ! _readonly ) {
_cache.publish();
}
refresh();
}
}
catch( final IOException x ) {
x.printStackTrace();
}
}
private void moveUI() {
final Set<Shareable> shareables = _cache.select( s -> true );
for( final Shareable shareable : shareables ) {
final ShareableShape shape = (ShareableShape)shareable;
if( _cache.owns( shape._id )) {
shape.moveIt( _shapesArea.getLayoutBounds());
_cache.update( shape );
}
}
}
void animationActivity() {
if( _moveThem ) {
Platform.runLater( this::moveUI );
}
}
@FXML
private void drag( MouseEvent event ) {
if( _dragged == null ) {
if( event.getTarget() instanceof javafx.scene.shape.Shape ) {
_dragged = (Node)event.getTarget();
_nodeX = _dragged.getLayoutX();
_nodeY = _dragged.getLayoutY();
_fromX = event.getX();
_fromY = event.getY();
}
}
else {
final double dx = event.getX() - _fromX;
final double dy = event.getY() - _fromY;
_dragged.setLayoutX( _nodeX + dx );
_dragged.setLayoutY( _nodeY + dy );
}
event.consume();
}
@FXML
private void drop( MouseEvent event ) {
try {
final double dx = event.getX() - _fromX;
final double dy = event.getY() - _fromY;
_dragged.setLayoutX( _nodeX + dx );
_dragged.setLayoutY( _nodeY + dy );
final ShareableShape shape = (ShareableShape)_dragged.getUserData();
_cache.update( shape );
}
catch( final Throwable t ) {
t.printStackTrace();
}
_dragged = null;
event.consume();
}
public static void main( String[] args ) {
App.launch( args, ShapesUI.class );
}
}
| gpl-2.0 |
moabson/j-ftp | src/java/net/sf/jftp/gui/tasks/ProxyChooser.java | 3067 | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.sf.jftp.gui.tasks;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import net.sf.jftp.config.Settings;
import net.sf.jftp.gui.framework.HButton;
import net.sf.jftp.gui.framework.HPanel;
import net.sf.jftp.gui.framework.HTextField;
import net.sf.jftp.system.logging.Log;
public class ProxyChooser extends HPanel implements ActionListener
{
private HTextField proxy;
private HTextField port;
private HButton ok = new HButton("Ok");
public ProxyChooser()
{
//setSize(500,120);
//setTitle("Proxy settings...");
//setLocation(50,150);
//getContentPane().
setLayout(new FlowLayout(FlowLayout.LEFT));
proxy = new HTextField("Socks proxy:", "");
port = new HTextField("Port:", "");
proxy.setText(Settings.getSocksProxyHost());
port.setText(Settings.getSocksProxyPort());
//getContentPane().
add(proxy);
//getContentPane().
add(port);
//getContentPane().
add(ok);
//getContentPane().
add(new JLabel("Please note that you have to restart JFtp to apply the changes!"));
ok.addActionListener(this);
//setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == ok)
{
//setVisible(false);
String h = proxy.getText().trim();
String p = port.getText().trim();
java.util.Properties sysprops = System.getProperties();
// Remove previous values
sysprops.remove("socksProxyHost");
sysprops.remove("socksProxyPort");
Settings.setProperty("jftp.socksProxyHost", h);
Settings.setProperty("jftp.socksProxyPort", p);
Settings.save();
Log.out("proxy vars: " + h + ":" + p);
if(h.equals("") || p.equals(""))
{
return;
}
// Set your values
sysprops.put("socksProxyHost", h);
sysprops.put("socksProxyPort", p);
Log.out("new proxy vars set.");
remove(3);
add(new JLabel("Options set. Please restart JFtp."));
validate();
setVisible(true);
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java | 7436 | /*
* Copyright 2000-2006 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.RootPaneUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/**
* A multiplexing UI used to combine <code>RootPaneUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
* @since 1.4
*/
public class MultiRootPaneUI extends RootPaneUI {
/**
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector uis = new Vector();
////////////////////
// Common UI methods
////////////////////
/**
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// RootPaneUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/**
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
((ComponentUI) (uis.elementAt(0))).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
/**
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).update(a,b);
}
}
/**
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*/
public static ComponentUI createUI(JComponent a) {
ComponentUI mui = new MultiRootPaneUI();
return MultiLookAndFeel.createUIs(mui,
((MultiRootPaneUI) mui).uis,
a);
}
/**
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).installUI(a);
}
}
/**
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).uninstallUI(a);
}
}
/**
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).paint(a,b);
}
}
/**
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getPreferredSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMinimumSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
((ComponentUI) (uis.elementAt(0))).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getMaximumSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a);
}
return returnValue;
}
/**
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b);
}
return returnValue;
}
}
| gpl-2.0 |
smarr/Truffle | truffle/src/com.oracle.truffle.api.dsl/src/com/oracle/truffle/api/dsl/Specialization.java | 17705 | /*
* Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.api.dsl;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.frame.Frame;
import com.oracle.truffle.api.frame.MaterializedFrame;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.UnexpectedResultException;
/**
* <p>
* Defines a method of a node subclass to represent one specialization of an operation. Multiple
* specializations can be defined in a node representing an operation. A specialization defines
* which kind of input is expected using the method signature and the annotation attributes. The
* specialized semantics of the operation are defined using the body of the annotated Java method. A
* specialization method must be declared in a class that is derived from {@link Node} that
* references a {@link TypeSystem}. At least one specialization must be defined per operation. If no
* specialization is valid for the given set of input values then an
* {@link UnsupportedSpecializationException} is thrown instead of invoking any specialization
* method.
* </p>
* <p>
* A specialization must have at least as many parameters as there are {@link NodeChild} annotations
* declared for the enclosing operation node. These parameters are declared in the same order as the
* {@link NodeChild} annotations (linear execution order). We call such parameters dynamic input
* parameters. Every specialization that is declared within an operation must have an equal number
* of dynamic input parameters.
* </p>
* <p>
* The supported kind of input values for a specialization are declared using guards. A
* specialization may provide declarative specifications for four kinds of guards:
* <ul>
* <li><b>Type guards</b> optimistically assume the type of an input value. A value that matches the
* type is cast to its expected type automatically. Type guards are modeled using the parameter type
* of the specialization method. Types used for type guards must be defined in the
* {@link TypeSystem}. If the type of the parameter is {@link Object} then no type guard is used for
* the dynamic input parameter.</li>
*
* <li><b>Expression guards</b> optimistically assume the return value of a user-defined expression
* to be <code>true</code>. Expression guards are modeled using Java expressions that return a
* <code>boolean</code> value. If the guard expression returns <code>false</code>, the
* specialization is no longer applicable and the operation is re-specialized. Guard expressions are
* declared using the {@link #guards()} attribute.</li>
*
* <li><b>Event guards</b> trigger re-specialization in case an exception is thrown in the
* specialization body. The {@link #rewriteOn()} attribute can be used to declare a list of such
* exceptions. Guards of this kind are useful to avoid calculating a value twice when it is used in
* the guard and its specialization.</li>
*
* <li><b>Assumption guards</b> optimistically assume that the state of an {@link Assumption}
* remains <code>true</code>. Assumptions can be assigned to specializations using the
* {@link #assumptions()} attribute.</li>
* </ul>
* </p>
* <p>
* The enclosing {@link Node} of a specialization method must have at least one <code>public</code>
* and non-<code>final</code> execute method. An execute method is a method that starts with
* 'execute'. If all execute methods declare the first parameter type as {@link Frame},
* {@link VirtualFrame} or {@link MaterializedFrame} then the same frame type can be used as
* optional first parameter of the specialization. This parameter does not count to the number of
* dynamic parameters.
* </p>
* <p>
* A specialization method may declare multiple parameters annotated with {@link Cached}. Cached
* parameters are initialized and stored once per specialization instantiation. For consistency
* between specialization declarations cached parameters must be declared last in a specialization
* method.
* </p>
* <p>
* If the operation is re-specialized or if it is executed for the first time then all declared
* specializations of the operation are tried in declaration order until the guards of the first
* specialization accepts the current input values. The new specialization is then added to the
* chain of current specialization instances which might consist of one (monomorph) or multiple
* instances (polymorph). If an assumption of an instantiated specialization is violated then
* re-specialization is triggered again.
* </p>
* <p>
* With guards in combination with cached parameters it is possible that multiple instances of the
* same specialization are created. The {@link #limit()} attribute can be used to limit the number
* of instantiations per specialization.
* </p>
*
* @see NodeChild
* @see Fallback
* @see Cached
* @see TypeSystem
* @see TypeSystemReference
* @see UnsupportedSpecializationException
* @since 0.8 or earlier
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Specialization {
/**
* References a specialization of a super class by its method name where this specialization is
* inserted before. The declaration order of a specialization is not usable for nodes where
* specializations are partly declared in the super class and partly declared in a derived
* class. By default all specializations declared in the derived class are appended to those in
* the super class. This attribute can be used to override the default behavior.
*
* @since 0.8 or earlier
*/
String insertBefore() default "";
/**
* <p>
* Declares an event guards that trigger re-specialization in case an exception is thrown in the
* specialization body. This attribute can be used to declare a list of such exceptions. Guards
* of this kind are useful to avoid calculating a value twice when it is used in the guard and
* its specialization.
* </p>
*
* <p>
* If an event guard exception is triggered then all instantiations of this specialization are
* removed. If one of theses exceptions is thrown once then no further instantiations of this
* specialization are going to be created for this node.
*
* In case of explicitly declared {@link UnexpectedResultException}s, the result from the
* exception will be used. For all other exception types, the next available specialization will
* be executed, so that the original specialization must ensure that no non-repeatable
* side-effect is caused until the rewrite is triggered.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
* @Specialization(rewriteOn = ArithmeticException.class)
* int doAddNoOverflow(int a, int b) {
* return Math.addExact(a, b);
* }
* @Specialization
* long doAddWithOverflow(int a, int b) {
* return a + b;
* }
* ...
* Example executions:
* execute(Integer.MAX_VALUE - 1, 1) => doAddNoOverflow(Integer.MAX_VALUE - 1, 1)
* execute(Integer.MAX_VALUE, 1) => doAddNoOverflow(Integer.MAX_VALUE, 1)
* => throws ArithmeticException
* => doAddWithOverflow(Integer.MAX_VALUE, 1)
* execute(Integer.MAX_VALUE - 1, 1) => doAddWithOverflow(Integer.MAX_VALUE - 1, 1)
* </pre>
*
* </p>
*
* @see Math#addExact(int, int)
* @since 0.8 or earlier
*/
Class<? extends Throwable>[] rewriteOn() default {};
/**
* <p>
* Declares other specializations of the same operation to be replaced by this specialization.
* Other specializations are referenced using their unique method name. If this specialization
* is instantiated then all replaced specialization instances are removed and never instantiated
* again for this node instance. Therefore this specialization should handle strictly more
* inputs than which were handled by the replaced specialization, otherwise the removal of the
* replaced specialization will lead to unspecialized types of input values. The replaces
* declaration is transitive for multiple involved specializations.
* </p>
* <b>Example usage:</b>
*
* <pre>
* @Specialization(guards = "b == 2")
* void doDivPowerTwo(int a, int b) {
* return a >> 1;
* }
* @Specialization(replaces ="doDivPowerTwo", guards = "b > 0")
* void doDivPositive(int a, int b) {
* return a / b;
* }
* ...
* Example executions with replaces="doDivPowerTwo":
* execute(4, 2) => doDivPowerTwo(4, 2)
* execute(9, 3) => doDivPositive(9, 3) // doDivPowerTwo instances get removed
* execute(4, 2) => doDivPositive(4, 2)
* Same executions without replaces="doDivPowerTwo"
* execute(4, 2) => doDivPowerTwo(4, 2)
* execute(9, 3) => doDivPositive(9, 3)
* execute(4, 2) => doDivPowerTwo(4, 2)
* </pre>
*
* </p>
*
* @see #guards()
* @since 0.22
*/
String[] replaces() default {};
/**
* <p>
* Declares <code>boolean</code> expressions that define whether or not input values are
* applicable to this specialization instance. Guard expressions must always return the same
* result for each combination of the enclosing node instance and the bound input values.
* </p>
* <p>
* If a guard expression does not bind any dynamic input parameters then the DSL assumes that
* the result will not change for this node after specialization instantiation. The DSL asserts
* this assumption if assertions are enabled (-ea).
* </p>
* <p>
* Guard expressions are defined using a subset of Java. This subset includes field/parameter
* accesses, function calls, type exact infix comparisons (==, !=, <, <=, >, >=), logical
* negation (!), logical disjunction (||), null, true, false, and integer literals. The return
* type of guard expressions must be <code>boolean</code>. Bound elements without receivers are
* resolved using the following order:
* <ol>
* <li>Dynamic and cached parameters of the enclosing specialization.</li>
* <li>Fields defined using {@link NodeField} for the enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of super types of the enclosing node.
* </li>
* <li>Public and static methods or fields imported using {@link ImportStatic}.</li>
* </ol>
* </p>
* <p>
* <b>Example usage:</b>
*
* <pre>
* static boolean acceptOperand(int operand) {
* assert operand <= 42;
* return (operand & 1) == 1;
* }
*
* @Specialization(guards = {"operand <= 42", "acceptOperand(operand)"})
* void doSpecialization(int operand) {...}
* </pre>
*
* </p>
*
* @see Cached
* @see ImportStatic
* @since 0.8 or earlier
*/
String[] guards() default {};
/**
* <p>
* Declares assumption guards that optimistically assume that the state of an {@link Assumption}
* remains valid. Assumption expressions are cached once per specialization instantiation. If
* one of the returned assumptions gets invalidated then the specialization instance is removed.
* If the assumption expression returns an array of assumptions then all assumptions of the
* array are checked. This is limited to one-dimensional arrays.
* </p>
* <p>
* Assumption expressions are defined using a subset of Java. This subset includes
* field/parameter accesses, function calls, type exact infix comparisons (==, !=, <, <=, >,
* >=), logical negation (!), logical disjunction (||), null, true, false, and integer literals.
* The return type of the expression must be {@link Assumption} or an array of
* {@link Assumption} instances. Assumption expressions are not allowed to bind to dynamic
* parameter values of the specialization. Bound elements without receivers are resolved using
* the following order:
* <ol>
* <li>Cached parameters of the enclosing specialization.</li>
* <li>Fields defined using {@link NodeField} for the enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of super types of the enclosing node.
* </li>
* <li>Public and static methods or fields imported using {@link ImportStatic}.</li>
* </ol>
* </p>
*
* <p>
* <b>Example usage:</b>
*
* <pre>
* abstract static class DynamicObject() { abstract Shape getShape(); ... }
* abstract static class Shape() { abstract Assumption getUnmodifiedAssuption(); ... }
*
* @Specialization(guards = "operand.getShape() == cachedShape", assumptions = "cachedShape.getUnmodifiedAssumption()")
* void doAssumeUnmodifiedShape(DynamicObject operand, @Cached("operand.getShape()") Shape cachedShape) {...}
* </pre>
*
* </p>
*
* @see Cached
* @see ImportStatic
* @since 0.8 or earlier
*/
String[] assumptions() default {};
/**
* <p>
* Declares the expression that limits the number of specialization instantiations. The default
* limit for specialization instantiations is defined as <code>"3"</code>. If the limit is
* exceeded no more instantiations of the enclosing specialization method are created. Please
* note that the existing specialization instantiations are <b>not</b> removed from the
* specialization chain. You can use {@link #replaces()} to remove unnecessary specializations
* instances.
* </p>
* <p>
* The limit expression is defined using a subset of Java. This subset includes field/parameter
* accesses, function calls, type exact infix comparisons (==, !=, <, <=, >, >=), logical
* negation (!), logical disjunction (||), null, true, false, and integer literals. The return
* type of the limit expression must be <code>int</code>. Limit expressions are not allowed to
* bind to dynamic parameter values of the specialization. Bound elements without receivers are
* resolved using the following order:
* <ol>
* <li>Cached parameters of the enclosing specialization.</li>
* <li>Fields defined using {@link NodeField} for the enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of enclosing node.</li>
* <li>Non-private, static or virtual methods or fields of super types of the enclosing node.
* </li>
* <li>Public and static methods or fields imported using {@link ImportStatic}.</li>
* </ol>
* </p>
*
* <p>
* <b>Example usage:</b>
*
* <pre>
* static int getCacheLimit() {
* return Integer.parseInt(System.getProperty("language.cacheLimit"));
* }
*
* @Specialization(guards = "operand == cachedOperand", limit = "getCacheLimit()")
* void doCached(Object operand, @Cached("operand") Object cachedOperand) {...}
* </pre>
*
* </p>
*
* @see #guards()
* @see #replaces()
* @see Cached
* @see ImportStatic
* @since 0.8 or earlier
*/
String limit() default "";
}
| gpl-2.0 |
patholog/code | pathology/src/com/pathology/entity/Image.java | 4987 | package com.pathology.entity;
import java.sql.Timestamp;
import java.util.Date;
/**
* Image entity. @author MyEclipse Persistence Tools
*/
public class Image implements java.io.Serializable {
// Fields
private Integer idImage;
private String caseId;
private Integer rowImage;
private Integer colImage;
private String pathImage;
private String path;
private String memo;
private String sortNo;
private String spellNo;
private String wubiNo;
private Integer updCnt;
private Timestamp crtTime;
private String crtUserId;
private String crtDeptCd;
private Date lastUpdTime;
private String lastUpdDeptCd;
private String lastUpdUserId;
private Integer delF;
private String pathologyNo;
private String fileName;
private Integer width;
private Integer height;
private Integer preHandleFlag;
// Constructors
/** default constructor */
public Image() {
}
/** minimal constructor */
public Image(Integer idImage) {
this.idImage = idImage;
}
/** full constructor */
public Image(Integer idImage, String caseId, Integer rowImage,
Integer colImage, String pathImage, String memo, String sortNo,
String spellNo, String wubiNo, Integer updCnt, Timestamp crtTime,
String crtUserId, String crtDeptCd, Date lastUpdTime,
String lastUpdDeptCd, String lastUpdUserId, Integer delF,
String pathologyNo) {
this.idImage = idImage;
this.caseId = caseId;
this.rowImage = rowImage;
this.colImage = colImage;
this.pathImage = pathImage;
this.memo = memo;
this.sortNo = sortNo;
this.spellNo = spellNo;
this.wubiNo = wubiNo;
this.updCnt = updCnt;
this.crtTime = crtTime;
this.crtUserId = crtUserId;
this.crtDeptCd = crtDeptCd;
this.lastUpdTime = lastUpdTime;
this.lastUpdDeptCd = lastUpdDeptCd;
this.lastUpdUserId = lastUpdUserId;
this.delF = delF;
this.pathologyNo = pathologyNo;
}
// Property accessors
public Integer getIdImage() {
return this.idImage;
}
public void setIdImage(Integer idImage) {
this.idImage = idImage;
}
public String getCaseId() {
return this.caseId;
}
public void setCaseId(String caseId) {
this.caseId = caseId;
}
public Integer getRowImage() {
return this.rowImage;
}
public void setRowImage(Integer rowImage) {
this.rowImage = rowImage;
}
public Integer getColImage() {
return this.colImage;
}
public void setColImage(Integer colImage) {
this.colImage = colImage;
}
public String getPathImage() {
return this.pathImage;
}
public void setPathImage(String pathImage) {
this.pathImage = pathImage;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getSortNo() {
return this.sortNo;
}
public void setSortNo(String sortNo) {
this.sortNo = sortNo;
}
public String getSpellNo() {
return this.spellNo;
}
public void setSpellNo(String spellNo) {
this.spellNo = spellNo;
}
public String getWubiNo() {
return this.wubiNo;
}
public void setWubiNo(String wubiNo) {
this.wubiNo = wubiNo;
}
public Integer getUpdCnt() {
return this.updCnt;
}
public void setUpdCnt(Integer updCnt) {
this.updCnt = updCnt;
}
public Timestamp getCrtTime() {
return this.crtTime;
}
public void setCrtTime(Timestamp crtTime) {
this.crtTime = crtTime;
}
public String getCrtUserId() {
return this.crtUserId;
}
public void setCrtUserId(String crtUserId) {
this.crtUserId = crtUserId;
}
public String getCrtDeptCd() {
return this.crtDeptCd;
}
public void setCrtDeptCd(String crtDeptCd) {
this.crtDeptCd = crtDeptCd;
}
public Date getLastUpdTime() {
return this.lastUpdTime;
}
public void setLastUpdTime(Date lastUpdTime) {
this.lastUpdTime = lastUpdTime;
}
public String getLastUpdDeptCd() {
return this.lastUpdDeptCd;
}
public void setLastUpdDeptCd(String lastUpdDeptCd) {
this.lastUpdDeptCd = lastUpdDeptCd;
}
public String getLastUpdUserId() {
return this.lastUpdUserId;
}
public void setLastUpdUserId(String lastUpdUserId) {
this.lastUpdUserId = lastUpdUserId;
}
public Integer getDelF() {
return this.delF;
}
public void setDelF(Integer delF) {
this.delF = delF;
}
public String getPathologyNo() {
return this.pathologyNo;
}
public void setPathologyNo(String pathologyNo) {
this.pathologyNo = pathologyNo;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getPreHandleFlag() {
return preHandleFlag;
}
public void setPreHandleFlag(Integer preHandleFlag) {
this.preHandleFlag = preHandleFlag;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
} | gpl-2.0 |
adum/bitbath | hackjvm/src/ojvm/loading/instructions/Ins_ldiv.java | 570 | package ojvm.loading.instructions;
import ojvm.data.JavaException;
import ojvm.operations.InstructionVisitor;
import ojvm.util.RuntimeConstants;
/**
* The encapsulation of a ldiv instruction.
* @author Amr Sabry
* @version jdk-1.1
*/
public class Ins_ldiv extends Instruction {
public Ins_ldiv (InstructionInputStream classFile) {
super(RuntimeConstants.opc_ldiv);
}
public void accept (InstructionVisitor iv) throws JavaException {
iv.visit_ldiv (this);
}
public String toString () {
return opcodeName;
}
}
| gpl-2.0 |
callakrsos/Gargoyle | gargoyle-commons/src/main/java/com/kyj/fx/commons/utils/ZipUtil.java | 7486 | /********************************
* 프로젝트 : idu-commons
* 패키지 : com.kyj.fx.commons.utils;
* 작성일 : 2018. 12. 14.
* 작성자 : callakrsos@naver.com
*
* base source from
* [ http://egloos.zum.com/yeon97/v/1551569 ]
*
* modifer kyj.
*******************************/
package com.kyj.fx.commons.utils;
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.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang3.StringUtils;
/**
* @author KYJ (callakrsos@naver.com)
*
*/
public class ZipUtil {
private static final int COMPRESSION_LEVEL = 8;
private static final int BUFFER_SIZE = 1024 * 2;
/**
* 지정된 폴더를 Zip 파일로 압축한다.
*
* @param sourcePath
* - 압축 대상 디렉토리
* @param output
* - 저장 zip 파일 이름
* @throws Exception
*/
public static void zip(String sourcePath, String output) throws Exception {
// 압축 대상(sourcePath)이 디렉토리나 파일이 아니면 리턴한다.
File sourceFile = new File(sourcePath);
if (!sourceFile.isFile() && !sourceFile.isDirectory()) {
throw new Exception("can't found zip target.");
}
// output 의 확장자가 zip이 아니면 리턴한다.
if (!(StringUtils.substringAfterLast(output, ".")).equalsIgnoreCase("zip")) {
throw new Exception("plz check output param extension.");
}
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(output); // FileOutputStream
bos = new BufferedOutputStream(fos); // BufferedStream
zos = new ZipOutputStream(bos); // ZipOutputStream
zos.setLevel(COMPRESSION_LEVEL); // 압축 레벨 - 최대 압축률은 9, 디폴트 8
zipEntry(sourceFile, sourcePath, zos); // Zip 파일 생성
zos.finish(); // ZipOutputStream finish
} finally {
if (zos != null) {
zos.close();
}
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
}
}
/**
* 압축
*
* @param sourceFile
* @param sourcePath
* @param zos
* @throws Exception
*/
private static void zipEntry(File sourceFile, String sourcePath, ZipOutputStream zos) throws Exception {
// sourceFile 이 디렉토리인 경우 하위 파일 리스트 가져와 재귀호출
if (sourceFile.isDirectory()) {
File[] fileArray = sourceFile.listFiles(); // sourceFile 의 하위 파일 리스트
for (int i = 0; i < fileArray.length; i++) {
zipEntry(fileArray[i], sourcePath, zos); // 재귀 호출
}
} else { // sourcehFile 이 디렉토리가 아닌 경우
BufferedInputStream bis = null;
try {
String sFilePath = sourceFile.getPath();
String zipEntryName = sFilePath.substring(sourcePath.length() + 1, sFilePath.length());
bis = new BufferedInputStream(new FileInputStream(sourceFile));
ZipEntry zentry = new ZipEntry(zipEntryName);
zentry.setTime(sourceFile.lastModified());
zos.putNextEntry(zentry);
byte[] buffer = new byte[BUFFER_SIZE];
int cnt = 0;
while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
zos.write(buffer, 0, cnt);
}
zos.closeEntry();
} finally {
if (bis != null) {
bis.close();
}
}
}
}
/**
* @작성자 : KYJ
* @작성일 : 2017. 4. 11.
* @param zipFile
* @param targets
* @throws Exception
*/
public static int zip(File zipFile, File[] targets) throws Exception {
if (targets == null)
throw new Exception(" targets is null.");
if (zipFile.isDirectory())
throw new Exception(" zipFile param must be file");
FileUtil.mkDirs(zipFile);
int result = 0;
// BufferedInputStream bis = null;
try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) {
for (File target : targets) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(target))) {
ZipEntry zentry = new ZipEntry(target.getName());
zentry.setTime(target.lastModified());
out.putNextEntry(zentry);
byte[] buffer = new byte[BUFFER_SIZE];
int cnt = 0;
while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
out.write(buffer, 0, cnt);
}
out.closeEntry();
result++;
}
}
}
return result;
}
/**
* extract zip file <br/>
*
* @param zipFile
* - 압축 풀 Zip 파일
* @param targetDir
* - 압축 푼 파일이 들어간 디렉토리
* @param fileNameToLowerCase
* - 파일명을 소문자로 바꿀지 여부
* @throws Exception
*/
public static void unzip(File zipFile, File targetDir, boolean fileNameToLowerCase) throws Exception {
FileInputStream fis = null;
ZipInputStream zis = null;
ZipEntry zentry = null;
try {
fis = new FileInputStream(zipFile); // FileInputStream
zis = new ZipInputStream(fis); // ZipInputStream
while ((zentry = zis.getNextEntry()) != null) {
String fileNameToUnzip = zentry.getName();
if (fileNameToLowerCase) { // fileName toLowerCase
fileNameToUnzip = fileNameToUnzip.toLowerCase();
}
File targetFile = new File(targetDir, fileNameToUnzip);
if (zentry.isDirectory()) {// case Directory
targetFile.mkdirs();
} else { // case File
// parent Directory 생성
targetFile.getParentFile().mkdirs();
unzipEntry(zis, targetFile);
}
}
} finally {
if (zis != null) {
zis.close();
}
if (fis != null) {
fis.close();
}
}
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2018. 12. 14.
* @param zipFile
* @param targetDir
* @throws Exception
*/
public static void unzip(File zipFile, File targetDir) throws Exception {
unzip(zipFile, targetDir, false);
}
/**
* Zip 파일의 한 개 엔트리의 압축을 푼다.
*
* @param zis
* - Zip Input Stream
* @param filePath
* - 압축 풀린 파일의 경로
* @return
* @throws Exception
*/
protected static File unzipEntry(ZipInputStream zis, File targetFile) throws Exception {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(targetFile);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = zis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} finally {
if (fos != null) {
fos.close();
}
}
return targetFile;
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2018. 12. 14.
* @param f
* @return
* @throws IOException
* @throws ZipException
*/
public static ZipFile toZipFile(File f) throws ZipException, IOException {
return new ZipFile(f);
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2018. 12. 14.
* @param f
* @param entryName
* @return
* @throws IOException
* @throws ZipException
*/
public static ZipEntry getZipEntry(File f, String entryName) throws ZipException, IOException {
return getZipEntry(toZipFile(f), entryName);
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2018. 12. 14.
* @param f
* @param entryName
* @return
*/
public static ZipEntry getZipEntry(ZipFile f, String entryName) {
return f.getEntry(entryName);
}
}
| gpl-2.0 |
unicesi/online-store-retailer | src/co/edu/icesi/driso/osr/ui/components/CategoriesSummary.java | 3971 | package co.edu.icesi.driso.osr.ui.components;
import java.io.File;
import co.edu.icesi.driso.osr.ui.views.client.CategoryView;
import co.edu.icesi.driso.osr.util.OSRUtilities;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.FileResource;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
public class CategoriesSummary extends CustomComponent {
public enum CategoriesPanelType {
HALF_SIZE_ITEM,
THIRD_SIZE_ITEM
}
public enum CategoriesPanelStyle {
MARLEY,
SADIE,
LAYLA,
OSCAR,
RUBY,
ROXY,
BUBBA,
GOLIATH
}
private static final long serialVersionUID = 1L;
private HorizontalLayout mainLayout;
private final CategoriesPanelType type;
private final CategoriesPanelStyle style;
private CustomLayout categoriesLayout;
public CategoriesSummary(CategoriesPanelType type, CategoriesPanelStyle style) {
this.type = type;
this.style = style;
buildMainLayout();
setCompositionRoot(mainLayout);
}
public CategoriesSummary(){
this(CategoriesPanelType.HALF_SIZE_ITEM, CategoriesPanelStyle.LAYLA);
}
private void buildMainLayout() {
mainLayout = new HorizontalLayout();
boolean bigPanel = type == CategoriesPanelType.HALF_SIZE_ITEM;
String layout = (bigPanel ? "grid" : "minigrid");
layout += "-" + style.toString();
categoriesLayout = new CustomLayout(layout);
// Get products
String[][] productsData = bigPanel ? getCategories() : getMiniCategories();
// Create items
int items = bigPanel ? 2 : 3;
for (int i = 1; i <= items; i++) {
addCategoryToGrid(
i,
categoriesLayout,
productsData[i-1][0],
productsData[i-1][1],
productsData[i-1][2],
productsData[i-1][3]
);
}
// Main layout
mainLayout.addComponent(categoriesLayout);
}
private void addCategoryToGrid(int n, CustomLayout categoriesLayout,
String imagePath, String heading, String caption, String link){
FileResource imageFile = new FileResource(new File(imagePath));
Image productImage = new Image(null, imageFile);
categoriesLayout.addComponent(productImage, "image" + n);
Label title = new Label("<h2>" + heading + "</h2>", ContentMode.HTML);
categoriesLayout.addComponent(title, "heading" + n);
Label description = new Label("<p>" + caption + "</p>", ContentMode.HTML);
categoriesLayout.addComponent(description, "paragraph" + n);
Link viewMoreLink = new Link("View more", new ExternalResource(link));
categoriesLayout.addComponent(viewMoreLink, "readmore" + n);
}
private String[][] getCategories(){
String[][] data = {
{
OSRUtilities.getRealPathFor("/WEB-INF/images/categories/18.jpg"),
"Men's <span>Fashion</span>",
"Rain never fails to dampen the mood, buy nice cloths for those rainy days!",
"#!" + CategoryView.NAME + "/1"
},
{
OSRUtilities.getRealPathFor("/WEB-INF/images/categories/21.jpg"),
"Leisure <span>Time</span>",
"Whenever, Wherever, Whatever!",
"#!" + CategoryView.NAME + "/2"
}
};
return data;
}
private String[][] getMiniCategories(){
String[][] data = {
{
OSRUtilities.getRealPathFor("/WEB-INF/images/categories/33.jpg"),
"All <span>Food</span>",
"You can find everything from organic food to the juiciest steak!",
"#!" + CategoryView.NAME + "/3"
},
{
OSRUtilities.getRealPathFor("/WEB-INF/images/categories/31.jpg"),
"On <span>Vacations</span>",
"Are you going somewhere? find clothing and accessories to go on vacations",
"#!" + CategoryView.NAME + "/4"
},
{
OSRUtilities.getRealPathFor("/WEB-INF/images/categories/29.jpg"),
"Work <span>Tools</span>",
"You can find everything from a bolt to a crane!",
"#!" + CategoryView.NAME + "/5"
}
};
return data;
}
}
| gpl-2.0 |
smarr/Truffle | substratevm/src/com.oracle.svm.core.jdk17/src/com/oracle/svm/core/jdk17/Target_jdk_internal_loader_BootLoader_JDK17OrLater.java | 1689 | /*
* Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 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.core.jdk17;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
import com.oracle.svm.core.jdk.JDK17OrLater;
@TargetClass(className = "jdk.internal.loader.BootLoader", onlyWith = JDK17OrLater.class)
final class Target_jdk_internal_loader_BootLoader_JDK17OrLater {
@SuppressWarnings("unused")
@Substitute
private static void loadLibrary(String name) {
System.loadLibrary(name);
}
}
| gpl-2.0 |
boyns/muffin | src/org/doit/muffin/filter/Cache.java | 15190 | /*
* Copyright (C) 2002 Doug Porter
*
* This file is part of Muffin.
*
* Muffin 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.
*
* Muffin 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 Muffin; see the file COPYING. If not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package org.doit.muffin.filter;
import org.doit.muffin.*;
import java.awt.Frame;
import java.util.*;
import java.io.*;
import java.net.*;
import java.text.DateFormat;
/** Web cache.
*/
public class Cache
implements FilterFactory
{
static final boolean Debugging = false;
static final String CacheDirectory = "Cache.cacheDirectory";
static final String CheckForUpdatesAlways = "Cache.checkForUpdates.always";
static final String CheckForUpdatesOncePerSession = "Cache.checkForUpdates.oncePerSession";
static final String CheckForUpdatesNever = "Cache.checkForUpdates.never";
static final String NoCachePatterns = "Cache.noCachePatterns";
static final String DefaultCacheDir = "webcache";
/** Url property name.
*/
static final String UrlProperty = "url";
/** CacheDate property name.
*/
static final String CacheDateProperty = "cache-date";
/** GMT time zone
*/
static final TimeZone GMT = TimeZone.getTimeZone ("GMT");
/** End of line
*/
final byte [] EOL = "\r\n".getBytes ();
private FilterManager manager;
private Prefs prefs;
private Frame frame = null;
MessageArea messages = new MessageArea();
public void setManager(FilterManager manager)
{
this.manager = manager;
}
public void setPrefs(Prefs prefs)
{
this.prefs = prefs;
}
public Prefs getPrefs()
{
return prefs;
}
public void viewPrefs()
{
if (frame == null)
{
frame = new CacheFrame (prefs, this);
}
frame.setVisible(true);
}
public Filter createFilter()
{
Filter f = new CacheFilter(this);
f.setPrefs (prefs);
return f;
}
public void shutdown()
{
if (frame != null)
{
frame.dispose ();
}
}
public void save()
{
manager.save (this);
}
String getCacheDirectory () {
String dir = prefs.getString(Cache.CacheDirectory);
if (dir == null ||
dir.length () <= 0) {
String slash = System.getProperty ("file.separator");
try {
File tryDir = new File (slash + "tmp");
if (! tryDir.exists ()) {
// Windows is case insensitive and some unix installations use "/temp", so this tries both
tryDir = new File (slash + "temp");
}
if (tryDir.exists ()) {
File cacheDir = new File (tryDir, DefaultCacheDir);
dir = cacheDir.getAbsolutePath ();
}
}
catch (Exception e) {
report ("Unable to get cache directory:" + e);
}
}
File cacheDir = new File (dir);
cacheDir.mkdirs ();
return cacheDir.getAbsolutePath ();
}
boolean checkForUpdatesOncePerSession () {
// default to true
return prefs.getString(Cache.CheckForUpdatesOncePerSession) == null ||
prefs.getBoolean(Cache.CheckForUpdatesOncePerSession);
}
boolean checkForUpdatesAlways () {
// default to false
return prefs.getString(Cache.CheckForUpdatesAlways) != null &&
prefs.getBoolean(Cache.CheckForUpdatesAlways);
}
boolean checkForUpdatesNever () {
// default to false
return prefs.getString(Cache.CheckForUpdatesNever) != null &&
prefs.getBoolean(Cache.CheckForUpdatesNever);
}
MessageArea getMessages() {
return messages;
}
/** Cache the reply.
*/
public synchronized void cacheReply (Reply reply) {
Request request = reply.getRequest ();
String url = getURL (request);
File tempCacheFile = getTempCacheFile (url);
File finalCacheFile = getCacheFile (url);
// don't interfere with a cache in progress
// delete any old incomplete file, but if the file's open now we can't delete it
tempCacheFile.delete ();
if (tempCacheFile.exists ()) {
report ("unable to cache " + url + ": "+ finalCacheFile.getAbsolutePath () + " still exists");
}
else {
// report ("caching " + url + " to "+ finalCacheFile.getAbsolutePath ());
boolean cacheComplete = false;
InputStream in = reply.getContent ();
if (in != null &&
// CacheFilter should have made this input stream a BufferedInputStream
in instanceof BufferedInputStream) {
try {
FileOutputStream cacheOut = new FileOutputStream (tempCacheFile);
try {
// write the properties
writeProperties (cacheOut, getProperties (url));
// write the reply headers
reply.write (cacheOut);
// copy the reply content
in.reset ();
copy (in, cacheOut);
cacheOut.close ();
cacheComplete = true;
report ("cached " + url + " to "+ finalCacheFile.getAbsolutePath ());
}
catch (IOException ioe) {
reportCacheError (url, ioe.toString ());
try {
cacheOut.close ();
}
catch (IOException ioe2) {
// just ignore it
}
}
}
catch (IOException ioe) {
reportCacheError (url, ioe.toString ());
}
}
else {
// other end may have closed socket
report ("unable to get content: " + url);
}
if (cacheComplete) {
tempCacheFile.renameTo (finalCacheFile);
}
else {
tempCacheFile.delete ();
}
}
}
/** Provide a cached reply to a request.
*/
public synchronized Reply getCachedReply (String url) {
Reply reply;
try {
FileInputStream in = new FileInputStream (getCacheFile (url));
// ignore the properties
readProperties (in);
reply = new Reply (in);
reply.read ();
}
catch (Exception e) {
// tell the user what happened
reply = new Reply();
report ("Error: Could not get " + url + " from cache: " + e);
StringBuffer text = new StringBuffer ();
text.append ("<h2>Cache error</h2>\n");
text.append ("Error getting " + url + " from cache: " + e + "\n");
// what result code do we want here?
reply.setStatusLine ("HTTP/1.0 500");
reply.setHeaderField ("Content-type", "text/html");
byte content[] = text.toString().getBytes();
reply.setHeaderField ("Content-length", Integer.toString (content.length));
reply.setContent ((InputStream) new ByteArrayInputStream (content));
}
return reply;
}
public void removeFromCache (String url) {
File cacheFile = getCacheFile (url);
if (cacheFile.exists ()) {
cacheFile.delete ();
report ("removed " + url + " from the cache");
}
else {
// report ("already removed or not in cache: " + url + ": " + cacheFile.getAbsolutePath ());
}
}
public synchronized boolean isCached (String url) {
boolean cached = getCacheFile (url).exists ();
StringBuffer report = new StringBuffer ();
if (cached) {
report.append ("already ");
}
else {
report.append ("not ");
}
report.append ("cached: " + url);
// report (report.toString ());
return cached;
}
/** Get the url from a request.
*
* An explicit ":80" port in a url causes duplicates in the cache. Strip it.
*
*/
public static String getURL (Request request) {
final int DefaultHttpPort = 80;
final String PortString = ":" + String.valueOf (DefaultHttpPort);
String url;
if (request != null) {
url = request.getURL ();
try {
URL u = new URL (url);
if (u.getPort () == DefaultHttpPort) {
int i = url.indexOf (PortString);
if (i >= 0) {
url = u.toString ();
i = url.indexOf (PortString);
if (i >= 0) {
url = url.substring (0, i) + url.substring (i + PortString.length ());
}
}
}
}
catch (java.net.MalformedURLException mue) {
// just leave the existing url alone
}
}
else {
Thread.dumpStack ();
url = "unknown url";
}
return url;
}
/* Get the url's cache file.
*/
public File getCacheFile (String url) {
File hostCacheDir = getHostCacheDir (url);
String filename = getFilename (url);
return new File (hostCacheDir, filename);
}
/* Get the url's filename.
* @param url Url
*/
public String getFilename (String url) {
// a hash collision will return the wrong page, but it's very unlikely within a single site
String urlHash = Integer.toHexString (url.hashCode ()).toUpperCase ();
return urlHash;
}
/* Get the url's temporary cache file.
*/
public File getTempCacheFile (String url) {
File hostCacheDir = getHostCacheDir (url);
String filename = getTempFilename (url);
return new File (hostCacheDir, filename);
}
/* Get the url's temporary filename.
* @param url Url
*/
public String getTempFilename (String url) {
return getFilename (url) + ".tmp";
}
/* Get the host dir for this url.
*/
public File getHostCacheDir (String url) {
File cacheDir = new File (getCacheDirectory ());
String host = getHost (url);
File hostCacheDir = new File (cacheDir, host);
hostCacheDir.mkdirs ();
return hostCacheDir;
}
/* Get the url's host.
* @param url Url
*/
public String getHost (String url) {
String host;
try {
host = new URL (url).getHost ();
}
catch (java.net.MalformedURLException mue) {
host = "unknown";
}
return host;
}
public Properties getProperties (String url) {
Properties props = new Properties ();
props.setProperty (Cache.UrlProperty, url);
// formating a date in Java is convoluted
DateFormat dateFormat = DateFormat.getDateTimeInstance (DateFormat.FULL, DateFormat.FULL, Locale.ENGLISH);
dateFormat.setTimeZone (GMT);
String datetime = dateFormat.format (new Date ());
props.setProperty (Cache.CacheDateProperty, datetime);
return props;
}
public synchronized void writeProperties (OutputStream out,
Properties props)
throws IOException {
// we don't use Properties.list() because it truncates lines
Enumeration names = props.propertyNames ();
while (names.hasMoreElements ()) {
String name = (String) names.nextElement ();
String value = props.getProperty (name);
String line = name + ": " + value;
out.write (line.getBytes ());
out.write (EOL);
}
// properties end in a blank line
out.write (EOL);
}
public Properties readProperties (InputStream in)
throws IOException {
Properties props = new Properties ();
// skip lines through the first blank line
Reply reply = new Reply (in);
String line = reply.readLine (in);
while (line != null &&
line.length () > 0) {
line = reply.readLine (in);
int i = line.indexOf (':');
if (i > 0) {
String attribute = line.substring (0, i).trim ();
String value = line.substring (i + 1).trim ();
props.put (attribute, value);
}
}
return props;
}
private void skipPastBlankLine (InputStream in)
throws IOException {
// skip lines through the first blank line
Reply reply = new Reply (in);
String line = reply.readLine (in);
while (line != null &&
line.length () > 0) {
line = reply.readLine (in);
}
}
private synchronized void copy (InputStream in,
OutputStream out)
throws IOException {
final int BufferSize = 10000;
byte [] buffer = new byte [BufferSize];
int count = in.read (buffer);
while (count >= 0) {
// factory.report ("copying " + String.valueOf (count) + " bytes"); //DEBUG
Thread.yield ();
out.flush ();
out.write (buffer, 0, count);
count = in.read (buffer);
}
out.flush ();
}
private void reportCacheError (String url,
String why) {
report ("Warning: Unable to cache url " + url + ": " + why);
}
void report (Request request, String message)
{
request.addLogEntry (getClass().getName(), message);
report (message);
}
void report (String message)
{
messages.append (message + "\n");
if (Debugging) {
System.out.println (message);
}
}
}
| gpl-2.0 |
tomdkt/DriveSales | src/main/java/br/com/drivesales/dto/LocationAndTotalDTO.java | 838 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.drivesales.dto;
import java.math.BigDecimal;
/**
*
* @author Thomas Daniel Kaneko Teixeira(tomdkt)
*/
public class LocationAndTotalDTO {
private String location;
private BigDecimal total;
public LocationAndTotalDTO(String location, BigDecimal total) {
this.location = location;
this.total = total;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
}
| gpl-2.0 |
midaboghetich/netnumero | gen/com/numhero/client/widget/panelsubmenu/com_numhero_client_widget_panelsubmenu_StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenBundle_en_US_InlineClientBundleGenerator.java | 1696 | package com.numhero.client.widget.panelsubmenu;
import com.google.gwt.resources.client.ResourcePrototype;
import com.google.gwt.core.client.GWT;
public class com_numhero_client_widget_panelsubmenu_StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenBundle_en_US_InlineClientBundleGenerator implements com.numhero.client.widget.panelsubmenu.StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenBundle {
public com.numhero.client.widget.panelsubmenu.StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenCss_style style() {
if (style == null) {
style = new com.numhero.client.widget.panelsubmenu.StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenCss_style() {
private boolean injected;
public boolean ensureInjected() {
if (!injected) {
injected = true;
com.google.gwt.dom.client.StyleInjector.inject(getText());
return true;
}
return false;
}
public String getName() {
return "style";
}
public String getText() {
return com.google.gwt.i18n.client.LocaleInfo.getCurrentLocale().isRTL() ? (("")) : ((""));
}
}
;
}
return style;
}
private static com.numhero.client.widget.panelsubmenu.StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenCss_style style;
public ResourcePrototype[] getResources() {
return new ResourcePrototype[] {
style(),
};
}
public native ResourcePrototype getResource(String name) /*-{
switch (name) {
case 'style': return this.@com.numhero.client.widget.panelsubmenu.StaffSubmenuPanel_StaffSubmenuPanelUiBinderImpl_GenBundle::style()();
}
return null;
}-*/;
}
| gpl-2.0 |
captainsoft/terminal-angel-disease | src/com/captainsoft/TADr/painting/replacer/TileGroupImageProxy.java | 881 | /*
* Copyright Captainsoft 2010 - 2015.
* All rights reserved.
*/
package com.captainsoft.TADr.painting.replacer;
import com.captainsoft.spark.utils.Utils;
/**
* Wraps a TileGroupImage in a proxy with the same interface.
*
* @author mathias fringes
*/
public class TileGroupImageProxy extends TileGroupImage {
private TileGroupImage proxied;
public TileGroupImageProxy(TileGroupImage proxied) {
super(proxied.image());
//
this.proxied = proxied;
this.image(this.proxied.image());
//
if (proxied.ground()) {
asGround();
}
if (proxied.overlay()) {
asOverlay();
}
if (proxied.secondOverlay()) {
asSecondOverlay();
}
}
@Override
public String toString() {
return Utils.stringer("TigProxy", proxied.toString());
}
} | gpl-2.0 |
Prasad1337/GANTTing | ganttproject/src/net/sourceforge/ganttproject/task/dependency/TaskDependencyConstraint.java | 2627 | /*
Copyright 2003-2012 Dmitry Barashev, GanttProject Team
This file is part of GanttProject, an opensource project management tool.
GanttProject 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.
GanttProject 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 GanttProject. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.ganttproject.task.dependency;
import java.util.Date;
import biz.ganttproject.core.time.GanttCalendar;
/**
* Created by IntelliJ IDEA. User: bard Date: 14.02.2004 Time: 2:35:20 To change
* this template use File | Settings | File Templates.
*/
public interface TaskDependencyConstraint extends Cloneable {
enum Type {
startstart, finishstart, finishfinish, startfinish;
public String getPersistentValue() {
return String.valueOf(ordinal() + 1);
}
public static Type fromPersistentValue(String dependencyTypeAsString) {
return Type.values()[Integer.parseInt(dependencyTypeAsString) - 1];
}
}
Type getType();
void setTaskDependency(TaskDependency dependency);
// boolean isFulfilled();
// void fulfil();
Collision getCollision();
Collision getBackwardCollision(Date depedantStart);
String getName();
TaskDependency.ActivityBinding getActivityBinding();
interface Collision {
GanttCalendar getAcceptableStart();
int getVariation();
int NO_VARIATION = 0;
int START_EARLIER_VARIATION = -1;
int START_LATER_VARIATION = 1;
boolean isActive();
}
class DefaultCollision implements Collision {
private final GanttCalendar myAcceptableStart;
private final int myVariation;
private final boolean isActive;
public DefaultCollision(GanttCalendar myAcceptableStart, int myVariation, boolean isActive) {
this.myAcceptableStart = myAcceptableStart;
this.myVariation = myVariation;
this.isActive = isActive;
}
@Override
public GanttCalendar getAcceptableStart() {
return myAcceptableStart;
}
@Override
public int getVariation() {
return myVariation;
}
@Override
public boolean isActive() {
return isActive;
}
}
Object clone() throws CloneNotSupportedException;
}
| gpl-2.0 |
XiaoLiuAI/RUPEE | src/java/stanford/StanfordEventTokenizer.java | 13842 | package stanford;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.process.AbstractTokenizer;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.PTBTokenizer;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ie.machinereading.domains.bionlp.*;
public class StanfordEventTokenizer {
// [input] should be the path to raw_text files
// [file_index] should contain the corpus name along with the file id.
public static void tokenize(String input, String output, String file_index) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(file_index));
String fileName;
while ((fileName= br.readLine()) != null){
// filenames.add(line);
String rawText = IOUtils.slurpFile(new File(input+fileName+".txt"));
String output_file_name = output+fileName+".tok";
File outputDir = new File(output_file_name.substring(0, output_file_name.lastIndexOf("/")));
if (!outputDir.exists()){
System.out.println("create directory:"+outputDir);
outputDir.mkdirs();
}
BufferedWriter os = new BufferedWriter(new FileWriter(new File(output_file_name)));
Collection<String> sentences = BioNLPFormatReader.splitSentences(rawText);
for (String sentence: sentences){
BioNLPTokenizer tokenizer = new BioNLPTokenizer(sentence);
List<CoreLabel> tokens = tokenizer.tokenize();
for (CoreLabel l: tokens){
os.write(l.word()+" ");
}
os.newLine();
}
os.close();
}
br.close();
}
// public static void main(String[] args) throws Exception{
//// String rawTextPath = "../../data/BioNLP11/train/";
//// String rawTextPath = "../../data/BioNLP11/development/";
//// String rawTextPath = "../../data/BioNLP11/test/";
//// String outPath = "../BioNLPNN_Multi_Preprocess/cache/BioNLP11/parsed/stanford_extractor/tokenised/test/";
//
//// String rawTextPath = "../../data/BioNLP11_Test/train/";
// String rawTextPath = "../../data/BioNLP11_Test/test/";
// String outPath = "../BioNLPNN_Multi_Preprocess/cache/BioNLP11_Test/parsed/stanford_extractor/tokenised/";
//
//// String rawTextPath = "../../data/Open-access-pubmed-NFkB/";
//// String outPath = "../../data/Open-access-pubmed-NFkB_tokenised_by_stanford_extractor/";
//// String rawTextPath = "../../data/Open-access-pubmed-NFkB-2/";
//// String outPath = "../../data/Open-access-pubmed-NFkB-2_tokenised_by_stanford_extractor/";
//
//// String rawTextPath = "../../data/BioNLP13/train/";
//// String rawTextPath = "../../data/BioNLP13/development/";
//// String outPath = "../BioNLPNN_Multi_Preprocess/cache/BioNLP13/parsed/stanford_extractor/tokenised/";
//
//// String rawTextPath = "../../data/MergeBioNLP_Test/train/";
//// String rawTextPath = "../../data/MergeBioNLP_Test/test/";
//// String rawTextPath = "../../data/MergeBioNLP/development/maskPMID/";
//// String outPath = "../BioNLPNN_Multi_Preprocess/cache/MergeBioNLP/parsed/stanford_extractor/tokenised/";
//// String outPath = "../BioNLPNN_Multi_Preprocess/cache/MergeBioNLP_Test/parsed/stanford_extractor/tokenised/";
// System.out.println("current dir:"+new File(".").getAbsolutePath());
// System.out.println("parse files under "+rawTextPath);
// File dir = new File(rawTextPath);
// System.out.println("absolute path:"+dir.getAbsolutePath());
// File[] files = dir.listFiles(new FilenameFilter(){
// public boolean accept(File dir, String filename){return filename.endsWith(".txt");}
// });
//
//// BioNLPFormatReader reader = new BioNLPFormatReader();
// File outputDir = new File(outPath);
// if (!outputDir.exists()){
// System.out.println("create directory:"+outputDir);
// outputDir.mkdir();
// }
// for (File file: files){
// String rawText = IOUtils.slurpFile(file);
//// rawText.replace("α", "alpha");
//// rawText.replace("β", "beta");
//// rawText.replace("γ", "gamma");
//// rawText.replace("-","-");
//// rawText.replace("ï","i");
//// rawText.replace("≤","<=");
//// rawText.replace("±","+/-");
//// rawText.replace("™","(TM)");
//// rawText.replace("×","x");
//// rawText.replace(" "," ");
//// rawText.replace("µ","mu");
//// rawText.replace("°","degrees");
//// rawText.replace("′","'");
//
// String fileName = file.getName();
// System.out.println("process "+fileName);
// fileName = outPath+fileName.substring(0, fileName.lastIndexOf(".txt"))+".tok";
// BufferedWriter os = new BufferedWriter(new FileWriter(new File(fileName)));
// Collection<String> sentences = BioNLPFormatReader.splitSentences(rawText);
// for (String sentence: sentences){
// BioNLPTokenizer tokenizer = new BioNLPTokenizer(sentence);
// List<CoreLabel> tokens = tokenizer.tokenize();
// for (CoreLabel l: tokens){
// os.write(l.word()+" ");
// }
// os.newLine();
// }
// os.close();
//// System.out.println("write into "+fileName);
// }
//
// }
protected static class BioNLPTokenizer {
AbstractTokenizer<CoreLabel> tokenizer;
CoreLabelTokenFactory tokenFactory;
/** If true, remove tokens that are standalone dashes. They are likely to hurt the parser. */
private static final boolean DISCARD_STANDALONE_DASHES = true;
// XXX the following list is domain specific
// this is a list of all suffixes which we'll split off if they follow a dash
// e.g. "X-induced" will be split into the three tokens "X", "-", and "induced"
private static final HashSet<String> VALID_DASH_SUFFIXES = new HashSet<String>(
Arrays.asList(new String[] { "\\w+ed", "\\w+ing", "(in)?dependent",
"deficient", "response", "protein", "by", "specific", "like",
"inducible", "responsive", "gene", "mRNA", "transcription",
"sensitive", "bound", "driven", "positive", "negative", "dominant",
"family", "resistant", "activity", "proximal", "defective" }));
private final Pattern dashSuffixes;
// matches a word followed by a slash followed by a word
private static final Pattern ANYSLASH_PATTERN = Pattern.compile("(\\w+)(/)(\\w+)");
public BioNLPTokenizer(String buffer) {
StringReader sr = new StringReader(buffer);
String options = "ptb3Escaping=false";
tokenFactory = new CoreLabelTokenFactory();
tokenizer = new PTBTokenizer<CoreLabel>(sr, tokenFactory, options);
String allSuffixes = makeRegexOr(VALID_DASH_SUFFIXES);
String allSuffixesRegex = "(\\w+)(-)(" + allSuffixes + ")";
dashSuffixes = Pattern.compile(allSuffixesRegex, Pattern.CASE_INSENSITIVE);
}
private String makeRegexOr(Iterable<String> pieces) {
StringBuilder suffixBuilder = new StringBuilder();
for (String suffix : pieces) {
if (suffixBuilder.length() > 0) {
suffixBuilder.append("|");
}
suffixBuilder.append("(" + suffix + ")");
}
return suffixBuilder.toString();
}
public List<CoreLabel> tokenize() {
List<CoreLabel> tokens = tokenizer.tokenize();
for (CoreLabel token:tokens){
if ((token.endPosition()-token.beginPosition())<token.word().length()){
for (CoreLabel tok:tokens){
System.out.print(tok.word()+" ");
}
System.out.println();
System.out.print("tranform "+token.word() +" to ");
token.setWord(token.word().substring(0,token.endPosition()-token.beginPosition()));
System.out.println(token.word());
}
}
return postprocess(tokens);
}
protected List<CoreLabel> postprocess(List<CoreLabel> tokens) {
// we can't use the regex "(anti)|(non)" since that will create an extra
// group and confuse breakOnPattern, thus we do an extra pass
tokens = breakOnPattern(tokens, Pattern.compile("(anti)(-)(\\w+)",
Pattern.CASE_INSENSITIVE));
tokens = breakOnPattern(tokens, Pattern.compile("(non)(-)(\\w+)",
Pattern.CASE_INSENSITIVE));
tokens = breakOnPattern(tokens, dashSuffixes);
// tokens = breakOnPattern(tokens, ANYSLASH_PATTERN);
tokens = breakOnPattern(tokens);//, ANYSLASH_PATTERN
// re-join trailing or preceding - or + to previous digit
tokens = joinSigns(tokens);
// convert parens to normalized forms, e.g., -LRB-. better for parsing
tokens = normalizeParens(tokens);
return tokens;
}
private List<CoreLabel> joinSigns(List<CoreLabel> tokens) {
List<CoreLabel> output = new ArrayList<CoreLabel>();
for (int i = 0; i < tokens.size(); i++) {
// -/-
if(i < tokens.size() - 3 &&
tokens.get(i).endPosition() == tokens.get(i + 1).beginPosition() && // neighbor
tokens.get(i + 1).word().equals("-") && // -/-
tokens.get(i + 2).word().equals("/") &&
tokens.get(i + 3).word().equals("-")){
String word = tokens.get(i).word() +
tokens.get(i + 1).word() +
tokens.get(i + 2).word() +
tokens.get(i + 3).word();
output.add(tokenFactory.makeToken(word, tokens.get(i).beginPosition(), word.length()));
i += 3;
continue;
}
// - or +
if(i < tokens.size() - 1){
CoreLabel crt = tokens.get(i);
CoreLabel nxt = tokens.get(i + 1);
// trailing +
if(crt.endPosition() == nxt.beginPosition() && // neighbor
! isParen(crt.word()) && // not '('
nxt.word().equals("+")){ // '[TOKEN]+'
String word = crt.word() + nxt.word();
output.add(tokenFactory.makeToken(word, crt.beginPosition(), word.length()));
i ++;
continue;
}
// trailing -
if(crt.endPosition() == nxt.beginPosition() &&
(i + 2 >= tokens.size() || nxt.endPosition() != tokens.get(i + 2).beginPosition()) && // not A-B, shoud be A-$ or A- B, to distinct the sign or hyphen
! isParen(crt.word()) && // current is not '('
nxt.word().equals("-")){ // '[TOKEN]-'
String word = crt.word() + nxt.word();
output.add(tokenFactory.makeToken(word, crt.beginPosition(), word.length()));
i ++;
continue;
}
// preceding -
if(crt.endPosition() == nxt.beginPosition() &&
(i == 0 || crt.beginPosition() != tokens.get(i - 1).endPosition()) &&
! isParen(nxt.word()) &&
crt.word().equals("-")){
String word = crt.word() + nxt.word();
output.add(tokenFactory.makeToken(word, crt.beginPosition(), word.length()));
i ++;
continue;
}
}
output.add(tokens.get(i));
}
return output;
}
private static final String [][] PARENS = {
{ "(", "-LRB-" },
{ ")", "-RRB-" },
{ "[", "-LSB-" },
{ "]", "-RSB-" }
};
private static boolean isParen(String s) {
for(int j = 0; j < PARENS.length; j ++){
if(s.equals(PARENS[j][0])){
return true;
}
}
return false;
}
private static List<CoreLabel> normalizeParens(List<CoreLabel> tokens) {
for (int i = 0; i < tokens.size(); i++) {
CoreLabel token = tokens.get(i);
for(int j = 0; j < PARENS.length; j ++){
if(token.word().equals(PARENS[j][0])){
token.set(TextAnnotation.class, PARENS[j][1]);
}
}
}
return tokens;
}
private List<CoreLabel> breakOnPattern(List<CoreLabel> tokens, Pattern pattern) {
List<CoreLabel> output = new ArrayList<CoreLabel>();
for (int i = 0; i < tokens.size(); i++) {
CoreLabel token = tokens.get(i);
Matcher matcher = pattern.matcher(token.word());
if (matcher.find()) {
int sepPos = matcher.start(2);
String s1 = token.word().substring(0, sepPos);
if(! DISCARD_STANDALONE_DASHES || ! s1.equals("-")){
output.add(tokenFactory.makeToken(s1, token.beginPosition(), sepPos));
}
String sep = matcher.group(2);
if(! DISCARD_STANDALONE_DASHES || ! sep.equals("-")){
output.add(tokenFactory.makeToken(sep, token.beginPosition() + sepPos, 1));
}
String s3 = token.word().substring(sepPos + 1);
if(! DISCARD_STANDALONE_DASHES || ! s3.equals("-")){
output.add(tokenFactory.makeToken(s3, token.beginPosition() + sepPos + 1,
token.endPosition() - token.beginPosition() - sepPos - 1));
}
} else {
output.add(token);
}
}
return output;
}
private List<CoreLabel> breakOnPattern(List<CoreLabel> tokens) {
Pattern pattern = ANYSLASH_PATTERN;
List<CoreLabel> output = new ArrayList<CoreLabel>();
for (int i = 0; i < tokens.size(); i++) {
CoreLabel token = tokens.get(i);
while(true){
Matcher matcher = pattern.matcher(token.word());
if (matcher.find()) {
int sepPos = matcher.start(2);
String s1 = token.word().substring(0, sepPos);
if(! DISCARD_STANDALONE_DASHES || ! s1.equals("-")){
output.add(tokenFactory.makeToken(s1, token.beginPosition(), sepPos));
}
String sep = matcher.group(2);
if(! DISCARD_STANDALONE_DASHES || ! sep.equals("-")){
output.add(tokenFactory.makeToken(sep, token.beginPosition() + sepPos, 1));
}
String s3 = token.word().substring(sepPos + 1);
if(! DISCARD_STANDALONE_DASHES || ! s3.equals("-")){
token = tokenFactory.makeToken(s3, token.beginPosition() + sepPos + 1,
token.endPosition() - token.beginPosition() - sepPos - 1);
}
} else {
output.add(token);
break;
}
}
}
return output;
}
}
}
| gpl-2.0 |
CSEMike/OneSwarm-Community-Server | src/edu/washington/cs/oneswarm/community2/server/TooManyRegistrationsException.java | 387 | package edu.washington.cs.oneswarm.community2.server;
import java.io.IOException;
public class TooManyRegistrationsException extends IOException {
private int howmany;
public TooManyRegistrationsException( int howmany ) {
super("Too many registrations: " + howmany);
this.howmany = howmany;
}
public TooManyRegistrationsException() {
super("Too many registrations");
}
}
| gpl-2.0 |
wjrivera/tms | workspace/TireManagementService/src/utilities/Invoice.java | 1827 | package utilities;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class Invoice {
//class variables
public static Integer NextInvoiceNumber = 1000;
private Integer invoiceNumber;
private Client client;
private UUID clientId;
private List<Job> jobs;
private Date date;
private Vehicle vehicle;
private String billTo;
//Invoice constructors with exisiting Invoicing or New Invoice created
public Invoice(Client c, UUID id, Date d, Vehicle v, List<Job> js, String bt) {
invoiceNumber = NextInvoiceNumber++;
client = c;
clientId = id;
date = d;
vehicle = v;
jobs = js;
billTo = bt;
}
public Invoice(int i, Client c, UUID id, Date d, Vehicle v, List<Job> js, String bt) {
invoiceNumber = i;
client = c;
clientId = id;
date = d;
vehicle = v;
jobs = js;
billTo = bt;
}
//the following are setters and getters.
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Invoice(int invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public UUID getClientId() {
return clientId;
}
public void setClientId(UUID clientId) {
this.clientId = clientId;
}
public List<Job> getJobs() {
return jobs;
}
public void setJobs(List<Job> jobs) {
this.jobs = jobs;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getInvoiceNumber() {
return invoiceNumber;
}
public void setInvoiceNumber(Integer invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
public String getBillTo() {
return billTo;
}
public void setBillTo(String billTo) {
this.billTo = billTo;
}
}
| gpl-2.0 |
vikto9494/Lobo_Browser | XAMJ_Project/Primary_Extension/org/lobobrowser/primary/ext/AddBookmarkDialog.java | 4283 | /*
GNU GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
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
verion 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 library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
package org.lobobrowser.primary.ext;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.lobobrowser.primary.gui.FieldType;
import org.lobobrowser.primary.gui.FormField;
import org.lobobrowser.primary.gui.FormPanel;
import org.lobobrowser.util.Strings;
public class AddBookmarkDialog extends JDialog {
private final FormField urlField = new FormField(FieldType.TEXT, "URL:");
private final FormField titleField = new FormField(FieldType.TEXT, "Title:");
private final FormField descriptionField = new FormField(FieldType.TEXT, "Description:");
private final FormField tagsField = new FormField(FieldType.TEXT, "Tags:");
private final java.net.URL url;
public AddBookmarkDialog(Frame owner, boolean modal, BookmarkInfo existingInfo) throws HeadlessException {
super(owner, modal);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.url = existingInfo.getUrl();
this.urlField.setEditable(false);
this.tagsField.setToolTip("List of keywords separated by blanks.");
this.urlField.setValue(existingInfo.getUrl().toExternalForm());
this.titleField.setValue(existingInfo.getTitle());
this.descriptionField.setValue(existingInfo.getDescription());
this.tagsField.setValue(existingInfo.getTagsText());
Container contentPane = this.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
FormPanel fieldsPanel = new FormPanel();
fieldsPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
fieldsPanel.addField(this.urlField);
fieldsPanel.addField(this.titleField);
fieldsPanel.addField(this.descriptionField);
fieldsPanel.addField(this.tagsField);
Dimension fpps = fieldsPanel.getPreferredSize();
fieldsPanel.setPreferredSize(new Dimension(400, fpps.height));
contentPane.add(fieldsPanel);
JComponent buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
JButton okButton = new JButton();
okButton.setAction(new OkAction());
okButton.setText("Save");
JButton cancelButton = new JButton();
cancelButton.setAction(new CancelAction());
cancelButton.setText("Cancel");
buttonsPanel.add(Box.createHorizontalGlue());
buttonsPanel.add(okButton);
buttonsPanel.add(Box.createRigidArea(new Dimension(4, 1)));
buttonsPanel.add(cancelButton);
buttonsPanel.add(Box.createHorizontalGlue());
contentPane.add(buttonsPanel);
contentPane.add(Box.createRigidArea(new Dimension(1, 4)));
}
private BookmarkInfo bookmarkInfo;
public BookmarkInfo getBookmarkInfo() {
return this.bookmarkInfo;
}
private class OkAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
BookmarkInfo binfo = new BookmarkInfo();
binfo.setUrl(url);
binfo.setTitle(titleField.getValue());
binfo.setDescription(descriptionField.getValue());
binfo.setTags(Strings.split(tagsField.getValue()));
bookmarkInfo = binfo;
AddBookmarkDialog.this.dispose();
}
}
private class CancelAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
bookmarkInfo = null;
AddBookmarkDialog.this.dispose();
}
}
}
| gpl-2.0 |
maiklos-mirrors/jfx78 | apps/samples/Ensemble8/src/samples/java/ensemble/samples/graphics2d/stopwatch/Watch.java | 9758 | /*
* Copyright (c) 2008, 2013 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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 Oracle Corporation 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 ensemble.samples.graphics2d.stopwatch;
import java.io.InputStream;
import java.text.DecimalFormat;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;
public class Watch extends Parent {
//visual nodes
private final Dial mainDial;
private final Dial minutesDial;
private final Dial tenthsDial;
private final Group background = new Group();
private final DigitalClock digitalClock = new DigitalClock();
private final StopWatchButton startButton;
private final StopWatchButton stopButton;
/**
* The number of milliseconds which have elapsed while the stopwatch has
* been running. That is, it is the total time kept on the stopwatch.
*/
private int elapsedMillis = 0;
/**
* Keeps track of the amount of the clock time (CPU clock) when the
* stopwatch run plunger was pressed, or when the last tick even occurred.
* This is used to calculate the elapsed time delta.
*/
private int lastClockTime = 0;
private DecimalFormat twoPlaces = new DecimalFormat("00");
private Timeline time = new Timeline();
public Watch() {
startButton = new StopWatchButton(Color.web("#8cc700"), Color.web("#71a000"));
stopButton = new StopWatchButton(Color.web("#AA0000"), Color.web("#660000"));
mainDial = new Dial(117, true, 12, 60, Color.RED, true);
minutesDial = new Dial(30, false, 12, 60, "minutes", Color.BLACK, false);
tenthsDial = new Dial(30, false, 12, 60, "10ths", Color.BLACK, false);
configureBackground();
myLayout();
configureListeners();
configureTimeline();
getChildren().addAll(background, minutesDial, tenthsDial, digitalClock, mainDial, startButton, stopButton);
}
private void configureTimeline() {
time.setCycleCount(Timeline.INDEFINITE);
KeyFrame keyFrame = new KeyFrame(Duration.millis(47), new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
calculate();
}
});
time.getKeyFrames().add(keyFrame);
}
private void configureBackground() {
ImageView imageView = new ImageView();
Image image = loadImage();
imageView.setImage(image);
Circle circle1 = new Circle();
circle1.setCenterX(140);
circle1.setCenterY(140);
circle1.setRadius(120);
circle1.setFill(Color.TRANSPARENT);
circle1.setStroke(Color.web("#0A0A0A"));
circle1.setStrokeWidth(0.3);
Circle circle2 = new Circle();
circle2.setCenterX(140);
circle2.setCenterY(140);
circle2.setRadius(118);
circle2.setFill(Color.TRANSPARENT);
circle2.setStroke(Color.web("#0A0A0A"));
circle2.setStrokeWidth(0.3);
Circle circle3 = new Circle();
circle3.setCenterX(140);
circle3.setCenterY(140);
circle3.setRadius(140);
circle3.setFill(Color.TRANSPARENT);
circle3.setStroke(Color.web("#818a89"));
circle3.setStrokeWidth(1);
Ellipse ellipse = new Ellipse(140, 95, 180, 95);
Circle ellipseClip = new Circle(140, 140, 140);
ellipse.setFill(Color.web("#535450"));
ellipse.setStrokeWidth(0);
GaussianBlur ellipseEffect = new GaussianBlur();
ellipseEffect.setRadius(10);
ellipse.setEffect(ellipseEffect);
ellipse.setOpacity(0.1);
ellipse.setClip(ellipseClip);
background.getChildren().addAll(imageView, circle1, circle2, circle3, ellipse);
}
private void myLayout() {
mainDial.setLayoutX(140);
mainDial.setLayoutY(140);
minutesDial.setLayoutX(100);
minutesDial.setLayoutY(100);
tenthsDial.setLayoutX(180);
tenthsDial.setLayoutY(100);
digitalClock.setLayoutX(79);
digitalClock.setLayoutY(195);
startButton.setLayoutX(223);
startButton.setLayoutY(1);
Rotate rotateRight = new Rotate(360 / 12);
startButton.getTransforms().add(rotateRight);
stopButton.setLayoutX(59.5);
stopButton.setLayoutY(0);
Rotate rotateLeft = new Rotate(-360 / 12);
stopButton.getTransforms().add(rotateLeft);
}
private void configureListeners() {
startButton.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
startButton.moveDown();
me.consume();
}
});
stopButton.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
stopButton.moveDown();
me.consume();
}
});
startButton.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
startButton.moveUp();
startStop();
me.consume();
}
});
stopButton.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
stopButton.moveUp();
stopReset();
me.consume();
}
});
startButton.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
me.consume();
}
});
stopButton.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent me) {
me.consume();
}
});
}
//MODEL
private void calculate() {
if (lastClockTime == 0) {
lastClockTime = (int) System.currentTimeMillis();
}
int now = (int) System.currentTimeMillis();
int delta = now - lastClockTime;
elapsedMillis += delta;
int tenths = (elapsedMillis / 10) % 100;
int seconds = (elapsedMillis / 1000) % 60;
int mins = (elapsedMillis / 60000) % 60;
refreshTimeDisplay(mins, seconds, tenths);
lastClockTime = now;
}
public void startStop() {
if (time.getStatus() != Animation.Status.STOPPED) {
// if started, stop it
time.stop();
lastClockTime = 0;
} else {
// if stopped, restart
time.play();
}
}
public void stopReset() {
if (time.getStatus() != Animation.Status.STOPPED) {
// if started, stop it
time.stop();
lastClockTime = 0;
} else {
// if stopped, reset it
lastClockTime = 0;
elapsedMillis = 0;
refreshTimeDisplay(0, 0, 0);
}
}
private void refreshTimeDisplay(int mins, int seconds, int tenths) {
double handAngle = ((360 / 60) * seconds);
mainDial.setAngle(handAngle);
double tenthsHandAngle = ((360 / 100.0) * tenths);
tenthsDial.setAngle(tenthsHandAngle);
double minutesHandAngle = ((360 / 60.0) * mins);
minutesDial.setAngle(minutesHandAngle);
String timeString = twoPlaces.format(mins) + ":" + twoPlaces.format(seconds) + "." + twoPlaces.format(tenths);
digitalClock.refreshDigits(timeString);
}
//IMAGE handling
public Image loadImage() {
InputStream is = Watch.class.getResourceAsStream("/ensemble/samples/shared-resources/stopwatch.png");
return new Image(is);
}
}
| gpl-2.0 |
Norkart/NK-VirtualGlobe | Xj3D/src/java/org/xj3d/ui/swt/device/keyboard/KeyboardTracker.java | 7335 | /*****************************************************************************
* Web3d.org Copyright (c) 2006
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.xj3d.ui.swt.device.keyboard;
// External imports
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
// Local imports
import org.xj3d.device.Tracker;
import org.xj3d.device.TrackerState;
import org.xj3d.device.ButtonModeConstants;
/**
* A tracker implementation for keyboard devices associated
* with instances of SWT UI widgets.
*
* @author Rex Melton
* @version $Revision: 1.4 $
*/
public class KeyboardTracker extends Tracker implements KeyListener {
/** What events is this tracker reporting. */
private static final int mask = MASK_POSITION;
/** The tracker state to return */
private TrackerState tstate;
/** Whether the forward key is held down */
private boolean active_forward;
/** Whether the backward key is held down */
private boolean active_backward;
/** Whether the left key is held down */
private boolean active_left;
/** Whether the right key is held down */
private boolean active_right;
/** Are any keys held */
private boolean inMotion;
/** How fast should we rotate. 0 to 2 */
private float rot_speed;
/** How fast should we translate. 0 to 2 */
private float trans_speed;
public KeyboardTracker() {
tstate = new TrackerState();
trans_speed = 1.0f;
rot_speed = 0.5f;
}
//------------------------------------------------------------------------
// Methods defined by Tracker
//------------------------------------------------------------------------
/**
* What action types does this sensor return. This a combination
* of ACTION masks.
*
* @return The action mask.
*/
public int getActionMask() {
return mask;
}
/**
* Notification that tracker polling is beginning.
*/
public void beginPolling() {
// TODO: Should we double buffer?
}
/**
* Notification that tracker polling is ending.
*/
public void endPolling() {
}
/**
* Get the current state of this tracker.
*
* @param layer The ID of the layer to get the state for
* @param subLayer The ID of the sub layer within the parent layer
* @param state The current state
*/
public void getState(int layer, int subLayer, TrackerState state) {
// Layer information is ignored.
state.actionMask = mask;
state.actionType = tstate.actionType;
state.devicePos[0] = tstate.devicePos[0];
state.devicePos[1] = tstate.devicePos[1];
state.devicePos[2] = tstate.devicePos[2];
state.deviceOri[0] = tstate.deviceOri[0];
state.deviceOri[1] = tstate.deviceOri[1];
state.deviceOri[2] = tstate.deviceOri[2];
state.worldPos[0] = tstate.worldPos[0];
state.worldPos[1] = tstate.worldPos[1];
state.worldPos[2] = tstate.worldPos[2];
state.worldOri[0] = tstate.worldOri[0];
state.worldOri[1] = tstate.worldOri[1];
state.worldOri[2] = tstate.worldOri[2];
state.buttonMode[0] = ButtonModeConstants.WALK;
// Switch to PAN for Doom style navigation
//state.buttonMode[1] = ButtonModeConstants.PAN;
state.buttonMode[1] = ButtonModeConstants.WALK;
for(int i=0; i < tstate.buttonState.length; i++) {
state.buttonState[i] = tstate.buttonState[i];
}
if (inMotion) {
tstate.actionType = TrackerState.TYPE_DRAG;
if (active_forward)
tstate.devicePos[1] = -trans_speed;
else if (active_backward)
tstate.devicePos[1] = trans_speed;
else
tstate.devicePos[1] = 0;
if (active_right)
tstate.devicePos[0] = rot_speed;
else if (active_left)
tstate.devicePos[0] = -rot_speed;
else
tstate.devicePos[0] = 0;
}
else
tstate.actionType = TrackerState.TYPE_NONE;
}
//------------------------------------------------------------------------
// Methods defined by KeyListener
//------------------------------------------------------------------------
/**
* Process a key press event.
*
* @param evt The event that caused this method to be called
*/
public void keyPressed(KeyEvent evt) {
boolean new_active=false;
int button=0;
int keyCode = evt.keyCode;
switch(keyCode) {
case SWT.ARROW_UP:
if (!inMotion)
new_active = true;
active_forward = true;
button = 0;
break;
case SWT.ARROW_RIGHT:
if (!inMotion)
new_active = true;
active_right = true;
button = 1;
break;
case SWT.ARROW_LEFT:
if (!inMotion)
new_active = true;
active_left = true;
button = 1;
break;
case SWT.ARROW_DOWN:
if (!inMotion)
new_active = true;
active_backward = true;
button = 0;
break;
}
if ((keyCode & SWT.SHIFT) != 0)
trans_speed = 3.0f;
else
trans_speed = 1.0f;
if (new_active) {
inMotion = true;
tstate.actionType = TrackerState.TYPE_PRESS;
tstate.devicePos[0] = 0.0f;
tstate.devicePos[1] = 0.0f;
tstate.devicePos[2] = 0.0f;
tstate.buttonState[0] = false;
tstate.buttonState[1] = false;
tstate.buttonState[button] = true;
}
}
/**
* Process a key release event.
*
* @param evt The event that caused this method to be called
*/
public void keyReleased(KeyEvent evt) {
int keyCode = evt.keyCode;
if ((keyCode & SWT.SHIFT) != 0)
trans_speed = 3.0f;
else
trans_speed = 1.0f;
switch(keyCode) {
case SWT.ARROW_UP:
active_forward = false;
break;
case SWT.ARROW_RIGHT:
active_right = false;
break;
case SWT.ARROW_LEFT:
active_left = false;
break;
case SWT.ARROW_DOWN:
active_backward = false;
break;
}
if (!active_forward && !active_right && !active_left) {
inMotion = false;
tstate.actionType = TrackerState.TYPE_RELEASE;
tstate.buttonState[0] = false;
tstate.buttonState[1] = false;
}
}
}
| gpl-2.0 |
camposer/cf | trade-processor/src/test/java/com/cf/tradeprocessor/test/config/ProxyConfigTest.java | 1281 | package com.cf.tradeprocessor.test.config;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:/proxy.properties")
public class ProxyConfigTest {
@Value("${proxy.host}")
public String proxyHost;
@Value("${proxy.port}")
public String proxyPort;
@Value("${proxy.user}")
public String proxyUser;
@Value("${proxy.password}")
public String proxyPassword;
@PostConstruct
public void configureProxy() {
if (proxyHost.trim().equals("") || proxyPort.trim().equals("")) // exiting because there's no proxy
return;
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
proxyUser, proxyPassword.toCharArray());
}
}
);
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
System.setProperty("http.proxyUser", proxyUser);
System.setProperty("http.proxyPassword", proxyPassword);
}
}
| gpl-2.0 |
profosure/porogram | TMessagesProj/src/main/java/com/porogram/profosure1/messenger/exoplayer2/extractor/ts/Id3Reader.java | 3959 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.porogram.profosure1.messenger.exoplayer2.extractor.ts;
import android.util.Log;
import com.porogram.profosure1.messenger.exoplayer2.C;
import com.porogram.profosure1.messenger.exoplayer2.Format;
import com.porogram.profosure1.messenger.exoplayer2.extractor.ExtractorOutput;
import com.porogram.profosure1.messenger.exoplayer2.extractor.TrackOutput;
import com.porogram.profosure1.messenger.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator;
import com.porogram.profosure1.messenger.exoplayer2.util.MimeTypes;
import com.porogram.profosure1.messenger.exoplayer2.util.ParsableByteArray;
/**
* Parses ID3 data and extracts individual text information frames.
*/
/* package */ final class Id3Reader implements ElementaryStreamReader {
private static final String TAG = "Id3Reader";
private static final int ID3_HEADER_SIZE = 10;
private final ParsableByteArray id3Header;
private TrackOutput output;
// State that should be reset on seek.
private boolean writingSample;
// Per sample state that gets reset at the start of each sample.
private long sampleTimeUs;
private int sampleSize;
private int sampleBytesRead;
public Id3Reader() {
id3Header = new ParsableByteArray(ID3_HEADER_SIZE);
}
@Override
public void seek() {
writingSample = false;
}
@Override
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
output = extractorOutput.track(idGenerator.getNextId());
output.format(Format.createSampleFormat(null, MimeTypes.APPLICATION_ID3, null, Format.NO_VALUE,
null));
}
@Override
public void packetStarted(long pesTimeUs, boolean dataAlignmentIndicator) {
if (!dataAlignmentIndicator) {
return;
}
writingSample = true;
sampleTimeUs = pesTimeUs;
sampleSize = 0;
sampleBytesRead = 0;
}
@Override
public void consume(ParsableByteArray data) {
if (!writingSample) {
return;
}
int bytesAvailable = data.bytesLeft();
if (sampleBytesRead < ID3_HEADER_SIZE) {
// We're still reading the ID3 header.
int headerBytesAvailable = Math.min(bytesAvailable, ID3_HEADER_SIZE - sampleBytesRead);
System.arraycopy(data.data, data.getPosition(), id3Header.data, sampleBytesRead,
headerBytesAvailable);
if (sampleBytesRead + headerBytesAvailable == ID3_HEADER_SIZE) {
// We've finished reading the ID3 header. Extract the sample size.
id3Header.setPosition(0);
if ('I' != id3Header.readUnsignedByte() || 'D' != id3Header.readUnsignedByte()
|| '3' != id3Header.readUnsignedByte()) {
Log.w(TAG, "Discarding invalid ID3 tag");
writingSample = false;
return;
}
id3Header.skipBytes(3); // version (2) + flags (1)
sampleSize = ID3_HEADER_SIZE + id3Header.readSynchSafeInt();
}
}
// Write data to the output.
int bytesToWrite = Math.min(bytesAvailable, sampleSize - sampleBytesRead);
output.sampleData(data, bytesToWrite);
sampleBytesRead += bytesToWrite;
}
@Override
public void packetFinished() {
if (!writingSample || sampleSize == 0 || sampleBytesRead != sampleSize) {
return;
}
output.sampleMetadata(sampleTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
writingSample = false;
}
}
| gpl-2.0 |
sleroy/jtestlink | corolla-backend/corolla-backend-application/src/main/java/com/tocea/corolla/products/dao/IProjectBranchDAO.java | 921 | package com.tocea.corolla.products.dao;
import java.util.Collection;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.tocea.corolla.products.domain.ProjectBranch;
public interface IProjectBranchDAO extends MongoRepository<ProjectBranch, String> {
/**
* Retrieves a ProjectBranch instance from its name and its project id
* @param name
* @return
*/
public ProjectBranch findByNameAndProjectId(String name, String projectId);
/**
* Retrieves all ProjectBranch instances from a project id
* @param projectId
* @return
*/
public Collection<ProjectBranch> findByProjectId(String projectId);
/**
* Retrieves the default branch of a given project
* @param projectId
* @return
*/
@Query(value="{ 'projectId': ?0, 'defaultBranch': true }")
public ProjectBranch findDefaultBranch(String projectId);
}
| gpl-2.0 |
santanche/java2learn | src/java/src/pt/c07bd/s01basico/s03generico/App03ConsultaTaxonomia.java | 2091 | package pt.c07bd.s01basico.s03generico;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class App03ConsultaTaxonomia
{
public static void main(String args[])
{
System.out.println("BD MySQL:");
executaConsulta("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/biblioteca", "root", "thelab");
System.out.println();
System.out.println("BD HSQLDB:");
executaConsulta("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:file:db/hsqldb/biblioteca;shutdown=true", "SA", "");
/*
System.out.println("BD Cloudscape Derby:");
executaConsulta("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:db/derby/biblioteca;create=true", "", "");
System.out.println("BD MS Access:");
executaConsulta("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:BancoDados", "", "");
*/
System.out.println();
}
public static void executaConsulta(String driver, String bd, String usuario, String senha)
{
try {
Class.forName(driver);
Connection conexao = DriverManager.getConnection(bd, usuario, senha);
Statement comando = conexao.createStatement();
ResultSet resultado = comando.executeQuery("SELECT Categoria, Superior FROM Taxonomia");
boolean temConteudo = resultado.next();
while (temConteudo)
{
String categoria= resultado.getString("Categoria"),
superior = resultado.getString("Superior");
System.out.println(categoria + "; " + superior);
temConteudo = resultado.next();
}
comando.close();
conexao.close();
} catch (ClassNotFoundException erro) {
System.out.println(erro.getMessage());
} catch (SQLException erro) {
System.out.println("Erro no SQL: " + erro.getMessage());
}
}
}
| gpl-2.0 |
HotswapProjects/HotswapAgent | hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Pair.java | 1900 | /*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package org.hotswap.agent.javassist.compiler.ast;
import org.hotswap.agent.javassist.compiler.CompileError;
/**
* A node of a a binary tree. This class provides concrete methods
* overriding abstract methods in ASTree.
*/
public class Pair extends ASTree {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected ASTree left, right;
public Pair(ASTree _left, ASTree _right) {
left = _left;
right = _right;
}
@Override
public void accept(Visitor v) throws CompileError { v.atPair(this); }
@Override
public String toString() {
StringBuffer sbuf = new StringBuffer();
sbuf.append("(<Pair> ");
sbuf.append(left == null ? "<null>" : left.toString());
sbuf.append(" . ");
sbuf.append(right == null ? "<null>" : right.toString());
sbuf.append(')');
return sbuf.toString();
}
@Override
public ASTree getLeft() { return left; }
@Override
public ASTree getRight() { return right; }
@Override
public void setLeft(ASTree _left) { left = _left; }
@Override
public void setRight(ASTree _right) { right = _right; }
}
| gpl-2.0 |
Go4Git/Prep-Audio-Client | src/org/stephen/model/Person.java | 826 | package org.stephen.model;
import java.io.Serializable;
/**
* A dummy class representing a person for
* testing purposes.
* @author Stephen Andrews
*/
public class Person implements Serializable {
private String name;
private int age;
private double income;
public Person(String name, int age, double income) {
this.name = name;
this.age = age;
this.income = income;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
@Override
public String toString() {
return "Person [" + name + ", " + age + ", " + income + "]";
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/external/bouncycastle/jce/provider/PKIXNameConstraintValidator.java | 57993 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package org.bouncycastle.jce.provider;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralSubtree;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class PKIXNameConstraintValidator
{
private Set excludedSubtreesDN = new HashSet();
private Set excludedSubtreesDNS = new HashSet();
private Set excludedSubtreesEmail = new HashSet();
private Set excludedSubtreesURI = new HashSet();
private Set excludedSubtreesIP = new HashSet();
private Set permittedSubtreesDN;
private Set permittedSubtreesDNS;
private Set permittedSubtreesEmail;
private Set permittedSubtreesURI;
private Set permittedSubtreesIP;
public PKIXNameConstraintValidator()
{
}
private static boolean withinDNSubtree(
ASN1Sequence dns,
ASN1Sequence subtree)
{
if (subtree.size() < 1)
{
return false;
}
if (subtree.size() > dns.size())
{
return false;
}
for (int j = subtree.size() - 1; j >= 0; j--)
{
if (!subtree.getObjectAt(j).equals(dns.getObjectAt(j)))
{
return false;
}
}
return true;
}
public void checkPermittedDN(ASN1Sequence dns)
throws PKIXNameConstraintValidatorException
{
checkPermittedDN(permittedSubtreesDN, dns);
}
public void checkExcludedDN(ASN1Sequence dns)
throws PKIXNameConstraintValidatorException
{
checkExcludedDN(excludedSubtreesDN, dns);
}
private void checkPermittedDN(Set permitted, ASN1Sequence dns)
throws PKIXNameConstraintValidatorException
{
if (permitted == null)
{
return;
}
if (permitted.isEmpty() && dns.size() == 0)
{
return;
}
Iterator it = permitted.iterator();
while (it.hasNext())
{
ASN1Sequence subtree = (ASN1Sequence)it.next();
if (withinDNSubtree(dns, subtree))
{
return;
}
}
throw new PKIXNameConstraintValidatorException(
"Subject distinguished name is not from a permitted subtree");
}
private void checkExcludedDN(Set excluded, ASN1Sequence dns)
throws PKIXNameConstraintValidatorException
{
if (excluded.isEmpty())
{
return;
}
Iterator it = excluded.iterator();
while (it.hasNext())
{
ASN1Sequence subtree = (ASN1Sequence)it.next();
if (withinDNSubtree(dns, subtree))
{
throw new PKIXNameConstraintValidatorException(
"Subject distinguished name is from an excluded subtree");
}
}
}
private Set intersectDN(Set permitted, Set dns)
{
Set intersect = new HashSet();
for (Iterator it = dns.iterator(); it.hasNext();)
{
ASN1Sequence dn = ASN1Sequence.getInstance(((GeneralSubtree)it
.next()).getBase().getName().getDERObject());
if (permitted == null)
{
if (dn != null)
{
intersect.add(dn);
}
}
else
{
Iterator _iter = permitted.iterator();
while (_iter.hasNext())
{
ASN1Sequence subtree = (ASN1Sequence)_iter.next();
if (withinDNSubtree(dn, subtree))
{
intersect.add(dn);
}
else if (withinDNSubtree(subtree, dn))
{
intersect.add(subtree);
}
}
}
}
return intersect;
}
private Set unionDN(Set excluded, ASN1Sequence dn)
{
if (excluded.isEmpty())
{
if (dn == null)
{
return excluded;
}
excluded.add(dn);
return excluded;
}
else
{
Set intersect = new HashSet();
Iterator it = excluded.iterator();
while (it.hasNext())
{
ASN1Sequence subtree = (ASN1Sequence)it.next();
if (withinDNSubtree(dn, subtree))
{
intersect.add(subtree);
}
else if (withinDNSubtree(subtree, dn))
{
intersect.add(dn);
}
else
{
intersect.add(subtree);
intersect.add(dn);
}
}
return intersect;
}
}
private Set intersectEmail(Set permitted, Set emails)
{
Set intersect = new HashSet();
for (Iterator it = emails.iterator(); it.hasNext();)
{
String email = extractNameAsString(((GeneralSubtree)it.next())
.getBase());
if (permitted == null)
{
if (email != null)
{
intersect.add(email);
}
}
else
{
Iterator it2 = permitted.iterator();
while (it2.hasNext())
{
String _permitted = (String)it2.next();
intersectEmail(email, _permitted, intersect);
}
}
}
return intersect;
}
private Set unionEmail(Set excluded, String email)
{
if (excluded.isEmpty())
{
if (email == null)
{
return excluded;
}
excluded.add(email);
return excluded;
}
else
{
Set union = new HashSet();
Iterator it = excluded.iterator();
while (it.hasNext())
{
String _excluded = (String)it.next();
unionEmail(_excluded, email, union);
}
return union;
}
}
/**
* Returns the intersection of the permitted IP ranges in
* <code>permitted</code> with <code>ip</code>.
*
* @param permitted A <code>Set</code> of permitted IP addresses with
* their subnet mask as byte arrays.
* @param ips The IP address with its subnet mask.
* @return The <code>Set</code> of permitted IP ranges intersected with
* <code>ip</code>.
*/
private Set intersectIP(Set permitted, Set ips)
{
Set intersect = new HashSet();
for (Iterator it = ips.iterator(); it.hasNext();)
{
byte[] ip = ASN1OctetString.getInstance(
((GeneralSubtree)it.next()).getBase().getName()).getOctets();
if (permitted == null)
{
if (ip != null)
{
intersect.add(ip);
}
}
else
{
Iterator it2 = permitted.iterator();
while (it2.hasNext())
{
byte[] _permitted = (byte[])it2.next();
intersect.addAll(intersectIPRange(_permitted, ip));
}
}
}
return intersect;
}
/**
* Returns the union of the excluded IP ranges in <code>excluded</code>
* with <code>ip</code>.
*
* @param excluded A <code>Set</code> of excluded IP addresses with their
* subnet mask as byte arrays.
* @param ip The IP address with its subnet mask.
* @return The <code>Set</code> of excluded IP ranges unified with
* <code>ip</code> as byte arrays.
*/
private Set unionIP(Set excluded, byte[] ip)
{
if (excluded.isEmpty())
{
if (ip == null)
{
return excluded;
}
excluded.add(ip);
return excluded;
}
else
{
Set union = new HashSet();
Iterator it = excluded.iterator();
while (it.hasNext())
{
byte[] _excluded = (byte[])it.next();
union.addAll(unionIPRange(_excluded, ip));
}
return union;
}
}
/**
* Calculates the union if two IP ranges.
*
* @param ipWithSubmask1 The first IP address with its subnet mask.
* @param ipWithSubmask2 The second IP address with its subnet mask.
* @return A <code>Set</code> with the union of both addresses.
*/
private Set unionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2)
{
Set set = new HashSet();
// difficult, adding always all IPs is not wrong
if (Arrays.areEqual(ipWithSubmask1, ipWithSubmask2))
{
set.add(ipWithSubmask1);
}
else
{
set.add(ipWithSubmask1);
set.add(ipWithSubmask2);
}
return set;
}
/**
* Calculates the interesction if two IP ranges.
*
* @param ipWithSubmask1 The first IP address with its subnet mask.
* @param ipWithSubmask2 The second IP address with its subnet mask.
* @return A <code>Set</code> with the single IP address with its subnet
* mask as a byte array or an empty <code>Set</code>.
*/
private Set intersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2)
{
if (ipWithSubmask1.length != ipWithSubmask2.length)
{
return Collections.EMPTY_SET;
}
byte[][] temp = extractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2);
byte ip1[] = temp[0];
byte subnetmask1[] = temp[1];
byte ip2[] = temp[2];
byte subnetmask2[] = temp[3];
byte minMax[][] = minMaxIPs(ip1, subnetmask1, ip2, subnetmask2);
byte[] min;
byte[] max;
max = min(minMax[1], minMax[3]);
min = max(minMax[0], minMax[2]);
// minimum IP address must be bigger than max
if (compareTo(min, max) == 1)
{
return Collections.EMPTY_SET;
}
// OR keeps all significant bits
byte[] ip = or(minMax[0], minMax[2]);
byte[] subnetmask = or(subnetmask1, subnetmask2);
return Collections.singleton(ipWithSubnetMask(ip, subnetmask));
}
/**
* Concatenates the IP address with its subnet mask.
*
* @param ip The IP address.
* @param subnetMask Its subnet mask.
* @return The concatenated IP address with its subnet mask.
*/
private byte[] ipWithSubnetMask(byte[] ip, byte[] subnetMask)
{
int ipLength = ip.length;
byte[] temp = new byte[ipLength * 2];
System.arraycopy(ip, 0, temp, 0, ipLength);
System.arraycopy(subnetMask, 0, temp, ipLength, ipLength);
return temp;
}
/**
* Splits the IP addresses and their subnet mask.
*
* @param ipWithSubmask1 The first IP address with the subnet mask.
* @param ipWithSubmask2 The second IP address with the subnet mask.
* @return An array with two elements. Each element contains the IP address
* and the subnet mask in this order.
*/
private byte[][] extractIPsAndSubnetMasks(
byte[] ipWithSubmask1,
byte[] ipWithSubmask2)
{
int ipLength = ipWithSubmask1.length / 2;
byte ip1[] = new byte[ipLength];
byte subnetmask1[] = new byte[ipLength];
System.arraycopy(ipWithSubmask1, 0, ip1, 0, ipLength);
System.arraycopy(ipWithSubmask1, ipLength, subnetmask1, 0, ipLength);
byte ip2[] = new byte[ipLength];
byte subnetmask2[] = new byte[ipLength];
System.arraycopy(ipWithSubmask2, 0, ip2, 0, ipLength);
System.arraycopy(ipWithSubmask2, ipLength, subnetmask2, 0, ipLength);
return new byte[][]
{ip1, subnetmask1, ip2, subnetmask2};
}
/**
* Based on the two IP addresses and their subnet masks the IP range is
* computed for each IP address - subnet mask pair and returned as the
* minimum IP address and the maximum address of the range.
*
* @param ip1 The first IP address.
* @param subnetmask1 The subnet mask of the first IP address.
* @param ip2 The second IP address.
* @param subnetmask2 The subnet mask of the second IP address.
* @return A array with two elements. The first/second element contains the
* min and max IP address of the first/second IP address and its
* subnet mask.
*/
private byte[][] minMaxIPs(
byte[] ip1,
byte[] subnetmask1,
byte[] ip2,
byte[] subnetmask2)
{
int ipLength = ip1.length;
byte[] min1 = new byte[ipLength];
byte[] max1 = new byte[ipLength];
byte[] min2 = new byte[ipLength];
byte[] max2 = new byte[ipLength];
for (int i = 0; i < ipLength; i++)
{
min1[i] = (byte)(ip1[i] & subnetmask1[i]);
max1[i] = (byte)(ip1[i] & subnetmask1[i] | ~subnetmask1[i]);
min2[i] = (byte)(ip2[i] & subnetmask2[i]);
max2[i] = (byte)(ip2[i] & subnetmask2[i] | ~subnetmask2[i]);
}
return new byte[][]{min1, max1, min2, max2};
}
private void checkPermittedEmail(Set permitted, String email)
throws PKIXNameConstraintValidatorException
{
if (permitted == null)
{
return;
}
Iterator it = permitted.iterator();
while (it.hasNext())
{
String str = ((String)it.next());
if (emailIsConstrained(email, str))
{
return;
}
}
if (email.length() == 0 && permitted.size() == 0)
{
return;
}
throw new PKIXNameConstraintValidatorException(
"Subject email address is not from a permitted subtree.");
}
private void checkExcludedEmail(Set excluded, String email)
throws PKIXNameConstraintValidatorException
{
if (excluded.isEmpty())
{
return;
}
Iterator it = excluded.iterator();
while (it.hasNext())
{
String str = (String)it.next();
if (emailIsConstrained(email, str))
{
throw new PKIXNameConstraintValidatorException(
"Email address is from an excluded subtree.");
}
}
}
/**
* Checks if the IP <code>ip</code> is included in the permitted set
* <code>permitted</code>.
*
* @param permitted A <code>Set</code> of permitted IP addresses with
* their subnet mask as byte arrays.
* @param ip The IP address.
* @throws PKIXNameConstraintValidatorException
* if the IP is not permitted.
*/
private void checkPermittedIP(Set permitted, byte[] ip)
throws PKIXNameConstraintValidatorException
{
if (permitted == null)
{
return;
}
Iterator it = permitted.iterator();
while (it.hasNext())
{
byte[] ipWithSubnet = (byte[])it.next();
if (isIPConstrained(ip, ipWithSubnet))
{
return;
}
}
if (ip.length == 0 && permitted.size() == 0)
{
return;
}
throw new PKIXNameConstraintValidatorException(
"IP is not from a permitted subtree.");
}
/**
* Checks if the IP <code>ip</code> is included in the excluded set
* <code>excluded</code>.
*
* @param excluded A <code>Set</code> of excluded IP addresses with their
* subnet mask as byte arrays.
* @param ip The IP address.
* @throws PKIXNameConstraintValidatorException
* if the IP is excluded.
*/
private void checkExcludedIP(Set excluded, byte[] ip)
throws PKIXNameConstraintValidatorException
{
if (excluded.isEmpty())
{
return;
}
Iterator it = excluded.iterator();
while (it.hasNext())
{
byte[] ipWithSubnet = (byte[])it.next();
if (isIPConstrained(ip, ipWithSubnet))
{
throw new PKIXNameConstraintValidatorException(
"IP is from an excluded subtree.");
}
}
}
/**
* Checks if the IP address <code>ip</code> is constrained by
* <code>constraint</code>.
*
* @param ip The IP address.
* @param constraint The constraint. This is an IP address concatenated with
* its subnetmask.
* @return <code>true</code> if constrained, <code>false</code>
* otherwise.
*/
private boolean isIPConstrained(byte ip[], byte[] constraint)
{
int ipLength = ip.length;
if (ipLength != (constraint.length / 2))
{
return false;
}
byte[] subnetMask = new byte[ipLength];
System.arraycopy(constraint, ipLength, subnetMask, 0, ipLength);
byte[] permittedSubnetAddress = new byte[ipLength];
byte[] ipSubnetAddress = new byte[ipLength];
// the resulting IP address by applying the subnet mask
for (int i = 0; i < ipLength; i++)
{
permittedSubnetAddress[i] = (byte)(constraint[i] & subnetMask[i]);
ipSubnetAddress[i] = (byte)(ip[i] & subnetMask[i]);
}
return Arrays.areEqual(permittedSubnetAddress, ipSubnetAddress);
}
private boolean emailIsConstrained(String email, String constraint)
{
String sub = email.substring(email.indexOf('@') + 1);
// a particular mailbox
if (constraint.indexOf('@') != -1)
{
if (email.equalsIgnoreCase(constraint))
{
return true;
}
}
// on particular host
else if (!(constraint.charAt(0) == '.'))
{
if (sub.equalsIgnoreCase(constraint))
{
return true;
}
}
// address in sub domain
else if (withinDomain(sub, constraint))
{
return true;
}
return false;
}
private boolean withinDomain(String testDomain, String domain)
{
String tempDomain = domain;
if (tempDomain.startsWith("."))
{
tempDomain = tempDomain.substring(1);
}
String[] domainParts = Strings.split(tempDomain, '.');
String[] testDomainParts = Strings.split(testDomain, '.');
// must have at least one subdomain
if (testDomainParts.length <= domainParts.length)
{
return false;
}
int d = testDomainParts.length - domainParts.length;
for (int i = -1; i < domainParts.length; i++)
{
if (i == -1)
{
if (testDomainParts[i + d].equals(""))
{
return false;
}
}
else if (!domainParts[i].equalsIgnoreCase(testDomainParts[i + d]))
{
return false;
}
}
return true;
}
private void checkPermittedDNS(Set permitted, String dns)
throws PKIXNameConstraintValidatorException
{
if (permitted == null)
{
return;
}
Iterator it = permitted.iterator();
while (it.hasNext())
{
String str = ((String)it.next());
// is sub domain
if (withinDomain(dns, str) || dns.equalsIgnoreCase(str))
{
return;
}
}
if (dns.length() == 0 && permitted.size() == 0)
{
return;
}
throw new PKIXNameConstraintValidatorException(
"DNS is not from a permitted subtree.");
}
private void checkExcludedDNS(Set excluded, String dns)
throws PKIXNameConstraintValidatorException
{
if (excluded.isEmpty())
{
return;
}
Iterator it = excluded.iterator();
while (it.hasNext())
{
String str = ((String)it.next());
// is sub domain or the same
if (withinDomain(dns, str) || dns.equalsIgnoreCase(str))
{
throw new PKIXNameConstraintValidatorException(
"DNS is from an excluded subtree.");
}
}
}
/**
* The common part of <code>email1</code> and <code>email2</code> is
* added to the union <code>union</code>. If <code>email1</code> and
* <code>email2</code> have nothing in common they are added both.
*
* @param email1 Email address constraint 1.
* @param email2 Email address constraint 2.
* @param union The union.
*/
private void unionEmail(String email1, String email2, Set union)
{
// email1 is a particular address
if (email1.indexOf('@') != -1)
{
String _sub = email1.substring(email1.indexOf('@') + 1);
// both are a particular mailbox
if (email2.indexOf('@') != -1)
{
if (email1.equalsIgnoreCase(email2))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(_sub, email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a particular host
else
{
if (_sub.equalsIgnoreCase(email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
// email1 specifies a domain
else if (email1.startsWith("."))
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (withinDomain(_sub, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2)
|| email1.equalsIgnoreCase(email2))
{
union.add(email2);
}
else if (withinDomain(email2, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
else
{
if (withinDomain(email2, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
// email specifies a host
else
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (_sub.equalsIgnoreCase(email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a particular host
else
{
if (email1.equalsIgnoreCase(email2))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
}
private void unionURI(String email1, String email2, Set union)
{
// email1 is a particular address
if (email1.indexOf('@') != -1)
{
String _sub = email1.substring(email1.indexOf('@') + 1);
// both are a particular mailbox
if (email2.indexOf('@') != -1)
{
if (email1.equalsIgnoreCase(email2))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(_sub, email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a particular host
else
{
if (_sub.equalsIgnoreCase(email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
// email1 specifies a domain
else if (email1.startsWith("."))
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (withinDomain(_sub, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2)
|| email1.equalsIgnoreCase(email2))
{
union.add(email2);
}
else if (withinDomain(email2, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
else
{
if (withinDomain(email2, email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
// email specifies a host
else
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (_sub.equalsIgnoreCase(email1))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2))
{
union.add(email2);
}
else
{
union.add(email1);
union.add(email2);
}
}
// email2 specifies a particular host
else
{
if (email1.equalsIgnoreCase(email2))
{
union.add(email1);
}
else
{
union.add(email1);
union.add(email2);
}
}
}
}
private Set intersectDNS(Set permitted, Set dnss)
{
Set intersect = new HashSet();
for (Iterator it = dnss.iterator(); it.hasNext();)
{
String dns = extractNameAsString(((GeneralSubtree)it.next())
.getBase());
if (permitted == null)
{
if (dns != null)
{
intersect.add(dns);
}
}
else
{
Iterator _iter = permitted.iterator();
while (_iter.hasNext())
{
String _permitted = (String)_iter.next();
if (withinDomain(_permitted, dns))
{
intersect.add(_permitted);
}
else if (withinDomain(dns, _permitted))
{
intersect.add(dns);
}
}
}
}
return intersect;
}
protected Set unionDNS(Set excluded, String dns)
{
if (excluded.isEmpty())
{
if (dns == null)
{
return excluded;
}
excluded.add(dns);
return excluded;
}
else
{
Set union = new HashSet();
Iterator _iter = excluded.iterator();
while (_iter.hasNext())
{
String _permitted = (String)_iter.next();
if (withinDomain(_permitted, dns))
{
union.add(dns);
}
else if (withinDomain(dns, _permitted))
{
union.add(_permitted);
}
else
{
union.add(_permitted);
union.add(dns);
}
}
return union;
}
}
/**
* The most restricting part from <code>email1</code> and
* <code>email2</code> is added to the intersection <code>intersect</code>.
*
* @param email1 Email address constraint 1.
* @param email2 Email address constraint 2.
* @param intersect The intersection.
*/
private void intersectEmail(String email1, String email2, Set intersect)
{
// email1 is a particular address
if (email1.indexOf('@') != -1)
{
String _sub = email1.substring(email1.indexOf('@') + 1);
// both are a particular mailbox
if (email2.indexOf('@') != -1)
{
if (email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(_sub, email2))
{
intersect.add(email1);
}
}
// email2 specifies a particular host
else
{
if (_sub.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
}
// email specifies a domain
else if (email1.startsWith("."))
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (withinDomain(_sub, email1))
{
intersect.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2)
|| email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
else if (withinDomain(email2, email1))
{
intersect.add(email2);
}
}
else
{
if (withinDomain(email2, email1))
{
intersect.add(email2);
}
}
}
// email1 specifies a host
else
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email2.indexOf('@') + 1);
if (_sub.equalsIgnoreCase(email1))
{
intersect.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2))
{
intersect.add(email1);
}
}
// email2 specifies a particular host
else
{
if (email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
}
}
private void checkExcludedURI(Set excluded, String uri)
throws PKIXNameConstraintValidatorException
{
if (excluded.isEmpty())
{
return;
}
Iterator it = excluded.iterator();
while (it.hasNext())
{
String str = ((String)it.next());
if (isUriConstrained(uri, str))
{
throw new PKIXNameConstraintValidatorException(
"URI is from an excluded subtree.");
}
}
}
private Set intersectURI(Set permitted, Set uris)
{
Set intersect = new HashSet();
for (Iterator it = uris.iterator(); it.hasNext();)
{
String uri = extractNameAsString(((GeneralSubtree)it.next())
.getBase());
if (permitted == null)
{
if (uri != null)
{
intersect.add(uri);
}
}
else
{
Iterator _iter = permitted.iterator();
while (_iter.hasNext())
{
String _permitted = (String)_iter.next();
intersectURI(_permitted, uri, intersect);
}
}
}
return intersect;
}
private Set unionURI(Set excluded, String uri)
{
if (excluded.isEmpty())
{
if (uri == null)
{
return excluded;
}
excluded.add(uri);
return excluded;
}
else
{
Set union = new HashSet();
Iterator _iter = excluded.iterator();
while (_iter.hasNext())
{
String _excluded = (String)_iter.next();
unionURI(_excluded, uri, union);
}
return union;
}
}
private void intersectURI(String email1, String email2, Set intersect)
{
// email1 is a particular address
if (email1.indexOf('@') != -1)
{
String _sub = email1.substring(email1.indexOf('@') + 1);
// both are a particular mailbox
if (email2.indexOf('@') != -1)
{
if (email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(_sub, email2))
{
intersect.add(email1);
}
}
// email2 specifies a particular host
else
{
if (_sub.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
}
// email specifies a domain
else if (email1.startsWith("."))
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email1.indexOf('@') + 1);
if (withinDomain(_sub, email1))
{
intersect.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2)
|| email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
else if (withinDomain(email2, email1))
{
intersect.add(email2);
}
}
else
{
if (withinDomain(email2, email1))
{
intersect.add(email2);
}
}
}
// email1 specifies a host
else
{
if (email2.indexOf('@') != -1)
{
String _sub = email2.substring(email2.indexOf('@') + 1);
if (_sub.equalsIgnoreCase(email1))
{
intersect.add(email2);
}
}
// email2 specifies a domain
else if (email2.startsWith("."))
{
if (withinDomain(email1, email2))
{
intersect.add(email1);
}
}
// email2 specifies a particular host
else
{
if (email1.equalsIgnoreCase(email2))
{
intersect.add(email1);
}
}
}
}
private void checkPermittedURI(Set permitted, String uri)
throws PKIXNameConstraintValidatorException
{
if (permitted == null)
{
return;
}
Iterator it = permitted.iterator();
while (it.hasNext())
{
String str = ((String)it.next());
if (isUriConstrained(uri, str))
{
return;
}
}
if (uri.length() == 0 && permitted.size() == 0)
{
return;
}
throw new PKIXNameConstraintValidatorException(
"URI is not from a permitted subtree.");
}
private boolean isUriConstrained(String uri, String constraint)
{
String host = extractHostFromURL(uri);
// a host
if (!constraint.startsWith("."))
{
if (host.equalsIgnoreCase(constraint))
{
return true;
}
}
// in sub domain or domain
else if (withinDomain(host, constraint))
{
return true;
}
return false;
}
private static String extractHostFromURL(String url)
{
// see RFC 1738
// remove ':' after protocol, e.g. http:
String sub = url.substring(url.indexOf(':') + 1);
// extract host from Common Internet Scheme Syntax, e.g. http://
if (sub.indexOf("//") != -1)
{
sub = sub.substring(sub.indexOf("//") + 2);
}
// first remove port, e.g. http://test.com:21
if (sub.lastIndexOf(':') != -1)
{
sub = sub.substring(0, sub.lastIndexOf(':'));
}
// remove user and password, e.g. http://john:password@test.com
sub = sub.substring(sub.indexOf(':') + 1);
sub = sub.substring(sub.indexOf('@') + 1);
// remove local parts, e.g. http://test.com/bla
if (sub.indexOf('/') != -1)
{
sub = sub.substring(0, sub.indexOf('/'));
}
return sub;
}
/**
* Checks if the given GeneralName is in the permitted set.
*
* @param name The GeneralName
* @throws PKIXNameConstraintValidatorException
* If the <code>name</code>
*/
public void checkPermitted(GeneralName name)
throws PKIXNameConstraintValidatorException
{
switch (name.getTagNo())
{
case 1:
checkPermittedEmail(permittedSubtreesEmail,
extractNameAsString(name));
break;
case 2:
checkPermittedDNS(permittedSubtreesDNS, DERIA5String.getInstance(
name.getName()).getString());
break;
case 4:
checkPermittedDN(ASN1Sequence.getInstance(name.getName()
.getDERObject()));
break;
case 6:
checkPermittedURI(permittedSubtreesURI, DERIA5String.getInstance(
name.getName()).getString());
break;
case 7:
byte[] ip = ASN1OctetString.getInstance(name.getName()).getOctets();
checkPermittedIP(permittedSubtreesIP, ip);
}
}
/**
* Check if the given GeneralName is contained in the excluded set.
*
* @param name The GeneralName.
* @throws PKIXNameConstraintValidatorException
* If the <code>name</code> is
* excluded.
*/
public void checkExcluded(GeneralName name)
throws PKIXNameConstraintValidatorException
{
switch (name.getTagNo())
{
case 1:
checkExcludedEmail(excludedSubtreesEmail, extractNameAsString(name));
break;
case 2:
checkExcludedDNS(excludedSubtreesDNS, DERIA5String.getInstance(
name.getName()).getString());
break;
case 4:
checkExcludedDN(ASN1Sequence.getInstance(name.getName()
.getDERObject()));
break;
case 6:
checkExcludedURI(excludedSubtreesURI, DERIA5String.getInstance(
name.getName()).getString());
break;
case 7:
byte[] ip = ASN1OctetString.getInstance(name.getName()).getOctets();
checkExcludedIP(excludedSubtreesIP, ip);
}
}
/**
* Updates the permitted set of these name constraints with the intersection
* with the given subtree.
*
* @param permitted The permitted subtrees
*/
public void intersectPermittedSubtree(ASN1Sequence permitted)
{
Map subtreesMap = new HashMap();
// group in sets in a map ordered by tag no.
for (Enumeration e = permitted.getObjects(); e.hasMoreElements();)
{
GeneralSubtree subtree = GeneralSubtree.getInstance(e.nextElement());
// BEGIN android-changed
Integer tagNo = Integer.valueOf(subtree.getBase().getTagNo());
// END android-changed
if (subtreesMap.get(tagNo) == null)
{
subtreesMap.put(tagNo, new HashSet());
}
((Set)subtreesMap.get(tagNo)).add(subtree);
}
for (Iterator it = subtreesMap.entrySet().iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
// go through all subtree groups
switch (((Integer)entry.getKey()).intValue())
{
case 1:
permittedSubtreesEmail = intersectEmail(permittedSubtreesEmail,
(Set)entry.getValue());
break;
case 2:
permittedSubtreesDNS = intersectDNS(permittedSubtreesDNS,
(Set)entry.getValue());
break;
case 4:
permittedSubtreesDN = intersectDN(permittedSubtreesDN,
(Set)entry.getValue());
break;
case 6:
permittedSubtreesURI = intersectURI(permittedSubtreesURI,
(Set)entry.getValue());
break;
case 7:
permittedSubtreesIP = intersectIP(permittedSubtreesIP,
(Set)entry.getValue());
}
}
}
private String extractNameAsString(GeneralName name)
{
return DERIA5String.getInstance(name.getName()).getString();
}
public void intersectEmptyPermittedSubtree(int nameType)
{
switch (nameType)
{
case 1:
permittedSubtreesEmail = new HashSet();
break;
case 2:
permittedSubtreesDNS = new HashSet();
break;
case 4:
permittedSubtreesDN = new HashSet();
break;
case 6:
permittedSubtreesURI = new HashSet();
break;
case 7:
permittedSubtreesIP = new HashSet();
}
}
/**
* Adds a subtree to the excluded set of these name constraints.
*
* @param subtree A subtree with an excluded GeneralName.
*/
public void addExcludedSubtree(GeneralSubtree subtree)
{
GeneralName base = subtree.getBase();
switch (base.getTagNo())
{
case 1:
excludedSubtreesEmail = unionEmail(excludedSubtreesEmail,
extractNameAsString(base));
break;
case 2:
excludedSubtreesDNS = unionDNS(excludedSubtreesDNS,
extractNameAsString(base));
break;
case 4:
excludedSubtreesDN = unionDN(excludedSubtreesDN,
(ASN1Sequence)base.getName().getDERObject());
break;
case 6:
excludedSubtreesURI = unionURI(excludedSubtreesURI,
extractNameAsString(base));
break;
case 7:
excludedSubtreesIP = unionIP(excludedSubtreesIP, ASN1OctetString
.getInstance(base.getName()).getOctets());
break;
}
}
/**
* Returns the maximum IP address.
*
* @param ip1 The first IP address.
* @param ip2 The second IP address.
* @return The maximum IP address.
*/
private static byte[] max(byte[] ip1, byte[] ip2)
{
for (int i = 0; i < ip1.length; i++)
{
if ((ip1[i] & 0xFFFF) > (ip2[i] & 0xFFFF))
{
return ip1;
}
}
return ip2;
}
/**
* Returns the minimum IP address.
*
* @param ip1 The first IP address.
* @param ip2 The second IP address.
* @return The minimum IP address.
*/
private static byte[] min(byte[] ip1, byte[] ip2)
{
for (int i = 0; i < ip1.length; i++)
{
if ((ip1[i] & 0xFFFF) < (ip2[i] & 0xFFFF))
{
return ip1;
}
}
return ip2;
}
/**
* Compares IP address <code>ip1</code> with <code>ip2</code>. If ip1
* is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1
* otherwise.
*
* @param ip1 The first IP address.
* @param ip2 The second IP address.
* @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise.
*/
private static int compareTo(byte[] ip1, byte[] ip2)
{
if (Arrays.areEqual(ip1, ip2))
{
return 0;
}
if (Arrays.areEqual(max(ip1, ip2), ip1))
{
return 1;
}
return -1;
}
/**
* Returns the logical OR of the IP addresses <code>ip1</code> and
* <code>ip2</code>.
*
* @param ip1 The first IP address.
* @param ip2 The second IP address.
* @return The OR of <code>ip1</code> and <code>ip2</code>.
*/
private static byte[] or(byte[] ip1, byte[] ip2)
{
byte[] temp = new byte[ip1.length];
for (int i = 0; i < ip1.length; i++)
{
temp[i] = (byte)(ip1[i] | ip2[i]);
}
return temp;
}
public int hashCode()
{
return hashCollection(excludedSubtreesDN)
+ hashCollection(excludedSubtreesDNS)
+ hashCollection(excludedSubtreesEmail)
+ hashCollection(excludedSubtreesIP)
+ hashCollection(excludedSubtreesURI)
+ hashCollection(permittedSubtreesDN)
+ hashCollection(permittedSubtreesDNS)
+ hashCollection(permittedSubtreesEmail)
+ hashCollection(permittedSubtreesIP)
+ hashCollection(permittedSubtreesURI);
}
private int hashCollection(Collection coll)
{
if (coll == null)
{
return 0;
}
int hash = 0;
Iterator it1 = coll.iterator();
while (it1.hasNext())
{
Object o = it1.next();
if (o instanceof byte[])
{
hash += Arrays.hashCode((byte[])o);
}
else
{
hash += o.hashCode();
}
}
return hash;
}
public boolean equals(Object o)
{
if (!(o instanceof PKIXNameConstraintValidator))
{
return false;
}
PKIXNameConstraintValidator constraintValidator = (PKIXNameConstraintValidator)o;
return collectionsAreEqual(constraintValidator.excludedSubtreesDN, excludedSubtreesDN)
&& collectionsAreEqual(constraintValidator.excludedSubtreesDNS, excludedSubtreesDNS)
&& collectionsAreEqual(constraintValidator.excludedSubtreesEmail, excludedSubtreesEmail)
&& collectionsAreEqual(constraintValidator.excludedSubtreesIP, excludedSubtreesIP)
&& collectionsAreEqual(constraintValidator.excludedSubtreesURI, excludedSubtreesURI)
&& collectionsAreEqual(constraintValidator.permittedSubtreesDN, permittedSubtreesDN)
&& collectionsAreEqual(constraintValidator.permittedSubtreesDNS, permittedSubtreesDNS)
&& collectionsAreEqual(constraintValidator.permittedSubtreesEmail, permittedSubtreesEmail)
&& collectionsAreEqual(constraintValidator.permittedSubtreesIP, permittedSubtreesIP)
&& collectionsAreEqual(constraintValidator.permittedSubtreesURI, permittedSubtreesURI);
}
private boolean collectionsAreEqual(Collection coll1, Collection coll2)
{
if (coll1 == coll2)
{
return true;
}
if (coll1 == null || coll2 == null)
{
return false;
}
if (coll1.size() != coll2.size())
{
return false;
}
Iterator it1 = coll1.iterator();
while (it1.hasNext())
{
Object a = it1.next();
Iterator it2 = coll2.iterator();
boolean found = false;
while (it2.hasNext())
{
Object b = it2.next();
if (equals(a, b))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
private boolean equals(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
if (o1 instanceof byte[] && o2 instanceof byte[])
{
return Arrays.areEqual((byte[])o1, (byte[])o2);
}
else
{
return o1.equals(o2);
}
}
/**
* Stringifies an IPv4 or v6 address with subnet mask.
*
* @param ip The IP with subnet mask.
* @return The stringified IP address.
*/
private String stringifyIP(byte[] ip)
{
String temp = "";
for (int i = 0; i < ip.length / 2; i++)
{
temp += Integer.toString(ip[i] & 0x00FF) + ".";
}
temp = temp.substring(0, temp.length() - 1);
temp += "/";
for (int i = ip.length / 2; i < ip.length; i++)
{
temp += Integer.toString(ip[i] & 0x00FF) + ".";
}
temp = temp.substring(0, temp.length() - 1);
return temp;
}
private String stringifyIPCollection(Set ips)
{
String temp = "";
temp += "[";
for (Iterator it = ips.iterator(); it.hasNext();)
{
temp += stringifyIP((byte[])it.next()) + ",";
}
if (temp.length() > 1)
{
temp = temp.substring(0, temp.length() - 1);
}
temp += "]";
return temp;
}
public String toString()
{
String temp = "";
temp += "permitted:\n";
if (permittedSubtreesDN != null)
{
temp += "DN:\n";
temp += permittedSubtreesDN.toString() + "\n";
}
if (permittedSubtreesDNS != null)
{
temp += "DNS:\n";
temp += permittedSubtreesDNS.toString() + "\n";
}
if (permittedSubtreesEmail != null)
{
temp += "Email:\n";
temp += permittedSubtreesEmail.toString() + "\n";
}
if (permittedSubtreesURI != null)
{
temp += "URI:\n";
temp += permittedSubtreesURI.toString() + "\n";
}
if (permittedSubtreesIP != null)
{
temp += "IP:\n";
temp += stringifyIPCollection(permittedSubtreesIP) + "\n";
}
temp += "excluded:\n";
if (!excludedSubtreesDN.isEmpty())
{
temp += "DN:\n";
temp += excludedSubtreesDN.toString() + "\n";
}
if (!excludedSubtreesDNS.isEmpty())
{
temp += "DNS:\n";
temp += excludedSubtreesDNS.toString() + "\n";
}
if (!excludedSubtreesEmail.isEmpty())
{
temp += "Email:\n";
temp += excludedSubtreesEmail.toString() + "\n";
}
if (!excludedSubtreesURI.isEmpty())
{
temp += "URI:\n";
temp += excludedSubtreesURI.toString() + "\n";
}
if (!excludedSubtreesIP.isEmpty())
{
temp += "IP:\n";
temp += stringifyIPCollection(excludedSubtreesIP) + "\n";
}
return temp;
}
}
| gpl-2.0 |
jaaakob/campusyusuf | src/de/jakobhaubold/tools/unierlangentechfak/DModel.java | 2002 | package de.jakobhaubold.tools.unierlangentechfak;
import java.util.ArrayList;
public class DModel {
public static ArrayList<DItem> DItems;
public static void LoadModel() {
DItems = new ArrayList<DItem>();
DItems.add(new DItem(1, "d.png", "Sultan Döner","Hauptstraße 15, 91054 Erlangen"));
DItems.add(new DItem(2, "d.png", "Balkan Döner","Bunsenstraße, 91058 Erlangen"));
DItems.add(new DItem(3, "d.png", "Cantine Erlangen","Bunsenstraße 41, 91058 Erlangen"));
DItems.add(new DItem(4, "d.png", "Adana Döner","Martin-Luther-Platz 2, 91054 Erlangen"));
DItems.add(new DItem(5, "d.png", "Pascha Döner","Nürnberger Straße 33, 91052 Erlangen"));
DItems.add(new DItem(6, "d.png", "Avrasya Restaurant","Hauptstraße 75, 91054 Erlangen"));
DItems.add(new DItem(7, "d.png", "Efendi","Nürnberger Str. 7, Arcaden EG, 91052 Erlangen"));
DItems.add(new DItem(8, "d.png", "Pizz'a Pizz' - Kleopatra","Hauptstr. 15, 91054 Erlangen"));
DItems.add(new DItem(9, "d.png", "Orient Döner","Hauptstraße 15, 91054 Erlangen"));
DItems.add(new DItem(10, "d.png", "Real Adana","Martin-Luther-Platz 2, 91054 Erlangen"));
DItems.add(new DItem(11, "d.png", "Araz Pizza & Döner","Hauptstraße 107, 91054 Erlangen"));
DItems.add(new DItem(12, "d.png", "Dönerhaus","Drausnickstraße 36, 91052 Erlangen"));
DItems.add(new DItem(13, "d.png", "Dönerking Coekpinar Celal","Krankenhausstr. 3, 91054 Erlangen"));
DItems.add(new DItem(14, "d.png", "Döner King","Untere Karlstr. 3, 91054 Erlangen "));
DItems.add(new DItem(15, "d.png", "Cesme","Goethestr. 60, 91054 Erlangen "));
DItems.add(new DItem(16, "d.png", "Orient Döner","Rathausplatz 5, 91052 Erlangen "));
}
public static DItem GetbyId(int id){
for(DItem Ditem : DItems) {
if (Ditem.Id == id) {
return Ditem;
}
}
return null;
}
} | gpl-2.0 |
loveyoupeng/rt | modules/controls/src/main/java/com/sun/javafx/scene/control/skin/TitledPaneSkin.java | 21516 | /*
* Copyright (c) 2010, 2015, 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.sun.javafx.scene.control.skin;
import com.sun.javafx.PlatformUtil;
import javafx.animation.Animation.Status;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import com.sun.javafx.scene.control.behavior.TitledPaneBehavior;
import javafx.beans.binding.DoubleBinding;
import javafx.geometry.Insets;
import javafx.scene.control.Accordion;
import javafx.scene.control.Labeled;
import javafx.scene.control.ContextMenu;
import javafx.scene.input.MouseButton;
import javafx.scene.text.Font;
public class TitledPaneSkin extends LabeledSkinBase<TitledPane, TitledPaneBehavior> {
public static final Duration TRANSITION_DURATION = new Duration(350.0);
// caching results in poorer looking text (it is blurry), so we don't do it
// unless on a low powered device (admittedly the test below isn't a great
// indicator of power, but it'll do for now).
private static final boolean CACHE_ANIMATION = PlatformUtil.isEmbedded();
private final TitleRegion titleRegion;
private final StackPane contentContainer;
private Node content;
private Timeline timeline;
private double transitionStartValue;
private Rectangle clipRect;
private Pos pos;
private HPos hpos;
private VPos vpos;
public TitledPaneSkin(final TitledPane titledPane) {
super(titledPane, new TitledPaneBehavior(titledPane));
clipRect = new Rectangle();
transitionStartValue = 0;
titleRegion = new TitleRegion();
content = getSkinnable().getContent();
contentContainer = new StackPane() {
{
getStyleClass().setAll("content");
if (content != null) {
getChildren().setAll(content);
}
}
};
contentContainer.setClip(clipRect);
if (titledPane.isExpanded()) {
setTransition(1.0f);
setExpanded(titledPane.isExpanded());
} else {
setTransition(0.0f);
if (content != null) {
content.setVisible(false);
}
}
getChildren().setAll(contentContainer, titleRegion);
registerChangeListener(titledPane.contentProperty(), "CONTENT");
registerChangeListener(titledPane.expandedProperty(), "EXPANDED");
registerChangeListener(titledPane.collapsibleProperty(), "COLLAPSIBLE");
registerChangeListener(titledPane.alignmentProperty(), "ALIGNMENT");
registerChangeListener(titledPane.widthProperty(), "WIDTH");
registerChangeListener(titledPane.heightProperty(), "HEIGHT");
registerChangeListener(titleRegion.alignmentProperty(), "TITLE_REGION_ALIGNMENT");
pos = titledPane.getAlignment();
hpos = pos == null ? HPos.LEFT : pos.getHpos();
vpos = pos == null ? VPos.CENTER : pos.getVpos();
}
public StackPane getContentContainer() {
return contentContainer;
}
@Override
protected void handleControlPropertyChanged(String property) {
super.handleControlPropertyChanged(property);
if ("CONTENT".equals(property)) {
content = getSkinnable().getContent();
if (content == null) {
contentContainer.getChildren().clear();
} else {
contentContainer.getChildren().setAll(content);
}
} else if ("EXPANDED".equals(property)) {
setExpanded(getSkinnable().isExpanded());
} else if ("COLLAPSIBLE".equals(property)) {
titleRegion.update();
} else if ("ALIGNMENT".equals(property)) {
pos = getSkinnable().getAlignment();
hpos = pos.getHpos();
vpos = pos.getVpos();
} else if ("TITLE_REGION_ALIGNMENT".equals(property)) {
pos = titleRegion.getAlignment();
hpos = pos.getHpos();
vpos = pos.getVpos();
} else if ("WIDTH".equals(property)) {
clipRect.setWidth(getSkinnable().getWidth());
} else if ("HEIGHT".equals(property)) {
clipRect.setHeight(contentContainer.getHeight());
} else if ("GRAPHIC_TEXT_GAP".equals(property)) {
titleRegion.requestLayout();
}
}
// Override LabeledSkinBase updateChildren because
// it removes all the children. The update() in TitleRegion
// will replace this method.
@Override protected void updateChildren() {
if (titleRegion != null) {
titleRegion.update();
}
}
private void setExpanded(boolean expanded) {
if (! getSkinnable().isCollapsible()) {
setTransition(1.0f);
return;
}
// we need to perform the transition between expanded / hidden
if (getSkinnable().isAnimated()) {
transitionStartValue = getTransition();
doAnimationTransition();
} else {
if (expanded) {
setTransition(1.0f);
} else {
setTransition(0.0f);
}
if (content != null) {
content.setVisible(expanded);
}
getSkinnable().requestLayout();
}
}
private DoubleProperty transition;
private void setTransition(double value) { transitionProperty().set(value); }
private double getTransition() { return transition == null ? 0.0 : transition.get(); }
private DoubleProperty transitionProperty() {
if (transition == null) {
transition = new SimpleDoubleProperty(this, "transition", 0.0) {
@Override protected void invalidated() {
contentContainer.requestLayout();
}
};
}
return transition;
}
private boolean isInsideAccordion() {
return getSkinnable().getParent() != null && getSkinnable().getParent() instanceof Accordion;
}
@Override protected void layoutChildren(final double x, double y,
final double w, final double h) {
// header
double headerHeight = snapSize(titleRegion.prefHeight(-1));
titleRegion.resize(w, headerHeight);
positionInArea(titleRegion, x, y,
w, headerHeight, 0, HPos.LEFT, VPos.CENTER);
// content
double contentHeight = (h - headerHeight) * getTransition();
if (isInsideAccordion()) {
if (prefHeightFromAccordion != 0) {
contentHeight = (prefHeightFromAccordion - headerHeight) * getTransition();
}
}
contentHeight = snapSize(contentHeight);
y += snapSize(headerHeight);
contentContainer.resize(w, contentHeight);
clipRect.setHeight(contentHeight);
positionInArea(contentContainer, x, y,
w, contentHeight, /*baseline ignored*/0, HPos.CENTER, VPos.CENTER);
}
@Override protected double computeMinWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) {
double titleWidth = snapSize(titleRegion.prefWidth(height));
double contentWidth = snapSize(contentContainer.minWidth(height));
return Math.max(titleWidth, contentWidth) + leftInset + rightInset;
}
@Override protected double computeMinHeight(double width, double topInset, double rightInset, double bottomInset, double leftInset) {
double headerHeight = snapSize(titleRegion.prefHeight(width));
double contentHeight = contentContainer.minHeight(width) * getTransition();
return headerHeight + snapSize(contentHeight) + topInset + bottomInset;
}
@Override protected double computePrefWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) {
double titleWidth = snapSize(titleRegion.prefWidth(height));
double contentWidth = snapSize(contentContainer.prefWidth(height));
return Math.max(titleWidth, contentWidth) + leftInset + rightInset;
}
@Override protected double computePrefHeight(double width, double topInset, double rightInset, double bottomInset, double leftInset) {
double headerHeight = snapSize(titleRegion.prefHeight(width));
double contentHeight = contentContainer.prefHeight(width) * getTransition();
return headerHeight + snapSize(contentHeight) + topInset + bottomInset;
}
@Override protected double computeMaxWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) {
return Double.MAX_VALUE;
}
double getTitleRegionSize(double width) {
return snapSize(titleRegion.prefHeight(width)) + snappedTopInset() + snappedBottomInset();
}
private double prefHeightFromAccordion = 0;
void setMaxTitledPaneHeightForAccordion(double height) {
this.prefHeightFromAccordion = height;
}
double getTitledPaneHeightForAccordion() {
double headerHeight = snapSize(titleRegion.prefHeight(-1));
double contentHeight = (prefHeightFromAccordion - headerHeight) * getTransition();
return headerHeight + snapSize(contentHeight) + snappedTopInset() + snappedBottomInset();
}
private void doAnimationTransition() {
if (content == null) {
return;
}
Duration duration;
if (timeline != null && (timeline.getStatus() != Status.STOPPED)) {
duration = timeline.getCurrentTime();
timeline.stop();
} else {
duration = TRANSITION_DURATION;
}
timeline = new Timeline();
timeline.setCycleCount(1);
KeyFrame k1, k2;
if (getSkinnable().isExpanded()) {
k1 = new KeyFrame(
Duration.ZERO,
event -> {
// start expand
if (CACHE_ANIMATION) content.setCache(true);
content.setVisible(true);
},
new KeyValue(transitionProperty(), transitionStartValue)
);
k2 = new KeyFrame(
duration,
event -> {
// end expand
if (CACHE_ANIMATION) content.setCache(false);
},
new KeyValue(transitionProperty(), 1, Interpolator.LINEAR)
);
} else {
k1 = new KeyFrame(
Duration.ZERO,
event -> {
// Start collapse
if (CACHE_ANIMATION) content.setCache(true);
},
new KeyValue(transitionProperty(), transitionStartValue)
);
k2 = new KeyFrame(
duration,
event -> {
// end collapse
content.setVisible(false);
if (CACHE_ANIMATION) content.setCache(false);
},
new KeyValue(transitionProperty(), 0, Interpolator.LINEAR)
);
}
timeline.getKeyFrames().setAll(k1, k2);
timeline.play();
}
class TitleRegion extends StackPane {
private final StackPane arrowRegion;
public TitleRegion() {
getStyleClass().setAll("title");
arrowRegion = new StackPane();
arrowRegion.setId("arrowRegion");
arrowRegion.getStyleClass().setAll("arrow-button");
StackPane arrow = new StackPane();
arrow.setId("arrow");
arrow.getStyleClass().setAll("arrow");
arrowRegion.getChildren().setAll(arrow);
// RT-13294: TitledPane : add animation to the title arrow
arrow.rotateProperty().bind(new DoubleBinding() {
{ bind(transitionProperty()); }
@Override protected double computeValue() {
return -90 * (1.0 - getTransition());
}
});
setAlignment(Pos.CENTER_LEFT);
setOnMouseReleased(e -> {
if( e.getButton() != MouseButton.PRIMARY ) return;
ContextMenu contextMenu = getSkinnable().getContextMenu() ;
if (contextMenu != null) {
contextMenu.hide() ;
}
if (getSkinnable().isCollapsible() && getSkinnable().isFocused()) {
getBehavior().toggle();
}
});
// title region consists of the title and the arrow regions
update();
}
private void update() {
getChildren().clear();
final TitledPane titledPane = getSkinnable();
if (titledPane.isCollapsible()) {
getChildren().add(arrowRegion);
}
// Only in some situations do we want to have the graphicPropertyChangedListener
// installed. Since updateChildren() is not called much, we'll just remove it always
// and reinstall it later if it is necessary to do so.
if (graphic != null) {
graphic.layoutBoundsProperty().removeListener(graphicPropertyChangedListener);
}
// Now update the graphic (since it may have changed)
graphic = titledPane.getGraphic();
// Now update the children (and add the graphicPropertyChangedListener as necessary)
if (isIgnoreGraphic()) {
if (titledPane.getContentDisplay() == ContentDisplay.GRAPHIC_ONLY) {
getChildren().clear();
getChildren().add(arrowRegion);
} else {
getChildren().add(text);
}
} else {
graphic.layoutBoundsProperty().addListener(graphicPropertyChangedListener);
if (isIgnoreText()) {
getChildren().add(graphic);
} else {
getChildren().addAll(graphic, text);
}
}
setCursor(getSkinnable().isCollapsible() ? Cursor.HAND : Cursor.DEFAULT);
}
@Override protected double computePrefWidth(double height) {
double left = snappedLeftInset();
double right = snappedRightInset();
double arrowWidth = 0;
double labelPrefWidth = labelPrefWidth(height);
if (arrowRegion != null) {
arrowWidth = snapSize(arrowRegion.prefWidth(height));
}
return left + arrowWidth + labelPrefWidth + right;
}
@Override protected double computePrefHeight(double width) {
double top = snappedTopInset();
double bottom = snappedBottomInset();
double arrowHeight = 0;
double labelPrefHeight = labelPrefHeight(width);
if (arrowRegion != null) {
arrowHeight = snapSize(arrowRegion.prefHeight(width));
}
return top + Math.max(arrowHeight, labelPrefHeight) + bottom;
}
@Override protected void layoutChildren() {
final double top = snappedTopInset();
final double bottom = snappedBottomInset();
final double left = snappedLeftInset();
final double right = snappedRightInset();
double width = getWidth() - (left + right);
double height = getHeight() - (top + bottom);
double arrowWidth = snapSize(arrowRegion.prefWidth(-1));
double arrowHeight = snapSize(arrowRegion.prefHeight(-1));
double labelWidth = snapSize(Math.min(width - arrowWidth / 2.0, labelPrefWidth(-1)));
double labelHeight = snapSize(labelPrefHeight(-1));
double x = left + arrowWidth + Utils.computeXOffset(width - arrowWidth, labelWidth, hpos);
if (HPos.CENTER == hpos) {
// We want to center the region based on the entire width of the TitledPane.
x = left + Utils.computeXOffset(width, labelWidth, hpos);
}
double y = top + Utils.computeYOffset(height, Math.max(arrowHeight, labelHeight), vpos);
arrowRegion.resize(arrowWidth, arrowHeight);
positionInArea(arrowRegion, left, top, arrowWidth, height,
/*baseline ignored*/0, HPos.CENTER, VPos.CENTER);
layoutLabelInArea(x, y, labelWidth, height, pos);
}
// Copied from LabeledSkinBase because the padding from TitledPane was being
// applied to the Label when it should not be.
private double labelPrefWidth(double height) {
// Get the preferred width of the text
final Labeled labeled = getSkinnable();
final Font font = text.getFont();
final String string = labeled.getText();
boolean emptyText = string == null || string.isEmpty();
Insets labelPadding = labeled.getLabelPadding();
double widthPadding = labelPadding.getLeft() + labelPadding.getRight();
double textWidth = emptyText ? 0 : Utils.computeTextWidth(font, string, 0);
// Now add on the graphic, gap, and padding as appropriate
final Node graphic = labeled.getGraphic();
if (isIgnoreGraphic()) {
return textWidth + widthPadding;
} else if (isIgnoreText()) {
return graphic.prefWidth(-1) + widthPadding;
} else if (labeled.getContentDisplay() == ContentDisplay.LEFT
|| labeled.getContentDisplay() == ContentDisplay.RIGHT) {
return textWidth + labeled.getGraphicTextGap() + graphic.prefWidth(-1) + widthPadding;
} else {
return Math.max(textWidth, graphic.prefWidth(-1)) + widthPadding;
}
}
// Copied from LabeledSkinBase because the padding from TitledPane was being
// applied to the Label when it should not be.
private double labelPrefHeight(double width) {
final Labeled labeled = getSkinnable();
final Font font = text.getFont();
final ContentDisplay contentDisplay = labeled.getContentDisplay();
final double gap = labeled.getGraphicTextGap();
final Insets labelPadding = labeled.getLabelPadding();
final double widthPadding = snappedLeftInset() + snappedRightInset() + labelPadding.getLeft() + labelPadding.getRight();
String str = labeled.getText();
if (str != null && str.endsWith("\n")) {
// Strip ending newline so we don't count another row.
str = str.substring(0, str.length() - 1);
}
if (!isIgnoreGraphic() &&
(contentDisplay == ContentDisplay.LEFT || contentDisplay == ContentDisplay.RIGHT)) {
width -= (graphic.prefWidth(-1) + gap);
}
width -= widthPadding;
// TODO figure out how to cache this effectively.
final double textHeight = Utils.computeTextHeight(font, str,
labeled.isWrapText() ? width : 0, text.getBoundsType());
// Now we want to add on the graphic if necessary!
double h = textHeight;
if (!isIgnoreGraphic()) {
final Node graphic = labeled.getGraphic();
if (contentDisplay == ContentDisplay.TOP || contentDisplay == ContentDisplay.BOTTOM) {
h = graphic.prefHeight(-1) + gap + textHeight;
} else {
h = Math.max(textHeight, graphic.prefHeight(-1));
}
}
return h + labelPadding.getTop() + labelPadding.getBottom();
}
}
}
| gpl-2.0 |
rkunas/pm4j | pm4j-pm/src/main/java/com/hiraas/pm4j/core/PmDateTimeAttrImpl.java | 1128 | package com.hiraas.pm4j.core;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.Serializable;
/**
* Created by ramazan on 20.11.14.
*/
public class PmDateTimeAttrImpl<T_PM_PARENT extends PmImpl> extends PmAttrImpl<T_PM_PARENT, DateTime> implements Serializable {
private DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss MM.dd.yyy");
private String stringValue;
public PmDateTimeAttrImpl(T_PM_PARENT parent) {
super(parent);
}
@Override
public Class getPmAttrType() {
return DateTime.class;
}
public String getStringValue() {
if (getValue() != null) {
stringValue = formatter.print(getValue());
} else {
stringValue = formatter.print(new DateTime());
}
return stringValue;
}
public void setStringValue(String val) {
this.stringValue = val;
setValue(stringToDateTime(val));
}
private final DateTime stringToDateTime(String s) {
return formatter.parseDateTime(s);
}
}
| gpl-2.0 |
sriharshaanp/Projects | BackwardChainingInferencer/src/com/kb/KB.java | 1230 | /**
*
*/
package com.kb;
import java.util.Map;
/**
* @author sriharsha
*
*/
public class KB {
private Map<String,String> premiseLiterals;
private Map<String,String> conclusionLiterals;
private Map<String,String> factLiterals;
/**
*
*/
public KB() {
// TODO Auto-generated constructor stub
}
/**
* @return the premiseLiterals
*/
public Map<String, String> getPremiseLiterals() {
return premiseLiterals;
}
/**
* @param premiseLiterals the premiseLiterals to set
*/
public void setPremiseLiterals(Map<String, String> premiseLiterals) {
this.premiseLiterals = premiseLiterals;
}
/**
* @return the conclusionLiterals
*/
public Map<String, String> getConclusionLiterals() {
return conclusionLiterals;
}
/**
* @param conclusionLiterals the conclusionLiterals to set
*/
public void setConclusionLiterals(Map<String, String> conclusionLiterals) {
this.conclusionLiterals = conclusionLiterals;
}
/**
* @return the factLiterals
*/
public Map<String, String> getFactLiterals() {
return factLiterals;
}
/**
* @param factLiterals the factLiterals to set
*/
public void setFactLiterals(Map<String, String> factLiterals) {
this.factLiterals = factLiterals;
}
}
| gpl-2.0 |
Fidouda/LOG8430 | org.eclipse.ui.tutorials.rcp.part3/src/org/eclipse/ui/tutorials/rcp/part3/ApplicationActionBarAdvisor.java | 2607 | package org.eclipse.ui.tutorials.rcp.part3;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarContributionItem;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* An action bar advisor is responsible for creating, adding, and disposing of the
* actions added to a workbench window. Each window will be populated with
* new actions.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
// Actions - important to allocate these only in makeActions, and then use them
// in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
private IWorkbenchAction exitAction;
private IWorkbenchAction newWindowAction;
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
protected void makeActions(final IWorkbenchWindow window) {
// Creates the actions and registers them.
// Registering is needed to ensure that key bindings work.
// The corresponding commands keybindings are defined in the plugin.xml file.
// Registering also provides automatic disposal of the actions when
// the window is closed.
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
newWindowAction = ActionFactory.OPEN_NEW_WINDOW.create(window);
register(newWindowAction);
}
protected void fillMenuBar(IMenuManager menuBar) {
MenuManager fileMenu = new MenuManager("&File", IWorkbenchActionConstants.M_FILE);
menuBar.add(fileMenu);
// File
fileMenu.add(newWindowAction);
fileMenu.add(new Separator());
fileMenu.add(exitAction);
}
protected void fillCoolBar(ICoolBarManager coolBar) {
IToolBarManager toolbar = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
coolBar.add(new ToolBarContributionItem(toolbar, "main"));
}
}
| gpl-2.0 |
truhanen/JSana | JSana/src/tietorakenteet/Esivalinnat.java | 10718 | /*******************************************************************************
* Copyright (C) 2013, 2015 Tuukka Ruhanen
*
* JSana is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* JSana 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 JSana; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*******************************************************************************/
package tietorakenteet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* <pre>
* Esivalintojen käsittelijäluokka.
*
* Vastuualueet:
* - uuden esivalinnan lisääminen
* - esivalintojen tallentaminen tiedostoon
* - esivalintojen järjesteleminen
* </pre>
* @author Tuukka R.
* @version Mar 8, 2012
* @example
* <pre name="test">
* Esivalinnat evt = new Esivalinnat();
* Esivalinta ev = new Esivalinta("1.Moos.1:1");
* Esivalinta ev2 = new Esivalinta("1.Moos.1:2");
*
* evt.lisaa(ev);
* evt.lisaa(ev2);
* evt.anna(0).equals(ev) === true;
*
* evt.poista(0);
* evt.anna(0).equals(ev2) === true;
* evt.getLkm() === 1;
* evt.lisaa(ev);
* evt.siirraYlosAlas(0, 1);
* evt.anna(0).equals(ev) === true;
* for (Esivalinta eva : evt) // iteraattorin testaus
* evt.getLkm() === 2;
* </pre>
*/
public class Esivalinnat implements Iterable<Esivalinta> {
private static final int MAX_LKM = 10;
private final String TIEDOSTOPAATE = "sch";
private int lkm = 0;
private Esivalinta[] alkiot = new Esivalinta[MAX_LKM];
private File tiedosto;
private boolean muutettu = false;
/**
* Oletusmuodostaja
*/
public Esivalinnat() {
// attribuuttien oma alustus riittää
}
/**
* Uuden esivalinnan lisääminen. Esivalintataulukon kokoa kasvatetaan tarvittaessa.
* @param eV lisättävä esivalinta
*/
public void lisaa(Esivalinta eV) {
if (lkm >= alkiot.length) {
Esivalinta[] alkiotOld = alkiot;
alkiot = new Esivalinta[lkm + 10];
for (int i = 0; i < lkm; i++) {
alkiot[i] = alkiotOld[i];
}
}
muutettu = true;
alkiot[lkm++] = eV;
}
/**
* Korvaa paikassa i olevan esivalinnan eV:llä.
* @param i
* @param eV
*/
public void replace(int i, Esivalinta eV) {
alkiot[i] = eV;
}
/**
* Poistaa indeksissä i olevan esivalinnan
* @param i indeksin numero, jota vastaava esivalinta poistetaan
*/
public void poista(int i) {
// tarkistetaan järkevyys TODO Errorit?
if (i < 0 || i >= lkm)
return;
muutettu = true;
lkm--;
for (int j = i; j < lkm; j++)
alkiot[j] = alkiot[j + 1];
alkiot[lkm] = null;
}
/**
* Poistaa kaikki esivalinnat (laittaa nulleiksi)
*/
public void tyhjenna() {
if (lkm == 0)
return;
muutettu = true;
for (int j = 0; j < lkm; j++)
alkiot[j] = null;
lkm = 0;
}
/**
* Antaa halutun Esivalinta-olion
* @param i halutun esivalinnan indeksi Esivalinnat-tietorakenteessa
* @return indeksiä i vastaava Esivalinta-olio
*/
public Esivalinta anna(int i) {
if (i < 0 || lkm <= i)
return null;
return alkiot[i];
}
// public void setNaytetty(int index, boolean naytetty) {
// alkiot[index].setNaytetty(naytetty);
// }
// public void nollaa() {
// for (Esivalinta eV : this) {
// eV.setNaytetty(false);
// }
// }
/**
* Palauttaa luotujen esivalintojen lukumäärän
* @return esivalintojen lukumäärä
*/
public int getLkm() {
return lkm;
}
/**
* Esivalinnan siirtäminen tietorakenteessa yläs tai alas.
* Käytännässä vaihtaa kahden alkion järjestystä ArrayListissä
* @param i siirrettävän esivalinnan indeksi
* @param suunta arvolla 1 alaspäin, arvolla -1 yläspäin
* @return the resulting index, -1 if nothing was done
*/
public int siirraYlosAlas(int i, int suunta) {
// ensin tarkistetaan järkevyys TODO Errorit?
if (i < 0 || i >= alkiot.length || Math.abs(suunta) != 1 || i + suunta == -1 || i + suunta == getLkm())
return -1;
muutettu = true;
Esivalinta eVTemp = alkiot[i + suunta];
alkiot[i + suunta] = alkiot[i];
alkiot[i] = eVTemp;
return i + suunta;
}
/**
* Iteraattori, joka käy luodut esivalinnat läpi
* @return itse tehty iteraattori
*/
@Override
public Iterator<Esivalinta> iterator() {
return new EsivalinnatIterator();
}
/**
* Oma iteraattori esivalinnoille
* @author Tuukka Ruhanen
* @version Mar 12, 2012
*/
public class EsivalinnatIterator implements Iterator<Esivalinta> {
private int kohdalla = -1;
@Override
public boolean hasNext() {
return kohdalla + 1 < lkm;
}
@Override
public Esivalinta next() throws NoSuchElementException {
if (!hasNext())
throw new NoSuchElementException("Ei ole enempää alkioita.");
kohdalla++;
return alkiot[kohdalla];
}
// poistamista ei tueta
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Poistamista ei tueta.");
}
}
/**
* Esivalintatiedoston sisällön lukeminen esivalinnoiksi
* @param tiedostoTemp luettava tiedosto; luetaan ensimmäinen juurihakemistosta löytyvä tiedosto, jos null
*/
public void lueTiedostosta(File tiedostoTemp) {
if (tiedostoTemp == null || !tiedostoTemp.exists()) {
tiedosto = lueEnsimmainen();
} else
tiedosto = tiedostoTemp;
if (tiedosto == null || tiedosto.getName().length() == 0)
return;
this.tyhjenna();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(tiedosto));
String rivi;
while ((rivi = in.readLine()) != null) {
// TODO Heittämään omaa erroria?
Esivalinta eV = new Esivalinta(rivi);
lisaa(eV);
}
} catch (FileNotFoundException ex) {
System.err.println("Input-tiedostoa ei läytynyt: " + ex.getMessage());
} catch (IOException ex) {
System.err.println("Input-tiedoston sisällässä on jotain vikaa: " + ex.getMessage());
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Hakee juurihakemistosta esivalintatiedostoa
* @return löytynyt esivalintatiedosto; null, jos ei löytynyt
*/
private File lueEnsimmainen() {
try {
String jarPath = Esivalinnat.class.getProtectionDomain().getCodeSource().getLocation().getPath();
jarPath = jarPath.substring(0, jarPath.lastIndexOf("/") + 1);
jarPath = URLDecoder.decode(jarPath, "UTF-8");
File[] filesWithJar = new File(jarPath).listFiles();
String workingPath = "./";
File[] filesWorking = new File(workingPath).listFiles();
File[] bothFiles = new File[filesWithJar.length + filesWorking.length];
System.arraycopy(filesWithJar, 0, bothFiles, 0, filesWithJar.length);
System.arraycopy(filesWorking, 0, bothFiles, filesWithJar.length, filesWorking.length);
if (bothFiles[0] == null)
return null;
for (File f : bothFiles) {
String name = f.getName();
int i = name.lastIndexOf('.');
String ext = null;
if (i > 0 && i < name.length() - 1) {
ext = name.substring(i + 1).toLowerCase();
}
if (ext != null && ext.equals(TIEDOSTOPAATE)) {
return f;
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Esivalintojen tallentaminen tekstitiedostoksi
* @param tiedostoTemp tallennettava tiedosto; tallennetaan alkuperäiseen, jos null. Mikäli kaikki esivalinnat on poistettu, tiedostokin poistetaan
* @return tallennetun tiedoston canonicalpath (null jos tiedostoa ei löydy tai sattuu virhe)
*/
public String tallennaTiedostoon(File tiedostoTemp) {
if (tiedostoTemp != null)
tiedosto = tiedostoTemp;
else {
if (tiedosto == null)
return null; // pitää luoda uusi tiedosto ("tallenna nimellä")
if (!muutettu)
return tiedosto.getAbsolutePath(); // ei suoriteta toimenpiteitä
}
tiedosto.delete();
if (getLkm() == 0) // jos tietorakenne on tyhjä, suoritetaan ainoastaan tiedoston poisto
return tiedosto.getAbsolutePath();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(tiedosto));
for (Esivalinta eV : this)
out.println(eV);
} catch (FileNotFoundException ex) {
System.err.println("Esivalintatiedosto ei aukea: " + ex.getMessage());
} finally {
if (out != null)
out.close();
}
muutettu = false;
return tiedosto.getAbsolutePath();
}
}
| gpl-2.0 |
ivaivalous/cfollow | server/api/src/main/java/bg/tsarstva/follow/api/webadmin/endpoint/SetUsername.java | 2036 | package bg.tsarstva.follow.api.webadmin.endpoint;
import java.sql.SQLException;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import bg.tsarstva.follow.api.database.query.SetUsernameQuery;
import bg.tsarstva.follow.api.security.jwt.UserJwt;
import bg.tsarstva.follow.api.webadmin.response.AuthenticationFailureResponse;
import bg.tsarstva.follow.api.webadmin.response.SetUsernameResponseBuilder;
import bg.tsarstva.follow.api.webadmin.response.SqlErrorResponse;
/**
* User register API
* @see https://github.com/ivaivalous/cfollow/wiki/%5BSPEC%5D-Follow-API-WebAdmin-Requests-Specification
* @author ivaylo.marinkov
*
*/
@Path("webadmin/setUsername")
public class SetUsername {
public SetUsername() {};
private static final Logger LOGGER = Logger.getLogger(SetUsername.class.getName());
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response setUsername(
@FormParam(value = "email") String email,
@FormParam(value = "newUsername") String newUsername,
@HeaderParam(value = "Authorization") String jwt
) {
SetUsernameQuery query;
SetUsernameResponseBuilder responseBuilder;
if(!UserJwt.validateJwt(jwt)) {
return Response.status(Status.UNAUTHORIZED).entity(new AuthenticationFailureResponse().getResponse().toString()).build();
}
try {
query = new SetUsernameQuery(email, newUsername).execute();
responseBuilder = new SetUsernameResponseBuilder(query);
} catch(SQLException | ClassNotFoundException e) {
LOGGER.severe("SQL error inserting new user: " + e.getMessage());
return Response.serverError().entity(new SqlErrorResponse().getResponse()).build();
}
return Response.ok().entity(responseBuilder.getResponse().toString()).build();
}
} | gpl-2.0 |
ttylinux/CodePiece | Animation/PropertyAnimation/PropertyAnims/TestPropertyAnimationActivity.java | 6009 | package com.androidbook.propertyanimation;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.TextView;
public class TestPropertyAnimationActivity extends Activity
{
private static String tag = "My activity";
private TextView m_tv = null;
private MyAnimatableView m_atv = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gatherControls();
}
private void gatherControls()
{
m_tv = (TextView)this.findViewById(R.id.tv_id);
m_atv = new MyAnimatableView(m_tv);
}
public void toggleAnimation(View btnView)
{
Button tButton = (Button)btnView;
//m_tv该对象必须要有相应的setter方法,在这里,要有setAlpha方法,且是public
if (m_tv.getAlpha() != 0)
{
ObjectAnimator fadeOut =
ObjectAnimator.ofFloat(m_tv, "alpha", 0f);
fadeOut.setDuration(5000);
fadeOut.start();
tButton.setText("Fade In");
}
else
{
ObjectAnimator fadeIn =
ObjectAnimator.ofFloat(m_tv, "alpha", 1f);
fadeIn.setDuration(5000);
fadeIn.start();
tButton.setText("Fade out");
}
}
public void sequentialAnimation(View bView)
{
m_tv.setAlpha(1f);
ObjectAnimator fadeOut =
ObjectAnimator.ofFloat(m_tv, "alpha", 0f);
ObjectAnimator fadeIn =
ObjectAnimator.ofFloat(m_tv, "alpha", 1f);
//通过AnimatorSet来组合多个动画对象ObjectAnimator
AnimatorSet as = new AnimatorSet();
as.playSequentially(fadeOut,fadeIn);
as.setDuration(5000); //5 secs
as.start();
}
public void sequentialAnimationXML(View bView)
{
//动画效果可以再XML文件中描述
m_tv.setAlpha(1f);
AnimatorSet set = (AnimatorSet)
AnimatorInflater.loadAnimator(this,
R.animator.fadein);
set.setTarget(m_tv);
set.start();
}
public void testAnimationBuilder(View v)
{
m_tv.setAlpha(1f);
ObjectAnimator fadeOut =
ObjectAnimator.ofFloat(m_tv, "alpha", 0f);
ObjectAnimator fadeIn =
ObjectAnimator.ofFloat(m_tv, "alpha", 1f);
AnimatorSet as = new AnimatorSet();
as.play(fadeOut).before(fadeIn); //fadeIn效果先于fadeOut发生。
as.setDuration(2000); //2 secs
as.start();
}
public void testPropertiesHolder(View v)
{
m_tv.setAlpha(1f);
float h = m_tv.getHeight();
float w = m_tv.getWidth();
float x = m_tv.getX();
float y = m_tv.getY();
//设置m_tv的当前位置
m_tv.setX(w);
m_tv.setY(h);
//Go to 50 on x
//这里设定的x是最终位置,而开始位置,由系统自己获取。
PropertyValuesHolder pvhX =
PropertyValuesHolder.ofFloat("x", x);
//Go to 100 on y
PropertyValuesHolder pvhY =
PropertyValuesHolder.ofFloat("y", y);
ObjectAnimator oa
= ObjectAnimator.ofPropertyValuesHolder(m_tv, pvhX, pvhY);
oa.setDuration(5000); //5 secs
//开始和结束慢速,中间快速
oa.setInterpolator(
new AccelerateDecelerateInterpolator());
oa.start();
}
public void testViewAnimator(View v)
{
m_tv.setAlpha(1f);
float h = m_tv.getHeight();
float w = m_tv.getWidth();
float x = m_tv.getX();
float y = m_tv.getY();
m_tv.setX(w);
m_tv.setY(h);
ViewGroup layout = (ViewGroup)m_tv.getParent();
layout.setClipChildren(true);
//Go to 50 on x
ViewPropertyAnimator vpa = m_tv.animate();
vpa.x(x);
vpa.y(y);
vpa.setDuration(5000); //5 secs
vpa.setInterpolator(
new AccelerateDecelerateInterpolator());
//vpa.start();
}
public void testTypeEvaluator(View v)
{
m_tv.setAlpha(1f);
float h = m_tv.getHeight();
float w = m_tv.getWidth();
float x = m_tv.getX();
float y = m_tv.getY();
//m_atv要有公开的方法setpoint
ObjectAnimator tea =
ObjectAnimator.ofObject(m_atv
,"point"
,new MyPointEvaluator()
,new PointF(w,h)
,new PointF(x,y));
tea.setDuration(5000);
tea.start();
}
public void testKeyFrames(View v)
{
m_tv.setAlpha(1f);
float h = m_tv.getHeight();
float w = m_tv.getWidth();
float x = m_tv.getX();
float y = m_tv.getY();
//Start frame : 0.2--总时间的20%处
//alpha: 0.8
Keyframe kf0 = Keyframe.ofFloat(0.2f, 0.8f);
//Middle frame: 0.5
//alpha: 0.2
Keyframe kf1 = Keyframe.ofFloat(.5f, 0.2f);
//end frame: 0.8
//alpha: 0.8
Keyframe kf2 = Keyframe.ofFloat(0.8f, 0.8f);
//设定了在整个动画时间中,会出现三个关键帧:
//处于20%的时间点,透明度为0.8;
//处于50%的时间点,透明度为0.2f;
//处于80%的时间点,透明度为0.8
PropertyValuesHolder pvhAlpha =
PropertyValuesHolder.ofKeyframe("alpha", kf0, kf1, kf2);
//从w移动到x--横坐标。
PropertyValuesHolder pvhX =
PropertyValuesHolder.ofFloat("x", w, x);
//end frame
ObjectAnimator anim =
ObjectAnimator.ofPropertyValuesHolder(m_tv, pvhAlpha,pvhX);
anim.setDuration(5000);
anim.start();
}
}
| gpl-2.0 |
gengjian1203/PlayFace | app/src/androidTest/java/com/mbpr/gengjian/playface/ApplicationTest.java | 357 | package com.mbpr.gengjian.playface;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | gpl-2.0 |
RomRaider/original.mirror | installer/IzPack/src/lib/com/izforge/izpack/panels/PacksPanelInterface.java | 1535 | /*
* IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2004 Gaganis Giorgos
*
* 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.izforge.izpack.panels;
import com.izforge.izpack.LocaleDatabase;
/**
* This interface is used to be able to access the common information in the PackPanel and the
* ImgPacksPAnel through a common type. I introduced it so that I can remove the duplicate
* PacksModel from each class and create a common one for both.
*
* This could be avoided by inheriting ImgPacksPanel from PacksPanel
*
* User: Gaganis Giorgos Date: Sep 17, 2004 Time: 8:29:22 AM
*/
/*
* @todo evaluate whether we want to eliminate this interface with inheritance
*/
public interface PacksPanelInterface
{
public LocaleDatabase getLangpack();
public int getBytes();
public void setBytes(int bytes);
public void showSpaceRequired();
public void showFreeSpace();
}
| gpl-2.0 |
RomRaider/original.mirror | installer/IzPack/src/lib/com/izforge/izpack/compiler/Property.java | 9822 | /*
* IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2004 Chadwick McHenry
*
* 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.izforge.izpack.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import net.n3.nanoxml.XMLElement;
import org.apache.tools.ant.taskdefs.Execute;
import com.izforge.izpack.util.VariableSubstitutor;
/**
* Sets a property by name, or set of properties (from file or resource) in the project. This is
* modeled after ant properties
* <p>
*
* Properties are immutable: once a property is set it cannot be changed. They are most definately
* not variable.
* <p>
*
* There are five ways to set properties:
* <ul>
* <li>By supplying both the <i>name</i> and <i>value</i> attributes.</li>
* <li>By setting the <i>file</i> attribute with the filename of the property file to load. This
* property file has the format as defined by the file used in the class java.util.Properties.</li>
* <li>By setting the <i>environment</i> attribute with a prefix to use. Properties will be
* defined for every environment variable by prefixing the supplied name and a period to the name of
* the variable.</li>
* </ul>
*
* Combinations of the above are considered an error.
* <p>
*
* The value part of the properties being set, might contain references to other properties. These
* references are resolved when the properties are set.
* <p>
*
* This also holds for properties loaded from a property file.
* <p>
*
* Properties are case sensitive.
* <p>
*
* When specifying the environment attribute, it's value is used as a prefix to use when retrieving
* environment variables. This functionality is currently only implemented on select platforms.
* <p>
*
* Thus if you specify environment="myenv" you will be able to access OS-specific
* environment variables via property names "myenv.PATH" or "myenv.TERM".
* <p>
*
* Note also that properties are case sensitive, even if the environment variables on your operating
* system are not, e.g. it will be ${env.Path} not ${env.PATH} on Windows 2000.
* <p>
*
* Note that when specifying either the <code>prefix</code> or <code>environment</code>
* attributes, if you supply a property name with a final "." it will not be doubled. ie
* environment="myenv." will still allow access of environment variables through
* "myenv.PATH" and "myenv.TERM".
* <p>
*/
public class Property
{
protected String name;
protected String value;
protected File file;
// protected String resource;
// protected Path classpath;
protected String env;
// protected Reference ref;
protected String prefix;
protected XMLElement xmlProp;
protected CompilerConfig config;
protected Compiler compiler;
public Property(XMLElement xmlProp, CompilerConfig config)
{
this.xmlProp = xmlProp;
this.config = config;
this.compiler = config.getCompiler();
name = xmlProp.getAttribute("name");
value = xmlProp.getAttribute("value");
env = xmlProp.getAttribute("environment");
if (env != null && !env.endsWith(".")) env += ".";
prefix = xmlProp.getAttribute("prefix");
if (prefix != null && !prefix.endsWith(".")) prefix += ".";
String filename = xmlProp.getAttribute("file");
if (filename != null) file = new File(filename);
}
/**
* get the value of this property
*
* @return the current value or the empty string
*/
public String getValue()
{
return toString();
}
/**
* get the value of this property
*
* @return the current value or the empty string
*/
public String toString()
{
return value == null ? "" : value;
}
/**
* Set the property in the project to the value. If the task was give a file, resource or env
* attribute here is where it is loaded.
*/
public void execute() throws CompilerException
{
if (name != null)
{
if (value == null)
config.parseError(xmlProp, "You must specify a value with the name attribute");
}
else
{
if (file == null && env == null)
config.parseError(xmlProp,
"You must specify file, or environment when not using the name attribute");
}
if (file == null && prefix != null)
config.parseError(xmlProp, "Prefix is only valid when loading from a file ");
if ((name != null) && (value != null))
addProperty(name, value);
else if (file != null)
loadFile(file);
else if (env != null) loadEnvironment(env);
}
/**
* load properties from a file
*
* @param file file to load
*/
protected void loadFile(File file) throws CompilerException
{
Properties props = new Properties();
config.getPackagerListener().packagerMsg("Loading " + file.getAbsolutePath(),
PackagerListener.MSG_VERBOSE);
try
{
if (file.exists())
{
FileInputStream fis = new FileInputStream(file);
try
{
props.load(fis);
}
finally
{
if (fis != null) fis.close();
}
addProperties(props);
}
else
{
config.getPackagerListener().packagerMsg(
"Unable to find property file: " + file.getAbsolutePath(),
PackagerListener.MSG_VERBOSE);
}
}
catch (IOException ex)
{
config.parseError(xmlProp, "Faild to load file: " + file.getAbsolutePath(), ex);
}
}
/**
* load the environment values
*
* @param prefix prefix to place before them
*/
protected void loadEnvironment(String prefix) throws CompilerException
{
Properties props = new Properties();
config.getPackagerListener().packagerMsg("Loading Environment " + prefix,
PackagerListener.MSG_VERBOSE);
Vector osEnv = Execute.getProcEnvironment();
for (Enumeration e = osEnv.elements(); e.hasMoreElements();)
{
String entry = (String) e.nextElement();
int pos = entry.indexOf('=');
if (pos == -1)
{
config.getPackagerListener().packagerMsg("Ignoring " + prefix,
PackagerListener.MSG_WARN);
}
else
{
props.put(prefix + entry.substring(0, pos), entry.substring(pos + 1));
}
}
addProperties(props);
}
/**
* Add a name value pair to the project property set
*
* @param name name of property
* @param value value to set
*/
protected void addProperty(String name, String value) throws CompilerException
{
value = compiler.replaceProperties(value);
compiler.addProperty(name, value);
}
/**
* iterate through a set of properties, resolve them then assign them
*/
protected void addProperties(Properties props) throws CompilerException
{
resolveAllProperties(props);
Enumeration e = props.keys();
while (e.hasMoreElements())
{
String name = (String) e.nextElement();
String value = props.getProperty(name);
if (prefix != null)
{
name = prefix + name;
}
addProperty(name, value);
}
}
/**
* resolve properties inside a properties object
*
* @param props properties to resolve
*/
private void resolveAllProperties(Properties props) throws CompilerException
{
VariableSubstitutor subs = new VariableSubstitutor(props);
subs.setBracesRequired(true);
for (Enumeration e = props.keys(); e.hasMoreElements();)
{
String name = (String) e.nextElement();
String value = props.getProperty(name);
int mods = -1;
do
{
StringReader read = new StringReader(value);
StringWriter write = new StringWriter();
try
{
mods = subs.substitute(read, write, "at");
// TODO: check for circular references. We need to know
// which
// variables were substituted to do that
props.put(name, value);
}
catch (IOException ex)
{
config.parseError(xmlProp, "Faild to load file: " + file.getAbsolutePath(),
ex);
}
}
while (mods != 0);
}
}
}
| gpl-2.0 |
plotters/prosc-woof | Fmp360_JDBC/src/com/prosc/fmpjdbc/util/ProcessExecutionException.java | 1126 | package com.prosc.fmpjdbc.util;
import com.prosc.fmpjdbc.util.StringUtils;
/**
* Created by IntelliJ IDEA. User: jesse Date: Mar 4, 2010 Time: 8:30:23 AM
*/
public class ProcessExecutionException extends Exception {
private byte[] data;
private int exitStatus;
public ProcessExecutionException( byte[] data, String errorMessage, int exitStatus ) {
super( errorMessage );
this.data = data;
this.exitStatus = exitStatus;
}
public byte[] getData() {
return data;
}
public int getExitStatus() {
return exitStatus;
}
//FIX! This is specific to FileMaker Server. Move this code into whatever calls this method.
public Integer getErrorCode() {
String errorCodeString = StringUtils.textBetween(getMessage(), "Error: ", StringUtils.CR);
if( errorCodeString == null ) {
return null;
} else {
int mark1 = errorCodeString.indexOf( ' ' );
if( mark1 != -1 ) {
errorCodeString = errorCodeString.substring( 0, mark1 ).trim(); //Strip out everything prior to the first space. Sometimes we get replies like this: "809 (Unknown error)"
}
return Integer.valueOf( errorCodeString );
}
}
}
| gpl-2.0 |
vnu-dse/rtl | src/rtl/org/tzi/rtl/tgg/mm/MTggRuleSelectedApplication.java | 572 | package org.tzi.rtl.tgg.mm;
public class MTggRuleSelectedApplication extends MTggRuleApplication {
private String ruleID;
private Object fCondition;
public MTggRuleSelectedApplication(){
}
public MTggRuleSelectedApplication(String _ruleID, Object _cond){
ruleID = _ruleID;
fCondition = _cond;
}
public void setRuleID(String ruleID) {
this.ruleID = ruleID;
}
public String getRuleID() {
return ruleID;
}
public void setfCondition(Object fCondition) {
this.fCondition = fCondition;
}
public Object getfCondition() {
return fCondition;
}
}
| gpl-2.0 |
iriber/miGestionSwing | src/main/java/com/migestion/swing/view/inputs/InputLengthValidator.java | 880 | package com.migestion.swing.view.inputs;
import javax.swing.JComponent;
/**
* Colabora con las validaciones de los inputs
* para longitudes permitidas.
*
* @author Bernardo Iribarne
*
*/
public class InputLengthValidator extends InputValidator{
private Integer maxSize;
private Integer minSize;
public InputLengthValidator(){
maxSize = null;
minSize = null;
}
public InputLengthValidator(Integer maxSize, Integer minSize){
this.maxSize = maxSize;
this.minSize = minSize;
}
public Boolean validate( InputInspector inspector, JComponent component ){
Object object = inspector.getValue(component);
Boolean ok = Boolean.TRUE;
if( maxSize != null)
ok = ok && ((String)object).length() <= maxSize;
if( minSize != null)
ok = ok && ((String)object).length() >= maxSize;
return ok;
}
}
| gpl-2.0 |
imclab/WebImageBrowser | WIB/src/java/edu/ucsd/ncmir/WIB/client/plugins/SLASHPlugin/messages/ThreeDGeometryUpdateMessage.java | 253 | package edu.ucsd.ncmir.WIB.client.plugins.SLASHPlugin.messages;
import edu.ucsd.ncmir.WIB.client.core.messages.ToggleDialogVisibilityMessage;
/**
*
* @author spl
*/
public class ThreeDGeometryUpdateMessage extends ToggleDialogVisibilityMessage {}
| gpl-2.0 |
codelibs/n2dms | src/main/java/com/openkm/servlet/admin/OmrServlet.java | 18962 | /**
*
*
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet.admin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.openkm.core.*;
import net.sourceforge.jiu.codecs.InvalidFileStructureException;
import net.sourceforge.jiu.codecs.InvalidImageIndexException;
import net.sourceforge.jiu.codecs.UnsupportedTypeException;
import net.sourceforge.jiu.ops.MissingParameterException;
import net.sourceforge.jiu.ops.WrongParameterException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.dao.OmrDAO;
import com.openkm.dao.bean.Omr;
import com.openkm.omr.OMRHelper;
import com.openkm.util.FileUtils;
import com.openkm.util.OMRException;
import com.openkm.util.PropertyGroupUtils;
import com.openkm.util.UserActivity;
import com.openkm.util.WebUtils;
/**
* omr servlet
*/
public class OmrServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(OmrServlet.class);
private static final int FILE_TEMPLATE = 1;
private static final int FILE_ASC = 2;
private static final int FILE_CONFIG = 3;
private static final int FILE_FIELDS = 4;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
log.debug("doGet({}, {})", request, response);
request.setCharacterEncoding("UTF-8");
String action = WebUtils.getString(request, "action");
String userId = request.getRemoteUser();
updateSessionManager(request);
try {
if (action.equals("create")) {
create(userId, request, response);
} else if (action.equals("edit")) {
edit(userId, request, response);
} else if (action.equals("delete")) {
delete(userId, request, response);
} else if (action.equals("downloadFile")) {
downloadFile(userId, request, response);
} else if (action.equals("editAsc")) {
editAscFile(userId, request, response);
} else if (action.equals("editFields")) {
editFieldsFile(userId, request, response);
} else if (action.equals("check")) {
check(userId, request, response);
} else {
list(userId, request, response);
}
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
sendErrorRedirect(request, response, e);
} catch (Exception e) {
log.error(e.getMessage(), e);
sendErrorRedirect(request, response, e);
}
}
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
log.debug("doPost({}, {})", request, response);
request.setCharacterEncoding("UTF-8");
String action = "";
String userId = request.getRemoteUser();
updateSessionManager(request);
try {
if (ServletFileUpload.isMultipartContent(request)) {
String fileName = null;
InputStream is = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Set<String> properties = new HashSet<String>();
Omr om = new Omr();
for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
FileItem item = it.next();
if (item.isFormField()) {
if (item.getFieldName().equals("action")) {
action = item.getString("UTF-8");
} else if (item.getFieldName().equals("om_id")) {
om.setId(Integer.parseInt(item.getString("UTF-8")));
} else if (item.getFieldName().equals("om_name")) {
om.setName(item.getString("UTF-8"));
} else if (item.getFieldName().equals("om_properties")) {
properties.add(item.getString("UTF-8"));
} else if (item.getFieldName().equals("om_active")) {
om.setActive(true);
}
} else {
is = item.getInputStream();
fileName = item.getName();
}
}
om.setProperties(properties);
if (action.equals("create") || action.equals("edit")) {
// Store locally template file to be used later
if (is != null && is.available() > 0) { // Case update only name
byte[] data = IOUtils.toByteArray(is);
File tmp = FileUtils.createTempFile();
FileOutputStream fos = new FileOutputStream(tmp);
IOUtils.write(data, fos);
IOUtils.closeQuietly(fos);
// Store template file
om.setTemplateFileName(FilenameUtils.getName(fileName));
om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
om.setTemplateFilContent(data);
IOUtils.closeQuietly(is);
// Create training files
Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);
// Store asc file
om.setAscFileName(om.getTemplateFileName() + ".asc");
om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
is = new FileInputStream(ascFile);
om.setAscFileContent(IOUtils.toByteArray(is));
IOUtils.closeQuietly(is);
// Store config file
om.setConfigFileName(om.getTemplateFileName() + ".config");
om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
is = new FileInputStream(configFile);
om.setConfigFileContent(IOUtils.toByteArray(is));
IOUtils.closeQuietly(is);
// Delete temporal files
FileUtils.deleteQuietly(tmp);
FileUtils.deleteQuietly(ascFile);
FileUtils.deleteQuietly(configFile);
}
if (action.equals("create")) {
long id = OmrDAO.getInstance().create(om);
// Activity log
UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
} else if (action.equals("edit")) {
OmrDAO.getInstance().updateTemplate(om);
om = OmrDAO.getInstance().findByPk(om.getId());
// Activity log
UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
}
list(userId, request, response);
} else if (action.equals("delete")) {
OmrDAO.getInstance().delete(om.getId());
// Activity log
UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
list(userId, request, response);
} else if (action.equals("editAsc")) {
Omr omr = OmrDAO.getInstance().findByPk(om.getId());
omr.setAscFileContent(IOUtils.toByteArray(is));
omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
omr.setAscFileName(omr.getTemplateFileName() + ".asc");
OmrDAO.getInstance().update(omr);
omr = OmrDAO.getInstance().findByPk(om.getId());
IOUtils.closeQuietly(is);
// Activity log
UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
list(userId, request, response);
} else if (action.equals("editFields")) {
Omr omr = OmrDAO.getInstance().findByPk(om.getId());
omr.setFieldsFileContent(IOUtils.toByteArray(is));
omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
OmrDAO.getInstance().update(omr);
omr = OmrDAO.getInstance().findByPk(om.getId());
IOUtils.closeQuietly(is);
// Activity log
UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
list(userId, request, response);
} else if (action.equals("check")) {
File form = FileUtils.createTempFile();
OutputStream formFile = new FileOutputStream(form);
formFile.write(IOUtils.toByteArray(is));
IOUtils.closeQuietly(formFile);
formFile.close();
Map<String, String> results = OMRHelper.process(form, om.getId());
FileUtils.deleteQuietly(form);
IOUtils.closeQuietly(is);
UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
results(userId, request, response, action, results, om.getId());
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
sendErrorRedirect(request, response, e);
}
}
/**
* List omr templates
*/
private void list(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,
DatabaseException {
log.debug("list({}, {}, {})", new Object[] { userId, request, response });
ServletContext sc = getServletContext();
List<Omr> list = OmrDAO.getInstance().findAll();
sc.setAttribute("omr", list);
sc.getRequestDispatcher("/admin/omr_list.jsp").forward(request, response);
log.debug("list: void");
}
/**
* New omr template
*/
private void create(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,
DatabaseException, ParseException, AccessDeniedException, RepositoryException {
log.debug("create({}, {}, {})", new Object[] { userId, request, response });
ServletContext sc = getServletContext();
Omr om = new Omr();
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", om);
sc.setAttribute("properties", PropertyGroupUtils.getAllGroupsProperties());
sc.getRequestDispatcher("/admin/omr_edit.jsp").forward(request, response);
log.debug("create: void");
}
/**
* edit type record
*/
private void edit(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,
DatabaseException, ParseException, AccessDeniedException, RepositoryException {
log.debug("edit({}, {}, {})", new Object[] { userId, request, response });
ServletContext sc = getServletContext();
long omId = WebUtils.getLong(request, "om_id");
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.setAttribute("properties", PropertyGroupUtils.getAllGroupsProperties());
sc.getRequestDispatcher("/admin/omr_edit.jsp").forward(request, response);
log.debug("edit: void");
}
/**
* delete type record
*/
private void delete(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,
DatabaseException {
log.debug("delete({}, {}, {})", new Object[] { userId, request, response });
ServletContext sc = getServletContext();
long omId = WebUtils.getLong(request, "om_id");
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.getRequestDispatcher("/admin/omr_edit.jsp").forward(request, response);
log.debug("delete: void");
}
/**
* download file
*/
private void downloadFile(String userId, HttpServletRequest request, HttpServletResponse response) throws DatabaseException,
IOException {
log.debug("downloadFile({}, {}, {})", new Object[] { userId, request, response });
long omId = WebUtils.getLong(request, "om_id");
int fileType = WebUtils.getInt(request, "type");
Omr omr = OmrDAO.getInstance().findByPk(omId);
if (omr != null && fileType >= FILE_TEMPLATE && fileType <= FILE_FIELDS) {
OutputStream os = response.getOutputStream();
try {
byte[] fileContent = null;
switch (fileType) {
case FILE_TEMPLATE:
fileContent = omr.getTemplateFileContent();
WebUtils.prepareSendFile(request, response, omr.getTemplateFileName(), omr.getTemplateFileMime(), false);
break;
case FILE_ASC:
fileContent = omr.getAscFileContent();
WebUtils.prepareSendFile(request, response, omr.getAscFileName(), omr.getAscFileMime(), false);
break;
case FILE_CONFIG:
fileContent = omr.getConfigFileContent();
WebUtils.prepareSendFile(request, response, omr.getConfigFileName(), omr.getConfigFileMime(), false);
break;
case FILE_FIELDS:
fileContent = omr.getFieldsFileContent();
WebUtils.prepareSendFile(request, response, omr.getFieldsFileName(), omr.getFieldsFileMime(), false);
break;
}
if (fileContent != null) {
response.setContentLength(fileContent.length);
os.write(fileContent);
os.flush();
}
} finally {
IOUtils.closeQuietly(os);
}
}
log.debug("downloadFile: void");
}
/**
* editAscFile
*/
private void editAscFile(String userId, HttpServletRequest request, HttpServletResponse response) throws DatabaseException,
ServletException, IOException {
ServletContext sc = getServletContext();
long omId = WebUtils.getLong(request, "om_id");
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.getRequestDispatcher("/admin/omr_edit_asc.jsp").forward(request, response);
log.debug("editAscFile: void");
}
/**
* editFieldsFile
*/
private void editFieldsFile(String userId, HttpServletRequest request, HttpServletResponse response) throws DatabaseException,
ServletException, IOException {
ServletContext sc = getServletContext();
long omId = WebUtils.getLong(request, "om_id");
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.getRequestDispatcher("/admin/omr_edit_fields.jsp").forward(request, response);
log.debug("editFieldsFile: void");
}
/**
* check
*/
private void check(String userId, HttpServletRequest request, HttpServletResponse response) throws DatabaseException, ServletException,
IOException {
ServletContext sc = getServletContext();
long omId = WebUtils.getLong(request, "om_id");
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.setAttribute("results", null);
sc.getRequestDispatcher("/admin/omr_check.jsp").forward(request, response);
log.debug("check: void");
}
/**
* results
*/
private void results(String userId, HttpServletRequest request, HttpServletResponse response, String action,
Map<String, String> results, long omId) throws DatabaseException, ServletException, IOException {
ServletContext sc = getServletContext();
sc.setAttribute("action", action);
sc.setAttribute("om", OmrDAO.getInstance().findByPk(omId));
sc.setAttribute("results", results);
sc.getRequestDispatcher("/admin/omr_check.jsp").forward(request, response);
log.debug("check: void");
}
}
| gpl-2.0 |
hdadler/sensetrace-src | com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-sdb/src-dev/java/dbtest/ParamsVocab.java | 1763 | /*
* 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 dbtest;
public class ParamsVocab
{
static public final String TempTableName = "TempTable" ;
static public final String VarcharType = "typeVarchar" ;
static public final String VarcharCol = "colVarchar" ;
static public final String TestLongBinary = "testLongBinary" ;
static public final String LongBinaryType = "typeLongBinary" ;
static public final String LongBinaryCol = "colLongBinary" ;
public static final String TestLongText = "testLongText" ;
public static final String LongTextType = "typeLongtext" ;
public static final String LongTextCol = "colLongText" ;
static public final String User = "user" ;
static public final String Password = "password" ;
static public final String JDBC = "jdbc" ;
public static final String Driver = "driver" ;
public static final String DBType = "db" ;
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/lang/StringBuilder/Insert.java | 1301 | /*
* Copyright 2003 Sun Microsystems, Inc. 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.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/**
* @test
* @bug 4914802
* @summary Test Insert method for infinite loop
*/
public class Insert {
public static void main (String argv[]) throws Exception {
StringBuilder sb = new StringBuilder();
sb.insert(0, false);
}
}
| gpl-2.0 |
calipho-sib/nextprot-api | core/src/main/java/org/nextprot/api/core/service/StatementService.java | 338 | package org.nextprot.api.core.service;
import org.nextprot.api.core.domain.DbXref;
import org.nextprot.api.core.domain.annotation.Annotation;
import java.util.List;
import java.util.Set;
public interface StatementService {
List<Annotation> getAnnotations(String entryAccession);
Set<DbXref> findDbXrefs(String entryAccession);
}
| gpl-2.0 |
NoTengoNombre/Java_ActualizarConocimientos | Java_Celia/src/java_celia/t6xEjerciciosBasicos/T6Ficheros/FileInputStreamLeerBinarios/T6EjemploLeerArchivoMostrarCaracteresEnBytes.java | 1981 | /**
* @created on : 27-sep-2017, 23:27:50
* @see
* @since
* @version
* @author Raul Vela Salas
*/
package java_celia.t6xEjerciciosBasicos.T6Ficheros.FileInputStreamLeerBinarios;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class T6EjemploLeerArchivoMostrarCaracteresEnBytes {
/**
*
* @return
*/
public static File leerArchivoEnBytes() {
// El nombre del fichero que vamos a utilizar
String nombreFich = "contar.txt";
// Creamos un nuevo fichero
File file = new File(nombreFich);
FileInputStream fileinput = null;
try {
fileinput = new FileInputStream(file);
System.out.println("Tamaño del fichero : " + fileinput.available());
int content;
while ((content = fileinput.read()) != -1) {
//Convierte el byte leido en un char para mostrarlo
//Char
// System.out.println((char) content);
//Bytes
System.out.println(content);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(T6EjemploBusquedaFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(T6EjemploBusquedaFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (fileinput != null) {
fileinput.close();
}
} catch (IOException ex) {
Logger.getLogger(T6EjemploBusquedaFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error IO : " + ex.getMessage() + " - " + " Mensaje : " + ex.getLocalizedMessage());
}
}
return file;
}
public static void main(String[] args) {
leerArchivoEnBytes();
}
}
| gpl-2.0 |
dain/graal | graal/com.oracle.graal.word/src/com/oracle/graal/word/phases/WordTypeRewriterPhase.java | 19895 | /*
* Copyright (c) 2012, 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.
*
* 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.graal.word.phases;
import static com.oracle.graal.api.meta.LocationIdentity.*;
import java.lang.reflect.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.api.replacements.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.compiler.common.calc.*;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.HeapAccess.BarrierType;
import com.oracle.graal.nodes.calc.*;
import com.oracle.graal.nodes.extended.*;
import com.oracle.graal.nodes.java.*;
import com.oracle.graal.nodes.type.*;
import com.oracle.graal.nodes.util.*;
import com.oracle.graal.phases.*;
import com.oracle.graal.phases.graph.*;
import com.oracle.graal.word.*;
import com.oracle.graal.word.Word.Opcode;
import com.oracle.graal.word.Word.Operation;
import com.oracle.graal.word.nodes.*;
/**
* Transforms all uses of the {@link Word} class into unsigned operations on {@code int} or
* {@code long} values, depending on the word kind of the underlying platform.
*/
public class WordTypeRewriterPhase extends Phase {
protected final MetaAccessProvider metaAccess;
protected final SnippetReflectionProvider snippetReflection;
protected final ResolvedJavaType wordBaseType;
protected final ResolvedJavaType wordImplType;
protected final ResolvedJavaType objectAccessType;
protected final ResolvedJavaType barrieredAccessType;
protected final Kind wordKind;
public WordTypeRewriterPhase(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection, Kind wordKind) {
this.metaAccess = metaAccess;
this.snippetReflection = snippetReflection;
this.wordKind = wordKind;
this.wordBaseType = metaAccess.lookupJavaType(WordBase.class);
this.wordImplType = metaAccess.lookupJavaType(Word.class);
this.objectAccessType = metaAccess.lookupJavaType(ObjectAccess.class);
this.barrieredAccessType = metaAccess.lookupJavaType(BarrieredAccess.class);
}
@Override
protected void run(StructuredGraph graph) {
InferStamps.inferStamps(graph);
for (Node n : graph.getNodes()) {
if (n instanceof ValueNode) {
changeToWord(graph, (ValueNode) n);
}
}
for (Node node : graph.getNodes()) {
rewriteNode(graph, node);
}
}
/**
* Change the stamp for word nodes from the object stamp ({@link WordBase} or anything extending
* or implementing that interface) to the primitive word stamp.
*/
protected void changeToWord(StructuredGraph graph, ValueNode node) {
if (isWord(node)) {
if (node.isConstant()) {
ConstantNode oldConstant = (ConstantNode) node;
assert oldConstant.getValue().getKind() == Kind.Object;
WordBase value = (WordBase) snippetReflection.asObject(oldConstant.getValue());
ConstantNode newConstant = ConstantNode.forIntegerKind(wordKind, value.rawValue(), node.graph());
graph.replaceFloating(oldConstant, newConstant);
} else {
node.setStamp(StampFactory.forKind(wordKind));
}
}
}
/**
* Clean up nodes that are no longer necessary or valid after the stamp change, and perform
* intrinsification of all methods called on word types.
*/
protected void rewriteNode(StructuredGraph graph, Node node) {
if (node instanceof CheckCastNode) {
rewriteCheckCast(graph, (CheckCastNode) node);
} else if (node instanceof LoadFieldNode) {
rewriteLoadField(graph, (LoadFieldNode) node);
} else if (node instanceof AccessIndexedNode) {
rewriteAccessIndexed(graph, (AccessIndexedNode) node);
} else if (node instanceof MethodCallTargetNode) {
rewriteInvoke(graph, (MethodCallTargetNode) node);
}
}
/**
* Remove casts between word types (which by now no longer have kind Object).
*/
protected void rewriteCheckCast(StructuredGraph graph, CheckCastNode node) {
if (node.getKind() == wordKind) {
node.replaceAtUsages(node.object());
graph.removeFixed(node);
}
}
/**
* Fold constant field reads, e.g. enum constants.
*/
protected void rewriteLoadField(StructuredGraph graph, LoadFieldNode node) {
ConstantNode constant = node.asConstant(metaAccess, node.object());
if (constant != null) {
node.replaceAtUsages(graph.unique(constant));
graph.removeFixed(node);
}
}
/**
* Change loads and stores of word-arrays. Since the element kind is managed by the node on its
* own and not in the stamp, {@link #changeToWord} does not perform all necessary changes.
*/
protected void rewriteAccessIndexed(StructuredGraph graph, AccessIndexedNode node) {
ResolvedJavaType arrayType = StampTool.typeOrNull(node.array());
/*
* There are cases where the array does not have a known type yet, i.e., the type is null.
* In that case we assume it is not a word type.
*/
if (arrayType != null && isWord(arrayType.getComponentType()) && node.elementKind() != wordKind) {
/*
* The elementKind of the node is a final field, and other information such as the stamp
* depends on elementKind. Therefore, just create a new node and replace the old one.
*/
if (node instanceof LoadIndexedNode) {
graph.replaceFixedWithFixed(node, graph.add(new LoadIndexedNode(node.array(), node.index(), wordKind)));
} else if (node instanceof StoreIndexedNode) {
graph.replaceFixedWithFixed(node, graph.add(new StoreIndexedNode(node.array(), node.index(), wordKind, ((StoreIndexedNode) node).value())));
} else {
throw GraalInternalError.shouldNotReachHere();
}
}
}
/**
* Intrinsification of methods defined on the {@link Word} class that are annotated with
* {@link Operation}.
*/
protected void rewriteInvoke(StructuredGraph graph, MethodCallTargetNode callTargetNode) {
ResolvedJavaMethod targetMethod = callTargetNode.targetMethod();
final boolean isWordBase = wordBaseType.isAssignableFrom(targetMethod.getDeclaringClass());
final boolean isObjectAccess = objectAccessType.equals(targetMethod.getDeclaringClass());
final boolean isBarrieredAccess = barrieredAccessType.equals(targetMethod.getDeclaringClass());
if (!isWordBase && !isObjectAccess && !isBarrieredAccess) {
/*
* Not a method defined on WordBase or a subclass / subinterface, and not on
* ObjectAccess and not on BarrieredAccess, so nothing to rewrite.
*/
return;
}
Invoke invoke = callTargetNode.invoke();
if (!callTargetNode.isStatic()) {
assert callTargetNode.receiver().getKind() == wordKind : "changeToWord() missed the receiver " + callTargetNode.receiver();
targetMethod = wordImplType.resolveMethod(targetMethod, invoke.getContextType());
}
Operation operation = targetMethod.getAnnotation(Word.Operation.class);
assert operation != null : targetMethod;
NodeInputList<ValueNode> arguments = callTargetNode.arguments();
switch (operation.opcode()) {
case NODE_CLASS:
assert arguments.size() == 2;
ValueNode left = arguments.get(0);
ValueNode right = operation.rightOperandIsInt() ? toUnsigned(graph, arguments.get(1), Kind.Int) : fromSigned(graph, arguments.get(1));
ValueNode replacement = graph.addOrUnique(createBinaryNodeInstance(operation.node(), left, right));
if (replacement instanceof FixedWithNextNode) {
graph.addBeforeFixed(invoke.asNode(), (FixedWithNextNode) replacement);
}
replace(invoke, replacement);
break;
case COMPARISON:
assert arguments.size() == 2;
replace(invoke, comparisonOp(graph, operation.condition(), arguments.get(0), fromSigned(graph, arguments.get(1))));
break;
case NOT:
assert arguments.size() == 1;
replace(invoke, graph.unique(new XorNode(arguments.get(0), ConstantNode.forIntegerKind(wordKind, -1, graph))));
break;
case READ_POINTER:
case READ_OBJECT:
case READ_BARRIERED: {
assert arguments.size() == 2 || arguments.size() == 3;
Kind readKind = asKind(callTargetNode.returnType());
LocationNode location;
if (arguments.size() == 2) {
location = makeLocation(graph, arguments.get(1), readKind, ANY_LOCATION);
} else {
location = makeLocation(graph, arguments.get(1), readKind, arguments.get(2));
}
replace(invoke, readOp(graph, arguments.get(0), invoke, location, operation.opcode()));
break;
}
case READ_HEAP: {
assert arguments.size() == 3;
Kind readKind = asKind(callTargetNode.returnType());
LocationNode location = makeLocation(graph, arguments.get(1), readKind, ANY_LOCATION);
BarrierType barrierType = (BarrierType) snippetReflection.asObject(arguments.get(2).asConstant());
replace(invoke, readOp(graph, arguments.get(0), invoke, location, barrierType, true));
break;
}
case WRITE_POINTER:
case WRITE_OBJECT:
case WRITE_BARRIERED:
case INITIALIZE: {
assert arguments.size() == 3 || arguments.size() == 4;
Kind writeKind = asKind(targetMethod.getSignature().getParameterType(targetMethod.isStatic() ? 2 : 1, targetMethod.getDeclaringClass()));
LocationNode location;
if (arguments.size() == 3) {
location = makeLocation(graph, arguments.get(1), writeKind, LocationIdentity.ANY_LOCATION);
} else {
location = makeLocation(graph, arguments.get(1), writeKind, arguments.get(3));
}
replace(invoke, writeOp(graph, arguments.get(0), arguments.get(2), invoke, location, operation.opcode()));
break;
}
case ZERO:
assert arguments.size() == 0;
replace(invoke, ConstantNode.forIntegerKind(wordKind, 0L, graph));
break;
case FROM_UNSIGNED:
assert arguments.size() == 1;
replace(invoke, fromUnsigned(graph, arguments.get(0)));
break;
case FROM_SIGNED:
assert arguments.size() == 1;
replace(invoke, fromSigned(graph, arguments.get(0)));
break;
case TO_RAW_VALUE:
assert arguments.size() == 1;
replace(invoke, toUnsigned(graph, arguments.get(0), Kind.Long));
break;
case FROM_OBJECT:
assert arguments.size() == 1;
WordCastNode objectToWord = graph.add(WordCastNode.objectToWord(arguments.get(0), wordKind));
graph.addBeforeFixed(invoke.asNode(), objectToWord);
replace(invoke, objectToWord);
break;
case FROM_ARRAY:
assert arguments.size() == 2;
replace(invoke, graph.unique(new ComputeAddressNode(arguments.get(0), arguments.get(1), StampFactory.forKind(wordKind))));
break;
case TO_OBJECT:
assert arguments.size() == 1;
WordCastNode wordToObject = graph.add(WordCastNode.wordToObject(arguments.get(0), wordKind));
graph.addBeforeFixed(invoke.asNode(), wordToObject);
replace(invoke, wordToObject);
break;
default:
throw new GraalInternalError("Unknown opcode: %s", operation.opcode());
}
}
protected ValueNode fromUnsigned(StructuredGraph graph, ValueNode value) {
return convert(graph, value, wordKind, true);
}
private ValueNode fromSigned(StructuredGraph graph, ValueNode value) {
return convert(graph, value, wordKind, false);
}
protected ValueNode toUnsigned(StructuredGraph graph, ValueNode value, Kind toKind) {
return convert(graph, value, toKind, true);
}
private static ValueNode convert(StructuredGraph graph, ValueNode value, Kind toKind, boolean unsigned) {
if (value.getKind() == toKind) {
return value;
}
if (toKind == Kind.Int) {
assert value.getKind() == Kind.Long;
return graph.unique(new NarrowNode(value, 32));
} else {
assert toKind == Kind.Long;
assert value.getKind().getStackKind() == Kind.Int;
if (unsigned) {
return graph.unique(new ZeroExtendNode(value, 64));
} else {
return graph.unique(new SignExtendNode(value, 64));
}
}
}
/**
* Create an instance of a binary node which is used to lower Word operations. This method is
* called for all Word operations which are annotated with @Operation(node = ...) and
* encapsulates the reflective allocation of the node.
*/
private static ValueNode createBinaryNodeInstance(Class<? extends ValueNode> nodeClass, ValueNode left, ValueNode right) {
try {
Constructor<? extends ValueNode> constructor = nodeClass.getConstructor(ValueNode.class, ValueNode.class);
return constructor.newInstance(left, right);
} catch (Throwable ex) {
throw new GraalInternalError(ex).addContext(nodeClass.getName());
}
}
private ValueNode comparisonOp(StructuredGraph graph, Condition condition, ValueNode left, ValueNode right) {
assert left.getKind() == wordKind && right.getKind() == wordKind;
// mirroring gets the condition into canonical form
boolean mirror = condition.canonicalMirror();
ValueNode a = mirror ? right : left;
ValueNode b = mirror ? left : right;
CompareNode comparison;
if (condition == Condition.EQ || condition == Condition.NE) {
comparison = new IntegerEqualsNode(a, b);
} else if (condition.isUnsigned()) {
comparison = new IntegerBelowNode(a, b);
} else {
comparison = new IntegerLessThanNode(a, b);
}
ConstantNode trueValue = ConstantNode.forInt(1, graph);
ConstantNode falseValue = ConstantNode.forInt(0, graph);
if (condition.canonicalNegate()) {
ConstantNode temp = trueValue;
trueValue = falseValue;
falseValue = temp;
}
ConditionalNode materialize = graph.unique(new ConditionalNode(graph.unique(comparison), trueValue, falseValue));
return materialize;
}
private LocationNode makeLocation(StructuredGraph graph, ValueNode offset, Kind readKind, ValueNode locationIdentity) {
if (locationIdentity.isConstant()) {
return makeLocation(graph, offset, readKind, (LocationIdentity) snippetReflection.asObject(locationIdentity.asConstant()));
}
return SnippetLocationNode.create(snippetReflection, locationIdentity, ConstantNode.forConstant(snippetReflection.forObject(readKind), metaAccess, graph), ConstantNode.forLong(0, graph),
fromSigned(graph, offset), ConstantNode.forInt(1, graph), graph);
}
protected LocationNode makeLocation(StructuredGraph graph, ValueNode offset, Kind readKind, LocationIdentity locationIdentity) {
return IndexedLocationNode.create(locationIdentity, readKind, 0, fromSigned(graph, offset), graph, 1);
}
protected ValueNode readOp(StructuredGraph graph, ValueNode base, Invoke invoke, LocationNode location, Opcode op) {
assert op == Opcode.READ_POINTER || op == Opcode.READ_OBJECT || op == Opcode.READ_BARRIERED;
final BarrierType barrier = (op == Opcode.READ_BARRIERED ? BarrierType.PRECISE : BarrierType.NONE);
final boolean compressible = (op == Opcode.READ_OBJECT || op == Opcode.READ_BARRIERED);
return readOp(graph, base, invoke, location, barrier, compressible);
}
protected ValueNode readOp(StructuredGraph graph, ValueNode base, Invoke invoke, LocationNode location, BarrierType barrierType, boolean compressible) {
JavaReadNode read = graph.add(new JavaReadNode(base, location, barrierType, compressible));
graph.addBeforeFixed(invoke.asNode(), read);
/*
* The read must not float outside its block otherwise it may float above an explicit zero
* check on its base address.
*/
read.setGuard(BeginNode.prevBegin(invoke.asNode()));
return read;
}
protected ValueNode writeOp(StructuredGraph graph, ValueNode base, ValueNode value, Invoke invoke, LocationNode location, Opcode op) {
assert op == Opcode.WRITE_POINTER || op == Opcode.WRITE_OBJECT || op == Opcode.WRITE_BARRIERED || op == Opcode.INITIALIZE;
final BarrierType barrier = (op == Opcode.WRITE_BARRIERED ? BarrierType.PRECISE : BarrierType.NONE);
final boolean compressible = (op == Opcode.WRITE_OBJECT || op == Opcode.WRITE_BARRIERED);
final boolean initialize = (op == Opcode.INITIALIZE);
JavaWriteNode write = graph.add(new JavaWriteNode(base, value, location, barrier, compressible, initialize));
write.setStateAfter(invoke.stateAfter());
graph.addBeforeFixed(invoke.asNode(), write);
return write;
}
protected void replace(Invoke invoke, ValueNode value) {
FixedNode next = invoke.next();
invoke.setNext(null);
invoke.asNode().replaceAtPredecessor(next);
invoke.asNode().replaceAtUsages(value);
GraphUtil.killCFG(invoke.asNode());
}
protected boolean isWord(ValueNode node) {
return isWord(StampTool.typeOrNull(node));
}
protected boolean isWord(ResolvedJavaType type) {
return type != null && wordBaseType.isAssignableFrom(type);
}
protected Kind asKind(JavaType type) {
if (type instanceof ResolvedJavaType && isWord((ResolvedJavaType) type)) {
return wordKind;
} else {
return type.getKind();
}
}
}
| gpl-2.0 |
ntj/ComplexRapidMiner | src/de/tud/inf/example/table/ArrayAttributeDescription.java | 469 | package de.tud.inf.example.table;
import com.rapidminer.example.table.ExampleTable;
public class ArrayAttributeDescription extends GeometryAttributeDescription {
public ArrayAttributeDescription(int[] attIds, int[] paramIds,
String symbol, String name, String hint) {
super(attIds, paramIds, symbol, name, hint);
// TODO Auto-generated constructor stub
}
@Override
public void checkConstraints(ExampleTable et) {
super.checkConstraints(et);
//
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.adempiere.libero.libero/src/main/java/org/eevolution/mrp/spi/impl/CompositeMRPSupplyProducer.java | 6451 | package org.eevolution.mrp.spi.impl;
/*
* #%L
* de.metas.adempiere.libero.libero
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.adempiere.ad.modelvalidator.DocTimingType;
import org.adempiere.ad.modelvalidator.ModelChangeType;
import org.adempiere.model.InterfaceWrapperHelper;
import org.adempiere.util.Check;
import org.adempiere.util.lang.IMutable;
import org.adempiere.util.lang.Mutable;
import org.eevolution.exceptions.LiberoException;
import org.eevolution.mrp.api.IMRPCreateSupplyRequest;
import org.eevolution.mrp.api.IMRPDemandToSupplyAllocation;
import org.eevolution.mrp.api.IMRPExecutor;
import org.eevolution.mrp.spi.IMRPSupplyProducer;
import de.metas.material.planning.IMaterialPlanningContext;
public class CompositeMRPSupplyProducer implements IMRPSupplyProducer
{
private final List<IMRPSupplyProducer> producers = new ArrayList<IMRPSupplyProducer>();
private final List<IMRPSupplyProducer> producersRO = Collections.unmodifiableList(producers);
public void addMRPSupplyProducer(final IMRPSupplyProducer supplyProducer)
{
if (producers.contains(supplyProducer))
{
return;
}
producers.add(supplyProducer);
}
public List<IMRPSupplyProducer> getAllSupplyProducers()
{
return producersRO;
}
public List<IMRPSupplyProducer> getSupplyProducers(final String tableName)
{
Check.assumeNotEmpty(tableName, LiberoException.class, "tableName not null");
List<IMRPSupplyProducer> result = null;
for (final IMRPSupplyProducer producer : producers)
{
final Set<String> sourceTableNames = producer.getSourceTableNames();
if (!sourceTableNames.contains(tableName))
{
continue;
}
if (result == null)
{
result = new ArrayList<IMRPSupplyProducer>();
}
result.add(producer);
}
if (result == null)
{
return Collections.emptyList();
}
else
{
return result;
}
}
@Override
public Set<String> getSourceTableNames()
{
final Set<String> sourceTableNames = new LinkedHashSet<String>(); // keep the order
for (final IMRPSupplyProducer producer : producers)
{
sourceTableNames.addAll(producer.getSourceTableNames());
}
return sourceTableNames;
}
@Override
public boolean applies(final IMaterialPlanningContext mrpContext, final IMutable<String> notAppliesReason)
{
final StringBuilder notAppliesReasonBuf = new StringBuilder();
for (final IMRPSupplyProducer producer : producers)
{
final IMutable<String> notAppliesReasonProducer = new Mutable<String>();
if (producer.applies(mrpContext, notAppliesReasonProducer))
{
return true;
}
appendNotAppliesReason(notAppliesReasonBuf, notAppliesReasonProducer);
}
notAppliesReason.setValue(notAppliesReasonBuf.toString());
return false;
}
private final void appendNotAppliesReason(final StringBuilder notAppliesReasonBuf, final IMutable<String> notAppliesReason)
{
if (Check.isEmpty(notAppliesReason.getValue(), true))
{
return;
}
if (notAppliesReasonBuf.length() > 0)
{
notAppliesReasonBuf.append("; ");
}
notAppliesReasonBuf.append(notAppliesReason.getValue());
}
@Override
public void onRecordChange(final Object model, final ModelChangeType changeType)
{
for (final IMRPSupplyProducer producer : producers)
{
producer.onRecordChange(model, changeType);
}
}
@Override
public void onDocumentChange(final Object model, final DocTimingType timing)
{
for (final IMRPSupplyProducer producer : producers)
{
producer.onDocumentChange(model, timing);
}
}
@Override
public boolean isRecreatedMRPRecordsSupported(final String tableName)
{
for (final IMRPSupplyProducer producer : producers)
{
if (producer.isRecreatedMRPRecordsSupported(tableName))
{
return true;
}
}
return false;
}
@Override
public void recreateMRPRecords(final Object model)
{
Check.assumeNotNull(model, "model not null");
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
for (final IMRPSupplyProducer producer : producers)
{
// skip producer if it does not support our tableName
if (!producer.isRecreatedMRPRecordsSupported(tableName))
{
continue;
}
producer.recreateMRPRecords(model);
}
}
@Override
public void createSupply(final IMRPCreateSupplyRequest request)
{
for (final IMRPSupplyProducer producer : producers)
{
producer.createSupply(request);
}
}
public IMRPSupplyProducer getSupplyProducers(final IMaterialPlanningContext mrpContext)
{
final StringBuilder notAppliesReasonBuf = new StringBuilder();
for (final IMRPSupplyProducer producer : producers)
{
final IMutable<String> notAppliesReasonProducer = new Mutable<String>();
if (producer.applies(mrpContext, notAppliesReasonProducer))
{
return producer;
}
appendNotAppliesReason(notAppliesReasonBuf, notAppliesReasonProducer);
}
throw new IllegalStateException("No MRP supply producer found for " + mrpContext + " because: " + notAppliesReasonBuf.toString());
}
@Override
public void cleanup(final IMaterialPlanningContext mrpContext, final IMRPExecutor executor)
{
for (final IMRPSupplyProducer producer : producers)
{
producer.cleanup(mrpContext, executor);
}
}
@Override
public void onQtyOnHandReservation(final IMaterialPlanningContext mrpContext,
final IMRPExecutor mrpExecutor,
final IMRPDemandToSupplyAllocation mrpDemandToSupplyAllocation)
{
for (final IMRPSupplyProducer producer : producers)
{
producer.onQtyOnHandReservation(mrpContext, mrpExecutor, mrpDemandToSupplyAllocation);
}
}
@Override
public Class<?> getDocumentClass()
{
throw new UnsupportedOperationException();
}
}
| gpl-2.0 |
rchakra3/TomR | src/network/incoming/persistent/RequestHandler.java | 947 | package network.incoming.persistent;
import java.io.IOException;
import network.requests.NWRequest;
import org.codehaus.jackson.map.ObjectMapper;
//retrieves the next incoming request
public class RequestHandler extends PersistentIncomingConnectionHandler {
protected RequestHandler(int incoming_port) {
super(incoming_port);
// TODO Auto-generated constructor stub
}
/**
* Shifted this method here from ConnectionHandler so ConnectionHandler can be reused for responses
*/
protected NWRequest getNextRequest(){
ObjectMapper mapper = new ObjectMapper();
NWRequest request=null;
//currently using scanner. Scanner waits for a newLine character which marks the end of an object
if(inputScanner.hasNextLine()){
try {
request=mapper.readValue(inputScanner.nextLine(), NWRequest.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return request;
}
}
| gpl-2.0 |
ruslanrf/wpps | wpps_plugins/tuwien.dbai.wpps.core/src/tuwien/dbai/wpps/core/wpmodel/physmodel/im/instadp/interf/IIMListItem.java | 285 | /**
*
*/
package tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp.interf;
import java.util.Collection;
/**
* @author Ruslan (ruslanrf@gmail.com)
* @created Oct 5, 2012 1:41:56 PM
*/
public interface IIMListItem extends IIMElement {
Collection<IIMElement> getContent();
}
| gpl-2.0 |
msurkovsky/despr | basic-extensions-types/src/cz/vsb/cs/sur096/despr/types/renderers/ChoosableCellRenderer.java | 1457 | package cz.vsb.cs.sur096.despr.types.renderers;
import cz.vsb.cs.sur096.despr.types.Choosable;
import cz.vsb.cs.sur096.despr.view.inputparameters.ParameterCellRenderer;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JTable;
/**
* Renderer hodnoty kterou lze vybrat s konečné množiny možností.
* To jsou typy implementující rozhraní
* {@code cz.vsb.cs.sur096.despr.types.Chooseable} z Despr-API.
*
* @author Martin Šurkovský, sur096,
* <a href="mailto:martin.surkovsky@gmail.com">martin.surkovsky at gmail.com</a>
* @version 2012/02/21/17/08
*/
public class ChoosableCellRenderer implements ParameterCellRenderer {
private JLabel renderer;
public ChoosableCellRenderer() {
renderer = new JLabel();
Font f = renderer.getFont();
renderer.setFont(f.deriveFont(Font.BOLD));
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Choosable) {
Choosable choosable = (Choosable) value;
renderer.setText(choosable.getChoosedValue().name());
}
renderer.setBackground(table.getBackground());
boolean isEditable = table.isEnabled() & table.getModel().isCellEditable(row, column);
renderer.setEnabled(isEditable);
return renderer;
}
}
| gpl-2.0 |
bdaum/zoraPD | com.bdaum.zoom.ui/src/com/bdaum/zoom/ui/internal/dialogs/PageProcessor.java | 16880 | /*
* This file is part of the ZoRa project: http://www.photozora.org.
*
* ZoRa 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.
*
* ZoRa 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 ZoRa; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* (c) 2009 Berthold Daum
*/
package com.bdaum.zoom.ui.internal.dialogs;
import java.io.File;
import java.util.Date;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.bdaum.zoom.batch.internal.IFileWatcher;
import com.bdaum.zoom.cat.model.PageLayout_typeImpl;
import com.bdaum.zoom.cat.model.asset.Asset;
import com.bdaum.zoom.cat.model.meta.Meta;
import com.bdaum.zoom.core.Assetbox;
import com.bdaum.zoom.core.Constants;
import com.bdaum.zoom.core.Core;
import com.bdaum.zoom.core.Format;
import com.bdaum.zoom.core.IAssetProvider;
import com.bdaum.zoom.core.ICore;
import com.bdaum.zoom.core.QueryField;
import com.bdaum.zoom.core.db.IDbManager;
import com.bdaum.zoom.core.internal.CoreActivator;
import com.bdaum.zoom.core.internal.Utilities;
import com.bdaum.zoom.image.ImageConstants;
import com.bdaum.zoom.image.ImageUtilities;
import com.bdaum.zoom.image.ZImage;
import com.bdaum.zoom.image.recipe.UnsharpMask;
import com.bdaum.zoom.ui.dialogs.AcousticMessageDialog;
import com.bdaum.zoom.ui.internal.TemplateProcessor;
import com.bdaum.zoom.ui.internal.UiActivator;
@SuppressWarnings("restriction")
public class PageProcessor {
private static final double MMPERINCH = 25.4d;
private static final int fontSize = 8;
private static final int titleSize = 12;
private static final int subtitleSize = 10;
private static final int footerSize = 9;
private final TemplateProcessor captionProcessor = new TemplateProcessor(Constants.PI_ALL);
private PageLayout_typeImpl layout;
private List<Asset> assets;
private int w;
private int h;
private int pages;
private Font titleFont;
private int topMargins;
private Font subtitleFont;
private int titlePixelSize;
private int subtitleLead;
private int footerPixelSize;
private int bottomMargins;
private Font footerFont;
private int subtitlePixelSize;
private int imagesPerPage;
private double imageWidth;
private double imageHeight;
private int cellWidth;
private int cellHeight;
private int leftMargins;
private int titleTextSize;
private Font textFont;
private int fontPixelSize;
private int fontLead;
private int upperWaste;
private Date now;
private Meta meta;
private String fileName;
private String collection = ""; //$NON-NLS-1$
private int keyLine;
private IAdaptable adaptable;
private int cms;
private int rightMargins;
private int seqNo = 0;
private final UnsharpMask umask;
protected String opId = java.util.UUID.randomUUID().toString();
protected IFileWatcher fileWatcher = CoreActivator.getDefault().getFileWatchManager();
protected boolean aborted;
private ZImage swtImage;
private double iDpi;
private double dpiX;
private double dpiY;
public PageProcessor(PrinterData printerData, PageLayout_typeImpl layout, List<Asset> assets, int w, int h,
double factorX, double factorY, Rectangle trim, Point printerDpi, int cms, UnsharpMask umask,
IAdaptable adaptable) {
this.umask = umask;
this.adaptable = adaptable;
this.layout = layout;
this.assets = assets;
this.w = w;
this.h = h;
this.cms = cms;
dpiX = printerDpi.x * factorX;
dpiY = printerDpi.y * factorY;
iDpi = Math.min(dpiX, dpiY);
double minAspectRatio = Double.MAX_VALUE;
double maxAspectRatio = 0;
for (Asset asset : assets) {
Double aspectRatio = (Double) QueryField.ASPECTRATIO.obtainFieldValue(asset);
if (aspectRatio != null) {
maxAspectRatio = Math.max(maxAspectRatio, aspectRatio);
minAspectRatio = Math.min(minAspectRatio, aspectRatio);
}
}
minAspectRatio = (minAspectRatio + maxAspectRatio) / 2;
keyLine = (int) (layout.getKeyLine() * iDpi / 144);
fontPixelSize = (int) (fontSize * iDpi / 72);
fontLead = fontPixelSize / 3;
titlePixelSize = 0;
int titleLead = 0;
if (!layout.getTitle().isEmpty()) {
titlePixelSize = (int) (titleSize * iDpi / 72);
titleLead = titlePixelSize;
}
subtitlePixelSize = 0;
subtitleLead = 0;
if (!layout.getSubtitle().isEmpty()) {
subtitlePixelSize = (int) (subtitleSize * iDpi / 72);
subtitleLead = subtitlePixelSize;
}
titleTextSize = titlePixelSize + titleLead + subtitlePixelSize + subtitleLead;
footerPixelSize = (int) (footerSize * iDpi / 72);
int footerLead = footerPixelSize;
int footerTextSize = footerPixelSize + footerLead;
int textHeight = 0;
if (!layout.getCaption1().isEmpty())
textHeight += fontPixelSize + fontLead;
if (!layout.getCaption2().isEmpty())
textHeight += fontPixelSize + fontLead;
int horizontalGap = (int) (layout.getHorizontalGap() * iDpi / MMPERINCH);
leftMargins = (int) Math.max(layout.getLeftMargin() * iDpi / MMPERINCH, -trim.x * factorX * iDpi / dpiX);
rightMargins = (int) Math.max(layout.getRightMargin() * iDpi / MMPERINCH,
(trim.width + trim.x) * factorX * iDpi / dpiX);
topMargins = (int) Math.max(layout.getTopMargin() * iDpi / MMPERINCH, -trim.y * factorY * iDpi / dpiY);
bottomMargins = (int) Math.max(layout.getBottomMargin() * iDpi / MMPERINCH,
(trim.height + trim.y) * factorY * iDpi / dpiY);
int verticalGap = (int) (layout.getVerticalGap() * iDpi / MMPERINCH);
int useableWidth = w - leftMargins - rightMargins;
cellWidth = (useableWidth + horizontalGap) / layout.getColumns();
float useableHeight = h - topMargins - bottomMargins - titleTextSize - footerTextSize;
imageWidth = cellWidth - horizontalGap - keyLine;
float maxImageHeight = useableHeight - textHeight - verticalGap - keyLine;
imageHeight = imageWidth / minAspectRatio;
while (imageHeight > maxImageHeight) {
imageWidth *= 0.99d;
imageHeight = imageWidth / minAspectRatio;
}
cellHeight = (int) (imageHeight + textHeight + verticalGap + keyLine);
int rows = (int) ((useableHeight + verticalGap) / cellHeight);
int usedSpace = rows * cellHeight;
upperWaste = (int) ((useableHeight - usedSpace) / 2);
imagesPerPage = layout.getColumns() * rows;
int size = assets.size();
pages = (size + imagesPerPage - 1) / imagesPerPage;
now = new Date();
ICore core = Core.getCore();
IDbManager dbManager = core.getDbManager();
meta = dbManager.getMeta(true);
fileName = dbManager.getFileName();
IAssetProvider assetProvider = core.getAssetProvider();
if (assetProvider != null)
collection = Utilities.getExternalAlbumName(assetProvider.getCurrentCollection());
}
private ZImage loadHighresImage(final Device device, Assetbox box, SubMonitor progress, final Asset asset) {
MultiStatus status = new MultiStatus(UiActivator.PLUGIN_ID, 0, Messages.PageProcessor_page_rending_report,
null);
box.setStatus(status);
File file = box.obtainFile(asset);
if (file != null) {
int pixelWidth = (int) (imageWidth * iDpi / 25.4d);
int pixelHeight = (int) (imageHeight * iDpi / 25.4d);
boolean r = asset.getRotation() % 180 != 0;
double w = r ? asset.getHeight() : asset.getWidth();
double h = r ? asset.getWidth() : asset.getHeight();
double scale = w == 0 || h == 0 ? 1d : (2 * pixelWidth <= w && 2 * pixelHeight <= h) ? 0.5d : 1d;
ZImage hrImage = null;
try {
hrImage = CoreActivator.getDefault().getHighresImageLoader().loadImage(
progress != null ? progress.newChild(1000) : null, status, file, asset.getRotation(),
asset.getFocalLengthIn35MmFilm(), null, scale, Double.MAX_VALUE, true, ImageConstants.SRGB,
null, umask, null, fileWatcher, opId, null);
if (status.isOK())
UiActivator.getDefault().getLog().log(status);
} catch (UnsupportedOperationException e) {
// Do nothing
}
return hrImage;
}
return null;
}
public boolean render(final Device device, final GC gc, final int pageNo, final IProgressMonitor jmon) {
if (imageWidth <= 0) {
AcousticMessageDialog.openError(adaptable.getAdapter(Shell.class), Messages.PageProcessor_printing_error,
Messages.PageProcessor_margins_too_large);
return true;
}
if (pageNo > pages)
return true;
aborted = false;
Color white = device.getSystemColor(SWT.COLOR_WHITE);
gc.setBackground(white);
gc.fillRectangle(0, 0, w, h);
final Image canvas = new Image(device, (int) (w * iDpi / dpiX), (int) (h * iDpi / dpiY));
Rectangle cBounds = canvas.getBounds();
final GC iGc = new GC(canvas);
try {
iGc.setBackground(white);
iGc.setForeground(device.getSystemColor(SWT.COLOR_DARK_GRAY));
iGc.fillRectangle(cBounds);
final int size = assets.size();
if (!layout.getTitle().isEmpty()) {
if (titleFont == null)
titleFont = createFont(device, titleSize, SWT.BOLD);
iGc.setFont(titleFont);
String title = computeTitle(layout.getTitle(), fileName, now, size, pageNo, pages, collection, meta);
iGc.drawText(title, (cBounds.width - iGc.textExtent(title).x) / 2, topMargins, true);
}
if (!layout.getSubtitle().isEmpty()) {
if (subtitleFont == null)
subtitleFont = createFont(device, subtitleSize, SWT.NORMAL);
iGc.setFont(subtitleFont);
String subtitle = computeTitle(layout.getSubtitle(), fileName, now, size, pageNo, pages, collection,
meta);
iGc.drawText(subtitle, (cBounds.width - iGc.textExtent(subtitle).x) / 2,
topMargins + titlePixelSize + subtitleLead, true);
}
if (!layout.getFooter().isEmpty()) {
if (footerFont == null)
footerFont = createFont(device, footerSize, SWT.NORMAL);
iGc.setFont(footerFont);
String footer = computeTitle(layout.getFooter(), fileName, now, size, pageNo, pages, collection, meta);
iGc.drawText(footer, (cBounds.width - iGc.textExtent(footer).x) / 2,
cBounds.height - bottomMargins - footerPixelSize, true);
}
Runnable runnable = new Runnable() {
public void run() {
SubMonitor progress = jmon == null ? null : SubMonitor.convert(jmon, 1000 * size);
try (Assetbox box = new Assetbox(null, null, false)) {
if (progress != null)
progress.beginTask(NLS.bind(Messages.PageProcessor_rendering_images, imagesPerPage),
1000 * imagesPerPage);
final int pixelWidth = (int) (imageWidth * iDpi / 72);
final int pixelHeight = (int) (imageHeight * iDpi / 72);
int pageItem = 0;
int i = 0;
lp: while (true) {
for (int j = 0; j < layout.getColumns(); j++) {
if (progress != null && progress.isCanceled())
break lp;
int n = i * layout.getColumns() + j;
if (n >= imagesPerPage)
break lp;
int a = (pageNo - 1) * imagesPerPage + n;
if (a >= size)
break lp;
++pageItem;
++seqNo;
if (swtImage != null) {
swtImage.dispose();
swtImage = null;
}
Asset asset = assets.get(a);
if (device instanceof Printer)
swtImage = loadHighresImage(device, box, progress, asset);
if (swtImage == null)
swtImage = new ZImage(ImageUtilities.loadThumbnail(device, asset.getJpegThumbnail(),
cms, SWT.IMAGE_JPEG, true), null);
Rectangle ibounds = swtImage.getBounds();
double factor = Math.min(imageWidth / ibounds.width, imageHeight / ibounds.height);
int iw = (int) (ibounds.width * factor);
int ih = (int) (ibounds.height * factor);
int cx;
if (layout.getFacingPages() && pageNo % 2 == 0)
cx = cellWidth * j + rightMargins;
else
cx = cellWidth * j + leftMargins;
int cy = cellHeight * i + topMargins + titleTextSize + upperWaste;
int ix = cx + (cellWidth - iw) / 2;
int iy = cy + (cellHeight - ih) / 2;
if (keyLine > 0) {
iGc.setLineWidth(keyLine);
iGc.drawRectangle(ix - (keyLine + 1) / 2, iy - (keyLine + 2) / 2, iw + keyLine,
ih + keyLine);
}
swtImage.draw(iGc, 0, 0, ibounds.width, ibounds.height - 1, ix, iy, iw, ih,
ZImage.CROPPED, pixelWidth, pixelHeight, false);
if (!layout.getCaption1().isEmpty()) {
if (textFont == null)
textFont = createFont(device, fontSize, SWT.NORMAL);
iGc.setFont(textFont);
String caption1 = captionProcessor.processTemplate(layout.getCaption1(), asset, collection, pageItem, seqNo);
int tx = (cx + (cellWidth - iGc.textExtent(caption1).x) / 2);
int ty = (iy + ih + fontLead + keyLine);
iGc.drawText(caption1, tx, ty, true);
}
if (!layout.getCaption2().isEmpty()) {
if (textFont == null)
textFont = createFont(device, fontSize, SWT.NORMAL);
iGc.setFont(textFont);
String caption2 = captionProcessor.processTemplate(layout.getCaption2(), asset, collection, pageItem, seqNo);
int tx = (cx + (cellWidth - iGc.textExtent(caption2).x) / 2);
int ty = (iy + ih + 2 * fontLead + fontPixelSize + keyLine);
iGc.drawText(caption2, tx, ty, true);
}
swtImage.dispose();
swtImage = null;
}
++i;
}
} finally {
fileWatcher.stopIgnoring(opId);
aborted = progress != null && progress.isCanceled();
}
}
};
if (device instanceof Display)
BusyIndicator.showWhile((Display) device, runnable);
else
runnable.run();
gc.drawImage(canvas, 0, 0, cBounds.width, cBounds.height, 0, 0, w, h);
} finally {
iGc.dispose();
canvas.dispose();
}
return aborted;
}
public static String computeTitle(String template, String catname, Date date, int count, int pageNo, int pages,
String collection, Meta meta) {
StringBuilder sb = new StringBuilder(template);
for (String tv : Constants.PT_ALL)
while (true) {
int p = sb.indexOf(tv);
if (p < 0)
break;
replaceTitleContent(sb, p, tv, catname, date, count, pageNo, pages, collection, meta);
}
return sb.toString();
}
private static void replaceTitleContent(StringBuilder sb, int p, String tv, String catname, Date date, int count,
int pageNo, int pages, String collection, Meta meta) {
String value = ""; //$NON-NLS-1$
if (tv == Constants.PT_CATALOG)
value = catname;
else if (tv == Constants.PT_TODAY)
value = Format.YMDT_SLASH.get().format(date);
else if (tv == Constants.PT_COUNT)
value = String.valueOf(count);
else if (tv == Constants.PT_PAGENO)
value = String.valueOf(pageNo);
else if (tv == Constants.PT_PAGECOUNT)
value = String.valueOf(pages);
else if (tv == Constants.PT_COLLECTION)
value = collection;
else if (tv == Constants.PT_USER)
value = System.getProperty("user.name"); //$NON-NLS-1$
else if (tv == Constants.PT_OWNER)
value = meta.getOwner();
sb.replace(p, p + tv.length(), value);
}
private static Font createFont(Device device, int size, int style) {
return new Font(device, device.getSystemFont().getFontData()[0].getName(), size, style);
}
public int getPageCount() {
return pages;
}
public void dispose() {
if (swtImage != null)
swtImage.dispose();
if (titleFont != null)
titleFont.dispose();
if (subtitleFont != null)
subtitleFont.dispose();
if (footerFont != null)
footerFont.dispose();
if (textFont != null)
textFont.dispose();
}
public int getImagesPerPage() {
return imagesPerPage;
}
}
| gpl-2.0 |
imglib/imglib2-script | src/test/java/net/imglib2/script/TestExtend.java | 2970 | /*
* #%L
* ImgLib2: a general-purpose, multidimensional image processing library.
* %%
* Copyright (C) 2009 - 2016 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld,
* John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke,
* Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner,
* Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert,
* Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin,
* Jean-Yves Tinevez and Michael Zinsmaier.
* %%
* 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 net.imglib2.script;
import ij.IJ;
import net.imglib2.exception.ImgLibException;
import net.imglib2.img.Img;
import net.imglib2.script.ImgLib;
import net.imglib2.script.view.Extend;
import net.imglib2.script.view.ExtendMirrorDouble;
import net.imglib2.script.view.ExtendMirrorSingle;
import net.imglib2.script.view.ExtendPeriodic;
import net.imglib2.script.view.ROI;
import net.imglib2.type.numeric.integer.UnsignedByteType;
/**
* TODO
*
*/
public class TestExtend
{
public static void main(String[] args) {
Img<UnsignedByteType> img = ImgLib.wrap(IJ.openImage("/home/albert/Desktop/t2/bridge.gif"));
Img<UnsignedByteType> multiPeriodic =
new ROI<UnsignedByteType>(
new ExtendPeriodic<UnsignedByteType>(img),
new long[]{-512, -512},
new long[]{1024, 1024});
Img<UnsignedByteType> multiMirroredDouble =
new ROI<UnsignedByteType>(
new ExtendMirrorDouble<UnsignedByteType>(img),
new long[]{-512, -512},
new long[]{1024, 1024});
Img<UnsignedByteType> multiMirroredSingle =
new ROI<UnsignedByteType>(
new ExtendMirrorSingle<UnsignedByteType>(img),
new long[]{-512, -512},
new long[]{1024, 1024});
Img<UnsignedByteType> centered =
new ROI<UnsignedByteType>(
new Extend<UnsignedByteType>(img, 0),
new long[]{-512, -512},
new long[]{1024, 1024});
// Above, notice the negative offsets. This needs fixing, it's likely due to recent change
// in how offsets are used. TODO
try {
ImgLib.show(multiPeriodic, "periodic");
ImgLib.show(multiMirroredDouble, "mirror double edge");
ImgLib.show(multiMirroredSingle, "mirror single edge");
ImgLib.show(centered, "translated 0 background");
} catch (ImgLibException e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
salvadormarmol/NSL_3_0_S | nslj/src/system/Console.java | 4633 | /* SCCS - @(#)Console.java 1.5 - 09/01/99 - 00:19:50 */
/*
* $Log: Console.java,v $
* Revision 1.1.1.1 1997/03/12 22:52:21 nsl
* new dir structure
*
* Revision 1.1.1.1 1997/02/08 00:40:40 nsl
* Imported the Source directory
*
*/
/*
* Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM)
* Published By SunSoft Press/Prentice-Hall
* Copyright (C) 1996 Sun Microsystems Inc.
* All Rights Reserved. ISBN 0-13-565755-5
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for NON-COMMERCIAL purposes
* and without fee is hereby granted provided that this
* copyright notice appears in all copies.
*
* THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR
* WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
* AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
* BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
/**
* An easy interface to read numbers and strings from
* standard input
* @version 1.01 15 Feb 1996
* @author Cay Horstmann
*/
package nslj.src.system;
public class Console
{ /**
* print a prompt on the console but don't print a newline
* @param prompt the prompt string to display
*/
public static void printPrompt(String prompt)
{ System.out.print(prompt + " ");
System.out.flush();
}
/**
* read a string from the console. The string is
* terminated by a newline.
* Multiple space is trim to single space
* @return the input string (without the newline)
*/
public static String readString()
{ int ch;
String r = "";
boolean done = false;
boolean multiple_space =true;
while (!done)
{ try
{ ch = System.in.read();
if (ch < 0 || (char)ch == '\n')
done = true;
else if ((char)ch == ' '){
if (multiple_space== true)
continue;
else{
r = r + (char)ch;
multiple_space = true;
}
}
else {
r = r + (char) ch;
multiple_space = false;
}
}
catch(java.io.IOException e)
{ done = true;
}
}
return r;
}
/**
* read a string from the console. The string is
* terminated by a newline
* @param prompt the prompt string to display
* @return the input string (without the newline)
*/
public static String readString(String prompt)
{ printPrompt(prompt);
return readString();
}
/**
* read a word from the console. The word is
* any set of characters terminated by whitespace
* @return the 'word' entered
*/
public static String readWord()
{ int ch;
String r = "";
boolean done = false;
while (!done)
{ try
{ ch = System.in.read();
if (ch < 0
|| java.lang.Character.isSpaceChar((char)ch))
done = true;
else
r = r + (char) ch;
}
catch(java.io.IOException e)
{ done = true;
}
}
return r;
}
/**
* read an integer from the console. The input is
* terminated by a newline
* @param prompt the prompt string to display
* @return the input value as an int
* @exception NumberFormatException if bad input
*/
public static int readInt(String prompt)
{ while(true)
{ printPrompt(prompt);
try
{ return Integer.valueOf
(readString().trim()).intValue();
} catch(NumberFormatException e)
{ System.out.println
("Not an integer. Please try again!");
}
}
}
/**
* read a floating point number from the console.
* The input is terminated by a newline
* @param prompt the prompt string to display
* @return the input value as a double
* @exception NumberFormatException if bad input
*/
public static double readDouble(String prompt)
{ while(true)
{ printPrompt(prompt);
try
{ return Double.valueOf
(readString().trim()).doubleValue();
} catch(NumberFormatException e)
{ System.out.println
("Not a floating point number. Please try again!");
}
}
}
}
| gpl-2.0 |
javaliquan/XWorld | XWorld/src/main/java/com/founderdpt/comm/xworld/util/string/StringMatch.java | 5362 | package com.founderdpt.comm.xworld.util.string;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
public class StringMatch {
public static String translateParamtwo(String expression, char[] openChars,
Map map) {
int maxLoopCount = 1;
String result = expression;
for (char open : openChars) {
int loopCount = 1;
int pos = 0;
// this creates an implicit StringBuffer and shouldn't be used in
// the inner loop
final String lookupChars = open + "{";
while (true) {
int start = expression.indexOf(lookupChars, pos);
if (start == -1) {
pos = 0;
loopCount++;
start = expression.indexOf(lookupChars);
}
if (loopCount > maxLoopCount) {
// translateVariables prevent infinite loop / expression
// recursive evaluation
break;
}
int length = expression.length();
int x = start + 2;
int end;
char c;
int count = 1;
while (start != -1 && x < length && count != 0) {
c = expression.charAt(x++);
if (c == '{') {
count++;
} else if (c == '}') {
count--;
}
}
end = x - 1;
if ((start != -1) && (end != -1) && (count == 0)) {
String var = expression.substring(start + 2, end);
Object obj = map.get(var);
String o ="";
if(obj instanceof String[]){
o=((String[])obj)[0];
}
if(obj instanceof String){
o=(String) obj;
}
String left = expression.substring(0, start);
String right = expression.substring(end + 1);
String middle = null;
if (o != null) {
middle = o.toString();
if (StringUtils.isEmpty(left)) {
result = o;
} else {
result = left.concat(middle);
}
if (StringUtils.isNotEmpty(right)) {
result = result.toString().concat(right);
}
expression = left.concat(middle).concat(right);
} else {
// the variable doesn't exist, so don't display anything
expression = left.concat(right);
result = expression;
}
pos = (left != null && left.length() > 0 ? left.length() - 1
: 0)
+ (middle != null && middle.length() > 0 ? middle
.length() - 1 : 0) + 1;
pos = Math.max(pos, 1);
} else {
break;
}
}
}
return result;
}
/**
* 匹配$[XXX]
* @param expression
* @param openChars
* @param map
* @return
*/
public static String translateParam(String expression, char[] openChars,
Map map) {
int maxLoopCount = 1;
String result = expression;
for (char open : openChars) {
int loopCount = 1;
int pos = 0;
// this creates an implicit StringBuffer and shouldn't be used in
// the inner loop
final String lookupChars = open + "[";
while (true) {
int start = expression.indexOf(lookupChars, pos);
if (start == -1) {
pos = 0;
loopCount++;
start = expression.indexOf(lookupChars);
}
if (loopCount > maxLoopCount) {
// translateVariables prevent infinite loop / expression
// recursive evaluation
break;
}
int length = expression.length();
int x = start + 2;
int end;
char c;
int count = 1;
while (start != -1 && x < length && count != 0) {
c = expression.charAt(x++);
if (c == '[') {
count++;
} else if (c == ']') {
count--;
}
}
end = x - 1;
if ((start != -1) && (end != -1) && (count == 0)) {
String var = expression.substring(start + 2, end);
Object obj = map.get(var);
String o ="";
if(obj instanceof String[]){
o=((String[])obj)[0];
}
if(obj instanceof String){
o=(String) obj;
}
String left = expression.substring(0, start);
String right = expression.substring(end + 1);
String middle = null;
if (o != null) {
middle = o.toString();
if (StringUtils.isEmpty(left)) {
result = o;
} else {
result = left.concat(middle);
}
if (StringUtils.isNotEmpty(right)) {
result = result.toString().concat(right);
}
expression = left.concat(middle).concat(right);
} else {
// the variable doesn't exist, so don't display anything
expression = left.concat(right);
result = expression;
}
pos = (left != null && left.length() > 0 ? left.length() - 1
: 0)
+ (middle != null && middle.length() > 0 ? middle
.length() - 1 : 0) + 1;
pos = Math.max(pos, 1);
} else {
break;
}
}
}
return result;
}
/**
* 匹配${XXX}
* @param expression
* @param openChars
* @param map
* @return
*/
public static String translateParam(String expression,Map map) {
if(map==null){
return expression;
}
return translateParamtwo(expression, new char[] { '$' },map);
}
/**
* 全局匹配 匹配$[XXX]
* @param expression
* @param map
* @return
*/
public static String translateParamGlobal(String expression,Map map) {
if(map==null){
return expression;
}
return translateParam(expression, new char[] { '$' },map);
}
}
| gpl-2.0 |
burakince/HackerRank | src/main/java/net/burakince/hackerrank/java_anagrams/Solution.java | 733 | package net.burakince.hackerrank.java_anagrams;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
final Scanner sc = new Scanner(System.in);
final String s1 = sc.nextLine();
final String s2 = sc.nextLine();
System.out.println(isAnagram(s1, s2) ? "Anagrams" : "Not Anagrams");
sc.close();
}
private static boolean isAnagram(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
String sc1 = new String(c1);
String sc2 = new String(c2);
return sc1.equals(sc2);
}
}
| gpl-2.0 |
FauxFaux/jdk9-hotspot | test/compiler/compilercontrol/mixed/RandomValidCommandsTest.java | 1980 | /*
* Copyright (c) 2015, 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.
*
* 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.
*/
/*
* @test
* @bug 8137167
* @summary Randomly generates valid commands with random types
* @modules java.base/jdk.internal.misc
* @library /testlibrary /test/lib /
*
* @build compiler.compilercontrol.mixed.RandomValidCommandsTest
* compiler.compilercontrol.share.pool.sub.*
* compiler.compilercontrol.share.pool.subpack.*
* sun.hotspot.WhiteBox
* compiler.testlibrary.CompilerUtils
* compiler.compilercontrol.share.actions.*
* @run driver ClassFileInstaller sun.hotspot.WhiteBox
* sun.hotspot.WhiteBox$WhiteBoxPermission
* @run driver/timeout=600 compiler.compilercontrol.mixed.RandomValidCommandsTest
*/
package compiler.compilercontrol.mixed;
import compiler.compilercontrol.share.MultiCommand;
public class RandomValidCommandsTest {
public static void main(String[] args) {
MultiCommand.generateRandomTest(true).test();
}
}
| gpl-2.0 |
smarr/GraalCompiler | graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/debug/BenchmarkCounters.java | 18788 | /*
* Copyright (c) 2013, 2014, 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.
*
* 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.graal.hotspot.debug;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import jdk.internal.jvmci.common.JVMCIError;
import jdk.internal.jvmci.hotspot.CompilerToVM;
import jdk.internal.jvmci.hotspot.HotSpotVMConfig;
import jdk.internal.jvmci.inittimer.SuppressFBWarnings;
import jdk.internal.jvmci.options.Option;
import jdk.internal.jvmci.options.OptionType;
import jdk.internal.jvmci.options.OptionValue;
import com.oracle.graal.debug.TTY;
import com.oracle.graal.hotspot.replacements.NewObjectSnippets;
import com.oracle.graal.nodes.debug.DynamicCounterNode;
//JaCoCo Exclude
/**
* This class contains infrastructure to maintain counters based on {@link DynamicCounterNode}s. The
* infrastructure is enabled by specifying either the GenericDynamicCounters or
* BenchmarkDynamicCounters option.
* <p>
*
* The counters are kept in a special area allocated for each native JavaThread object, and the
* number of counters is configured using {@code -XX:JVMCICounterSize=value}.
* {@code -XX:+/-JVMCICountersExcludeCompiler} configures whether to exclude compiler threads
* (defaults to true).
*
* The subsystems that use the logging need to have their own options to turn on the counters, and
* insert DynamicCounterNodes when they're enabled.
*
* Counters will be displayed as a rate (per second) if their group name starts with "~", otherwise
* they will be displayed as a total number.
*
* <h1>Example</h1> In order to create statistics about allocations within the DaCapo pmd benchmark
* the following steps are necessary:
* <ul>
* <li>Set {@code -XX:JVMCICounterSize=value}. The actual required value depends on the granularity
* of the profiling, 10000 should be enough for most cases.</li>
* <li>Also: {@code -XX:+/-JVMCICountersExcludeCompiler} specifies whether the numbers generated by
* compiler threads should be excluded (default: true).</li>
* <li>Start the DaCapo pmd benchmark with
* {@code "-G:BenchmarkDynamicCounters=err, starting ====, PASSED in "} and
* {@code -G:+ProfileAllocations}.</li>
* <li>The numbers will only include allocation from compiled code!</li>
* <li>The counters can be further configured by modifying the
* {@link NewObjectSnippets#PROFILE_MODE} field.</li>
* </ul>
*/
public class BenchmarkCounters {
static class Options {
//@formatter:off
@Option(help = "Turn on the benchmark counters, and displays the results on VM shutdown", type = OptionType.Debug)
private static final OptionValue<Boolean> GenericDynamicCounters = new OptionValue<>(false);
@Option(help = "Turn on the benchmark counters, and displays the results every n milliseconds", type = OptionType.Debug)
private static final OptionValue<Integer> TimedDynamicCounters = new OptionValue<>(-1);
@Option(help = "Turn on the benchmark counters, and listen for specific patterns on System.out/System.err:%n" +
"Format: (err|out),start pattern,end pattern (~ matches multiple digits)%n" +
"Examples:%n" +
" dacapo = 'err, starting =====, PASSED in'%n" +
" specjvm2008 = 'out,Iteration ~ (~s) begins:,Iteration ~ (~s) ends:'", type = OptionType.Debug)
private static final OptionValue<String> BenchmarkDynamicCounters = new OptionValue<>(null);
@Option(help = "Use grouping separators for number printing", type = OptionType.Debug)
private static final OptionValue<Boolean> DynamicCountersPrintGroupSeparator = new OptionValue<>(true);
@Option(help = "Print in human readable format", type = OptionType.Debug)
private static final OptionValue<Boolean> DynamicCountersHumanReadable = new OptionValue<>(true);
//@formatter:on
}
private static final boolean DUMP_STATIC = false;
public static boolean enabled = false;
private static class Counter {
public final int index;
public final String group;
public final AtomicLong staticCounters;
public Counter(int index, String group, AtomicLong staticCounters) {
this.index = index;
this.group = group;
this.staticCounters = staticCounters;
}
}
public static final ConcurrentHashMap<String, Counter> counterMap = new ConcurrentHashMap<>();
public static long[] delta;
public static int getIndexConstantIncrement(String name, String group, HotSpotVMConfig config, long increment) {
Counter counter = getCounter(name, group, config);
counter.staticCounters.addAndGet(increment);
return counter.index;
}
public static int getIndex(String name, String group, HotSpotVMConfig config) {
Counter counter = getCounter(name, group, config);
return counter.index;
}
@SuppressFBWarnings(value = "AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION", justification = "concurrent abstraction calls are in synchronized block")
private static Counter getCounter(String name, String group, HotSpotVMConfig config) throws JVMCIError {
if (!enabled) {
throw new JVMCIError("cannot access count index when counters are not enabled: " + group + ", " + name);
}
String nameGroup = name + "#" + group;
Counter counter = counterMap.get(nameGroup);
if (counter == null) {
synchronized (BenchmarkCounters.class) {
counter = counterMap.get(nameGroup);
if (counter == null) {
counter = new Counter(counterMap.size(), group, new AtomicLong());
counterMap.put(nameGroup, counter);
}
}
}
assert counter.group.equals(group) : "mismatching groups: " + counter.group + " vs. " + group;
int countersSize = config.jvmciCountersSize;
if (counter.index >= countersSize) {
throw new JVMCIError("too many counters, reduce number of counters or increase -XX:JVMCICounterSize=... (current value: " + countersSize + ")");
}
return counter;
}
private static synchronized void dump(PrintStream out, double seconds, long[] counters, int maxRows) {
if (!counterMap.isEmpty()) {
out.println("====== dynamic counters (" + counterMap.size() + " in total) ======");
TreeSet<String> set = new TreeSet<>();
counterMap.forEach((nameGroup, counter) -> set.add(counter.group));
for (String group : set) {
if (group != null) {
if (DUMP_STATIC) {
dumpCounters(out, seconds, counters, true, group, maxRows);
}
dumpCounters(out, seconds, counters, false, group, maxRows);
}
}
out.println("============================");
clear(counters);
}
}
private static synchronized void clear(long[] counters) {
delta = counters;
}
private static synchronized void dumpCounters(PrintStream out, double seconds, long[] counters, boolean staticCounter, String group, int maxRows) {
// collect the numbers
long[] array;
if (staticCounter) {
array = new long[counterMap.size()];
for (Counter counter : counterMap.values()) {
array[counter.index] = counter.staticCounters.get();
}
} else {
array = counters.clone();
for (int i = 0; i < array.length; i++) {
array[i] -= delta[i];
}
}
Set<Entry<String, Counter>> counterEntrySet = counterMap.entrySet();
if (Options.DynamicCountersHumanReadable.getValue()) {
dumpHumanReadable(out, seconds, staticCounter, group, maxRows, array, counterEntrySet);
} else {
dumpComputerReadable(out, staticCounter, group, array, counterEntrySet);
}
}
private static String getName(String nameGroup, String group) {
return nameGroup.substring(0, nameGroup.length() - group.length() - 1);
}
private static void dumpHumanReadable(PrintStream out, double seconds, boolean staticCounter, String group, int maxRows, long[] array, Set<Entry<String, Counter>> counterEntrySet) {
// sort the counters by putting them into a sorted map
TreeMap<Long, String> sorted = new TreeMap<>();
long sum = 0;
for (Map.Entry<String, Counter> entry : counterEntrySet) {
Counter counter = entry.getValue();
int index = counter.index;
if (counter.group.equals(group)) {
sum += array[index];
sorted.put(array[index] * array.length + index, getName(entry.getKey(), group));
}
}
if (sum > 0) {
long cutoff = sorted.size() < 10 ? 1 : Math.max(1, sum / 100);
int cnt = sorted.size();
// remove everything below cutoff and keep at most maxRows
Iterator<Map.Entry<Long, String>> iter = sorted.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Long, String> entry = iter.next();
long counter = entry.getKey() / array.length;
if (counter < cutoff || cnt > maxRows) {
iter.remove();
}
cnt--;
}
String numFmt = Options.DynamicCountersPrintGroupSeparator.getValue() ? "%,19d" : "%19d";
if (staticCounter) {
out.println("=========== " + group + " (static counters):");
for (Map.Entry<Long, String> entry : sorted.entrySet()) {
long counter = entry.getKey() / array.length;
out.format(Locale.US, numFmt + " %3d%% %s\n", counter, percentage(counter, sum), entry.getValue());
}
out.format(Locale.US, numFmt + " total\n", sum);
} else {
if (group.startsWith("~")) {
out.println("=========== " + group + " (dynamic counters), time = " + seconds + " s:");
for (Map.Entry<Long, String> entry : sorted.entrySet()) {
long counter = entry.getKey() / array.length;
out.format(Locale.US, numFmt + "/s %3d%% %s\n", (long) (counter / seconds), percentage(counter, sum), entry.getValue());
}
out.format(Locale.US, numFmt + "/s total\n", (long) (sum / seconds));
} else {
out.println("=========== " + group + " (dynamic counters):");
for (Map.Entry<Long, String> entry : sorted.entrySet()) {
long counter = entry.getKey() / array.length;
out.format(Locale.US, numFmt + " %3d%% %s\n", counter, percentage(counter, sum), entry.getValue());
}
out.format(Locale.US, numFmt + " total\n", sum);
}
}
}
}
private static void dumpComputerReadable(PrintStream out, boolean staticCounter, String group, long[] array, Set<Entry<String, Counter>> counterEntrySet) {
String category = staticCounter ? "static counters" : "dynamic counters";
for (Map.Entry<String, Counter> entry : counterEntrySet) {
Counter counter = entry.getValue();
if (counter.group.equals(group)) {
String name = getName(entry.getKey(), group);
int index = counter.index;
long value = array[index];
// TODO(je): escape strings
out.printf("%s;%s;%s;%d\n", category, group, name, value);
}
}
}
private static long percentage(long counter, long sum) {
return (counter * 200 + 1) / sum / 2;
}
private abstract static class CallbackOutputStream extends OutputStream {
protected final PrintStream delegate;
private final byte[][] patterns;
private final int[] positions;
public CallbackOutputStream(PrintStream delegate, String... patterns) {
this.delegate = delegate;
this.positions = new int[patterns.length];
this.patterns = new byte[patterns.length][];
for (int i = 0; i < patterns.length; i++) {
this.patterns[i] = patterns[i].getBytes();
}
}
protected abstract void patternFound(int index);
@Override
public void write(int b) throws IOException {
try {
delegate.write(b);
for (int i = 0; i < patterns.length; i++) {
int j = positions[i];
byte[] cs = patterns[i];
byte patternChar = cs[j];
if (patternChar == '~' && Character.isDigit(b)) {
// nothing to do...
} else {
if (patternChar == '~') {
patternChar = cs[++positions[i]];
}
if (b == patternChar) {
positions[i]++;
} else {
positions[i] = 0;
}
}
if (positions[i] == patterns[i].length) {
positions[i] = 0;
patternFound(i);
}
}
} catch (RuntimeException e) {
e.printStackTrace(delegate);
throw e;
}
}
}
public static void initialize(final CompilerToVM compilerToVM) {
final class BenchmarkCountersOutputStream extends CallbackOutputStream {
private long startTime;
private boolean running;
private boolean waitingForEnd;
private BenchmarkCountersOutputStream(PrintStream delegate, String start, String end) {
super(delegate, new String[]{"\n", end, start});
}
@Override
protected void patternFound(int index) {
switch (index) {
case 2:
startTime = System.nanoTime();
BenchmarkCounters.clear(compilerToVM.collectCounters());
running = true;
break;
case 1:
if (running) {
waitingForEnd = true;
}
break;
case 0:
if (waitingForEnd) {
waitingForEnd = false;
running = false;
BenchmarkCounters.dump(delegate, (System.nanoTime() - startTime) / 1000000000d, compilerToVM.collectCounters(), 100);
}
break;
}
}
}
if (Options.BenchmarkDynamicCounters.getValue() != null) {
String[] arguments = Options.BenchmarkDynamicCounters.getValue().split(",");
if (arguments.length == 0 || (arguments.length % 3) != 0) {
throw new JVMCIError("invalid arguments to BenchmarkDynamicCounters: (err|out),start,end,(err|out),start,end,... (~ matches multiple digits)");
}
for (int i = 0; i < arguments.length; i += 3) {
if (arguments[i].equals("err")) {
System.setErr(new PrintStream(new BenchmarkCountersOutputStream(System.err, arguments[i + 1], arguments[i + 2])));
} else if (arguments[i].equals("out")) {
System.setOut(new PrintStream(new BenchmarkCountersOutputStream(System.out, arguments[i + 1], arguments[i + 2])));
} else {
throw new JVMCIError("invalid arguments to BenchmarkDynamicCounters: err|out");
}
}
enabled = true;
}
if (Options.GenericDynamicCounters.getValue()) {
enabled = true;
}
if (Options.TimedDynamicCounters.getValue() > 0) {
Thread thread = new Thread() {
long lastTime = System.nanoTime();
PrintStream out = TTY.out;
@Override
public void run() {
while (true) {
try {
Thread.sleep(Options.TimedDynamicCounters.getValue());
} catch (InterruptedException e) {
}
long time = System.nanoTime();
dump(out, (time - lastTime) / 1000000000d, compilerToVM.collectCounters(), 10);
lastTime = time;
}
}
};
thread.setDaemon(true);
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
enabled = true;
}
if (enabled) {
clear(compilerToVM.collectCounters());
}
}
public static void shutdown(CompilerToVM compilerToVM, long compilerStartTime) {
if (Options.GenericDynamicCounters.getValue()) {
dump(TTY.out, (System.nanoTime() - compilerStartTime) / 1000000000d, compilerToVM.collectCounters(), 100);
}
}
}
| gpl-2.0 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/graph/SimpleTypedEdge.java | 2912 | /*
* Copyright 2011 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
*
* The S-Space package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.ucla.sspace.graph;
/**
* An implementation of a {@link TypedEdge}.
*/
public class SimpleTypedEdge<T> implements TypedEdge<T>, java.io.Serializable {
private static final long serialVersionUID = 1L;
private final int from;
private final int to;
private final T type;
public SimpleTypedEdge(T edgeType, int from, int to) {
this.type = edgeType;
if (type == null)
throw new NullPointerException("edge type cannot be null");
this.from = from;
this.to = to;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public <E extends Edge> E clone(int from, int to) {
return (E)(new SimpleTypedEdge<T>(type, from, to));
}
/**
* {@inheritDoc}
*/
public T edgeType() {
return type;
}
/**
* Returns {@code true} if {@code o} is an {@link TypedEdge} with the same
* edge type and has the same vertices (independent of that edge's
* orientation).
*/
public boolean equals(Object o) {
if (o instanceof Edge) {
TypedEdge<?> e = (TypedEdge)o;
return e.edgeType().equals(type)
// Undirected vertex test
&& ((e.from() == from && e.to() == to)
|| e.from() == to && e.to() == from);
}
return false;
}
public int hashCode() {
return from ^ to;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public <E extends Edge> E flip() {
return (E)(new SimpleTypedEdge<T>(type, to, from));
}
/**
* {@inheritDoc}
*/
public int from() {
return from;
}
/**
* {@inheritDoc}
*/
public int to() {
return to;
}
public String toString() {
return "(" + from + "<-->" + to + "):" + type;
}
} | gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08548.java | 3839 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08548")
public class BenchmarkTest08548 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
// FILE URIs are tricky because they are different between Mac and Windows because of lack of standardization.
// Mac requires an extra slash for some reason.
String startURIslashes = "";
if (System.getProperty("os.name").indexOf("Windows") != -1)
if (System.getProperty("os.name").indexOf("Windows") != -1)
startURIslashes = "/";
else startURIslashes = "//";
try {
java.net.URI fileURI = new java.net.URI("file", null, startURIslashes
+ org.owasp.benchmark.helpers.Utils.testfileDir.replace('\\', java.io.File.separatorChar).replace(' ', '_') + bar, null, null);
new java.io.File(fileURI);
} catch (java.net.URISyntaxException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a57470 = param; //assign
StringBuilder b57470 = new StringBuilder(a57470); // stick in stringbuilder
b57470.append(" SafeStuff"); // append some safe content
b57470.replace(b57470.length()-"Chars".length(),b57470.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map57470 = new java.util.HashMap<String,Object>();
map57470.put("key57470", b57470.toString()); // put in a collection
String c57470 = (String)map57470.get("key57470"); // get it back out
String d57470 = c57470.substring(0,c57470.length()-1); // extract most of it
String e57470 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d57470.getBytes() ) )); // B64 encode and decode it
String f57470 = e57470.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g57470 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g57470); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/hibernate-core/org/hibernate/param/DynamicFilterParameterSpecification.java | 2814 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.param;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.Type;
/**
* A specialized ParameterSpecification impl for dealing with a dynamic filter parameters.
*
* @see org.hibernate.Session#enableFilter(String)
*
* @author Steve Ebersole
*/
public class DynamicFilterParameterSpecification implements ParameterSpecification {
private final String filterName;
private final String parameterName;
private final Type definedParameterType;
/**
* Constructs a parameter specification for a particular filter parameter.
*
* @param filterName The name of the filter
* @param parameterName The name of the parameter
* @param definedParameterType The paremeter type specified on the filter metadata
*/
public DynamicFilterParameterSpecification(
String filterName,
String parameterName,
Type definedParameterType) {
this.filterName = filterName;
this.parameterName = parameterName;
this.definedParameterType = definedParameterType;
}
@Override
public int bind(
PreparedStatement statement,
QueryParameters qp,
SharedSessionContractImplementor session,
int start) throws SQLException {
final int columnSpan = definedParameterType.getColumnSpan( session.getFactory() );
final String fullParamName = filterName + '.' + parameterName;
final Object value = session.getLoadQueryInfluencers().getFilterParameterValue(fullParamName);
final Type type = session.getLoadQueryInfluencers().getFilterParameterType(fullParamName);
if ( Collection.class.isInstance( value ) ) {
int positions = 0;
Iterator itr = ( ( Collection ) value ).iterator();
while ( itr.hasNext() ) {
Object next = itr.next();
qp.bindDynamicParameter( type, next );
definedParameterType.nullSafeSet( statement, next, start + positions, session );
positions += columnSpan;
}
return positions;
}
else {
qp.bindDynamicParameter(type, value);
definedParameterType.nullSafeSet( statement, value, start, session );
return columnSpan;
}
}
@Override
public Type getExpectedType() {
return definedParameterType;
}
@Override
public void setExpectedType(Type expectedType) {
// todo : throw exception? maybe warn if not the same?
}
@Override
public String renderDisplayInfo() {
return "dynamic-filter={filterName=" + filterName + ",paramName=" + parameterName + "}";
}
}
| gpl-2.0 |
aarexer/mystamps | src/main/java/ru/mystamps/web/controller/interceptor/ByteArrayMultipartFile.java | 2336 | /*
* Copyright (C) 2009-2018 Slava Semushin <slava.semushin@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ru.mystamps.web.controller.interceptor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.springframework.web.multipart.MultipartFile;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
class ByteArrayMultipartFile implements MultipartFile {
private final byte[] content;
private final String contentType;
private final String link;
@Override
public String getName() {
throw new IllegalStateException("Not implemented");
}
@Override
public String getOriginalFilename() {
return link;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return getSize() == 0;
}
@Override
public long getSize() {
if (content == null) {
return 0;
}
return content.length;
}
@Override
public byte[] getBytes() throws IOException {
return content; // NOPMD: MethodReturnsInternalArray
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
// Default mode is: CREATE, WRITE, and TRUNCATE_EXISTING.
// To prevent unexpected rewriting of existing file, we're overriding this behavior by
// explicitly specifying options.
Files.write(
dest.toPath(),
content,
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE
);
}
}
| gpl-2.0 |
mmuellerTGM/SEW_Workspace | A12_LottoSpiel/src/mueller/LottoTip.java | 284 | package mueller;
import java.util.HashSet;
public class LottoTip {
/**
* Der Lotto Tipp(6 einmalige zahlen zwischen 1-45)
*/
HashSet<Integer> tip = new HashSet<Integer>();
public LottoTip() {
while (tip.size()<=6) {
tip.add((int) ((Math.random()*46)+1));
}
}
}
| gpl-2.0 |
yolile/ASPHelper | src/helper/clases/Produccion.java | 1851 | /*-
* Copyright (c)
*
* 2015 - Yohanna Lisnichuk
* 2015 - Victor Ughelli
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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 src.helper.clases;
import java.util.List;
/**
* Clase que representa a una produccion de la forma A:BC donde A es izquierda y
* BC derecha
*
* @author Yohanna Lisnichuk
* @since 1.0
* @version 1.0 25/10/2015
*
*/
public class Produccion {
public Produccion(String izquierda, List<String> derecha, boolean procesado) {
super();
this.izquierda = izquierda;
this.derecha = derecha;
this.procesado = procesado;
}
private String izquierda;
private boolean procesado;
private List<String> derecha;
@Override
public String toString() {
return izquierda + "->" + derecha;
}
public String getIzquierda() {
return izquierda;
}
public void setIzquierda(String izquierda) {
this.izquierda = izquierda;
}
public List<String> getDerecha() {
return derecha;
}
public void setDerecha(List<String> derecha) {
this.derecha = derecha;
}
public boolean isProcesado() {
return procesado;
}
public void setProcesado(boolean procesado) {
this.procesado = procesado;
}
}
| gpl-2.0 |
GrenderG/TinyList | app/src/main/java/es/dmoral/tinylist/adapters/SavedListsAdapter.java | 8149 | package es.dmoral.tinylist.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import es.dmoral.tinylist.R;
import es.dmoral.tinylist.activities.EditListActivity;
import es.dmoral.tinylist.activities.MainActivity;
import es.dmoral.tinylist.fragments.SavedListsFragment;
import es.dmoral.tinylist.helpers.TinyListSQLHelper;
import es.dmoral.tinylist.models.Task;
import es.dmoral.tinylist.models.TaskList;
/**
* Created by grend on 13/01/2016.
*/
public class SavedListsAdapter extends RecyclerView.Adapter<SavedListsAdapter.ViewHolder> {
private final ArrayList<TaskList> taskLists;
private final Context context;
@SuppressLint("SimpleDateFormat")
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/* Cached item to restore (if user wants to), used when an item is removed. */
private TaskList cachedItem;
private int contextMenuSelectedPosition;
public SavedListsAdapter(ArrayList<TaskList> taskLists, Context context) {
this.taskLists = taskLists;
this.context = context;
}
@Override
public SavedListsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new SavedListsAdapter.ViewHolder(
LayoutInflater.from(parent.getContext()).inflate(R.layout.saved_list_cardview, parent, false));
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.cardView.setCardBackgroundColor(taskLists.get(holder.getAdapterPosition()).getBackgroundColor());
holder.taskListTitle.setVisibility(View.VISIBLE);
if (taskLists.get(holder.getAdapterPosition()).getTitle().isEmpty())
holder.taskListTitle.setVisibility(View.GONE);
else
holder.taskListTitle.setText(taskLists.get(holder.getAdapterPosition()).getTitle());
holder.taskContainer.removeAllViews();
for (Task task : taskLists.get(holder.getAdapterPosition()).getTasks()) {
TextView taskDescription = new TextView(context);
taskDescription.setText(task.getTask());
taskDescription.setTextSize(18f);
if (task.isChecked()) {
taskDescription.setPaintFlags(taskDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
taskDescription.setAlpha(0.3f);
}
holder.taskContainer.addView(taskDescription);
}
holder.taskListDate.setText(dateFormat.format(taskLists.get(holder.getAdapterPosition()).getCreationDate()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, EditListActivity.class);
intent.putExtra(EditListActivity.INTENT_EDIT, taskLists.get(holder.getAdapterPosition()));
context.startActivity(intent);
}
});
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
setContextMenuSelectedPosition(holder.getAdapterPosition());
return false;
}
});
holder.archiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final TaskList taskListToArchive = taskLists.get(holder.getAdapterPosition());
taskListToArchive.setIsArchived(true);
TinyListSQLHelper.getSqlHelper(context).addOrUpdateTaskList(taskListToArchive);
removeItem(holder.getAdapterPosition());
((SavedListsFragment) ((MainActivity) context).getCurrentVisibleFragment()).undoSnackbar();
}
});
holder.shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String shareIntentText = "";
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntentText += taskLists.get(holder.getAdapterPosition()).getTitle() + "\n\n";
for (Task task : taskLists.get(holder.getAdapterPosition()).getTasks()) {
shareIntentText += (task.isChecked() ? Task.DONE_TASK_MARK : Task.UNDONE_TASK_MARK)
+ " " + task.getTask() + "\n";
}
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, shareIntentText.trim());
context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string.share_with)));
}
});
}
@Override
public int getItemCount() {
return this.taskLists.size();
}
/**
* This method removes an item and notifies their removal and notifies the change of
* the views below the removed item.
*
* @param position position of the item to remove
*/
public void removeItem(int position) {
this.cachedItem = this.taskLists.get(position);
this.taskLists.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount() - position);
}
/**
* Replaces all items with new ones.
*
* @param newTaskLists items to replace.
*/
public void replaceWith(ArrayList<TaskList> newTaskLists) {
this.taskLists.clear();
this.taskLists.addAll(newTaskLists);
notifyDataSetChanged();
}
/**
* Get item at the desired position.
*
* @param position desired position
* @return item at the desired position.
*/
public TaskList getItem(int position) {
return this.taskLists.get(position);
}
/**
* This method returns the cached item (see its description to know more)
*
* @return cached item.
*/
public TaskList getCachedItem() {
return this.cachedItem;
}
/**
* Sets the cached item (see its description to know more)
*
* @param item cached item.
*/
public void setCachedItem(TaskList item) {
this.cachedItem = item;
}
public int getContextMenuSelectedPosition() {
return contextMenuSelectedPosition;
}
public void setContextMenuSelectedPosition(int contextMenuSelectedPosition) {
this.contextMenuSelectedPosition = contextMenuSelectedPosition;
}
@Override
public void onViewRecycled(ViewHolder holder) {
holder.cardView.setOnLongClickListener(null);
super.onViewRecycled(holder);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
@Bind(R.id.task_list_title)
TextView taskListTitle;
@Bind(R.id.task_container)
LinearLayout taskContainer;
@Bind(R.id.task_list_date)
TextView taskListDate;
@Bind(R.id.card_view_saved_lists)
CardView cardView;
@Bind(R.id.archive)
ImageView archiveButton;
@Bind(R.id.share)
ImageView shareButton;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.add(Menu.NONE, R.id.contextual_delete_menu, Menu.NONE, R.string.delete_list_cont_menu);
}
}
}
| gpl-2.0 |
cfloersch/sdp | src/main/java/xpertss/sdp/SessionParser.java | 26974 | /**
* Created By: cfloersch
* Date: 6/2/13
* Copyright 2013 XpertSoftware
*/
package xpertss.sdp;
import xpertss.lang.Integers;
import xpertss.lang.Longs;
import xpertss.lang.Objects;
import xpertss.lang.Strings;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Parser to parse SessionDescription objects from standard SDP files.
* <p>
* This parser performs only rudimentary validation of data. Numbers
* must properly parse to numbers, the minimum number of fields must
* be defined, and field ordering is enforced. However, relational
* rules are not currently implemented.
* <p><pre>
* Session description
* v= (one protocol version)
* o= (one originator and session identifier)
* s= (one session name)
* i= (zero or one session information)
* u= (zero or one URI of description)
* e= (zero or more email address)
* p= (zero or more phone number)
* c= (zero or one connection information)
* b= (zero or more bandwidth information lines)
* One or more time descriptions ("t=" and "r=" lines; see below)
* z= (zero or one time zone adjustments)
* k= (zero or one encryption key)
* a= (zero or more session attribute lines)
* Zero or more media descriptions
*
* Time description
* t= (one time the session is active)
* r= (zero or more repeat times)
*
* Media description, if present
* m= (one media name and transport address)
* i= (zero or one media title)
* c= (zero or one connection information)
* b= (zero or more bandwidth information lines)
* k= (zero or one encryption key)
* a= (zero or more media attribute lines)
* </pre>
*/
public class SessionParser {
private static final Set<String> validchars = new HashSet<>();
static {
validchars.add("v");
validchars.add("o");
validchars.add("s");
validchars.add("i");
validchars.add("u");
validchars.add("e");
validchars.add("p");
validchars.add("c");
validchars.add("b");
validchars.add("t");
validchars.add("r");
validchars.add("z");
validchars.add("k");
validchars.add("a");
validchars.add("m");
}
/**
* Parse a string which represents an SDP file returning a Session Description if
* it successfully parsed the data.
*
* @throws SdpParseException If an error occurs parsing the structure of the document
* @throws NullPointerException If the supplied source string is null
*/
public SessionDescription parse(String str) throws SdpParseException, NullPointerException
{
return parse(new Scanner(str));
}
/**
* Parse the contents of a given sdp file identified by a Path object returning a Session
* Description if it successfully parsed the data.
*
* @throws SdpParseException If an error occurs parsing the structure of the document
* @throws NullPointerException If the supplied source path is null
* @throws IOException If an I/O error occurs opening source
*/
public SessionDescription parse(Path path) throws SdpParseException, NullPointerException, IOException
{
return parse(new Scanner(path, "UTF-8"));
}
/**
* Parse the sdp contents from a given Reader object returning a Session Description if it
* successfully parsed the data.
*
* @throws SdpParseException If an error occurs parsing the structure of the document
* @throws NullPointerException If the supplied source reader is null
*/
public SessionDescription parse(Reader reader) throws SdpParseException, NullPointerException
{
return parse(new Scanner(reader));
}
/**
* Parse the sdp contents from a given InputStream object returning a Session Description if it
* successfully parsed the data.
*
* @throws SdpParseException If an error occurs parsing the structure of the document
* @throws NullPointerException If the supplied source stream is null
*/
public SessionDescription parse(InputStream stream) throws SdpParseException, NullPointerException
{
return parse(new Scanner(stream, "UTF-8"));
}
private SessionDescription parse(Scanner scanner) throws SdpParseException
{
try {
SessionBuilder builder = SessionBuilder.create();
SessionFieldParser chain = createParserChain();
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(Strings.isEmpty(line)) break;
if(line.length() < 3 || line.charAt(1) != '=') throw new SdpParseException("invalid line format: " + line);
if(!validchars.contains(Character.toString(line.charAt(0))))
throw new SdpParseException("invalid field: " + line);
chain = chain.parse(builder, line);
}
chain.finish(builder);
return builder.build();
} finally {
scanner.close();
}
}
private SessionFieldParser createParserChain()
{
SessionFieldParser parser = new MediaFieldParser();
parser = new KeyFieldParser(new AttributeFieldParser(parser));
parser = new TimeFieldParser(new TimeZonesFieldParser(parser));
parser = new ConnectionFieldParser(new BandwidthFieldParser(parser));
parser = new EmailFieldParser(new PhoneFieldParser(parser));
parser = new InfoFieldParser(new UriFieldParser(parser));
parser = new OriginFieldParser(new SessionNameFieldParser(parser));
return new VersionFieldParser((parser));
}
private interface SessionFieldParser {
public SessionFieldParser parse(SessionBuilder builder, String line);
public void finish(SessionBuilder builder);
}
private interface MediaSubFieldParser {
public MediaSubFieldParser parse(MediaBuilder builder, String line);
public void finish(MediaBuilder builder);
}
private class VersionFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public VersionFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("v")) {
int version = Integers.parse(line.substring(2), -1);
if(version < 0) throw new SdpParseException("invalid version specified: " + line.substring(2));
builder.setVersion(version);
return next;
}
throw new SdpParseException("invalid session description: expecting version");
}
@Override
public void finish(SessionBuilder builder)
{
throw new SdpParseException("premature end of stream: expecting version");
}
}
private class OriginFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public OriginFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("o")) {
String[] parts = line.substring(2).split("\\s+");
if(parts.length != 6) throw new SdpParseException("invalid origin line: " + line.substring(2));
OriginBuilder origin = OriginBuilder.create().setUsername(parts[0]);
long sessionId = Longs.parse(parts[1], -1);
if(sessionId < 0) throw new SdpParseException("invalid origin sessionId: " + parts[1]);
origin.setSessionId(sessionId);
long version = Longs.parse(parts[2], -1);
if(version < 0) throw new SdpParseException("invalid origin session version: " + parts[2]);
origin.setSessionVersion(version);
origin.setNetworkType(parts[3]).setAddressType(parts[4]).setAddress(parts[5]);
builder.setOrigin(origin.build());
return next;
}
throw new SdpParseException("invalid session description: expecting origin");
}
@Override
public void finish(SessionBuilder builder)
{
throw new SdpParseException("premature end of stream: expecting origin");
}
}
private class SessionNameFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public SessionNameFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("s")) {
builder.setSessionName(line.substring(2));
return next;
}
throw new SdpParseException("invalid session description: expecting session name");
}
@Override
public void finish(SessionBuilder builder)
{
throw new SdpParseException("premature end of stream: expecting session name");
}
}
private class InfoFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public InfoFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("i")) {
builder.setInfo(line.substring(2));
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class UriFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public UriFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("u")) {
builder.setUri(line.substring(2));
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class EmailFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public EmailFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("e")) {
builder.addEmail(line.substring(2));
return this;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class PhoneFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public PhoneFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("p")) {
builder.addPhone(line.substring(2));
return this;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class ConnectionFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public ConnectionFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("c")) {
String[] parts = line.substring(2).split("\\s+");
if(parts.length != 3) throw new SdpParseException("invalid connection line: " + line.substring(2));
builder.setConnection(parts[2], parts[1], parts[0]);
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class BandwidthFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public BandwidthFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("b")) {
String[] parts = line.substring(2).split(":");
if(parts.length != 2) throw new SdpParseException("invalid bandwidth line: " + line.substring(2));
int kbps = Integers.parse(parts[1], -1);
if(kbps < 0) throw new SdpParseException("invalid bandwidth value specified: " + parts[1]);
builder.addBandwidth(parts[0], kbps);
return this;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class TimeFieldParser implements SessionFieldParser {
private SessionFieldParser next;
private TimeBuilder time;
public TimeFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("t")) {
if(time != null) builder.addTimeDescription(time.build());
String[] parts = line.substring(2).split("\\s+");
if(parts.length != 2) throw new SdpParseException("invalid time field: " + line.substring(2));
long start = Longs.parse(parts[0], -1);
if(start < 0) throw new SdpParseException("invalid start time: " + parts[0]);
long stop = Longs.parse(parts[1], -1);
if(stop < 0) throw new SdpParseException("invalid stop time: " + parts[1]);
time = TimeBuilder.create().setTime(Utils.toDate(start), Utils.toDate(stop));
return this;
} else if(line.startsWith("r")) {
if(time == null) throw new SdpParseException("invalid session description: expecting time");
String[] parts = line.substring(2).split("\\s+");
if(parts.length < 3) throw new SdpParseException("invalid repeat time field: " + line.substring(2));
long interval = fromCompactTime(parts[0]);
if(interval < 1) throw new SdpParseException("invalid repeat time interval: " + parts[0]);
long duration = fromCompactTime(parts[1]);
if(duration < 1) throw new SdpParseException("invalid repeat time duration: " + parts[1]);
long[] offsets = new long[parts.length - 2];
for(int i = 0; i < offsets.length; i++) {
offsets[i] = fromCompactTime(parts[i+2]);
if(offsets[i] < 0) throw new SdpParseException("invalid repeat time offset: " + parts[i+2]);
}
time.addRepeatTime(interval, duration, offsets);
return this;
} else if(time != null) {
builder.addTimeDescription(time.build());
return next.parse(builder, line);
}
throw new SdpParseException("invalid session description: expecting time");
}
@Override
public void finish(SessionBuilder builder)
{
if(time != null) builder.addTimeDescription(time.build());
else throw new SdpParseException("premature end of stream: expecting time");
}
}
private class TimeZonesFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public TimeZonesFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("z")) {
String[] parts = line.substring(2).split("\\s+");
if(parts.length % 2 != 0) throw new SdpParseException("invalid timezones field: " + line.substring(2));
for(int i = 0; i < parts.length - 1; i += 2) {
long date = Longs.parse(parts[i], -1);
if(date < 0) throw new SdpParseException("invalid date found: " + parts[i]);
builder.addTimeAdjustment(Utils.toDate(date), fromCompactTime(parts[i + 1]));
}
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class KeyFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public KeyFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("k")) {
int idx = line.indexOf(":");
if(idx < 0) {
builder.setKey(line.substring(2), null);
} else if(idx < line.length() - 1) {
builder.setKey(line.substring(2, idx), line.substring(idx + 1));
} else {
builder.setKey(line.substring(2, idx), null);
}
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class AttributeFieldParser implements SessionFieldParser {
private SessionFieldParser next;
public AttributeFieldParser(SessionFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("a")) {
int idx = line.indexOf(":");
if(idx < 0) {
builder.addAttribute(line.substring(2), null);
} else if(idx == line.length() - 1) {
builder.addAttribute(line.substring(2, idx), null);
} else {
builder.addAttribute(line.substring(2, idx), line.substring(idx+1));
}
return this;
}
return next.parse(builder, line);
}
@Override
public void finish(SessionBuilder builder)
{
next.finish(builder);
}
}
private class MediaFieldParser implements SessionFieldParser {
private MediaBuilder media;
private MediaSubFieldParser chain;
@Override
public SessionFieldParser parse(SessionBuilder builder, String line)
{
if(line.startsWith("m")) {
if(media != null) {
builder.addMediaDescription(media.build());
}
media = MediaBuilder.create();
chain = createParserChain();
String[] parts = line.substring(2).split("\\s+");
if(parts.length < 4) throw new SdpParseException("incomplete media field: " + line.substring(2));
String[] ports = parts[1].split("/", 2);
int port = Integers.parse(ports[0], -1);
if(port < 0 || port > 65535) throw new SdpParseException("found invalid port: " + ports[0]);
int count = (ports.length < 2) ? 1 : Integers.parse(ports[1], -1);
if(count < 1) throw new SdpParseException("found invalid port count: " + ports[1]);
int[] formats = new int[parts.length - 3];
for(int i = 0; i < formats.length; i++) {
formats[i] = Integers.parse(parts[i+3], -1);
if(formats[i] < 0) throw new SdpParseException("invalid format found: " + parts[i+3]);
}
media.setMedia(parts[0], port, count, parts[2], formats);
} else if(media != null) {
chain = chain.parse(media, line);
} else {
throw new SdpParseException("invalid session description: expecting media");
}
return this;
}
@Override
public void finish(SessionBuilder builder)
{
if(media != null) {
chain.finish(media);
builder.addMediaDescription(media.build());
}
}
private MediaSubFieldParser createParserChain()
{
MediaSubFieldParser parser = new AttributeMediaSubFieldParser();
parser = new KeyMediaSubFieldParser(parser);
parser = new BandwidthMediaSubFieldParser(parser);
parser = new ConnectionMediaSubFieldParser(parser);
return new InfoMediaSubFieldParser(parser);
}
private class InfoMediaSubFieldParser implements MediaSubFieldParser {
private MediaSubFieldParser next;
public InfoMediaSubFieldParser(MediaSubFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public MediaSubFieldParser parse(MediaBuilder builder, String line)
{
if(line.startsWith("i")) {
builder.setInfo(line.substring(2));
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(MediaBuilder builder)
{
next.finish(builder);
}
}
private class ConnectionMediaSubFieldParser implements MediaSubFieldParser {
private MediaSubFieldParser next;
public ConnectionMediaSubFieldParser(MediaSubFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public MediaSubFieldParser parse(MediaBuilder builder, String line)
{
if(line.startsWith("c")) {
String[] parts = line.substring(2).split("\\s+");
if(parts.length != 3) throw new SdpParseException("invalid connection line: " + line.substring(2));
builder.setConnection(parts[2], parts[1], parts[0]);
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(MediaBuilder builder)
{
next.finish(builder);
}
}
private class BandwidthMediaSubFieldParser implements MediaSubFieldParser {
private MediaSubFieldParser next;
public BandwidthMediaSubFieldParser(MediaSubFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public MediaSubFieldParser parse(MediaBuilder builder, String line)
{
if(line.startsWith("b")) {
String[] parts = line.substring(2).split(":");
if(parts.length != 2) throw new SdpParseException("invalid bandwidth line: " + line.substring(2));
int kbps = Integers.parse(parts[1], -1);
if(kbps < 0) throw new SdpParseException("invalid bandwidth value specified: " + parts[1]);
builder.addBandwidth(parts[0], kbps);
return this;
}
return next.parse(builder, line);
}
@Override
public void finish(MediaBuilder builder)
{
next.finish(builder);
}
}
private class KeyMediaSubFieldParser implements MediaSubFieldParser {
private MediaSubFieldParser next;
public KeyMediaSubFieldParser(MediaSubFieldParser next)
{
this.next = Objects.notNull(next, "next may not be null");
}
@Override
public MediaSubFieldParser parse(MediaBuilder builder, String line)
{
if(line.startsWith("k")) {
int idx = line.indexOf(":");
if(idx < 0) {
builder.setKey(line.substring(2), null);
} else if(idx < line.length() - 1) {
builder.setKey(line.substring(2, idx), line.substring(idx + 1));
} else {
builder.setKey(line.substring(2, idx), null);
}
return next;
}
return next.parse(builder, line);
}
@Override
public void finish(MediaBuilder builder)
{
next.finish(builder);
}
}
private class AttributeMediaSubFieldParser implements MediaSubFieldParser {
@Override
public MediaSubFieldParser parse(MediaBuilder builder, String line)
{
if(line.startsWith("a")) {
int idx = line.indexOf(":");
if(idx < 0) {
builder.addAttribute(line.substring(2), null);
} else if(idx == line.length() - 1) {
builder.addAttribute(line.substring(2, idx), null);
} else {
builder.addAttribute(line.substring(2, idx), line.substring(idx+1));
}
return this;
}
throw new SdpParseException("misplaced field: " + line);
}
@Override
public void finish(MediaBuilder builder)
{
// what to do??
}
}
}
private static long fromCompactTime(String compact)
{
try {
char lastChar = compact.charAt(compact.length() - 1);
if(!Character.isDigit(lastChar)) {
long value = Long.parseLong(compact.substring(0, compact.length() - 1));
if(lastChar == 'd') {
return DAYS.toSeconds(value);
} else if(lastChar == 'h') {
return HOURS.toSeconds(value);
} else if(lastChar == 'm') {
return MINUTES.toSeconds(value);
} else if(lastChar == 's') {
return SECONDS.toSeconds(value);
}
throw new SdpParseException("unknown time unit found: " + compact);
} else {
return Long.parseLong(compact);
}
} catch(NumberFormatException nfe) {
throw new SdpParseException("invalid time unit found: " + compact);
}
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08678.java | 2109 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08678")
public class BenchmarkTest08678 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
response.getWriter().print(bar.toCharArray());
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
jboss/jboss-jad-api_spec | src/main/java/javax/enterprise/deploy/shared/StateType.java | 2876 | package javax.enterprise.deploy.shared;
/**
* An enumeration of deployment states.
*
* @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
* @version $Revision$
*/
public class StateType
{
// Constants -----------------------------------------------------
/** The RUNNING integer value */
private static final int RUNNING_INT = 0;
/** The COMPLETED integer value */
private static final int COMPLETED_INT = 1;
/** The FAILED integer value */
private static final int FAILED_INT = 2;
/** The RELEASED integer value */
private static final int RELEASED_INT = 3;
/** The state type for an RUNNING */
public static final StateType RUNNING = new StateType(RUNNING_INT);
/** The state type for an COMPLETED */
public static final StateType COMPLETED = new StateType(COMPLETED_INT);
/** The state type for an FAILED */
public static final StateType FAILED = new StateType(FAILED_INT);
/** The state type for an RELEASED */
public static final StateType RELEASED = new StateType(RELEASED_INT);
/** The state types */
private static final StateType[] stateTypes = new StateType[]
{
RUNNING, COMPLETED, FAILED, RELEASED
};
/** The state descriptions */
private static final String[] stateDescs = new String[]
{
"Running",
"Completed",
"Failed",
"Released"
};
// Attributes ----------------------------------------------------
/** The value */
private int value;
/**
* Create a new StateType
*
* @param value the value
*/
protected StateType(int value)
{
this.value = value;
}
// Public --------------------------------------------------------
/**
* Get the value
*
* @return the value
*/
public int getValue()
{
return value;
}
/**
* Get the string table for class command type
*
* [todo] check this?
* @return the string table
*/
protected String[] getStringTable()
{
return stateDescs;
}
/**
* Get the enumerated values for module type
*
* @return the string table
*/
protected StateType[] getEnumValueTable()
{
return stateTypes;
}
/**
* Get the state type for an integer
*
* @param type the type
* @return the state type
*/
public static StateType getStateType(int type)
{
if (type >= stateTypes.length)
return null;
return stateTypes[type];
}
public String toString()
{
return stateDescs[value];
}
/**
* Return the offset of the first element
*
* @return the offset
*/
protected int getOffset()
{
return RUNNING_INT;
}
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| gpl-2.0 |
moiarcsan/openls1.3 | src/main/java/org/jvnet/ogc/SpeedType.java | 1807 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.10.29 at 06:46:24 PM CET
//
package org.jvnet.ogc;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SpeedType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SpeedType">
* <complexContent>
* <extension base="{http://www.opengis.net/xls}AbstractMeasureType">
* <attribute name="uom" type="{http://www.opengis.net/xls}SpeedUnitType" default="KPH" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SpeedType")
public class SpeedType
extends AbstractMeasureType
{
@XmlAttribute(name = "uom")
protected SpeedUnitType uom;
/**
* Gets the value of the uom property.
*
* @return
* possible object is
* {@link SpeedUnitType }
*
*/
public SpeedUnitType getUom() {
if (uom == null) {
return SpeedUnitType.KPH;
} else {
return uom;
}
}
/**
* Sets the value of the uom property.
*
* @param value
* allowed object is
* {@link SpeedUnitType }
*
*/
public void setUom(SpeedUnitType value) {
this.uom = value;
}
}
| gpl-2.0 |
geomatico/52n-sos-4.0 | core/api/src/main/java/org/n52/sos/ogc/ows/SosServiceIdentificationFactory.java | 5754 | /**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* info@52north.org
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.ogc.ows;
import static org.n52.sos.ogc.ows.SosServiceIdentificationFactorySettings.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.n52.sos.config.SettingsManager;
import org.n52.sos.config.annotation.Configurable;
import org.n52.sos.config.annotation.Setting;
import org.n52.sos.exception.ConfigurationException;
import org.n52.sos.ogc.sos.SosConstants;
import org.n52.sos.service.operator.ServiceOperatorRepository;
import org.n52.sos.util.LazyThreadSafeProducer;
import org.n52.sos.util.Validation;
import org.n52.sos.util.XmlHelper;
/**
* @author Christian Autermann <c.autermann@52north.org>
*/
@Configurable
public class SosServiceIdentificationFactory extends LazyThreadSafeProducer<SosServiceIdentification> {
private File file;
private String[] keywords;
private String title;
private String description;
private String serviceType;
private String serviceTypeCodeSpace;
private String fees;
private String constraints;
public SosServiceIdentificationFactory() throws ConfigurationException {
SettingsManager.getInstance().configure(this);
}
@Setting(FILE)
public void setFile(File file) {
this.file = file;
setRecreate();
}
public void setKeywords(String[] keywords) {
this.keywords = keywords == null ? new String[0] : Arrays.copyOf(keywords, keywords.length);
setRecreate();
}
@Setting(KEYWORDS)
public void setKeywords(String keywords) {
if (keywords != null) {
String[] keywordArray = keywords.split(",");
ArrayList<String> keywordList = new ArrayList<String>(keywordArray.length);
for (String s : keywordArray) {
if (s != null && !s.trim()
.isEmpty()) {
keywordList.add(s.trim());
}
}
setKeywords(keywordList.toArray(new String[keywordList.size()]));
} else {
setKeywords(new String[0]);
}
}
@Setting(TITLE)
public void setTitle(String title) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Title", title);
this.title = title;
setRecreate();
}
@Setting(ABSTRACT)
public void setAbstract(String description) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Abstract", description);
this.description = description;
setRecreate();
}
@Setting(SERVICE_TYPE)
public void setServiceType(String serviceType) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Service Type", serviceType);
this.serviceType = serviceType;
setRecreate();
}
@Setting(SERVICE_TYPE_CODE_SPACE)
public void setServiceTypeCodeSpace(String serviceTypeCodeSpace) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Service Type Code Space", serviceType);
this.serviceTypeCodeSpace = serviceTypeCodeSpace;
setRecreate();
}
@Setting(FEES)
public void setFees(String fees) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Fees", fees);
this.fees = fees;
setRecreate();
}
@Setting(ACCESS_CONSTRAINTS)
public void setConstraints(String constraints) throws ConfigurationException {
Validation.notNullOrEmpty("Service Identification Access Constraints", constraints);
this.constraints = constraints;
setRecreate();
}
@Override
protected SosServiceIdentification create() throws ConfigurationException {
SosServiceIdentification serviceIdentification = new SosServiceIdentification();
if (this.file != null) {
try {
serviceIdentification.setServiceIdentification(XmlHelper.loadXmlDocumentFromFile(this.file));
} catch (OwsExceptionReport ex) {
throw new ConfigurationException(ex);
}
} else {
serviceIdentification.setAbstract(this.description);
serviceIdentification.setAccessConstraints(this.constraints);
serviceIdentification.setFees(this.fees);
serviceIdentification.setServiceType(this.serviceType);
serviceIdentification.setServiceTypeCodeSpace(this.serviceTypeCodeSpace);
serviceIdentification.setTitle(this.title);
serviceIdentification.setVersions(ServiceOperatorRepository.getInstance()
.getSupportedVersions(SosConstants.SOS));
serviceIdentification.setKeywords(Arrays.asList(this.keywords));
}
return serviceIdentification;
}
}
| gpl-2.0 |