repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
StarkoMania/scrum-it
src/main/java/de/rs/scrumit/controller/MainIncludeComposer.java
2033
/* * Copyright (C) 2014 Robert Stark * * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ package de.rs.scrumit.controller; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zul.Include; import de.rs.scrumit.component.BaseComponentComposer; import de.rs.scrumit.entity.ApplicationNavigationEntryModel; import de.rs.scrumit.service.MenuService; @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class MainIncludeComposer extends BaseComponentComposer { private static final long serialVersionUID = 1L; @WireVariable("menuService") MenuService menuService; @Wire Include mainInclude; public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); subscribe("onProjectSelectionChange", new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { String src = mainInclude.getSrc(); mainInclude.setSrc(null); mainInclude.setSrc(src); } }); ApplicationNavigationEntryModel navigationEntry = menuService.getCurrentPage(); String target = navigationEntry.getTarget(); mainInclude.setSrc(target); } }
gpl-3.0
irontec/LibreCon-app
mobile/android/app/src/main/java-gen/librecon/Schedule.java
7468
package librecon; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. import android.os.Parcel; import android.os.Parcelable; import java.util.Locale; /** * Entity mapped to table SCHEDULE. */ public class Schedule implements Parcelable { private Long id; private String nameEs; private String nameEu; private String nameEn; private String date; private String descriptionEs; private String descriptionEu; private String descriptionEn; private String picUrl; private String picUrlSquare; private String startDatetime; private String finishDatetime; private String links; private String tags; private String location; private String targetDate; private String color; private String speakers; public Schedule() { } public Schedule(Long id) { this.id = id; } public Schedule(Long id, String nameEs, String nameEu, String nameEn, String date, String descriptionEs, String descriptionEu, String descriptionEn, String picUrl, String picUrlSquare, String startDatetime, String finishDatetime, String links, String tags, String location, String targetDate, String color) { this.id = id; this.nameEs = nameEs; this.nameEu = nameEu; this.nameEn = nameEn; this.date = date; this.descriptionEs = descriptionEs; this.descriptionEu = descriptionEu; this.descriptionEn = descriptionEn; this.picUrl = picUrl; this.picUrlSquare = picUrlSquare; this.startDatetime = startDatetime; this.finishDatetime = finishDatetime; this.links = links; this.tags = tags; this.location = location; this.targetDate = targetDate; this.color = color; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNameEs() { return nameEs; } public void setNameEs(String nameEs) { this.nameEs = nameEs; } public String getNameEu() { return nameEu; } public void setNameEu(String nameEu) { this.nameEu = nameEu; } public String getNameEn() { return nameEn; } public void setNameEn(String nameEn) { this.nameEn = nameEn; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDescriptionEs() { return descriptionEs; } public void setDescriptionEs(String descriptionEs) { this.descriptionEs = descriptionEs; } public String getDescriptionEu() { return descriptionEu; } public void setDescriptionEu(String descriptionEu) { this.descriptionEu = descriptionEu; } public String getDescriptionEn() { return descriptionEn; } public void setDescriptionEn(String descriptionEn) { this.descriptionEn = descriptionEn; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getPicUrlSquare() { return picUrlSquare; } public void setPicUrlSquare(String picUrlSquare) { this.picUrlSquare = picUrlSquare; } public String getStartDatetime() { return startDatetime; } public void setStartDatetime(String startDatetime) { this.startDatetime = startDatetime; } public String getFinishDatetime() { return finishDatetime; } public void setFinishDatetime(String finishDatetime) { this.finishDatetime = finishDatetime; } public String getLinks() { return links; } public void setLinks(String links) { this.links = links; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getTargetDate() { return targetDate; } public void setTargetDate(String targetDate) { this.targetDate = targetDate; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getName() { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); if (language.equals("eu")) return this.nameEu; else if (language.equals("en")) return this.nameEn; else return this.nameEs; } public String getDescription() { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); if (language.equals("eu")) return this.descriptionEu; else if (language.equals("en")) return this.descriptionEn; else return this.descriptionEs; } public String getSpeakers() { return this.speakers; } public void setSpeakers(String speakers) { this.speakers = speakers; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(this.id); dest.writeString(this.nameEs); dest.writeString(this.nameEu); dest.writeString(this.nameEn); dest.writeString(this.date); dest.writeString(this.descriptionEs); dest.writeString(this.descriptionEu); dest.writeString(this.descriptionEn); dest.writeString(this.picUrl); dest.writeString(this.picUrlSquare); dest.writeString(this.startDatetime); dest.writeString(this.finishDatetime); dest.writeString(this.links); dest.writeString(this.tags); dest.writeString(this.location); dest.writeString(this.targetDate); dest.writeString(this.color); } private Schedule(Parcel in) { this.id = (Long) in.readValue(Long.class.getClassLoader()); this.nameEs = in.readString(); this.nameEu = in.readString(); this.nameEn = in.readString(); this.date = in.readString(); this.descriptionEs = in.readString(); this.descriptionEu = in.readString(); this.descriptionEn = in.readString(); this.picUrl = in.readString(); this.picUrlSquare = in.readString(); this.startDatetime = in.readString(); this.finishDatetime = in.readString(); this.links = in.readString(); this.tags = in.readString(); this.location = in.readString(); this.targetDate = in.readString(); this.color = in.readString(); } public static final Creator<Schedule> CREATOR = new Creator<Schedule>() { public Schedule createFromParcel(Parcel source) { return new Schedule(source); } public Schedule[] newArray(int size) { return new Schedule[size]; } }; }
gpl-3.0
ecerulm/en4j
NBPlatformApp/Synchronization/src/main/java/com/rubenlaguna/en4j/sync/package-info.java
1023
/* * Copyright (C) 2010 Ruben Laguna <ruben.laguna@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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //@org.netbeans.spi.options.OptionsPanelController.ContainerRegistration(id ="EN4J", categoryName = "#OptionsCategory_Name_EN4J", iconBase="com/rubenlaguna/en4j/sync/configuration-icon.png", keywords="#OptionsCategory_Keywords_EN4J", keywordsCategory = "EN4J") package com.rubenlaguna.en4j.sync;
gpl-3.0
ieugen/Teachingbox
src/org/hswgt/teachingbox/core/rl/network/NetworkNode.java
2818
/** * * $Id: NetworkNode.java 669 2010-06-14 14:53:38Z twanschik $ * * @version $Rev: 669 $ * @author $Author: twanschik $ * @date $Date: 2010-06-14 16:53:38 +0200 (Mo, 14 Jun 2010) $ * */ package org.hswgt.teachingbox.core.rl.network; import java.io.Serializable; import org.hswgt.teachingbox.core.rl.tools.Copyable; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import java.util.LinkedList; import java.util.List; // Abstract class representing a node in a network. Currently all nodes hold a // position so put it into the NetworkNode itself. public abstract class NetworkNode implements Copyable<NetworkNode>, Serializable { private static final long serialVersionUID = -1375335252449897775L; protected DoubleMatrix1D position; // dimension indicates how much dimensions this node covers protected int dimension = 0; protected List<NetworkNodeObserver> observers = new LinkedList<NetworkNodeObserver>(); protected Network net = null; // abstract method to implement public abstract double getValue(DoubleMatrix1D state); public double getValue(double[] state) { return getValue(new DenseDoubleMatrix1D(state)); } public DoubleMatrix1D getPosition() { return position.copy(); } public void setPosition(DoubleMatrix1D position) { boolean notify = true; if (this.position != null && this.position.equals(position)) notify = false; this.position = position.copy(); if (notify) this.notifyShapeChanged(); } public void setPosition(double[] position) { this.setPosition(new DenseDoubleMatrix1D(position)); } public void notifyPositionChanged() { for (NetworkNodeObserver observer: observers) observer.positionChanged(this); } // classes derived from NetworkNode should call notifyShapeChanged // if the change the shape. For RBFs this should be called if sigma changes! public void notifyShapeChanged() { for (NetworkNodeObserver observer: observers) observer.shapeChanged(this); } /** * Attaches an observer to this * * @param obs The observer to attach */ public void addObserver(final NetworkNodeObserver obs) { if( !this.observers.contains(obs) ) this.observers.add(obs); } /** * Remove an observer from this * @param obs The observer to detach */ public void removeObserver(final NetworkNodeObserver obs) { this.observers.remove(obs); } public Network getNet() { return net; } public void setNet(Network net) { this.net = net; } public int getDimension() { return dimension; } }
gpl-3.0
fanruan/finereport-design
designer_base/src/com/fr/design/extra/ShopManagerPane.java
1223
package com.fr.design.extra; import com.fr.design.dialog.BasicPane; import com.fr.general.Inter; import java.awt.BorderLayout; import java.awt.Component; /** * @author richie * @date 2015-03-09 * @since 8.0 * 应用中心的构建采用JavaScript代码来动态实现,但是不总是依赖于服务器端的HTML * 采用JDK提供的JavaScript引擎,实际是用JavaScript语法实现Java端的功能,并通过JavaScript引擎动态调用 * JavaScript放在安装目录下的scripts/store目录下,检测到新版本的时候,可以通过更新这个目录下的文件实现热更新 * 不直接嵌入WebView组件的原因是什么呢? * 因为如果直接嵌入WebView,和设计器的交互就需要预先设定好,这样灵活性会差很多,而如果使用JavaScript引擎, * 就可以直接在JavaScript中和WebView组件做交互,而同时JavaScript中可以调用任何的设计器API. */ public class ShopManagerPane extends BasicPane { public ShopManagerPane(Component webPane) { setLayout(new BorderLayout()); add(webPane, BorderLayout.CENTER); } @Override protected String title4PopupWindow() { return Inter.getLocText("FR-Designer-Plugin_Manager"); } }
gpl-3.0
alvarogzp/net-top
app/src/main/java/org/alvarogp/nettop/common/di/components/ActivityComponent.java
334
package org.alvarogp.nettop.common.di.components; import org.alvarogp.nettop.common.di.modules.ActivityModule; import org.alvarogp.nettop.common.di.scopes.PerActivity; import dagger.Component; @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { }
gpl-3.0
kidcontact/FocusSIS
app/src/main/java/com/slensky/focussis/parser/DemographicParser.java
8492
package com.slensky.focussis.parser; import android.support.annotation.NonNull; import android.util.Log; import android.util.SparseArray; import com.slensky.focussis.data.Demographic; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedSet; import java.util.TreeSet; /** * Created by slensky on 3/24/18. */ public class DemographicParser extends FocusPageParser { private static final String TAG = "DemographicParser"; private JSONArray result0; // contains basic information like first/last name private JSONArray result1; // custom demographic fields, e.g. nickname, locker #, bus # private JSONArray result2; // parental permissions @Override public Demographic parse(String jsonStr) throws JSONException { JSONArray json = new JSONArray(jsonStr); result0 = json.getJSONObject(0).getJSONArray("result"); result1 = json.getJSONObject(1).getJSONArray("result"); result2 = json.getJSONObject(2).getJSONArray("result"); // Get basic user info which should always be present (result0) String first = findField(result0, "First Name", "students|first_name", "first_name").getString("value"); Object middleObj = findField(result0, "Middle Name", "students|middle_name", "middle_name").get("value"); String middle = JSONObject.NULL.equals(middleObj) ? null : (String) middleObj; String last = findField(result0, "Last Name", "students|last_name", "last_name").getString("value"); String name = first + " " + (middle != null ? middle + " " : "") + last; int passLength = findField(result0, "Password", "students|password", "password").getString("value").length(); // Collect all custom field titles and values (result1) Map<String, String> customFields = new LinkedHashMap<>(); for (int i = 0; i < result1.length(); i++) { if (!(result1.get(i) instanceof JSONObject)) { continue; } JSONObject field = result1.getJSONObject(i); if (field.has("title") && field.has("value") && !JSONObject.NULL.equals(field.get("value"))) { String value = field.getString("value"); try { if (field.has("options") && field.get("options") instanceof JSONArray) { JSONArray options = field.getJSONArray("options"); for (int j = 0; j < options.length(); j++) { if (options.get(j) instanceof JSONObject && options.getJSONObject(j).getString("value").equals(value)) { value = options.getJSONObject(j).getString("text"); break; } } } } catch (JSONException e) { Log.w(TAG, "JSONException while attempting to parseRequirements options for custom field " + field.getString("title")); Log.w(TAG, field.toString(2)); e.printStackTrace(); } customFields.put(field.getString("title").trim(), value.trim()); } } // Collect all parental document/permission information (result2) // sort the table by the sort_order element so that data fields will be after their headers SortedSet<JSONObject> formsPermissionsBySortOrder = new TreeSet<>(new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { try { return o1.getInt("sort_order") - o2.getInt("sort_order"); } catch (JSONException e) { return 0; // should never happen, we ensure objects have this property before inserting them } } }); Map<String, Boolean> parentalForms = new LinkedHashMap<>(); Map<String, Boolean> parentalPermissions = new LinkedHashMap<>(); for (int i = 0; i < result2.length(); i++) { JSONObject o = result2.getJSONObject(i); if (o.has("title") && o.has("value") && o.has("type") && o.has("sort_order")) { formsPermissionsBySortOrder.add(o); } } boolean isFormsSection = false; boolean isPermissionsSection = false; for (JSONObject o : formsPermissionsBySortOrder) { if (o.getString("type").equals("holder")) { // "holder" type seems to be a header if (o.getString("title").toLowerCase().contains("documents")) { isPermissionsSection = false; isFormsSection = true; } else if (o.getString("title").toLowerCase().contains("permissions")) { isPermissionsSection = true; isFormsSection = false; } else { Log.w(TAG, "Unrecognized holder " + o.getString("title")); } } else if (o.getString("type").equals("checkbox")) { String title = o.getString("title").trim(); String v = o.getString("value"); boolean value = v.equals("1") || v.equals("true"); if (isFormsSection) { parentalForms.put(title, value); } else if (isPermissionsSection) { parentalPermissions.put(title, value); } } } return new Demographic(name, passLength, customFields, parentalForms, parentalPermissions); } // searches through the given result to find the field that has either the title, id, or column_name given // prefers to find a matching title, then matching id, then matching columnName private JSONObject findField(@NonNull JSONArray result, @NonNull String title, @NonNull String id, @NonNull String columnName) throws JSONException { // result title for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("title").equals(title)) { Log.v(TAG, String.format("\"%s\" retrieved via title", title)); return field; } } // result id for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("id").equals(id)) { Log.v(TAG, String.format("\"%s\" retrieved via id", title)); return field; } } // result columnName for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("column_name").equals(columnName)) { Log.v(TAG, String.format("\"%s\" retrieved via column_name", title)); return field; } } throw new NoSuchElementException(String.format("Field title %s, id %s, column_name %s could not be found", title, id, columnName)); } private String getTextFromOptions(JSONObject field, String defaultText) throws JSONException { if (!field.has("options")) { throw new NoSuchElementException("Requested field does not have options"); } String value = field.getString("value"); JSONArray options = field.getJSONArray("options"); for (int i = 0; i < options.length(); i++) { JSONObject option = options.getJSONObject(i); if (option.getString("value").equals(value)) { return option.getString("text"); } } // get title for warning log string String title = "[title not in json]"; if (field.has("title")) { title = field.getString("title"); } Log.w(TAG, String.format("Using defaultText for field title %s", title)); return defaultText; } }
gpl-3.0
SiDzej/Simply-Ladders
common/cj/ladders/lib/Reference.java
260
package cj.ladders.lib; public class Reference { public static final String MOD_ID = "ladders"; public static final String MOD_NAME = "Simply Ladders"; public static final String VERSION = "0.0.1"; public static final String TEXTURES = MOD_ID + ":"; }
gpl-3.0
raulsmail/GlowPower
src/main/java/com/bluepowermod/network/NetworkHandler.java
4437
/* * This file is part of Blue Power. * * Blue Power 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. * * Blue Power 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 Blue Power. If not, see <http://www.gnu.org/licenses/> */ package com.bluepowermod.network; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; import com.bluepowermod.network.messages.LocationDoublePacket; import com.bluepowermod.network.messages.LocationIntPacket; import com.bluepowermod.network.messages.MessageCircuitDatabaseTemplate; import com.bluepowermod.network.messages.MessageDebugBlock; import com.bluepowermod.network.messages.MessageGuiUpdate; import com.bluepowermod.network.messages.MessageMultipartRemove; import com.bluepowermod.network.messages.MessageSendClientServerTemplates; import com.bluepowermod.network.messages.MessageUpdateTextfield; import com.bluepowermod.util.Refs; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; /** * * @author MineMaarten */ public class NetworkHandler { public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(Refs.MODID); private static int discriminant; /* * The integer is the ID of the message, the Side is the side this message will be handled (received) on! */ public static void init() { INSTANCE.registerMessage(MessageGuiUpdate.class, MessageGuiUpdate.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageUpdateTextfield.class, MessageUpdateTextfield.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageMultipartRemove.class, MessageMultipartRemove.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageCircuitDatabaseTemplate.class, MessageCircuitDatabaseTemplate.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageCircuitDatabaseTemplate.class, MessageCircuitDatabaseTemplate.class, discriminant++, Side.CLIENT); INSTANCE.registerMessage(MessageDebugBlock.class, MessageDebugBlock.class, discriminant++, Side.CLIENT); INSTANCE.registerMessage(MessageSendClientServerTemplates.class, MessageSendClientServerTemplates.class, discriminant++, Side.CLIENT); } /* * public static void INSTANCE.registerMessage(Class<? extends AbstractPacket<? extends IMessage>> clazz){ INSTANCE.registerMessage(clazz, clazz, * discriminant++, Side.SERVER, discriminant++, Side.SERVER); } */ public static void sendToAll(IMessage message) { INSTANCE.sendToAll(message); } public static void sendTo(IMessage message, EntityPlayerMP player) { INSTANCE.sendTo(message, player); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationIntPacket message, World world, double distance) { sendToAllAround(message, message.getTargetPoint(world, distance)); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationIntPacket message, World world) { sendToAllAround(message, message.getTargetPoint(world)); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationDoublePacket message, World world) { sendToAllAround(message, message.getTargetPoint(world)); } public static void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point) { INSTANCE.sendToAllAround(message, point); } public static void sendToDimension(IMessage message, int dimensionId) { INSTANCE.sendToDimension(message, dimensionId); } public static void sendToServer(IMessage message) { INSTANCE.sendToServer(message); } }
gpl-3.0
neo4j-contrib/neo4j-lucene5-index
src/test/java/org/neo4j/graphdb/RelationshipIndexFacadeMethods.java
5800
/* * Copyright (c) 2002-2015 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb; import org.neo4j.graphdb.index.RelationshipIndex; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableCollection; public class RelationshipIndexFacadeMethods { private static final FacadeMethod<RelationshipIndex> GET_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.get( "foo", 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> query( String key, " + "Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo", 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> query( Object queryOrQueryObjectOrNull, Node startNodeOrNull, " + "Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.query( 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> GET = new FacadeMethod<RelationshipIndex>( "IndexHits<T>" + " get( String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.get( "foo", "bar" ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY = new FacadeMethod<RelationshipIndex>( "IndexHits<T> query( String key, Object queryOrQueryObject )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo", "bar" ); } }; private static final FacadeMethod<RelationshipIndex> QUERY = new FacadeMethod<RelationshipIndex>( "IndexHits<T> query( Object queryOrQueryObject )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo" ); } }; private static final FacadeMethod<RelationshipIndex> ADD = new FacadeMethod<RelationshipIndex>( "void add( T " + "entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.add( null, "foo", 42 ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY_AND_VALUE = new FacadeMethod<RelationshipIndex>( "void remove( T entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null, "foo", 42 ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY = new FacadeMethod<RelationshipIndex>( "void remove( T entity, String key )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null, "foo" ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE = new FacadeMethod<RelationshipIndex>( "void " + "remove( T entity )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null ); } }; private static final FacadeMethod<RelationshipIndex> DELETE = new FacadeMethod<RelationshipIndex>( "void delete()" ) { @Override public void call( RelationshipIndex self ) { self.delete(); } }; private static final FacadeMethod<RelationshipIndex> PUT_IF_ABSENT = new FacadeMethod<RelationshipIndex>( "T " + "putIfAbsent( T entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.putIfAbsent( null, "foo", 42 ); } }; static final Iterable<FacadeMethod<RelationshipIndex>> ALL_RELATIONSHIP_INDEX_FACADE_METHODS = unmodifiableCollection( asList( GET_WITH_FILTER, QUERY_BY_KEY_WITH_FILTER, QUERY_WITH_FILTER, GET, QUERY_BY_KEY, QUERY, ADD, REMOVE_BY_KEY_AND_VALUE, REMOVE_BY_KEY, REMOVE, DELETE, PUT_IF_ABSENT ) ); }
gpl-3.0
hyperbox/api
src/main/java/io/kamax/hbox/ClassManager.java
7888
/* * Hyperbox - Virtual Infrastructure Manager * Copyright (C) 2015 - Max Dor * * https://apps.kamax.io/hyperbox * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.kamax.hbox; import io.kamax.hbox.exception.HyperboxException; import io.kamax.tools.logging.Logger; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; public class ClassManager { private static Map<URL, Reflections> classes = new HashMap<URL, Reflections>(); static { Set<URL> urls = new HashSet<URL>(); for (URL url : ClasspathHelper.forJavaClassPath()) { if (url.getFile().endsWith(".jar") || url.getFile().endsWith(".class") || url.getFile().endsWith("/")) { urls.add(url); } } scan(urls); } private static void scan(Set<URL> urls, ClassLoader... loaders) { Long start = System.currentTimeMillis(); Reflections scan = new Reflections(new ConfigurationBuilder().addClassLoaders(loaders).setUrls(urls) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()) .setExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()))); for (URL url : urls) { classes.put(url, scan); } Logger.debug("Scanning urls took " + (System.currentTimeMillis() - start) + " ms"); } public static void add(Set<URL> rawUrls, ClassLoader... loaders) { Set<URL> urls = new HashSet<URL>(); for (URL rawUrl : rawUrls) { if (!classes.containsKey(rawUrl)) { Logger.debug("Adding " + rawUrl.toString() + " to URL to scan"); urls.add(rawUrl); } } scan(urls, loaders); } public static void reload(Set<URL> rawUrls, ClassLoader... loaders) { scan(rawUrls, loaders); } public static void remove(Set<URL> urls) { for (URL url : urls) { classes.remove(url); Logger.debug("URL removed: " + url); } Logger.debug(classes.keySet().size() + " remaining URLs:"); for (URL url : classes.keySet()) { Logger.debug("\t" + url); } } @SuppressWarnings("unchecked") public static <T> T loadClass(Class<T> itWannabeClass, String it) { try { Class<T> itClass = (Class<T>) Class.forName(it); T itInstance = itClass.newInstance(); return itInstance; } catch (Exception e) { Logger.error("Failed to load " + it + " : " + e.getLocalizedMessage()); Logger.exception(e); throw new HyperboxException(e); } } public static <T> Set<Class<? extends T>> getSubTypes(Class<T> type) { Long start = System.currentTimeMillis(); Set<Class<? extends T>> classList = new HashSet<Class<? extends T>>(); for (Reflections data : classes.values()) { for (Class<? extends T> rawClass : data.getSubTypesOf(type)) { /* * Since we have modules, it is possible that several classes have the same name. * To avoid any conflict, we want to make sure only the good classes are returned. * * For the queried class type, if it comes from the system class loader (same as us), we have no problem * since that class type will be unique in the system. * * On the other hand, if the queried class type is not from the system class loader, it means it comes * from a module. In that case, we must only return results that are from the same class loader. */ if (ClassManager.class.getClassLoader().equals(type.getClassLoader()) || rawClass.getClassLoader().equals(type.getClassLoader())) { classList.addAll(data.getSubTypesOf(type)); } } } Logger.debug(type.getSimpleName() + " providers took " + (System.currentTimeMillis() - start) + " ms to find"); return classList; } public static <T> Set<Class<? extends T>> getAnnotatedSubTypes(Class<T> type, Class<? extends Annotation> note) { Long start = System.currentTimeMillis(); Set<Class<? extends T>> classList = new HashSet<Class<? extends T>>(); for (Class<? extends T> subType : getSubTypes(type)) { if (Modifier.isAbstract(subType.getModifiers())) { Logger.debug(subType.getName() + " is abstract and was ignored"); } else { for (Annotation subTypeNote : subType.getAnnotations()) { if (!subTypeNote.annotationType().equals(note)) { Logger.debug(subTypeNote.annotationType().getName() + " ignored, does not have annotation " + note.getName()); } else { Logger.debug("Found match for " + type.getName() + ": " + subType.getName()); classList.add(subType); } } } } Logger.debug(type.getSimpleName() + " providers took " + (System.currentTimeMillis() - start) + " ms to find"); return classList; } public static <T> Set<T> getQuiet(Class<T> type) { Set<T> loadedClasses = new HashSet<T>(); Set<Class<? extends T>> classes = getSubTypes(type); for (Class<? extends T> rawObject : classes) { try { if (!Modifier.isAbstract(rawObject.getModifiers())) { T view = rawObject.newInstance(); loadedClasses.add(view); } } catch (Exception e) { Logger.debug("Failed to load " + rawObject.getSimpleName() + " : " + e.getLocalizedMessage()); } } return loadedClasses; } public static <T> Set<T> getAtLeastOneOrFail(Class<T> type) throws HyperboxException { Set<T> objects = getQuiet(type); if (objects.isEmpty()) { throw new HyperboxException("Unable to find any match for " + type.getSimpleName()); } return objects; } public static <T> Set<T> getAllOrFail(Class<T> type) throws HyperboxException { try { Set<Class<? extends T>> classes = getSubTypes(type); Set<T> loadedClasses = new HashSet<T>(); for (Class<? extends T> rawObject : classes) { if (!Modifier.isAbstract(rawObject.getModifiers())) { T view = rawObject.newInstance(); loadedClasses.add(view); } } return loadedClasses; } catch (Exception e) { Logger.exception(e); throw new HyperboxException("Failed to load " + type.getSimpleName(), e); } } }
gpl-3.0
zluuluyenz/mtech
js/lab9/Dell.java
1937
package lab9; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Dell extends Product { private int mark_id ; public Dell() { super(); } public Dell(int id, String name, int quantity, float price, int markId){ super(id,name,quantity,price); this.mark_id = markId; } @Override void displayProduct() { System.out.println(getID() +"\t"+ getName()+"\t"+getQuantity()+"\t"+getPrice()+"\t"+getCost()); } void createProduct() { System.out.println("Nhap vao du lieu product"); try{ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Id : "); String s = bufferRead.readLine(); setID(Integer.parseInt(s)); System.out.println("Name: "); s = bufferRead.readLine(); setName(s); System.out.println("Quantity: "); s = bufferRead.readLine(); setQuantity(Integer.parseInt(s)); System.out.println("Price: "); setPrice(Float.parseFloat(s)); } catch(IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (MyException e) { e.getMessage(); } catch (Exception e) { e.printStackTrace(); } } float getCost(){ return getQuantity()*getPrice(); } void sortProduct(Product p[]){ } Product findProduct(int quantity, Product p[]) { return null; } public static void main(String[] args) { int n = 0; System.out.println("Nhap vao so phan tu"); BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); try { String s = bufferRead.readLine(); n = Integer.parseInt(s); } catch (Exception e) { e.printStackTrace(); } Dell pd[] = new Dell[n]; for(int i =0; i <n ; i++) { Dell d = new Dell(); d.createProduct(); pd[i] = d; } } public int getMark_id() { return mark_id; } public void setMark_id(int mark_id) { this.mark_id = mark_id; } }
gpl-3.0
shuichi/MediaMatrix
src/main/java/mediamatrix/utils/FileSearch.java
2770
package mediamatrix.utils; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TreeSet; public class FileSearch { public static final int TYPE_FILE_OR_DIR = 1; public static final int TYPE_FILE = 2; public static final int TYPE_DIR = 3; public File[] listFiles(String directoryPath, String fileName) { if (fileName != null) { fileName = fileName.replace(".", "\\."); fileName = fileName.replace("*", ".*"); } return listFiles(directoryPath, fileName, TYPE_FILE, true, 0); } public File[] listFiles(String directoryPath, String fileNamePattern, int type, boolean isRecursive, int period) { File dir = new File(directoryPath); if (!dir.isDirectory()) { throw new IllegalArgumentException(); } File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; addFile(type, fileNamePattern, file, period); if (isRecursive && file.isDirectory()) { listFiles(file.getAbsolutePath(), fileNamePattern, type, isRecursive, period); } } } return set.toArray(new File[set.size()]); } private void addFile(int type, String match, File file, int period) { switch (type) { case TYPE_FILE: if (!file.isFile()) { return; } break; case TYPE_DIR: if (!file.isDirectory()) { return; } break; } if (match != null && !file.getName().matches(match)) { return; } if (period != 0) { Date lastModifiedDate = new Date(file.lastModified()); String lastModifiedDateStr = new SimpleDateFormat("yyyyMMdd").format(lastModifiedDate); long oneDayTime = 24L * 60L * 60L * 1000L; long periodTime = oneDayTime * Math.abs(period); Date designatedDate = new Date(System.currentTimeMillis() - periodTime); String designatedDateStr = new SimpleDateFormat("yyyyMMdd").format(designatedDate); if (period > 0) { if (lastModifiedDateStr.compareTo(designatedDateStr) < 0) { return; } } else { if (lastModifiedDateStr.compareTo(designatedDateStr) > 0) { return; } } } set.add(file); } private TreeSet<File> set = new TreeSet<File>(); public void clear() { set.clear(); } }
gpl-3.0
Zrips/Residence
src/com/bekvon/bukkit/residence/utils/TimeModifier.java
1185
package com.bekvon.bukkit.residence.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public enum TimeModifier { s(1), m(60), h(60 * 60), d(60 * 60 * 24), w(60 * 60 * 24 * 7), M(60 * 60 * 24 * 30), Y(60 * 60 * 24 * 365); private int modifier = 0; static Pattern patern = Pattern.compile("(\\d+[a-z])"); TimeModifier(int modifier) { this.modifier = modifier; } public int getModifier() { return modifier; } public void setModifier(int modifier) { this.modifier = modifier; } public static Long getTimeRangeFromString(String time) { try { return Long.parseLong(time); } catch (Exception e) { } Matcher match = patern.matcher(time); Long total = null; while (match.find()) { String t = match.group(1); for (TimeModifier one : TimeModifier.values()) { if (t.endsWith(one.name())) { try { Long amount = Long.parseLong(t.substring(0, t.length() - one.name().length())); if (total == null) total = 0L; total += amount * one.getModifier(); } catch (Exception e) { break; } } } } return total; } }
gpl-3.0
qiuyb/ssmWork
TagFavorite/src/test/java/com/qyb/tagfavorite/ConnTest.java
1094
package com.qyb.tagfavorite; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; public class ConnTest { //测试mybatis框架与数据库的连接 @Test public void test() { //加载配置文件mybatis.xml try { InputStream in=Resources.getResourceAsStream("mybatis.xml"); //通过配置文件,创建一个SqlSession工厂对象 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); //通过工厂生产SqlSession对象 SqlSession session=factory.openSession(); //通过会话对象获得连接 Connection con=session.getConnection(); //断言连接不为空 assertNotNull("数据库连接失败...",con); } catch (IOException e) { e.printStackTrace(); } } }
gpl-3.0
justdoonemore/word.playdough
word.playdough.model/src/test/java/com/jdom/word/playdough/model/gamepack/ServerCommunicationManagerImplTest.java
18294
/** * Copyright (C) 2012 Just Do One More * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jdom.word.playdough.model.gamepack; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; import com.jdom.word.playdough.model.ServerCommunicationManagerImpl; import com.jdom.word.playdough.model.WordPlaydoughConfiguration; import com.jdom.word.playdough.model.ServerCommunicationManagerImpl.CacheStatusMarker; @RunWith(PowerMockRunner.class) public class ServerCommunicationManagerImplTest { final HttpClient mockClient = PowerMockito.mock(HttpClient.class); final HttpMethod mockMethod = PowerMockito.mock(HttpMethod.class); final CacheStatusMarker mockCacheStatusMarker = PowerMockito .mock(CacheStatusMarker.class); final WordPlaydoughConfiguration mockConfiguration = PowerMockito .mock(WordPlaydoughConfiguration.class); @Test public void testRetrievesScoreFromServerAndGetsResponse() throws HttpException, IOException { final int score = 30; final String user = "testUser"; final String word = "testWord"; // Required return values PowerMockito.when(mockMethod.getResponseBodyAsString()).thenReturn( "" + score); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); int returnValue = impl.getUserHighScoreForWord(user, word); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).getResponseBodyAsString(); verify(mockMethod).releaseConnection(); assertEquals("Incorrect score was retrieved!", score, returnValue); } @Test public void testDoesNotRetrieveScoreFromServerIfConfiguredAsSuch() throws HttpException, IOException { final String user = "testUser"; final String word = "testWord"; // Required return values PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.getUserHighScoreForWord(user, word); // Verifications of stuff we expect to ALWAYS happen verify(mockClient, never()).executeMethod(mockMethod); verify(mockMethod, never()).getResponseBodyAsString(); verify(mockMethod, never()).releaseConnection(); } @Test public void testSendsScoreToServer() throws HttpException, IOException { final int score = 30; final String user = "testUser"; final String word = "testWord"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.proposeUserHighScoreForWord(user, word, score); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); } @Test public void testDoesNotSendScoreToServerIfConfiguredAsSuch() throws HttpException, IOException { final int score = 30; final String user = "testUser"; final String word = "testWord"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.proposeUserHighScoreForWord(user, word, score); // Verifications of stuff we expect to ALWAYS happen verify(mockClient, never()).executeMethod(mockMethod); verify(mockMethod, never()).releaseConnection(); } @Test public void testRetrievesLockStatusFromServerAndGetsResponse() throws IOException { final boolean lockStatus = true; final String user = "testUser"; final String pack = "testPack"; // Required return values PowerMockito.when(mockMethod.getResponseBodyAsString()).thenReturn( "" + lockStatus); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); boolean returnValue = impl.isGamePackLocked(user, pack); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).getResponseBodyAsString(); verify(mockMethod).releaseConnection(); assertEquals("Incorrect lock status was retrieved!", lockStatus, returnValue); } @Test public void testDoesNotRetrieveLockStatusFromServerIfConfiguredAsSuch() throws IOException { final boolean lockStatus = true; final String user = "testUser"; final String pack = "testPack"; // Required return values PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.isGamePackLocked(user, pack); // Verifications of stuff we expect to ALWAYS happen verify(mockClient, never()).executeMethod(mockMethod); verify(mockMethod, never()).getResponseBodyAsString(); verify(mockMethod, never()).releaseConnection(); } @Test public void testSendsLockStatusToServer() throws HttpException, IOException { final boolean lockStatus = false; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.sendLockStatus(user, pack, lockStatus); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); } @Test public void testDoesNotSendsLockStatusToServerIfConfiguredAsSuch() throws HttpException, IOException { final boolean lockStatus = false; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.sendLockStatus(user, pack, lockStatus); // Verifications of stuff we expect to ALWAYS happen verify(mockClient, never()).executeMethod(mockMethod); verify(mockMethod, never()).releaseConnection(); } @Test public void testIfConfiguredToNotUseServerLockStatusIsSentToCache() throws HttpException, IOException { final boolean lockStatus = false; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.sendLockStatus(user, pack, lockStatus); // Verifications verify(mockCacheStatusMarker).addCachedLockStatus(user, pack, lockStatus); } @Test public void testIfConfiguredToNotUseServerHighScoreIsSentToCache() throws HttpException, IOException { final int score = 30; final String user = "testUser"; final String word = "testWord"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.proposeUserHighScoreForWord(user, word, score); // Verifications verify(mockCacheStatusMarker).addCachedUserHighScore(user, word, score); } @Test public void testIfConfiguredToNotUseServerGetHighScoreIsFromCache() throws HttpException, IOException { final int score = 30; final String user = "testUser"; final String word = "testWord"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); PowerMockito.when(mockCacheStatusMarker.getCachedUserHighScore(word)) .thenReturn(score); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertEquals("Didn't get the correct score from the cache!", score, impl.getUserHighScoreForWord(user, word)); // Verifications verify(mockCacheStatusMarker, times(1)).getCachedUserHighScore(word); } @Test public void testIfConfiguredToNotUseServerGetLockStatusIsFromCache() throws IOException { final boolean lockStatus = true; final String user = "testUser"; final String pack = "testPack"; // Required return values PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(false); PowerMockito.when(mockCacheStatusMarker.isGamePackLocked(user, pack)) .thenReturn(lockStatus); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertTrue(impl.isGamePackLocked(user, pack)); // Verifications verify(mockCacheStatusMarker, times(1)).isGamePackLocked(user, pack); } @Test public void testIfServerIsUnreachableDuringSetLockStatusDirtyMarkerSetToTrue() throws HttpException, IOException { final boolean lockStatus = false; final String user = "testUser"; final String pack = "testPack"; PowerMockito.doThrow(new RuntimeException("blah")).when(mockClient) .executeMethod(mockMethod); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.sendLockStatus(user, pack, lockStatus); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(true); } @Test public void testIfServerIsReachableDuringSetLockStatusDirtyMarkerSetToFalse() throws HttpException, IOException { final boolean lockStatus = false; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.sendLockStatus(user, pack, lockStatus); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); } @Test public void testIfServerIsUnreachableDuringSetHighScoreDirtyMarkerSetToTrue() throws HttpException, IOException { final int score = 10; final String user = "testUser"; final String word = "testPack"; PowerMockito.doThrow(new RuntimeException("blah")).when(mockClient) .executeMethod(mockMethod); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.proposeUserHighScoreForWord(user, word, score); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(true); } @Test public void testIfServerIsReachableDuringSetHighScoreDirtyMarkerSetToFalse() throws HttpException, IOException { final int score = 10; final String user = "testUser"; final String word = "testPack"; PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); impl.proposeUserHighScoreForWord(user, word, score); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); } @Test public void testIfCacheWasDirtyAndSetHighScoreSucceedsReturnsTrue() throws HttpException, IOException { final int score = 10; final String user = "testUser"; final String word = "testPack"; PowerMockito.when(mockCacheStatusMarker.getCacheStatus()).thenReturn( true); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertTrue( "Should have received true since the cache was dirty and now it's not!", impl.proposeUserHighScoreForWord(user, word, score)); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); } @Test public void testIfCacheWasNotDirtyAndProposeHighScoreSucceedsReturnsFalse() throws HttpException, IOException { final int score = 10; final String user = "testUser"; final String word = "testPack"; PowerMockito.when(mockCacheStatusMarker.getCacheStatus()).thenReturn( false); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertFalse( "Should have received false since the cache was not dirty!", impl.proposeUserHighScoreForWord(user, word, score)); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); } @Test public void testIfCacheWasDirtyAndSetLockStatusSucceedsReturnsTrue() throws HttpException, IOException { final boolean lockStatus; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockCacheStatusMarker.getCacheStatus()).thenReturn( true); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertTrue( "Should have received true since the cache was dirty and now it's not!", impl.sendLockStatus(user, pack, true)); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); // Now verify no puts and only one get from the cache verify(mockCacheStatusMarker, Mockito.never()).addCachedLockStatus( user, pack, true); verify(mockCacheStatusMarker, Mockito.times(1)).getCachedLockStatuses(); } @Test public void testIfCacheWasNotDirtyAndSetLockStatusSucceedsDoesNotPutOrGetDataInCache() throws HttpException, IOException { final boolean lockStatus = true; final String user = "testUser"; final String pack = "testPack"; PowerMockito.when(mockCacheStatusMarker.getCacheStatus()).thenReturn( false); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertFalse( "Should have received false since the cache was not dirty!", impl.sendLockStatus(user, pack, lockStatus)); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); // Now verify no gets/puts from the cache verify(mockCacheStatusMarker, Mockito.never()).addCachedLockStatus( user, pack, lockStatus); verify(mockCacheStatusMarker, Mockito.never()).getCachedLockStatuses(); } @Test public void testIfCacheWasDirtyAndProposeUserScoreSucceedsReturnsTrueCacheDataIsSent() throws HttpException, IOException { final int score = 10; final String user = "testUser"; final String word = "word"; PowerMockito.when(mockCacheStatusMarker.getCacheStatus()).thenReturn( true); PowerMockito.when(mockConfiguration.isCommunicateWithServer()) .thenReturn(true); TestMockServerCommunicationManager impl = new TestMockServerCommunicationManager(); assertTrue( "Should have received true since the cache was dirty and now it's not!", impl.proposeUserHighScoreForWord(user, word, score)); // Verifications of stuff we expect to ALWAYS happen verify(mockClient).executeMethod(mockMethod); verify(mockMethod).releaseConnection(); verify(mockCacheStatusMarker).setCacheStatus(false); // Now verify no puts and only one get from the cache verify(mockCacheStatusMarker, Mockito.never()).addCachedUserHighScore( user, word, score); verify(mockCacheStatusMarker, Mockito.times(1)) .getCachedUserHighScores(); } class TestMockServerCommunicationManager extends ServerCommunicationManagerImpl { public TestMockServerCommunicationManager() { super(mockCacheStatusMarker, mockConfiguration); } @Override protected HttpMethod getHttpMethod(String url) { return mockMethod; } @Override protected HttpClient getHttpClient() { return mockClient; } } }
gpl-3.0
Bvink/WildTornado
src/ch/swingfx/twinkle/style/background/ColorBackground.java
1751
/* * This library is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. For the terms of this * license, see licenses/gpl_v3.txt or <http://www.gnu.org/licenses/>. * * You are free to use this library under the terms of the GNU General * Public License, 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. * * Alternatively, you can license this library under a commercial * license, as set out in licenses/commercial.txt. */ package ch.swingfx.twinkle.style.background; import ch.swingfx.color.ColorUtil; import java.awt.*; import java.awt.geom.RoundRectangle2D; /** * Paints a color as background * @author Heinrich Spreiter * */ public class ColorBackground implements IBackground { /** Color of the background */ private Color fColor; /** * Create a new {@link ColorBackground} * @param color color of this background */ public ColorBackground(Color color) { fColor = color; } public void paintBackground(Graphics g, boolean isMouseOver, int cornerRadius) { final Graphics2D copy = (Graphics2D) g.create(); final Shape clip = copy.getClip(); copy.setColor(fColor); copy.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if(cornerRadius == 0) { copy.fill(clip); } else { copy.fill(new RoundRectangle2D.Double(0, 0, clip.getBounds().getWidth(), clip.getBounds().getHeight(), cornerRadius, cornerRadius)); } copy.dispose(); } public void setAlpha(float alpha) { fColor = ColorUtil.withAlpha(fColor, alpha); } }
gpl-3.0
ArmandDelessert/WarTanks
NavalBattle/src/navalbattle/protocol/messages/common/NavalBattlePositionMyBoats.java
3356
package navalbattle.protocol.messages.common; import java.util.ArrayList; import navalbattle.boats.BoatPosition; import navalbattle.protocol.common.NavalBattleProtocol; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import xmlhelper.XMLHelper; public class NavalBattlePositionMyBoats extends NavalBattleMessage { private ArrayList<BoatPosition> boats = null; public ArrayList<BoatPosition> getBoats() { return boats; } @Override public Document getXMLRepresentation() { Document doc = XMLHelper.createBaseDocument(); Element rootNode = doc.createElement("request"); rootNode.setAttribute("type", "positionMyBoats"); Element boatsNode = doc.createElement("boats"); for (BoatPosition boat : this.boats) { Element boatNode = doc.createElement("boat"); boatNode.setAttribute("x", Integer.toString(boat.getX())); boatNode.setAttribute("y", Integer.toString(boat.getY())); boatNode.setAttribute("size", Integer.toString(boat.getLength())); boatNode.setAttribute("orientation", ((boat.getOrientation() == NavalBattleProtocol.BOAT_ORIENTATION.HORIZONTAL) ? "horizontal" : "vertical")); boatsNode.appendChild(boatNode); } rootNode.appendChild(boatsNode); doc.appendChild(rootNode); return doc; } @Override public NavalBattlePositionMyBoats parse(Document message) throws InvalidMessage { ArrayList<BoatPosition> boatsRead = new ArrayList<>(); Node rootNode = message.getDocumentElement(); Node boatsNode = XMLHelper.getChildren(rootNode).get("boats"); NodeList allBoats = boatsNode.getChildNodes(); final int boatsCount = allBoats.getLength(); for (int i = 0; i < boatsCount; ++i) { int x; int y; int length; NavalBattleProtocol.BOAT_ORIENTATION orientation; Node boatNode = allBoats.item(i); if (boatNode.getNodeType() != Node.ELEMENT_NODE) continue; NamedNodeMap nodeAttributes = boatNode.getAttributes(); x = Integer.parseInt(nodeAttributes.getNamedItem("x").getNodeValue()); y = Integer.parseInt(nodeAttributes.getNamedItem("y").getNodeValue()); length = Integer.parseInt(nodeAttributes.getNamedItem("size").getNodeValue()); if (x < 0 || y < 0 || length <= 0) { throw new InvalidMessage(); } switch (nodeAttributes.getNamedItem("orientation").getTextContent()) { case "horizontal": orientation = NavalBattleProtocol.BOAT_ORIENTATION.HORIZONTAL; break; case "vertical": orientation = NavalBattleProtocol.BOAT_ORIENTATION.VERTICAL; break; default: throw new InvalidMessage(); } boatsRead.add(new BoatPosition(x, y, orientation, length)); } this.setValues(boatsRead); return this; } public void setValues(ArrayList<BoatPosition> boats) { this.boats = boats; } }
gpl-3.0
donatellosantoro/Llunatic
LunaticGUI/gui/src/it/unibas/lunatic/gui/node/DbNode.java
2551
package it.unibas.lunatic.gui.node; import it.unibas.lunatic.Scenario; import it.unibas.lunatic.gui.node.chase.mc.ChaseStepNode; import it.unibas.lunatic.model.chase.chasemc.DeltaChaseStep; import speedy.model.database.IDatabase; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; public class DbNode extends AbstractNode implements IChaseNode { private IDatabase db; private DeltaChaseStep chaseStep; private ChaseStepNode chaseStepNode; private Scenario scenario; public DbNode(Scenario scenario, IDatabase db, DeltaChaseStep chaseStep, ChaseStepNode chaseStepNode, boolean showId) { this(scenario, db, chaseStep.getId(), Children.create(new DbChildFactory(db, chaseStepNode, chaseStep, scenario), true), showId); this.chaseStep = chaseStep; this.chaseStepNode = chaseStepNode; } public DbNode(Scenario scenario, IDatabase db, String qualifier, boolean showId) { this(scenario, db, qualifier, Children.create(new DbChildFactory(db, scenario), true), showId); } public DbNode(Scenario scenario, IDatabase db, String qualifier) { this(scenario, db, qualifier, true); } protected DbNode(Scenario scenario, IDatabase db, String qualifier, Children c, boolean showId) { super(c); this.db = db; this.scenario = scenario; if (!qualifier.equals("")) { qualifier = qualifier.concat(":"); } String name = getTargetDbName(scenario, db); setName(qualifier.concat(name)); if (!showId) { setDisplayName(name); } this.setIconBaseWithExtension("it/unibas/lunatic/icons/database.gif"); } @Override public DeltaChaseStep getChaseStep() { assert chaseStep != null; return chaseStep; } @Override public boolean isMcResultNode() { return chaseStep != null; } public boolean hasChaseStepNode() { return chaseStepNode != null; } public ChaseStepNode getChaseStepNode() { return chaseStepNode; } public IDatabase getDb() { assert db != null; return db; } public Scenario getScenario() { return scenario; } public static String getTargetDbName(Scenario scenario, IDatabase db) { if (db.getName().equalsIgnoreCase("virtualtarget")) { return scenario.getTarget().getName(); } return db.getName(); } }
gpl-3.0
desht/sensibletoolbox
src/main/java/me/desht/sensibletoolbox/items/itemroutermodules/SilkyBreakerModule.java
2143
package me.desht.sensibletoolbox.items.itemroutermodules; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.CraftingInventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.EnchantmentStorageMeta; public class SilkyBreakerModule extends BreakerModule { private static final ItemStack pick = new ItemStack(Material.DIAMOND_PICKAXE, 1); static { pick.addEnchantment(Enchantment.SILK_TOUCH, 1); } public SilkyBreakerModule() { super(); } public SilkyBreakerModule(ConfigurationSection conf) { super(conf); } @Override public String getItemName() { return "I.R. Mod: Silky Breaker"; } @Override public String[] getLore() { return new String[] { "Insert into an Item Router", "Silk touches a block in its", " configured direction and", " pulls it into the item router.", "NOTE: must use a Silk Touch", " enchanted book to craft." }; } @Override public Recipe getRecipe() { ShapelessRecipe recipe = new ShapelessRecipe(toItemStack()); BreakerModule b = new BreakerModule(); registerCustomIngredients(b); recipe.addIngredient(b.getMaterialData()); recipe.addIngredient(Material.ENCHANTED_BOOK); return recipe; } @Override public boolean validateCrafting(CraftingInventory inventory) { for (ItemStack stack : inventory.getMatrix()) { if (stack != null && stack.getType() == Material.ENCHANTED_BOOK) { EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta(); if (meta.getStoredEnchantLevel(Enchantment.SILK_TOUCH) < 1) { return false; } } } return true; } protected ItemStack getBreakerTool() { return pick; } }
gpl-3.0
deric/clusteval-parent
clusteval-packages/src/main/java/de/clusteval/data/statistics/ClusteringCoefficientRDataStatistic.java
2303
/******************************************************************************* * Copyright (c) 2013 Christian Wiwie. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Christian Wiwie - initial API and implementation ******************************************************************************/ /** * */ package de.clusteval.data.statistics; import java.io.File; import de.clusteval.framework.RLibraryRequirement; import de.clusteval.framework.repository.RegisterException; import de.clusteval.framework.repository.Repository; /** * @author Christian Wiwie * */ @RLibraryRequirement(requiredRLibraries = {"igraph"}) public class ClusteringCoefficientRDataStatistic extends DoubleValueDataStatistic { /* * (non-Javadoc) * * @see utils.Statistic#getAlias() */ @Override public String getAlias() { return "Clustering Coefficient (R)"; } /** * @param repository * @param register * @param changeDate * @param absPath * @throws RegisterException * */ public ClusteringCoefficientRDataStatistic(final Repository repository, final boolean register, final long changeDate, final File absPath) throws RegisterException { super(repository, register, changeDate, absPath, 0.0); } /** * @param repository * @param register * @param changeDate * @param absPath * @param value * @throws RegisterException */ public ClusteringCoefficientRDataStatistic(final Repository repository, final boolean register, final long changeDate, final File absPath, final double value) throws RegisterException { super(repository, register, changeDate, absPath, value); } /** * The copy constructor for this statistic. * * @param other * The object to clone. * @throws RegisterException */ public ClusteringCoefficientRDataStatistic( final ClusteringCoefficientRDataStatistic other) throws RegisterException { super(other); } /* * (non-Javadoc) * * @see data.statistics.DataStatistic#requiresGoldStandard() */ @Override public boolean requiresGoldStandard() { return false; } }
gpl-3.0
JannuMies/poc-proxyer-thingy
src/main/java/net/talviuni/proxyer/TranslationInterface.java
235
package net.talviuni.proxyer; public interface TranslationInterface<S, T> { public Class<S> getSourceClass(); public Class<T> getTargetClass(); public <O extends Object> T translate(O objectToTranslate); }
gpl-3.0
ZargorNET/RegisterP
src/main/java/de/zargornet/registerp/utils/databasequeries/IDatabaseQueries.java
454
package de.zargornet.registerp.utils.databasequeries; import org.bukkit.Location; import java.util.UUID; /** * Interface for database queries */ public interface IDatabaseQueries { void addAccount(UUID uuid, String password); void setPassword(UUID uuid, String newPassword); void remAccount(UUID uuid); String getPassword(UUID uuid); Location getLastPosition(UUID uuid); void setLastPosition(UUID uuid, Location loc); }
gpl-3.0
sosilent/euca
clc/modules/www/src/main/java/com/eucalyptus/webui/shared/user/UserApp.java
4714
package com.eucalyptus.webui.shared.user; import java.util.Date; public class UserApp implements java.io.Serializable { private static final long serialVersionUID = 1L; private int id; private Date apptime; private EnumUserAppStatus status; private String comment; private String keyPair; private String securityGroup; private int ncpus; private int mem; private int disk; private int bw; private int userId; private int vmImageTypeId; private Date srvStartingTime; private Date srvEndingTime; private String euca_vm_instance_key; private int cpu_srv_id; private int mem_srv_id; private int disk_srv_id; private int bw_srv_id; private int public_ip_srv_id; private int private_ip_srv_id; public UserApp() { } public UserApp(int id, Date apptime, EnumUserAppStatus status, int del, String comment, int ncpus, int mem, int disk, int bw, String keyPair, String securityGroup, int userId, int vmImageTypeId, Date srvStartingTime, Date srvEndingTime, String euca_vm_instance_key, int cpu_srv_id, int mem_srv_id, int disk_srv_id, int bw_srv_id, int public_ip_srv_id, int private_ip_srv_id) { this.setUAId(id); this.setAppTime(apptime); this.setStatus(status); this.setSrvStartingTime(srvStartingTime); this.setSrvEndingingTime(srvEndingTime); this.setComment(comment); this.setNcpus(ncpus); this.setMem(mem); this.setDisk(disk); this.setBw(bw); this.setKeyPair(keyPair); this.setSecurityGroup(securityGroup); this.setUserId(userId); this.setVmImageTypeId(vmImageTypeId); this.setEucaVMInstanceKey(euca_vm_instance_key); this.setCPUSrvId(cpu_srv_id); this.setMemSrvId(mem_srv_id); this.setDiskSrvId(disk_srv_id); this.setBwSrvId(bw_srv_id); this.setPubIpSrvId(public_ip_srv_id); this.setPriIpSrvId(private_ip_srv_id); } public void setUAId(int ua_id) { this.id = ua_id; } public int getUAId() { return this.id; } public void setAppTime(Date apptime) { this.apptime = apptime; } public Date getAppTime() { return this.apptime; } public void setStatus(EnumUserAppStatus status) { this.status = status; } public EnumUserAppStatus getStatus() { return this.status; } public void setComment(String comment) { this.comment = comment; } public String getComments() { return this.comment; } public void setNcpus(int ncpus) { this.ncpus = ncpus; } public int getNcpus() { return this.ncpus; } public void setMem(int mem) { this.mem = mem; } public int getMem() { return this.mem; } public void setDisk(int disk) { this.disk = disk; } public int getDisk() { return this.disk; } public void setBw(int bw) { this.bw = bw; } public int getBw() { return this.bw; } public void setUserId(int userId) { this.userId = userId; } public int getUserId() { return this.userId; } public void setVmImageTypeId(int vmImageTypeId) { this.vmImageTypeId = vmImageTypeId; } public int getVmIdImageTypeId() { return this.vmImageTypeId; } public void setSrvStartingTime(Date startingTime) { this.srvStartingTime = startingTime; } public Date getSrvStartingTime() { return this.srvStartingTime; } public void setSrvEndingingTime(Date endingTime) { this.srvEndingTime = endingTime; } public Date getSrvEndingTime() { return this.srvEndingTime; } public void setKeyPair(String keyPair) { this.keyPair = keyPair; } public String getKeyPair() { return this.keyPair; } public void setSecurityGroup(String securityGroup) { this.securityGroup = securityGroup; } public String getSecurityGroup() { return this.securityGroup; } public void setEucaVMInstanceKey(String euca_vm_instance_key) { this.euca_vm_instance_key = euca_vm_instance_key; } public String getEucaVMInstanceKey() { return this.euca_vm_instance_key; } public void setCPUSrvId(int cpu_srv_id) { this.cpu_srv_id = cpu_srv_id; } public int getCPUSrvId() { return this.cpu_srv_id; } public void setMemSrvId(int mem_srv_id) { this.mem_srv_id = mem_srv_id; } public int getMemSrvId() { return this.mem_srv_id; } public void setDiskSrvId(int disk_srv_id) { this.disk_srv_id = disk_srv_id; } public int getDiskSrvId() { return this.disk_srv_id; } public void setBwSrvId(int bw_srv_id) { this.bw_srv_id = bw_srv_id; } public int getBwSrvId() { return this.bw_srv_id; } public void setPubIpSrvId(int public_ip_srv_id) { this.public_ip_srv_id = public_ip_srv_id; } public int getPubIpSrvId() { return this.public_ip_srv_id; } public void setPriIpSrvId(int private_ip_srv_id) { this.private_ip_srv_id = private_ip_srv_id; } public int getPriIpSrvId() { return this.private_ip_srv_id; } }
gpl-3.0
tghoward/geopaparazzi
geopaparazzi_core/src/main/java/eu/geopaparazzi/core/maptools/tools/NoEditableLayerToolGroup.java
6694
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.core.maptools.tools; import android.content.Context; import android.graphics.Canvas; import android.graphics.PorterDuff.Mode; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageButton; import android.widget.LinearLayout; import org.mapsforge.android.maps.MapView; import java.util.HashMap; import java.util.Map; import eu.geopaparazzi.library.core.maps.SpatialiteMap; import eu.geopaparazzi.library.database.GPLog; import eu.geopaparazzi.library.features.EditManager; import eu.geopaparazzi.library.features.ILayer; import eu.geopaparazzi.library.features.Tool; import eu.geopaparazzi.library.features.ToolGroup; import eu.geopaparazzi.library.util.Compat; import eu.geopaparazzi.library.util.GPDialogs; import eu.geopaparazzi.spatialite.database.spatial.SpatialiteSourcesManager; import eu.geopaparazzi.spatialite.database.spatial.core.tables.SpatialVectorTable; import eu.geopaparazzi.core.R; /** * The main polygon layer editing tool group, which just shows the tool palette. * * @author Andrea Antonello (www.hydrologis.com) */ public class NoEditableLayerToolGroup implements ToolGroup, OnClickListener, OnTouchListener { private ImageButton selectAllButton; private MapView mapView; private int selectionColor; /** * Constructor. * * @param mapView the map view. */ public NoEditableLayerToolGroup(MapView mapView) { this.mapView = mapView; LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); selectionColor = Compat.getColor(parent.getContext(), R.color.main_selection); } public void activate() { if (mapView != null) mapView.setClickable(true); } public void initUI() { LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); Context context = parent.getContext(); ILayer editLayer = EditManager.INSTANCE.getEditLayer(); int padding = 2; selectAllButton = new ImageButton(context); selectAllButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); selectAllButton.setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_24dp)); selectAllButton.setPadding(0, padding, 0, padding); selectAllButton.setOnClickListener(this); selectAllButton.setOnTouchListener(this); parent.addView(selectAllButton); } public void disable() { EditManager.INSTANCE.setActiveTool(null); LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); if (parent != null) parent.removeAllViews(); } public void onClick(View v) { if (v == selectAllButton) { Tool currentTool = EditManager.INSTANCE.getActiveTool(); if (currentTool != null && currentTool instanceof InfoTool) { // if the same tool is re-selected, it is disabled EditManager.INSTANCE.setActiveTool(null); } else { // check maps enablement try { HashMap<SpatialiteMap, SpatialVectorTable> spatialiteMaps2TablesMap = SpatialiteSourcesManager.INSTANCE.getSpatialiteMaps2TablesMap(); boolean atLeastOneEnabled = false; for (Map.Entry<SpatialiteMap, SpatialVectorTable> entry : spatialiteMaps2TablesMap.entrySet()) { if (entry.getKey().isVisible) { atLeastOneEnabled = true; break; } } if (!atLeastOneEnabled) { LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); if (parent != null) { Context context = parent.getContext(); GPDialogs.warningDialog(context, context.getString(R.string.no_queriable_layer_is_visible), null); } return; } } catch (Exception e) { GPLog.error(this, null, e); } Tool activeTool = new InfoTool(this, mapView); EditManager.INSTANCE.setActiveTool(activeTool); } } handleToolIcons(v); } @SuppressWarnings("deprecation") private void handleToolIcons(View activeToolButton) { Context context = activeToolButton.getContext(); Tool currentTool = EditManager.INSTANCE.getActiveTool(); if (selectAllButton != null) if (currentTool != null && activeToolButton == selectAllButton) { selectAllButton .setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_active_24dp)); } else { selectAllButton.setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_24dp)); } } public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { v.getBackground().setColorFilter(selectionColor, Mode.SRC_ATOP); v.invalidate(); break; } case MotionEvent.ACTION_UP: { v.getBackground().clearColorFilter(); v.invalidate(); break; } } return false; } public void onToolFinished(Tool tool) { } public void onToolDraw(Canvas canvas) { // nothing to draw } public boolean onToolTouchEvent(MotionEvent event) { return false; } public void onGpsUpdate(double lon, double lat) { // ignore } }
gpl-3.0
CovertHypnosis/Java
Vending/java/com/aws/model/User.java
1953
package com.aws.model; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import java.io.Serializable; import java.util.List; @DynamoDBTable(tableName = "users") public class User implements Serializable { private static final long serialVersionUID = 1L; private String userId; private String firstName; private String lastName; private String age; private List<Environments> environments; @DynamoDBHashKey(attributeName = "userId") @DynamoDBAutoGeneratedKey public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @DynamoDBAttribute public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @DynamoDBAttribute public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @DynamoDBAttribute public String getAge() { return age; } public void setAge(String age) { this.age = age; } @DynamoDBAttribute public List<Environments> getEnvironments() { return environments; } public void setEnvironments(List<Environments> environments) { this.environments = environments; } @Override public String toString() { return "User{" + "userId='" + userId + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age='" + age + '\'' + ", environments=" + environments + '}'; } }
gpl-3.0
GedMarc/JWebSwing
src/test/java/com/jwebmp/core/events/search/SearchAdapterTest.java
1403
/* * Copyright (C) 2017 GedMarc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jwebmp.core.events.search; import com.jwebmp.BaseTestClass; import com.jwebmp.core.base.ajax.AjaxCall; import com.jwebmp.core.base.ajax.AjaxResponse; import com.jwebmp.core.base.html.Div; import com.jwebmp.core.base.html.DivSimple; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class SearchAdapterTest extends BaseTestClass { @Test public void test() { Div test = new DivSimple<>(); test.setID("test"); SearchAdapter aa = new SearchAdapter(test) { @Override public void onSearch(AjaxCall call, AjaxResponse response) { } }; test.addEvent(aa.setID("test")); assertTrue(!test.getEvents() .isEmpty()); } }
gpl-3.0
pwnall/battlecode-server
src/main/battlecode/world/signal/BugSignal.java
1550
package battlecode.world.signal; import battlecode.engine.signal.Signal; import battlecode.world.InternalRobot; import battlecode.common.ComponentType; import battlecode.common.MapLocation; import battlecode.common.RobotLevel; /** * Signifies that a robot just attacked * * @author adamd */ public class BugSignal extends Signal { private static final long serialVersionUID = 8064711239347833273L; /** TheID of the robot that attacked. */ public final int robotID; /** The location that the robot attacked */ public final MapLocation targetLoc; /** The height of the position that the robot attacked */ public final RobotLevel targetHeight; /** * Creates a signal for a robot broadcast. * * @param robot the robot that attacked * @param targetLoc the location that the robot attacked */ public BugSignal(InternalRobot robot, MapLocation targetLoc, RobotLevel targetHeight) { this.robotID = robot.getID(); this.targetLoc = targetLoc; this.targetHeight = targetHeight; } /** * Returns the ID of the robot that just broadcast. * * @return the messaging robot's ID */ public int getRobotID() { return robotID; } /** * Returns the location that the robot attacked * * @return the location that the robot attacked */ public MapLocation getTargetLoc() { return targetLoc; } /** * Returns the height of the position that the robot attacked * * @return the height of the position that the robot attacked */ public RobotLevel getTargetHeight() { return targetHeight; } }
gpl-3.0
mvaudel/onyase
src/main/java/no/uib/onyase/applications/engine/modules/PeptideModificationsIterator.java
532
package no.uib.onyase.applications.engine.modules; import java.util.HashMap; /** * Iterator for the possible modifications carried by a peptide. * * @author Marc Vaudel */ public interface PeptideModificationsIterator { /** * Indicates whether there is a next profile. * * @return a boolean indicating whether there is a next profile */ public boolean hasNext(); /** * Returns the next profile. * * @return the next profile */ public HashMap<String, int[]> next(); }
gpl-3.0
amoraes/spring-boot-unesp
services/src/main/java/br/unesp/exemplo/api/valueobjects/InscricaoVOPut.java
1180
package br.unesp.exemplo.api.valueobjects; import java.io.Serializable; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Value Object para comunicação REST da entidade Inscricao PUT (atualização) * @author Alessandro Moraes */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeName("Inscricao") public class InscricaoVOPut implements Serializable { private static final long serialVersionUID = 8853148012477575858L; @NotNull private String nome; @NotNull private String cpf; @NotNull private String email; private String tamanhoCamiseta; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTamanhoCamiseta() { return tamanhoCamiseta; } public void setTamanhoCamiseta(String tamanhoCamiseta) { this.tamanhoCamiseta = tamanhoCamiseta; } }
gpl-3.0
pseppecher/jamel
src/jamel/models/util/JobContract.java
653
package jamel.models.util; /** * Represents a labor contract. */ public interface JobContract { /** * Breaks the contract. */ void breach(); /** * Returns the starting period of this contract. * * @return the starting period of this contract. */ int getStart(); /** * Returns the wage. * * @return the wage. */ long getWage(); /** * Returns the worker. * * @return the worker. */ Worker getWorker(); /** * Returns {@code true} if the contract is valid, {@code false} * otherwise. * * @return {@code true} if the contract is valid, {@code false} * otherwise. */ boolean isValid(); }
gpl-3.0
TheHecticByte/BananaJ1.7.10Beta
src/net/minecraft/Server1_7_10/command/server/CommandWhitelist.java
5087
package net.minecraft.Server1_7_10.command.server; import com.mojang.authlib.GameProfile; import java.util.List; import net.minecraft.Server1_7_10.command.CommandBase; import net.minecraft.Server1_7_10.command.CommandException; import net.minecraft.Server1_7_10.command.ICommandSender; import net.minecraft.Server1_7_10.command.WrongUsageException; import net.minecraft.Server1_7_10.server.MinecraftServer; import net.minecraft.Server1_7_10.util.ChatComponentText; import net.minecraft.Server1_7_10.util.ChatComponentTranslation; public class CommandWhitelist extends CommandBase { private static final String __OBFID = "CL_00001186"; public String getCommandName() { return "whitelist"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } public String getCommandUsage(ICommandSender p_71518_1_) { return "commands.whitelist.usage"; } public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) { if (p_71515_2_.length >= 1) { MinecraftServer var3 = MinecraftServer.getServer(); if (p_71515_2_[0].equals("on")) { var3.getConfigurationManager().setWhiteListEnabled(true); func_152373_a(p_71515_1_, this, "commands.whitelist.enabled", new Object[0]); return; } if (p_71515_2_[0].equals("off")) { var3.getConfigurationManager().setWhiteListEnabled(false); func_152373_a(p_71515_1_, this, "commands.whitelist.disabled", new Object[0]); return; } if (p_71515_2_[0].equals("list")) { p_71515_1_.addChatMessage(new ChatComponentTranslation("commands.whitelist.list", new Object[] {Integer.valueOf(var3.getConfigurationManager().func_152598_l().length), Integer.valueOf(var3.getConfigurationManager().getAvailablePlayerDat().length)})); String[] var5 = var3.getConfigurationManager().func_152598_l(); p_71515_1_.addChatMessage(new ChatComponentText(joinNiceString(var5))); return; } GameProfile var4; if (p_71515_2_[0].equals("add")) { if (p_71515_2_.length < 2) { throw new WrongUsageException("commands.whitelist.add.usage", new Object[0]); } var4 = var3.func_152358_ax().func_152655_a(p_71515_2_[1]); if (var4 == null) { throw new CommandException("commands.whitelist.add.failed", new Object[] {p_71515_2_[1]}); } var3.getConfigurationManager().func_152601_d(var4); func_152373_a(p_71515_1_, this, "commands.whitelist.add.success", new Object[] {p_71515_2_[1]}); return; } if (p_71515_2_[0].equals("remove")) { if (p_71515_2_.length < 2) { throw new WrongUsageException("commands.whitelist.remove.usage", new Object[0]); } var4 = var3.getConfigurationManager().func_152599_k().func_152706_a(p_71515_2_[1]); if (var4 == null) { throw new CommandException("commands.whitelist.remove.failed", new Object[] {p_71515_2_[1]}); } var3.getConfigurationManager().func_152597_c(var4); func_152373_a(p_71515_1_, this, "commands.whitelist.remove.success", new Object[] {p_71515_2_[1]}); return; } if (p_71515_2_[0].equals("reload")) { var3.getConfigurationManager().loadWhiteList(); func_152373_a(p_71515_1_, this, "commands.whitelist.reloaded", new Object[0]); return; } } throw new WrongUsageException("commands.whitelist.usage", new Object[0]); } /** * Adds the strings available in this command to the given list of tab completion options. */ public List addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) { if (p_71516_2_.length == 1) { return getListOfStringsMatchingLastWord(p_71516_2_, new String[] {"on", "off", "list", "add", "remove", "reload"}); } else { if (p_71516_2_.length == 2) { if (p_71516_2_[0].equals("remove")) { return getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().getConfigurationManager().func_152598_l()); } if (p_71516_2_[0].equals("add")) { return getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().func_152358_ax().func_152654_a()); } } return null; } } }
gpl-3.0
Duke2k/jatf
jatf-tests/src/main/java/jatf/dependency/AnnotationTypeTest.java
2474
/* This file is part of JATF. <p> JATF is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. <p> JATF is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. <p> You should have received a copy of the GNU General Public License along with JATF. If not, see <http://www.gnu.org/licenses/>. */ package jatf.dependency; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import jatf.annotations.MustHaveAnnotation; import jatf.annotations.MustNotHaveAnnotation; import org.junit.Test; import org.junit.runner.RunWith; import java.lang.annotation.Annotation; import java.util.Set; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(DataProviderRunner.class) public class AnnotationTypeTest extends DependencyTestBase { @DataProvider public static Object[][] provideClassesToTest() { Set<Class<?>> classesToTest = provideClassesFor(AnnotationTypeTest.class); return getProvider(classesToTest); } @Test @UseDataProvider(DATA_PROVIDER_NAME) public void isAnnotated(Class<?> clazz) { Annotation[] annotations = clazz.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType().equals(MustHaveAnnotation.class)) { assertTrue("Required annotation " + annotation + " not present in " + clazz.getName(), checkIfAnnotationIsPresentIn(clazz, ((MustHaveAnnotation) annotation).annotation())); } if (annotation.annotationType().equals(MustNotHaveAnnotation.class)) { assertFalse("Forbidden annotation " + annotation + " present in " + clazz.getName(), checkIfAnnotationIsPresentIn(clazz, ((MustNotHaveAnnotation) annotation).annotation())); } } } private boolean checkIfAnnotationIsPresentIn(Class<?> clazz, Class<? extends Annotation> annotation) { Annotation[] annotations = clazz.getAnnotations(); for (Annotation a : annotations) { if (a.annotationType().equals(annotation)) { return true; } } return false; } }
gpl-3.0
jmastri/automata
sample_automata/src/main/java/com/teksystems/qe/automata/sample/amazon/views/AmazonBaseView.java
967
package com.teksystems.qe.automata.sample.amazon.views; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.teksystems.qe.automata.interfaces.BaseView; import com.teksystems.qe.automata.sample.amazon.data.AmazonUser; public abstract class AmazonBaseView implements BaseView{ protected WebDriver driver; protected AmazonUser user; /** * Define global elements here */ @FindBy(xpath="//input[@name='field-keywords']") WebElement searchInput; @FindBy(xpath="//input[contains(@class,'nav-input') and @type='submit']") WebElement searchSubmit; public AmazonBaseView(WebDriver driver, AmazonUser user){ this.driver = driver; this.user = user; PageFactory.initElements(driver, this); } public abstract void complete(); public void navigate() { return; } /** * Put utility functions here */ }
gpl-3.0
srirang/numbrcrunchr
src/test/java/com/numbrcrunchr/domain/FeasibilityAnalysisProjectionServiceTest.java
8965
package com.numbrcrunchr.domain; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.List; import org.joda.time.DateMidnight; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/domainApplicationContext.xml" }) public class FeasibilityAnalysisProjectionServiceTest { @Autowired private FeasibilityAnalysisProjectionService projectionService; @Autowired private ProjectionParameters projectionParameters; private long income; private long ongoingCosts; private long weeklyRent; private byte weeksRented; private long loanAmount; private double interestRate; private double propertyManagementFee; private long landlordInsurance; private long maintenance; private long strata; private long waterRates; private long cleaning; private long councilRates; private long gardening; private long taxExpenses; private long miscOngoingExpenses; private double capitalGrowthRate; private double cpi; private double salaryIncreaseRate; private double rentIncreaseRate; private int loanTerm; private int interestOnlyPeriod; private int projectionYears; @Test public void checkProjectionFor1Year() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); List<FeasibilityAnalysisResult> projections = projectionService .runProjection(property, 1, projectionParameters) .getProjections(); assertEquals(2, projections.size()); } @Test public void checkProjectionFor1YearWithoutMedicareLevy() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); property.getOwnerList().get(0).setMedicareLevyApplies(Boolean.FALSE); List<FeasibilityAnalysisResult> projections = projectionService .runProjection(property, 1, projectionParameters) .getProjections(); assertEquals(2, projections.size()); } @Test public void checkProjectionFor2Years() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; List<FeasibilityAnalysisResult> projections = runSomeProjections(); assertEquals(3, projections.size()); } private List<FeasibilityAnalysisResult> runSomeProjections() { Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); List<FeasibilityAnalysisResult> projections = projectionService .runProjection(property, 2, projectionParameters) .getProjections(); return projections; } @Test public void checkProjectionFor20Years() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); List<FeasibilityAnalysisResult> projections = projectionService .runProjection(property, 20, projectionParameters) .getProjections(); assertEquals(21, projections.size()); } @Test public void checkProjectionFor320kPropertyAt320PerWeekOver25Years() { income = 100000; weeklyRent = 320; weeksRented = 50; loanAmount = 320000; interestRate = 6; landlordInsurance = 400; maintenance = 100; strata = 0; waterRates = 800; cleaning = 100; councilRates = 1500; gardening = 100; taxExpenses = 100; miscOngoingExpenses = 0; projectionYears = 24; cpi = 3; capitalGrowthRate = 8; salaryIncreaseRate = 3.5; rentIncreaseRate = 4; loanTerm = 30; interestOnlyPeriod = 10; Date purchaseDate = new DateMidnight(2014, 2, 11).toDate(); ProjectionParameters projectionParameters = new ProjectionParameters(); projectionParameters.setCapitalGrowthRate(capitalGrowthRate); projectionParameters.setCpi(cpi); projectionParameters.setRentIncreaseRate(rentIncreaseRate); projectionParameters.setSalaryIncreaseRate(salaryIncreaseRate); OngoingCosts ongoingCosts = new OngoingCosts(); ongoingCosts.setMaintenance(maintenance); ongoingCosts.setStrata(strata); ongoingCosts.setWaterCharges(waterRates); ongoingCosts.setCleaning(cleaning); ongoingCosts.setCouncilRates(councilRates); ongoingCosts.setGardening(gardening); ongoingCosts.setTaxExpenses(taxExpenses); ongoingCosts.setMiscOngoingExpenses(miscOngoingExpenses); ongoingCosts.setLandlordsInsurance(landlordInsurance); Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); property.setLoanTerm(loanTerm); property.setPurchaseDate(purchaseDate); property.setInterestOnlyPeriod(interestOnlyPeriod); property.setManagementFeeRate(8.8); Projection projection = projectionService.runProjection(property, projectionYears, projectionParameters); projection.changeFrequency(FeasibilityAnalysisResult.MONTHLY); } @Test public void checkProjectionFor50Years() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); Projection projection = projectionService.runProjection(property, 50, projectionParameters); projection.toString(); assertEquals(16, projection.getCashflowPositiveYearIndex()); List<FeasibilityAnalysisResult> projections = projection .getProjections(); // TODO Why does projection for n years return n+1 results? assertEquals(31, projections.size()); } @Test public void checkThatLoanBalanceReducesForPrincipalAndInterestProjection() { income = 120000; ongoingCosts = 7000; weeklyRent = 320; weeksRented = 50; loanAmount = 427320; interestRate = 8; propertyManagementFee = 10; Property property = PropertyTest.createProperty(income, true, loanAmount, ongoingCosts, weeksRented, weeklyRent, interestRate, propertyManagementFee); property.setInterestOnlyPeriod(0); Projection projection = projectionService.runProjection(property, 20, projectionParameters); List<FeasibilityAnalysisResult> projections = projection .getProjections(); double previousLoanBalance = loanAmount + 1; int i = 1; for (FeasibilityAnalysisResult result : projections) { assertTrue(result.getLoanBalance() < previousLoanBalance); if (i == 1) { assertEquals("Y 1 (partial)", result.getYear()); } else { assertEquals("Y " + i, result.getYear()); } i++; previousLoanBalance = result.getLoanBalance(); } } }
gpl-3.0
qt-haiku/LibreOffice
xmerge/source/xmerge/java/org/openoffice/xmerge/merger/diff/CharArrayLCSAlgorithm.java
7570
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package org.openoffice.xmerge.merger.diff; import java.util.ArrayList; import org.openoffice.xmerge.merger.Difference; /** * <p>This is an implementations of <code>DiffAlgorithm</code> interface * which will difference char arrays.</p> * * <p>It also use Longest Common Subsequence (LCS). The algorithm is based * on the book "Introduction to Algorithms" by Thomas H.Cormen, * Charles E.Leiserson, and Ronald L.Riverst (MIT Press 1990) page 314.</p> */ public class CharArrayLCSAlgorithm { /** * Return an <code>Difference</code> array. This method finds out * the difference between two sequences. * * @param orgSeq The original sequence. * @param modSeq The modified (or changed) sequence to * compare against the origial. * * @return A <code>Difference</code> array. */ public Difference[] computeDiffs(char[] orgSeq, char[] modSeq) { int orgSeqlen = orgSeq.length; int modSeqlen = modSeq.length; int[][] diffTable; // Diff table is used to keep track which element is the same or not // in those 2 sequences diffTable = createDiffTable(orgSeq, modSeq); ArrayList<Difference> diffResult = new ArrayList<Difference>(); generateResult(diffTable, orgSeqlen, modSeqlen, diffResult); Difference[] diffArray = new Difference[0]; // convert the vector to array, it has to do in here as // generateResult is called recursively if (diffResult.size() > 0) { diffArray = new Difference[diffResult.size()]; diffResult.toArray(diffArray); } diffTable = null; diffResult = null; return diffArray; } /** * Create the difference table. * The difference table is used internal to keep track what * elements are common or different in the two sequences. * * @param orgSeq The original sequence to be used as a base. * @param modSeq The modified sequence to compare. * * @return A difference table as a two-dimensional array of * integers. */ private int[][] createDiffTable(char[] orgSeq, char[] modSeq) { int orgSeqlen = orgSeq.length + 1; int modSeqlen = modSeq.length + 1; int[][] diffTable; // initialize the diffTable (it need to be 1 row/col bigger // than the original str) diffTable = new int[orgSeqlen][]; for (int i = 0; i < orgSeqlen; i++) { diffTable[i] = new int[modSeqlen]; } // compute the diff Table using LCS algorithm, refer to the book // mentioned at the top of the program for (int i = 1; i < orgSeqlen; i++) { for (int j = 1; j < modSeqlen; j++) { if (orgSeq[i-1] == modSeq[j-1]) { diffTable[i][j] = diffTable[i-1][j-1]+1; } else { if (diffTable[i-1][j] >= diffTable[i][j-1]) { diffTable[i][j] = diffTable[i-1][j]; } else { diffTable[i][j] = diffTable[i][j-1]; } } } } return diffTable; } /** * Generate the <code>Difference</code> result vector. * This method will be called recursively to backtrack the difference * table to get the difference result (and also the LCS). * * @param diffTable The difference table containing the * <code>Difference</code> result. * @param i The nth element in original sequence to * compare. This method is called recursively * with i and j decreased until 0. * @param j The nth element in modified sequence to * compare. * @param diffVector A vector to output the <code>Difference</code> * result. Can not use a return variable as it * is a recursive method. The vector will contain * <code>Difference</code> objects with operation * and positions filled in. */ private void generateResult(int[][] diffTable, int i, int j, ArrayList<Difference> diffVector) { // handle the first element if (i == 0 || j == 0) { if (i == 0 && j == 0) { // return } else if (j == 0) { for (int cnt = 0; cnt < i; cnt++) { Difference diff = new Difference(Difference.DELETE, cnt, j); diffVector.add(diff); } } else { for (int cnt = 0; cnt < j; cnt++) { Difference diff = new Difference(Difference.ADD, i, cnt); diffVector.add(diff); } } return; } // for the detail of this algorithm, refer to the book mentioned on // the top and page 317 and 318. if ((diffTable[i-1][j-1] == diffTable[i][j] -1) && (diffTable[i-1][j-1] == diffTable[i-1][j]) && (diffTable[i-1][j-1] == diffTable[i][j-1])) { // the element of ith and jth in org and mod sequence is the same generateResult(diffTable, i-1, j-1, diffVector); } else { if (diffTable[i-1][j] > diffTable[i][j-1]) { // recursively call first, then add the result so that // the beginning of the diffs will be stored first generateResult(diffTable, i-1, j, diffVector); Difference diff = new Difference(Difference.DELETE, i-1, j); diffVector.add(diff); } else if (diffTable[i-1][j] < diffTable[i][j-1]) { // recursively call first, then add the result so that // the beginning of the diffs will be stored first generateResult(diffTable, i, j-1, diffVector); Difference diff = new Difference(Difference.ADD, i, j-1); diffVector.add(diff); } else { // diffTable[i-1][j] == diffTable[i][j-1] // recursively call first, then add the result so that // the beginning of the diffs will be stored first generateResult(diffTable, i-1, j-1, diffVector); Difference diff = new Difference(Difference.CHANGE, i-1, j-1); diffVector.add(diff); } } } }
gpl-3.0
hartwigmedical/hmftools
protect/src/main/java/com/hartwig/hmftools/protect/ProtectConfig.java
9388
package com.hartwig.hmftools.protect; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Set; import com.google.common.collect.Sets; import com.hartwig.hmftools.common.genome.refgenome.RefGenomeVersion; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.immutables.value.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Value.Immutable @Value.Style(passAnnotations = { NotNull.class, Nullable.class }) public interface ProtectConfig { String DOID_SEPARATOR = ";"; // General params needed for every analysis String TUMOR_SAMPLE_ID = "tumor_sample_id"; String REFERENCE_SAMPLE_ID = "reference_sample_id"; String PRIMARY_TUMOR_DOIDS = "primary_tumor_doids"; String OUTPUT_DIRECTORY = "output_dir"; // Input files used by the algorithm String SERVE_ACTIONABILITY_DIRECTORY = "serve_actionability_dir"; String DOID_JSON = "doid_json"; // Files containing the actual genomic results for this sample. String PURPLE_PURITY_TSV = "purple_purity_tsv"; String PURPLE_QC_FILE = "purple_qc_file"; String PURPLE_GENE_COPY_NUMBER_TSV = "purple_gene_copy_number_tsv"; String PURPLE_SOMATIC_DRIVER_CATALOG_TSV = "purple_somatic_driver_catalog_tsv"; String PURPLE_GERMLINE_DRIVER_CATALOG_TSV = "purple_germline_driver_catalog_tsv"; String PURPLE_SOMATIC_VARIANT_VCF = "purple_somatic_variant_vcf"; String PURPLE_GERMLINE_VARIANT_VCF = "purple_germline_variant_vcf"; String LINX_FUSION_TSV = "linx_fusion_tsv"; String LINX_BREAKEND_TSV = "linx_breakend_tsv"; String LINX_DRIVER_CATALOG_TSV = "linx_driver_catalog_tsv"; String ANNOTATED_VIRUS_TSV = "annotated_virus_tsv"; String CHORD_PREDICTION_TXT = "chord_prediction_txt"; // Some additional optional params and flags String LOG_DEBUG = "log_debug"; @NotNull static Options createOptions() { Options options = new Options(); options.addOption(TUMOR_SAMPLE_ID, true, "The sample ID for which PROTECT will run."); options.addOption(REFERENCE_SAMPLE_ID, true, "(Optional) The reference sample of the tumor sample for which PROTECT will run."); options.addOption(PRIMARY_TUMOR_DOIDS, true, "A semicolon-separated list of DOIDs representing the primary tumor of patient."); options.addOption(OUTPUT_DIRECTORY, true, "Path to where the PROTECT output data will be written to."); options.addOption(RefGenomeVersion.REF_GENOME_VERSION, true, "Ref genome version to use (either '37' or '38')"); options.addOption(SERVE_ACTIONABILITY_DIRECTORY, true, "Path towards the SERVE actionability directory."); options.addOption(DOID_JSON, true, "Path to JSON file containing the full DOID tree."); options.addOption(PURPLE_PURITY_TSV, true, "Path towards the purple purity TSV."); options.addOption(PURPLE_QC_FILE, true, "Path towards the purple qc file."); options.addOption(PURPLE_GENE_COPY_NUMBER_TSV, true, "Path towards the purple gene copynumber TSV."); options.addOption(PURPLE_SOMATIC_DRIVER_CATALOG_TSV, true, "Path towards the purple somatic driver catalog TSV."); options.addOption(PURPLE_GERMLINE_DRIVER_CATALOG_TSV, true, "Path towards the purple germline driver catalog TSV."); options.addOption(PURPLE_SOMATIC_VARIANT_VCF, true, "Path towards the purple somatic variant VCF."); options.addOption(PURPLE_GERMLINE_VARIANT_VCF, true, "Path towards the purple germline variant VCF."); options.addOption(LINX_FUSION_TSV, true, "Path towards the LINX fusion TSV."); options.addOption(LINX_BREAKEND_TSV, true, "Path towards the LINX breakend TSV."); options.addOption(LINX_DRIVER_CATALOG_TSV, true, "Path towards the LINX driver catalog TSV."); options.addOption(ANNOTATED_VIRUS_TSV, true, "Path towards the annotated virus TSV."); options.addOption(CHORD_PREDICTION_TXT, true, "Path towards the CHORD prediction TXT."); options.addOption(LOG_DEBUG, false, "If provided, set the log level to debug rather than default."); return options; } @NotNull String tumorSampleId(); @Nullable String referenceSampleId(); @NotNull Set<String> primaryTumorDoids(); @NotNull String outputDir(); @NotNull RefGenomeVersion refGenomeVersion(); @NotNull String serveActionabilityDir(); @NotNull String doidJsonFile(); @NotNull String purplePurityTsv(); @NotNull String purpleQcFile(); @NotNull String purpleGeneCopyNumberTsv(); @NotNull String purpleSomaticDriverCatalogTsv(); @NotNull String purpleGermlineDriverCatalogTsv(); @NotNull String purpleSomaticVariantVcf(); @NotNull String purpleGermlineVariantVcf(); @NotNull String linxFusionTsv(); @NotNull String linxBreakendTsv(); @NotNull String linxDriverCatalogTsv(); @NotNull String annotatedVirusTsv(); @NotNull String chordPredictionTxt(); @NotNull static ProtectConfig createConfig(@NotNull CommandLine cmd) throws ParseException, IOException { if (cmd.hasOption(LOG_DEBUG)) { Configurator.setRootLevel(Level.DEBUG); } return ImmutableProtectConfig.builder() .tumorSampleId(nonOptionalValue(cmd, TUMOR_SAMPLE_ID)) .referenceSampleId(optionalValue(cmd, REFERENCE_SAMPLE_ID)) .primaryTumorDoids(toStringSet(nonOptionalValue(cmd, PRIMARY_TUMOR_DOIDS), DOID_SEPARATOR)) .outputDir(outputDir(cmd, OUTPUT_DIRECTORY)) .refGenomeVersion(RefGenomeVersion.from(nonOptionalValue(cmd, RefGenomeVersion.REF_GENOME_VERSION))) .serveActionabilityDir(nonOptionalDir(cmd, SERVE_ACTIONABILITY_DIRECTORY)) .doidJsonFile(nonOptionalFile(cmd, DOID_JSON)) .purplePurityTsv(nonOptionalFile(cmd, PURPLE_PURITY_TSV)) .purpleQcFile(nonOptionalFile(cmd, PURPLE_QC_FILE)) .purpleGeneCopyNumberTsv(nonOptionalFile(cmd, PURPLE_GENE_COPY_NUMBER_TSV)) .purpleSomaticDriverCatalogTsv(nonOptionalFile(cmd, PURPLE_SOMATIC_DRIVER_CATALOG_TSV)) .purpleGermlineDriverCatalogTsv(nonOptionalFile(cmd, PURPLE_GERMLINE_DRIVER_CATALOG_TSV)) .purpleSomaticVariantVcf(nonOptionalFile(cmd, PURPLE_SOMATIC_VARIANT_VCF)) .purpleGermlineVariantVcf(nonOptionalFile(cmd, PURPLE_GERMLINE_VARIANT_VCF)) .linxFusionTsv(nonOptionalFile(cmd, LINX_FUSION_TSV)) .linxBreakendTsv(nonOptionalFile(cmd, LINX_BREAKEND_TSV)) .linxDriverCatalogTsv(nonOptionalFile(cmd, LINX_DRIVER_CATALOG_TSV)) .annotatedVirusTsv(nonOptionalFile(cmd, ANNOTATED_VIRUS_TSV)) .chordPredictionTxt(nonOptionalFile(cmd, CHORD_PREDICTION_TXT)) .build(); } @NotNull static Iterable<String> toStringSet(@NotNull String paramValue, @NotNull String separator) { return !paramValue.isEmpty() ? Sets.newHashSet(paramValue.split(separator)) : Sets.newHashSet(); } @NotNull static String nonOptionalValue(@NotNull CommandLine cmd, @NotNull String param) throws ParseException { String value = cmd.getOptionValue(param); if (value == null) { throw new ParseException("Parameter must be provided: " + param); } return value; } @Nullable static String optionalValue(@NotNull CommandLine cmd, @NotNull String param) { String value = null; if (cmd.hasOption(param)) { value = cmd.getOptionValue(param); } if (value != null && value.isEmpty()) { value = null; } return value; } @NotNull static String nonOptionalDir(@NotNull CommandLine cmd, @NotNull String param) throws ParseException { String value = nonOptionalValue(cmd, param); if (!pathExists(value) || !pathIsDirectory(value)) { throw new ParseException("Parameter '" + param + "' must be an existing directory: " + value); } return value; } @NotNull static String outputDir(@NotNull CommandLine cmd, @NotNull String param) throws ParseException, IOException { String value = nonOptionalValue(cmd, param); File outputDir = new File(value); if (!outputDir.exists() && !outputDir.mkdirs()) { throw new IOException("Unable to write to directory " + value); } return value; } @NotNull static String nonOptionalFile(@NotNull CommandLine cmd, @NotNull String param) throws ParseException { String value = nonOptionalValue(cmd, param); if (!pathExists(value)) { throw new ParseException("Parameter '" + param + "' must be an existing file: " + value); } return value; } static boolean pathExists(@NotNull String path) { return Files.exists(new File(path).toPath()); } static boolean pathIsDirectory(@NotNull String path) { return Files.isDirectory(new File(path).toPath()); } }
gpl-3.0
241180/Oryx
framework8-demo-master/todomvc/src/main/java/com/vaadin/tutorial/todomvc/TodoViewImpl.java
8359
package com.vaadin.tutorial.todomvc; import java.util.EnumSet; import com.vaadin.data.provider.ConfigurableFilterDataProvider; import com.vaadin.event.ShortcutListener; import com.vaadin.icons.VaadinIcons; import com.vaadin.shared.ui.ValueChangeMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Grid; import com.vaadin.ui.Grid.SelectionMode; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.RadioButtonGroup; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.renderers.ButtonRenderer; import com.vaadin.ui.themes.ValoTheme; public class TodoViewImpl extends VerticalLayout implements TodoView { private static final String WIDTH = "500px"; private final TodoPresenter presenter; private Grid<Todo> grid; private HorizontalLayout bottomBar; private Label itemCountLabel; private TextField newTodoField; private Button clearCompleted; private boolean allCompleted; private Button markAllDoneButton; private Todo currentlyEditedTodo; private EnterPressHandler newTodoFieldEnterPressHandler; private ConfigurableFilterDataProvider<Todo, Void, TaskFilter> filterDataProvider; public TodoViewImpl() { setWidth("100%"); setDefaultComponentAlignment(Alignment.TOP_CENTER); setMargin(false); setSpacing(false); Label headerLabel = new Label("todos"); headerLabel.addStyleName(ValoTheme.LABEL_H1); addComponent(headerLabel); initTopBar(); initGrid(); initBottomBar(); presenter = new TodoPresenter(this); } private void initTopBar() { HorizontalLayout topBar = new HorizontalLayout(); topBar.setWidth(WIDTH); markAllDoneButton = new Button(VaadinIcons.CHEVRON_DOWN); markAllDoneButton.setId("mark-all-done"); markAllDoneButton.addStyleName(ValoTheme.BUTTON_BORDERLESS); markAllDoneButton.addClickListener(event -> { allCompleted = !allCompleted; presenter.markAllCompleted(allCompleted); }); newTodoField = new TextField(); newTodoField.setId("new-todo"); newTodoField.addStyleName(ValoTheme.TEXTFIELD_BORDERLESS); newTodoField.addStyleName(ValoTheme.TEXTFIELD_LARGE); newTodoField.setWidth("100%"); // value might not be updated to server when quickly pressing enter // without this ... newTodoField.setValueChangeMode(ValueChangeMode.EAGER); newTodoField.setPlaceholder("What needs to be done?"); newTodoField.focus(); // auto-focus // there can only be one shortcut listener set, so need to add/remove // this in editTodo() newTodoFieldEnterPressHandler = new EnterPressHandler( this::onNewTodoFieldEnter); newTodoField.addShortcutListener(newTodoFieldEnterPressHandler); topBar.addComponents(markAllDoneButton, newTodoField); topBar.setExpandRatio(newTodoField, 1); topBar.setSpacing(false); addComponent(topBar); } private void initGrid() { grid = new Grid<>(); grid.setSelectionMode(SelectionMode.NONE); grid.setHeight(null); grid.setDetailsGenerator(this::createTodoEditor); grid.setStyleGenerator(this::createStyle); Grid.Column<Todo, String> completeButtonColumn = grid .addColumn(t -> "", new ButtonRenderer<>(event -> presenter.markCompleted( event.getItem(), !event.getItem() .isCompleted()))); completeButtonColumn.setWidth(80); Grid.Column<Todo, String> todoStringColumn = grid.addColumn( Todo::getText, new ButtonRenderer<>(e -> editTodo(e.getItem()))); todoStringColumn.setExpandRatio(1); Grid.Column<Todo, String> deleteButtonColumn = grid.addColumn(t -> "", new ButtonRenderer<>( event -> presenter.delete(event.getItem()))); deleteButtonColumn.setWidth(60); grid.removeHeaderRow(0); addComponent(grid); } private void initBottomBar() { itemCountLabel = new Label(); itemCountLabel.setId("count"); itemCountLabel.setWidth(13, Unit.EX); RadioButtonGroup<TaskFilter> filters = new RadioButtonGroup<>(null, EnumSet.allOf(TaskFilter.class)); filters.setItemCaptionGenerator(TaskFilter::getText); filters.setId("filters"); filters.addStyleName(ValoTheme.OPTIONGROUP_HORIZONTAL); filters.addStyleName(ValoTheme.OPTIONGROUP_SMALL); filters.setValue(TaskFilter.ALL); filters.addValueChangeListener(event -> { filterDataProvider.setFilter(event.getValue()); presenter.refreshView(); }); clearCompleted = new Button("Clear completed"); clearCompleted.setId("clear-completed"); clearCompleted.addStyleName(ValoTheme.BUTTON_BORDERLESS); clearCompleted.addStyleName(ValoTheme.BUTTON_SMALL); clearCompleted.addClickListener(event -> presenter.clearCompleted()); bottomBar = new HorizontalLayout(); bottomBar.setId("bottom-bar"); bottomBar.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); bottomBar.addComponents(itemCountLabel, filters, clearCompleted); bottomBar.setExpandRatio(filters, 1); bottomBar.setComponentAlignment(filters, Alignment.TOP_LEFT); bottomBar.setVisible(false); bottomBar.setWidth(WIDTH); addComponents(bottomBar); } @Override public void refresh() { grid.getDataProvider().refreshAll(); } @Override public void updateCounters(int completed, int active) { bottomBar.setVisible(completed != 0 || active != 0); clearCompleted.setVisible(completed != 0); allCompleted = active == 0; markAllDoneButton.setStyleName("all-done", allCompleted); if (active > 1) { itemCountLabel.setValue(String.format("%1$S items left", active)); } else { itemCountLabel.setValue(String.format("%1$S item left", active)); } } @Override public void setDataProvider(TodoJDBCDataProvider dataProvider) { filterDataProvider = dataProvider.withConfigurableFilter(); grid.setDataProvider(filterDataProvider); } private void onNewTodoFieldEnter() { String value = newTodoField.getValue().trim(); if (!value.isEmpty()) { presenter.add(new Todo(value)); newTodoField.setValue(""); } } private void editTodo(Todo newTodo) { if (currentlyEditedTodo == newTodo) { return; } if (currentlyEditedTodo != null) { presenter.updateTodo(currentlyEditedTodo); grid.setDetailsVisible(currentlyEditedTodo, false); newTodoField.addShortcutListener(newTodoFieldEnterPressHandler); } currentlyEditedTodo = newTodo; if (currentlyEditedTodo != null) { newTodoField.removeShortcutListener(newTodoFieldEnterPressHandler); grid.setDetailsVisible(currentlyEditedTodo, true); } } private TextField createTodoEditor(Todo todo) { TextField textField = new TextField(); textField.setId("todo-editor"); textField.setWidth("100%"); textField.setValue(todo.getText()); textField.focus(); textField.addValueChangeListener(e -> todo.setText(e.getValue())); textField.addShortcutListener( new EnterPressHandler(() -> editTodo(null))); textField.addBlurListener(e -> editTodo(null)); return textField; } private String createStyle(Todo todo) { return todo.isCompleted() ? "done" : ""; } private class EnterPressHandler extends ShortcutListener { private Runnable handler; public EnterPressHandler(Runnable handler) { super("", KeyCode.ENTER, new int[0]); this.handler = handler; } @Override public void handleAction(Object sender, Object target) { handler.run(); } } }
gpl-3.0
RichardBradley/casio-cfx-9800g
cfx-9800g-emulator/src/org/bradders/casiocfx9800g/node/TComma.java
807
/* This file was generated by SableCC (http://www.sablecc.org/). */ package org.bradders.casiocfx9800g.node; import org.bradders.casiocfx9800g.analysis.*; @SuppressWarnings("nls") public final class TComma extends Token { public TComma() { super.setText(","); } public TComma(int line, int pos) { super.setText(","); setLine(line); setPos(pos); } @Override public Object clone() { return new TComma(getLine(), getPos()); } @Override public void apply(Switch sw) { ((Analysis) sw).caseTComma(this); } @Override public void setText(@SuppressWarnings("unused") String text) { throw new RuntimeException("Cannot change TComma text."); } }
gpl-3.0
2686747/tagger-bot
src/main/java/org/tlg/bot/mem/msg/HelpMessage.java
551
/** * */ package org.tlg.bot.mem.msg; /** * @author "Maksim Vakhnik" * */ public class HelpMessage extends TextMessage { private static final String MSG = "Send to bot your pictures" + ", add tags to these media. After this you can " + "search these media by these tags " + "and send it to your companion in a chat.\n" + "More details you can see here:\n" + "http://2686747.github.io/tagger-bot/" ; public HelpMessage(final Long chatId) { super(chatId, HelpMessage.MSG); } }
gpl-3.0
remixgit/GraphicalEditor-Project
MaikaGraphicEditor/src/maika/controller/WorkspaceTreeControler.java
1508
package maika.controller; import java.beans.PropertyVetoException; import maika.application.Application; import maika.model.workspace.Diagram; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import maika.model.workspace.Project; import javax.swing.JInternalFrame; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; public class WorkspaceTreeControler implements TreeSelectionListener{ public void valueChanged(TreeSelectionEvent e) { // TODO Auto-generated method stub TreePath path = e.getPath(); for(int i=0; i<path.getPathCount(); i++){ if(path.getPathComponent(i) instanceof Diagram){ Diagram d=(Diagram)path.getPathComponent(i); JInternalFrame[] pom = new JInternalFrame[Application.getInstance().getDesktop().getAllFrames().length]; //napravim lokalne internal frameove for (int j = 0; j < pom.length; j++) { pom[j] = Application.getInstance().getDesktop().getAllFrames()[j]; //prepisem sve frameove u ove lokalne if(pom[j].getName() == d.getName()){ try { pom[j].setSelected(true); } catch (PropertyVetoException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; } } break; } } } }
gpl-3.0
esloho/coursera-algorithmsI
PercolationAssignment/Percolation/test/PercolationTest.java
1762
import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author esloho * */ public class PercolationTest { private static final int SIZE = 5; private Percolation percolation; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * Test method for {@link Percolation#Percolation(int)}. */ @Test public void testConstructorNotNull() { percolation = new Percolation(SIZE); Assert.assertNotNull(percolation); } @Test public void testConstructorClosed() { percolation = new Percolation(SIZE); for (int i = 1; i < SIZE; i++) { for (int j = 1; j < SIZE; j++) { Assert.assertFalse(percolation.isOpen(i, j)); } } } /** * Test method for {@link Percolation#open(int, int)}. */ @Test public void testOpen() { Assert.fail("Not yet implemented"); } /** * Test method for {@link Percolation#isOpen(int, int)}. */ @Test public void testIsOpen() { percolation = new Percolation(SIZE); Assert.assertFalse(percolation.isOpen(SIZE, SIZE)); percolation.open(SIZE, SIZE); Assert.assertTrue(percolation.isOpen(SIZE, SIZE)); percolation.open(SIZE, SIZE); Assert.assertTrue(percolation.isOpen(SIZE, SIZE)); } /** * Test method for {@link Percolation#isFull(int, int)}. */ @Test public void testIsFull() { Assert.fail("Not yet implemented"); } /** * Test method for {@link Percolation#percolates()}. */ @Test public void testPercolates() { Assert.fail("Not yet implemented"); } }
gpl-3.0
saurabhsjoshi/VITacademics-for-Android
app/src/main/java/com/karthikb351/vitinfo2/customwidget/TimeLineView.java
6833
/* * VITacademics * Copyright (C) 2015 Aneesh Neelam <neelam.aneesh@gmail.com> * Copyright (C) 2015 Saurabh Joshi <saurabhjoshi94@outlook.com> * Copyright (C) 2015 Gaurav Agerwala <gauravagerwala@gmail.com> * Copyright (C) 2015 Karthik Balakrishnan <karthikb351@gmail.com> * Copyright (C) 2015 Pulkit Juneja <pulkit.16296@gmail.com> * Copyright (C) 2015 Hemant Jain <hemanham@gmail.com> * Copyright (C) 2015 Darshan Mehta <darshanmehta17@gmail.com> * * This file is part of VITacademics. * * VITacademics 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. * * VITacademics 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 VITacademics. If not, see <http://www.gnu.org/licenses/>. */ package com.karthikb351.vitinfo2.customwidget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.View; import com.karthikb351.vitinfo2.R; public class TimeLineView extends View { public static final int STATE_FINISHED = 0X01; public static final int STATE_CURRENT = 0X02; public static final int STATE_SCHEDULED = 0X03; public static final int TYPE_INITIAL = 0x04; public static final int TYPE_INNER = 0x05; public static final int TYPE_END = 0x06; private float PADDING_TOP = 12; private float CIRCLE_RADIUS = 6; private float BORDER_THICKNESS = 4; private float STROKE_WIDTH_RING = 3.33f; private float STROKE_WIDTH_BORDER = 10; private float STROKE_WIDTH_LINE = 2; private int widgetState; private int widgetType; private Paint paintRing; private Paint paintDot; private Paint paintBorder; private Paint paintLine; private float cx; private float cy; private float height; private float width; private float density; private RectF rectF; private Path mPath; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); width = getWidth(); height = getHeight(); cx = width / 2; cy = PADDING_TOP + CIRCLE_RADIUS; switch (widgetState){ case STATE_CURRENT: rectF.set(cx - BORDER_THICKNESS, cy - BORDER_THICKNESS, cx + BORDER_THICKNESS, cy + BORDER_THICKNESS); mPath.reset(); for (int i = 0; i <= 360; i++) { mPath.addArc(rectF, i, 1); } canvas.drawPath(mPath, paintBorder); case STATE_SCHEDULED: rectF.set(cx - CIRCLE_RADIUS, cy - CIRCLE_RADIUS, cx + CIRCLE_RADIUS, cy + CIRCLE_RADIUS); mPath.reset(); for (int i = 0; i <= 360; i += 1) { mPath.addArc(rectF, i, 1); } canvas.drawPath(mPath, paintRing); break; case STATE_FINISHED: canvas.drawCircle(cx, cy, CIRCLE_RADIUS, paintDot); break; } switch (widgetType){ case TYPE_INITIAL: canvas.drawLine(cx, cy + (11 * density), cx, height, paintLine); break; case TYPE_INNER: canvas.drawLine(cx, cy - (11 * density), cx, 0, paintLine); canvas.drawLine(cx, cy + (11 * density), cx, height, paintLine); break; case TYPE_END: canvas.drawLine(cx, cy - (11 * density), cx, 0, paintLine); break; } } private void initialize(){ density = getContext().getResources().getDisplayMetrics().density; PADDING_TOP *= density; BORDER_THICKNESS += CIRCLE_RADIUS; BORDER_THICKNESS *= density; CIRCLE_RADIUS *= density; STROKE_WIDTH_RING *= density; STROKE_WIDTH_BORDER *= density; STROKE_WIDTH_LINE *= density; paintDot = new Paint(); paintDot.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary)); paintDot.setFlags(Paint.ANTI_ALIAS_FLAG); paintRing = new Paint(); paintRing.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary)); paintRing.setFlags(Paint.ANTI_ALIAS_FLAG); paintRing.setStrokeWidth(STROKE_WIDTH_RING); paintRing.setStyle(Paint.Style.FILL_AND_STROKE); paintBorder = new Paint(); paintBorder.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary)); paintBorder.setAlpha(90); paintBorder.setFlags(Paint.ANTI_ALIAS_FLAG); paintBorder.setStrokeWidth(STROKE_WIDTH_BORDER); paintBorder.setStyle(Paint.Style.FILL_AND_STROKE); paintLine = new Paint(); paintLine.setColor(ContextCompat.getColor(getContext(), R.color.text_secondary)); paintLine.setAlpha(70); paintLine.setFlags(Paint.ANTI_ALIAS_FLAG); paintLine.setStrokeWidth(STROKE_WIDTH_LINE); paintLine.setStyle(Paint.Style.FILL_AND_STROKE); widgetState = STATE_SCHEDULED; widgetType = TYPE_INNER; rectF = new RectF(); mPath = new Path(); } public void setState(int state){ switch (state){ case STATE_CURRENT: widgetState = STATE_CURRENT; break; case STATE_SCHEDULED: widgetState = STATE_SCHEDULED; break; case STATE_FINISHED: widgetState = STATE_FINISHED; break; default: break; } invalidate(); } public void setType(int type){ switch (type){ case TYPE_INITIAL: widgetType = TYPE_INITIAL; break; case TYPE_INNER: widgetType = TYPE_INNER; break; case TYPE_END: widgetType = TYPE_END; break; default: break; } invalidate(); } public TimeLineView(Context context) { super(context); initialize(); } public TimeLineView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } }
gpl-3.0
kriztan/Pix-Art-Messenger
src/main/java/eu/siacs/conversations/xmpp/forms/Data.java
3497
package eu.siacs.conversations.xmpp.forms; import android.os.Bundle; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import eu.siacs.conversations.utils.Namespace; import eu.siacs.conversations.xml.Element; public class Data extends Element { public static final String FORM_TYPE = "FORM_TYPE"; public Data() { super("x"); this.setAttribute("xmlns", Namespace.DATA); } public List<Field> getFields() { ArrayList<Field> fields = new ArrayList<Field>(); for (Element child : getChildren()) { if (child.getName().equals("field") && !FORM_TYPE.equals(child.getAttribute("var"))) { fields.add(Field.parse(child)); } } return fields; } public Field getFieldByName(String needle) { for (Element child : getChildren()) { if (child.getName().equals("field") && needle.equals(child.getAttribute("var"))) { return Field.parse(child); } } return null; } public Field put(String name, String value) { Field field = getFieldByName(name); if (field == null) { field = new Field(name); this.addChild(field); } field.setValue(value); return field; } public void put(String name, Collection<String> values) { Field field = getFieldByName(name); if (field == null) { field = new Field(name); this.addChild(field); } field.setValues(values); } public void submit(Bundle options) { for (Field field : getFields()) { if (options.containsKey(field.getFieldName())) { field.setValue(options.getString(field.getFieldName())); } } submit(); } public void submit() { this.setAttribute("type", "submit"); removeUnnecessaryChildren(); for (Field field : getFields()) { field.removeNonValueChildren(); } } private void removeUnnecessaryChildren() { for (Iterator<Element> iterator = this.children.iterator(); iterator.hasNext(); ) { Element element = iterator.next(); if (!element.getName().equals("field") && !element.getName().equals("title")) { iterator.remove(); } } } public static Data parse(Element element) { Data data = new Data(); data.setAttributes(element.getAttributes()); data.setChildren(element.getChildren()); return data; } public void setFormType(String formType) { Field field = this.put(FORM_TYPE, formType); field.setAttribute("type", "hidden"); } public String getFormType() { String type = getValue(FORM_TYPE); return type == null ? "" : type; } public String getValue(String name) { Field field = this.getFieldByName(name); return field == null ? null : field.getValue(); } public String getTitle() { return findChildContent("title"); } public static Data create(String type, Bundle bundle) { Data data = new Data(); data.setFormType(type); data.setAttribute("type", "submit"); for (String key : bundle.keySet()) { data.put(key, bundle.getString(key)); } return data; } }
gpl-3.0
wizjany/craftbook
src/main/java/com/sk89q/craftbook/bukkit/CircuitCore.java
41280
package com.sk89q.craftbook.bukkit; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import com.sk89q.craftbook.LocalComponent; import com.sk89q.craftbook.Mechanic; import com.sk89q.craftbook.MechanicFactory; import com.sk89q.craftbook.MechanicManager; import com.sk89q.craftbook.bukkit.commands.CircuitCommands; import com.sk89q.craftbook.circuits.GlowStone; import com.sk89q.craftbook.circuits.JackOLantern; import com.sk89q.craftbook.circuits.Netherrack; import com.sk89q.craftbook.circuits.Pipes; import com.sk89q.craftbook.circuits.gates.logic.AndGate; import com.sk89q.craftbook.circuits.gates.logic.Clock; import com.sk89q.craftbook.circuits.gates.logic.ClockDivider; import com.sk89q.craftbook.circuits.gates.logic.ClockST; import com.sk89q.craftbook.circuits.gates.logic.CombinationLock; import com.sk89q.craftbook.circuits.gates.logic.Counter; import com.sk89q.craftbook.circuits.gates.logic.DeMultiplexer; import com.sk89q.craftbook.circuits.gates.logic.Delayer; import com.sk89q.craftbook.circuits.gates.logic.Dispatcher; import com.sk89q.craftbook.circuits.gates.logic.DownCounter; import com.sk89q.craftbook.circuits.gates.logic.EdgeTriggerDFlipFlop; import com.sk89q.craftbook.circuits.gates.logic.FullAdder; import com.sk89q.craftbook.circuits.gates.logic.FullSubtractor; import com.sk89q.craftbook.circuits.gates.logic.HalfAdder; import com.sk89q.craftbook.circuits.gates.logic.HalfSubtractor; import com.sk89q.craftbook.circuits.gates.logic.InvertedRsNandLatch; import com.sk89q.craftbook.circuits.gates.logic.Inverter; import com.sk89q.craftbook.circuits.gates.logic.JkFlipFlop; import com.sk89q.craftbook.circuits.gates.logic.LevelTriggeredDFlipFlop; import com.sk89q.craftbook.circuits.gates.logic.LowDelayer; import com.sk89q.craftbook.circuits.gates.logic.LowNotPulser; import com.sk89q.craftbook.circuits.gates.logic.LowPulser; import com.sk89q.craftbook.circuits.gates.logic.Marquee; import com.sk89q.craftbook.circuits.gates.logic.MemoryAccess; import com.sk89q.craftbook.circuits.gates.logic.MemorySetter; import com.sk89q.craftbook.circuits.gates.logic.Monostable; import com.sk89q.craftbook.circuits.gates.logic.Multiplexer; import com.sk89q.craftbook.circuits.gates.logic.NandGate; import com.sk89q.craftbook.circuits.gates.logic.NotDelayer; import com.sk89q.craftbook.circuits.gates.logic.NotLowDelayer; import com.sk89q.craftbook.circuits.gates.logic.NotPulser; import com.sk89q.craftbook.circuits.gates.logic.Pulser; import com.sk89q.craftbook.circuits.gates.logic.Random3Bit; import com.sk89q.craftbook.circuits.gates.logic.Random5Bit; import com.sk89q.craftbook.circuits.gates.logic.RandomBit; import com.sk89q.craftbook.circuits.gates.logic.RandomBitST; import com.sk89q.craftbook.circuits.gates.logic.RangedOutput; import com.sk89q.craftbook.circuits.gates.logic.Repeater; import com.sk89q.craftbook.circuits.gates.logic.RsNandLatch; import com.sk89q.craftbook.circuits.gates.logic.RsNorFlipFlop; import com.sk89q.craftbook.circuits.gates.logic.ToggleFlipFlop; import com.sk89q.craftbook.circuits.gates.logic.XnorGate; import com.sk89q.craftbook.circuits.gates.logic.XorGate; import com.sk89q.craftbook.circuits.gates.world.blocks.BlockBreaker; import com.sk89q.craftbook.circuits.gates.world.blocks.BlockBreakerST; import com.sk89q.craftbook.circuits.gates.world.blocks.BlockLauncher; import com.sk89q.craftbook.circuits.gates.world.blocks.BonemealTerraformer; import com.sk89q.craftbook.circuits.gates.world.blocks.BonemealTerraformerST; import com.sk89q.craftbook.circuits.gates.world.blocks.CombineHarvester; import com.sk89q.craftbook.circuits.gates.world.blocks.CombineHarvesterST; import com.sk89q.craftbook.circuits.gates.world.blocks.Cultivator; import com.sk89q.craftbook.circuits.gates.world.blocks.CultivatorST; import com.sk89q.craftbook.circuits.gates.world.blocks.FlexibleSetBlock; import com.sk89q.craftbook.circuits.gates.world.blocks.Irrigator; import com.sk89q.craftbook.circuits.gates.world.blocks.IrrigatorST; import com.sk89q.craftbook.circuits.gates.world.blocks.LiquidFlood; import com.sk89q.craftbook.circuits.gates.world.blocks.LiquidFloodST; import com.sk89q.craftbook.circuits.gates.world.blocks.MultipleSetBlock; import com.sk89q.craftbook.circuits.gates.world.blocks.Planter; import com.sk89q.craftbook.circuits.gates.world.blocks.PlanterST; import com.sk89q.craftbook.circuits.gates.world.blocks.Pump; import com.sk89q.craftbook.circuits.gates.world.blocks.PumpST; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAbove; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveChest; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveChestST; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockAboveST; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelow; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowChest; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowChestST; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBlockBelowST; import com.sk89q.craftbook.circuits.gates.world.blocks.SetBridge; import com.sk89q.craftbook.circuits.gates.world.blocks.SetDoor; import com.sk89q.craftbook.circuits.gates.world.blocks.Spigot; import com.sk89q.craftbook.circuits.gates.world.entity.AdvancedEntitySpawner; import com.sk89q.craftbook.circuits.gates.world.entity.AnimalHarvester; import com.sk89q.craftbook.circuits.gates.world.entity.AnimalHarvesterST; import com.sk89q.craftbook.circuits.gates.world.entity.CreatureSpawner; import com.sk89q.craftbook.circuits.gates.world.entity.EntityCannon; import com.sk89q.craftbook.circuits.gates.world.entity.EntityCannonST; import com.sk89q.craftbook.circuits.gates.world.entity.EntityTrap; import com.sk89q.craftbook.circuits.gates.world.entity.EntityTrapST; import com.sk89q.craftbook.circuits.gates.world.entity.TeleportReciever; import com.sk89q.craftbook.circuits.gates.world.entity.TeleportRecieverST; import com.sk89q.craftbook.circuits.gates.world.entity.TeleportTransmitter; import com.sk89q.craftbook.circuits.gates.world.items.AutomaticCrafter; import com.sk89q.craftbook.circuits.gates.world.items.AutomaticCrafterST; import com.sk89q.craftbook.circuits.gates.world.items.ChestStocker; import com.sk89q.craftbook.circuits.gates.world.items.ChestStockerST; import com.sk89q.craftbook.circuits.gates.world.items.ContainerCollector; import com.sk89q.craftbook.circuits.gates.world.items.ContainerCollectorST; import com.sk89q.craftbook.circuits.gates.world.items.ContainerDispenser; import com.sk89q.craftbook.circuits.gates.world.items.ContainerDispenserST; import com.sk89q.craftbook.circuits.gates.world.items.ContainerStacker; import com.sk89q.craftbook.circuits.gates.world.items.ContainerStackerST; import com.sk89q.craftbook.circuits.gates.world.items.Distributer; import com.sk89q.craftbook.circuits.gates.world.items.DistributerST; import com.sk89q.craftbook.circuits.gates.world.items.ItemDispenser; import com.sk89q.craftbook.circuits.gates.world.items.ItemFan; import com.sk89q.craftbook.circuits.gates.world.items.ItemFanST; import com.sk89q.craftbook.circuits.gates.world.items.Sorter; import com.sk89q.craftbook.circuits.gates.world.items.SorterST; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ArrowBarrage; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ArrowShooter; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FireBarrage; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FireShooter; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.FlameThrower; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Jukebox; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.LightningSummon; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Melody; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.MessageSender; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ParticleEffect; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ParticleEffectST; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.PotionInducer; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.PotionInducerST; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.ProgrammableFireworkShow; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.RadioPlayer; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.RadioStation; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.SoundEffect; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.TimedExplosion; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.Tune; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessReceiver; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessReceiverST; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.WirelessTransmitter; import com.sk89q.craftbook.circuits.gates.world.miscellaneous.XPSpawner; import com.sk89q.craftbook.circuits.gates.world.sensors.BlockSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.BlockSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.ContentsSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.ContentsSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.DaySensor; import com.sk89q.craftbook.circuits.gates.world.sensors.DaySensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.EntitySensor; import com.sk89q.craftbook.circuits.gates.world.sensors.EntitySensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.ItemNotSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.ItemNotSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.ItemSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.ItemSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.LavaSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.LavaSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.LightSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.LightSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.PlayerSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.PlayerSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.PowerSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.PowerSensorST; import com.sk89q.craftbook.circuits.gates.world.sensors.WaterSensor; import com.sk89q.craftbook.circuits.gates.world.sensors.WaterSensorST; import com.sk89q.craftbook.circuits.gates.world.weather.RainSensor; import com.sk89q.craftbook.circuits.gates.world.weather.RainSensorST; import com.sk89q.craftbook.circuits.gates.world.weather.ServerTimeModulus; import com.sk89q.craftbook.circuits.gates.world.weather.TStormSensor; import com.sk89q.craftbook.circuits.gates.world.weather.TStormSensorST; import com.sk89q.craftbook.circuits.gates.world.weather.TimeControl; import com.sk89q.craftbook.circuits.gates.world.weather.TimeControlAdvanced; import com.sk89q.craftbook.circuits.gates.world.weather.TimeFaker; import com.sk89q.craftbook.circuits.gates.world.weather.TimeSet; import com.sk89q.craftbook.circuits.gates.world.weather.TimeSetST; import com.sk89q.craftbook.circuits.gates.world.weather.WeatherControl; import com.sk89q.craftbook.circuits.gates.world.weather.WeatherControlAdvanced; import com.sk89q.craftbook.circuits.gates.world.weather.WeatherFaker; import com.sk89q.craftbook.circuits.ic.IC; import com.sk89q.craftbook.circuits.ic.ICFactory; import com.sk89q.craftbook.circuits.ic.ICFamily; import com.sk89q.craftbook.circuits.ic.ICManager; import com.sk89q.craftbook.circuits.ic.ICMechanicFactory; import com.sk89q.craftbook.circuits.ic.RegisteredICFactory; import com.sk89q.craftbook.circuits.ic.RestrictedIC; import com.sk89q.craftbook.circuits.ic.SelfTriggeredIC; import com.sk89q.craftbook.circuits.ic.families.Family3I3O; import com.sk89q.craftbook.circuits.ic.families.Family3ISO; import com.sk89q.craftbook.circuits.ic.families.FamilyAISO; import com.sk89q.craftbook.circuits.ic.families.FamilySI3O; import com.sk89q.craftbook.circuits.ic.families.FamilySI5O; import com.sk89q.craftbook.circuits.ic.families.FamilySISO; import com.sk89q.craftbook.circuits.ic.families.FamilyVIVO; import com.sk89q.craftbook.circuits.plc.PlcFactory; import com.sk89q.craftbook.circuits.plc.lang.Perlstone; import com.sk89q.craftbook.util.config.YAMLICConfiguration; import com.sk89q.util.yaml.YAMLFormat; import com.sk89q.util.yaml.YAMLProcessor; /** * Author: Turtle9598 */ public class CircuitCore implements LocalComponent { private static CircuitCore instance; private CraftBookPlugin plugin = CraftBookPlugin.inst(); private MechanicManager manager; private ICManager icManager; private YAMLICConfiguration icConfiguration; private ICMechanicFactory ICFactory; private Pipes.Factory pipeFactory; private File romFolder; private File midiFolder; private File fireworkFolder; public static final ICFamily FAMILY_SISO = new FamilySISO(); public static final ICFamily FAMILY_3ISO = new Family3ISO(); public static final ICFamily FAMILY_SI3O = new FamilySI3O(); public static final ICFamily FAMILY_AISO = new FamilyAISO(); public static final ICFamily FAMILY_3I3O = new Family3I3O(); public static final ICFamily FAMILY_VIVO = new FamilyVIVO(); public static final ICFamily FAMILY_SI5O = new FamilySI5O(); public static boolean isEnabled() { return instance != null; } public CircuitCore() { instance = this; } public static CircuitCore inst() { return instance; } @Override public void enable() { plugin.registerCommands(CircuitCommands.class); plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "ic-config.yml"), "ic-config.yml", false); icConfiguration = new YAMLICConfiguration(new YAMLProcessor(new File(plugin.getDataFolder(), "ic-config.yml"), true, YAMLFormat.EXTENDED), plugin.getLogger()); manager = new MechanicManager(); plugin.registerManager(manager, true, true, true, false); midiFolder = new File(plugin.getDataFolder(), "midi/"); new File(getMidiFolder(), "playlists").mkdirs(); romFolder = new File(plugin.getDataFolder(), "rom/"); fireworkFolder = new File(plugin.getDataFolder(), "fireworks/"); getFireworkFolder(); registerMechanics(); try { icConfiguration.load(); } catch (Throwable e) { e.printStackTrace(); } } @Override public void disable() { unregisterAllMechanics(); ICManager.emptyCache(); icConfiguration.unload(); } public File getFireworkFolder() { if (!fireworkFolder.exists()) fireworkFolder.mkdir(); return fireworkFolder; } public File getRomFolder() { if (!romFolder.exists()) romFolder.mkdir(); return romFolder; } public File getMidiFolder() { if (!midiFolder.exists()) midiFolder.mkdir(); return midiFolder; } public ICMechanicFactory getICFactory() { return ICFactory; } public Pipes.Factory getPipeFactory() { return pipeFactory; } private void registerMechanics() { BukkitConfiguration config = CraftBookPlugin.inst().getConfiguration(); if (config.ICEnabled) { registerICs(); registerMechanic(ICFactory = new ICMechanicFactory(getIcManager())); } // Let's register mechanics! if (config.netherrackEnabled) registerMechanic(new Netherrack.Factory()); if (config.pumpkinsEnabled) registerMechanic(new JackOLantern.Factory()); if (config.glowstoneEnabled) registerMechanic(new GlowStone.Factory()); if (config.pipesEnabled) registerMechanic(pipeFactory = new Pipes.Factory()); } private void registerICs() { Server server = plugin.getServer(); // Let's register ICs! icManager = new ICManager(); ICFamily familySISO = FAMILY_SISO; ICFamily family3ISO = FAMILY_3ISO; ICFamily familySI3O = FAMILY_SI3O; ICFamily familyAISO = FAMILY_AISO; ICFamily family3I3O = FAMILY_3I3O; ICFamily familyVIVO = FAMILY_VIVO; ICFamily familySI5O = FAMILY_SI5O; // SISOs registerIC("MC1000", "repeater", new Repeater.Factory(server), familySISO, familyAISO); registerIC("MC1001", "inverter", new Inverter.Factory(server), familySISO, familyAISO); registerIC("MC1017", "re t flip", new ToggleFlipFlop.Factory(server, true), familySISO, familyAISO); registerIC("MC1018", "fe t flip", new ToggleFlipFlop.Factory(server, false), familySISO, familyAISO); registerIC("MC1020", "random bit", new RandomBit.Factory(server), familySISO, familyAISO); registerIC("MC1025", "server time", new ServerTimeModulus.Factory(server), familySISO, familyAISO); registerIC("MC1110", "transmitter", new WirelessTransmitter.Factory(server), familySISO, familyAISO); registerIC("MC1111", "receiver", new WirelessReceiver.Factory(server), familySISO, familyAISO); registerIC("MC1112", "tele-out", new TeleportTransmitter.Factory(server), familySISO, familyAISO); registerIC("MC1113", "tele-in", new TeleportReciever.Factory(server), familySISO, familyAISO); registerIC("MC1200", "spawner", new CreatureSpawner.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1201", "dispenser", new ItemDispenser.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1202", "c dispense", new ContainerDispenser.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1203", "strike", new LightningSummon.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1204", "trap", new EntityTrap.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1205", "set above", new SetBlockAbove.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1206", "set below", new SetBlockBelow.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1207", "flex set", new FlexibleSetBlock.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1208", "mult set", new MultipleSetBlock.Factory(server), familySISO, familyAISO); registerIC("MC1209", "collector", new ContainerCollector.Factory(server), familySISO, familyAISO); registerIC("MC1210", "emitter", new ParticleEffect.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1211", "set bridge", new SetBridge.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1212", "set door", new SetDoor.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1213", "sound", new SoundEffect.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1215", "set a chest", new SetBlockAboveChest.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1216", "set b chest", new SetBlockBelowChest.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1217", "pot induce", new PotionInducer.Factory(server), familySISO, familyAISO); registerIC("MC1218", "block launch", new BlockLauncher.Factory(server), familySISO, familyAISO); registerIC("MC1219", "auto craft", new AutomaticCrafter.Factory(server), familySISO, familyAISO); registerIC("MC1220", "a b break", new BlockBreaker.Factory(server, false), familySISO, familyAISO); registerIC("MC1221", "b b break", new BlockBreaker.Factory(server, true), familySISO, familyAISO); registerIC("MC1222", "liquid flood", new LiquidFlood.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1223", "terraform", new BonemealTerraformer.Factory(server), familySISO, familyAISO); registerIC("MC1224", "time bomb", new TimedExplosion.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1225", "pump", new Pump.Factory(server), familySISO, familyAISO); registerIC("MC1226", "spigot", new Spigot.Factory(server), familySISO, familyAISO); registerIC("MC1227", "avd spawner", new AdvancedEntitySpawner.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1228", "ent cannon", new EntityCannon.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1229", "sorter", new Sorter.Factory(server), familySISO, familyAISO); registerIC("MC1230", "sense day", new DaySensor.Factory(server), familySISO, familyAISO); registerIC("MC1231", "t control", new TimeControl.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1232", "time set", new TimeSet.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1233", "item fan", new ItemFan.Factory(server), familySISO, familyAISO); registerIC("MC1234", "planter", new Planter.Factory(server), familySISO, familyAISO); registerIC("MC1235", "cultivator", new Cultivator.Factory(server), familySISO, familyAISO); registerIC("MC1236", "fake weather", new WeatherFaker.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1237", "fake time", new TimeFaker.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1238", "irrigate", new Irrigator.Factory(server), familySISO, familyAISO); registerIC("MC1239", "harvester", new CombineHarvester.Factory(server), familySISO, familyAISO); registerIC("MC1240", "shoot arrow", new ArrowShooter.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1241", "shoot arrows", new ArrowBarrage.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1242", "stocker", new ChestStocker.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1243", "distributer", new Distributer.Factory(server), familySISO, familyAISO); registerIC("MC1244", "animal harvest", new AnimalHarvester.Factory(server), familySISO, familyAISO); registerIC("MC1245", "cont stacker", new ContainerStacker.Factory(server), familySISO, familyAISO); registerIC("MC1246", "xp spawner", new XPSpawner.Factory(server), familySISO, familyAISO); //Restricted //TODO Dyed Armour Spawner (MC1247) (Sign Title: DYE ARMOUR) registerIC("MC1250", "shoot fire", new FireShooter.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1251", "shoot fires", new FireBarrage.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1252", "flame thower", new FlameThrower.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1253", "firework show", new ProgrammableFireworkShow.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1260", "sense water", new WaterSensor.Factory(server), familySISO, familyAISO); registerIC("MC1261", "sense lava", new LavaSensor.Factory(server), familySISO, familyAISO); registerIC("MC1262", "sense light", new LightSensor.Factory(server), familySISO, familyAISO); registerIC("MC1263", "sense block", new BlockSensor.Factory(server), familySISO, familyAISO); registerIC("MC1264", "sense item", new ItemSensor.Factory(server), familySISO, familyAISO); registerIC("MC1265", "inv sense item", new ItemNotSensor.Factory(server), familySISO, familyAISO); registerIC("MC1266", "sense power", new PowerSensor.Factory(server), familySISO, familyAISO); //FIXME registerIC("MC1267", "sense move", new MovementSensor.Factory(server), familySISO, familyAISO); registerIC("MC1268", "sense contents", new ContentsSensor.Factory(server), familySISO, familyAISO); registerIC("MC1270", "melody", new Melody.Factory(server), familySISO, familyAISO); registerIC("MC1271", "sense entity", new EntitySensor.Factory(server), familySISO, familyAISO); registerIC("MC1272", "sense player", new PlayerSensor.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC1273", "jukebox", new Jukebox.Factory(server), familySISO, familyAISO); registerIC("MC1275", "tune", new Tune.Factory(server), familySISO, familyAISO); registerIC("MC1276", "radio station", new RadioStation.Factory(server), familySISO, familyAISO); registerIC("MC1277", "radio player", new RadioPlayer.Factory(server), familySISO, familyAISO); registerIC("MC1420", "divide clock", new ClockDivider.Factory(server), familySISO, familyAISO); registerIC("MC1421", "clock", new Clock.Factory(server), familySISO, familyAISO); registerIC("MC1510", "send message", new MessageSender.Factory(server), familySISO, familyAISO); registerIC("MC2100", "delayer", new Delayer.Factory(server), familySISO, familyAISO); registerIC("MC2101", "inv delayer", new NotDelayer.Factory(server), familySISO, familyAISO); registerIC("MC2110", "fe delayer", new LowDelayer.Factory(server), familySISO, familyAISO); registerIC("MC2111", "inv fe delayer", new NotLowDelayer.Factory(server), familySISO, familyAISO); registerIC("MC2500", "pulser", new Pulser.Factory(server), familySISO, familyAISO); registerIC("MC2501", "inv pulser", new NotPulser.Factory(server), familySISO, familyAISO); registerIC("MC2510", "fe pulser", new LowPulser.Factory(server), familySISO, familyAISO); registerIC("MC2511", "inv fe pulser", new LowNotPulser.Factory(server), familySISO, familyAISO); // SI3Os registerIC("MC2020", "random 3", new Random3Bit.Factory(server), familySI3O); registerIC("MC2999", "marquee", new Marquee.Factory(server), familySI3O); // 3ISOs registerIC("MC3002", "and", new AndGate.Factory(server), family3ISO); registerIC("MC3003", "nand", new NandGate.Factory(server), family3ISO); registerIC("MC3020", "xor", new XorGate.Factory(server), family3ISO); registerIC("MC3021", "xnor", new XnorGate.Factory(server), family3ISO); registerIC("MC3030", "nor flip", new RsNorFlipFlop.Factory(server), family3ISO); registerIC("MC3031", "inv nand latch", new InvertedRsNandLatch.Factory(server), family3ISO); registerIC("MC3032", "jk flip", new JkFlipFlop.Factory(server), family3ISO); registerIC("MC3033", "nand latch", new RsNandLatch.Factory(server), family3ISO); registerIC("MC3034", "edge df flip", new EdgeTriggerDFlipFlop.Factory(server), family3ISO); registerIC("MC3036", "level df flip", new LevelTriggeredDFlipFlop.Factory(server), family3ISO); registerIC("MC3040", "multiplexer", new Multiplexer.Factory(server), family3ISO); registerIC("MC3050", "combo", new CombinationLock.Factory(server), family3ISO); registerIC("MC3101", "down counter", new DownCounter.Factory(server), family3ISO); registerIC("MC3102", "counter", new Counter.Factory(server), family3ISO); registerIC("MC3231", "t control adva", new TimeControlAdvanced.Factory(server), family3ISO); // Restricted registerIC("MC3300", "ROM set", new MemorySetter.Factory(server), family3ISO); // Restricted registerIC("MC3301", "ROM get", new MemoryAccess.Factory(server), familySI3O); // Restricted // 3I3Os registerIC("MC4000", "full adder", new FullAdder.Factory(server), family3I3O); registerIC("MC4010", "half adder", new HalfAdder.Factory(server), family3I3O); registerIC("MC4040", "demultiplexer", new DeMultiplexer.Factory(server), family3I3O); registerIC("MC4100", "full subtr", new FullSubtractor.Factory(server), family3I3O); registerIC("MC4110", "half subtr", new HalfSubtractor.Factory(server), family3I3O); registerIC("MC4200", "dispatcher", new Dispatcher.Factory(server), family3I3O); // SI5O's registerIC("MC6020", "random 5", new Random5Bit.Factory(server), familySI5O); // PLCs registerIC("MC5000", "perlstone", PlcFactory.fromLang(server, new Perlstone(), false), familyVIVO); registerIC("MC5001", "perlstone 3i3o", PlcFactory.fromLang(server, new Perlstone(), false), family3I3O); // Self triggered registerIC("MC0020", "random 1 st", new RandomBitST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0111", "receiver st", new WirelessReceiverST.Factory(server), familySISO, familyAISO); registerIC("MC0113", "tele-in st", new TeleportRecieverST.Factory(server), familySISO, familyAISO); registerIC("MC0202", "c dispense st", new ContainerDispenserST.Factory(server), familySISO, familyAISO); registerIC("MC0204", "trap st", new EntityTrapST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0205", "set above st", new SetBlockAboveST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0206", "set below st", new SetBlockBelowST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0209", "collector st", new ContainerCollectorST.Factory(server), familySISO, familyAISO); registerIC("MC0210", "emitter st", new ParticleEffectST.Factory(server), familySISO, familyAISO); registerIC("MC0215", "set a chest st", new SetBlockAboveChestST.Factory(server), familySISO, familyAISO); registerIC("MC0216", "set b chest st", new SetBlockBelowChestST.Factory(server), familySISO, familyAISO); registerIC("MC0217", "pot induce st", new PotionInducerST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0219", "auto craft st", new AutomaticCrafterST.Factory(server), familySISO, familyAISO); registerIC("MC0220", "a bl break st", new BlockBreakerST.Factory(server, false), familySISO, familyAISO); registerIC("MC0221", "b bl break st", new BlockBreakerST.Factory(server, true), familySISO, familyAISO); registerIC("MC0222", "liq flood st", new LiquidFloodST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0223", "terraform st", new BonemealTerraformerST.Factory(server), familySISO, familyAISO); registerIC("MC0225", "pump st", new PumpST.Factory(server), familySISO, familyAISO); registerIC("MC0228", "ent cannon st", new EntityCannonST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0229", "sorter st", new SorterST.Factory(server), familySISO, familyAISO); registerIC("MC0230", "sense day st", new DaySensorST.Factory(server), familySISO, familyAISO); registerIC("MC0232", "time set st", new TimeSetST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0233", "item fan st", new ItemFanST.Factory(server), familySISO, familyAISO); registerIC("MC0234", "planter st", new PlanterST.Factory(server), familySISO, familyAISO); registerIC("MC0235", "cultivator st", new CultivatorST.Factory(server), familySISO, familyAISO); registerIC("MC0238", "irrigate st", new IrrigatorST.Factory(server), familySISO, familyAISO); registerIC("MC0239", "harvester st", new CombineHarvesterST.Factory(server), familySISO, familyAISO); registerIC("MC0242", "stocker st", new ChestStockerST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0243", "distributer st", new DistributerST.Factory(server), familySISO, familyAISO); registerIC("MC0244", "animal harvest st", new AnimalHarvesterST.Factory(server), familySISO, familyAISO); registerIC("MC0245", "cont stacker st", new ContainerStackerST.Factory(server), familySISO, familyAISO); registerIC("MC0260", "sense water st", new WaterSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0261", "sense lava st", new LavaSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0262", "sense light st", new LightSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0263", "sense block st", new BlockSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0264", "sense item st", new ItemSensorST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0265", "sense n item s", new ItemNotSensorST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0266", "sense power st", new PowerSensorST.Factory(server), familySISO, familyAISO); // Restricted //FIXME registerIC("MC0267", "sense move st", new MovementSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0268", "sense contents st", new ContentsSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0270", "sense power st", new PowerSensorST.Factory(server), familySISO, familyAISO); registerIC("MC0271", "sense entit st", new EntitySensorST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0272", "sense playe st", new PlayerSensorST.Factory(server), familySISO, familyAISO); // Restricted registerIC("MC0420", "clock st", new ClockST.Factory(server), familySISO, familyAISO); registerIC("MC0421", "monostable", new Monostable.Factory(server), familySISO, familyAISO); registerIC("MC0500", "range output", new RangedOutput.Factory(server), familySISO, familyAISO); // Xtra ICs // SISOs registerIC("MCX230", "rain sense", new RainSensor.Factory(server), familySISO, familyAISO); registerIC("MCX231", "storm sense", new TStormSensor.Factory(server), familySISO, familyAISO); registerIC("MCX233", "weather set", new WeatherControl.Factory(server), familySISO, familyAISO); // 3ISOs registerIC("MCT233", "weather set ad", new WeatherControlAdvanced.Factory(server), family3ISO); // Self triggered registerIC("MCZ230", "rain sense st", new RainSensorST.Factory(server), familySISO, familyAISO); registerIC("MCZ231", "storm sense st", new TStormSensorST.Factory(server), familySISO, familyAISO); } /** * Register a mechanic if possible * * @param name * @param factory * @param families */ public boolean registerIC(String name, String longName, ICFactory factory, ICFamily... families) { if (CraftBookPlugin.inst().getConfiguration().disabledICs.contains(name)) return false; return getIcManager().register(name, longName, factory, families); } /** * Register a mechanic if possible * * @param factory */ public void registerMechanic(MechanicFactory<? extends Mechanic> factory) { manager.register(factory); } /** * Register a array of mechanics if possible * * @param factories */ protected void registerMechanic(MechanicFactory<? extends Mechanic>[] factories) { for (MechanicFactory<? extends Mechanic> aFactory : factories) { registerMechanic(aFactory); } } /** * Unregister a mechanic if possible TODO Ensure no remnants are left behind * * @param factory * * @return true if the mechanic was successfully unregistered. */ protected boolean unregisterMechanic(MechanicFactory<? extends Mechanic> factory) { return manager.unregister(factory); } protected boolean unregisterAllMechanics() { Iterator<MechanicFactory<? extends Mechanic>> iterator = manager.factories.iterator(); while (iterator.hasNext()) { iterator.next(); manager.unregister(iterator); } return true; } public List<RegisteredICFactory> getICList() { if(getIcManager() == null) return new ArrayList<RegisteredICFactory>(); List<RegisteredICFactory> ics = new ArrayList<RegisteredICFactory>(); for (Map.Entry<String, RegisteredICFactory> e : getIcManager().registered.entrySet()) { ics.add(e.getValue()); } return ics; } public String getSearchID(Player p, String search) { ArrayList<String> icNameList = new ArrayList<String>(); icNameList.addAll(getIcManager().registered.keySet()); Collections.sort(icNameList); for (String ic : icNameList) { try { RegisteredICFactory ric = getIcManager().registered.get(ic); IC tic = ric.getFactory().create(null); if (search != null && !tic.getTitle().toLowerCase().contains(search.toLowerCase()) && !ric.getId().toLowerCase().contains(search.toLowerCase())) continue; return ic; } catch (Exception ignored) { } } return ""; } /** * Used for the /ic list command. * * @param p * * @return */ public String[] generateICText(Player p, String search, char[] parameters) { ArrayList<String> icNameList = new ArrayList<String>(); icNameList.addAll(getIcManager().registered.keySet()); Collections.sort(icNameList); ArrayList<String> strings = new ArrayList<String>(); boolean col = true; for (String ic : icNameList) { try { thisIC: { RegisteredICFactory ric = getIcManager().registered.get(ic); IC tic = ric.getFactory().create(null); if (search != null && !tic.getTitle().toLowerCase().contains(search.toLowerCase()) && !ric.getId().toLowerCase().contains(search.toLowerCase())) continue; if (parameters != null) { for (char c : parameters) { if (c == 'r' && !(ric.getFactory() instanceof RestrictedIC)) break thisIC; else if (c == 's' && ric.getFactory() instanceof RestrictedIC) break thisIC; else if (c == 'b' && !ric.getFactory().getClass().getPackage().getName().endsWith("blocks")) break thisIC; else if (c == 'i' && !ric.getFactory().getClass().getPackage().getName().endsWith("items")) break thisIC; else if (c == 'e' && !ric.getFactory().getClass().getPackage().getName().endsWith("entity")) break thisIC; else if (c == 'w' && !ric.getFactory().getClass().getPackage().getName().endsWith ("weather")) break thisIC; else if (c == 'l' && !ric.getFactory().getClass().getPackage().getName().endsWith("logic")) break thisIC; else if (c == 'm' && !ric.getFactory().getClass().getPackage().getName().endsWith ("miscellaneous")) break thisIC; else if (c == 'c' && !ric.getFactory().getClass().getPackage().getName().endsWith ("sensors")) break thisIC; } } col = !col; ChatColor colour = col ? ChatColor.YELLOW : ChatColor.GOLD; if (!ICMechanicFactory.checkPermissionsBoolean(CraftBookPlugin.inst().wrapPlayer(p), ric.getFactory(), ic.toLowerCase())) { colour = col ? ChatColor.RED : ChatColor.DARK_RED; } strings.add(colour + tic.getTitle() + " (" + ric.getId() + ")" + ": " + (tic instanceof SelfTriggeredIC ? "ST " : "T ") + (ric.getFactory() instanceof RestrictedIC ? ChatColor.DARK_RED + "R " : "")); } } catch (Throwable e) { plugin.getLogger().warning("An error occurred generating the docs for IC: " + ic + "."); plugin.getLogger().warning("Please report this error on: http://youtrack.sk89q.com/."); } } return strings.toArray(new String[strings.size()]); } public ICManager getIcManager () { return icManager; } }
gpl-3.0
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/service/CadastroProdutoService.java
918
package com.github.marcelothebuilder.webpedidos.service; import java.io.Serializable; import javax.inject.Inject; import com.github.marcelothebuilder.webpedidos.model.produto.Produto; import com.github.marcelothebuilder.webpedidos.repository.Produtos; import com.github.marcelothebuilder.webpedidos.util.interceptor.Transactional; public class CadastroProdutoService implements Serializable { private static final long serialVersionUID = 1L; @Inject private Produtos produtos; @Transactional public Produto salvar(Produto produto) { Produto produtoExistente = produtos.porSku(produto.getSku()); // TODO: ao invés de validar este erro aqui, deixar que o database // retorne o erro de unique constraint violation if (produtoExistente != null && !produtoExistente.equals(produto)) { throw new NegocioException("Já existe um produto com o mesmo Sku"); } return produtos.guardar(produto); } }
gpl-3.0
Panzer1119/JAddOn
src/jaddon/jlog/SystemInputStream.java
1701
/* * 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 jaddon.jlog; import jaddon.controller.StaticStandard; import java.io.InputStream; import java.util.Scanner; /** * * @author Paul */ public class SystemInputStream { private InputStream inputstream = null; private Scanner scanner = null; private JLogger logger = null; private final Thread thread = new Thread(new Runnable() { @Override public void run() { try { while(scanner != null && scanner.hasNextLine()) { try { logger.sendCommand(scanner.nextLine()); } catch (Exception ex) { } } } catch (Exception ex) { } StaticStandard.log("SystemInputSteam closed"); } }); public SystemInputStream(InputStream inputstream, JLogger logger) { this.inputstream = inputstream; this.logger = logger; updateScanner(); } public void updateScanner() { try { stop(); scanner = new Scanner(inputstream); thread.start(); } catch (Exception ex) { StaticStandard.logErr("Error while updating scanner: " + ex, ex); } } public void stop() { while(thread.isAlive()) { try { thread.stop(); } catch (Exception ex) { } } } }
gpl-3.0
hneemann/Digital
src/main/java/de/neemann/digital/builder/ExpressionExporter.java
1278
/* * Copyright (c) 2016 Helmut Neemann * Use of this source code is governed by the GPL v3 license * that can be found in the LICENSE file. */ package de.neemann.digital.builder; import de.neemann.digital.builder.jedec.FuseMapFillerException; import java.io.IOException; import java.io.OutputStream; /** * Interface used to create Jedec files. * Every supported device implements this interface. * * @param <T> concrete type of {@link ExpressionExporter} */ public interface ExpressionExporter<T extends ExpressionExporter> { /** * @return builder to add expressions */ BuilderInterface getBuilder(); /** * Gets the pin mapping which is to use/was used. * You can modify the mapping before getBuilder is called. * After the export you will find the used pin mapping. * * @return the actual pin mapping */ PinMap getPinMapping(); /** * Writes the JEDEC file to the given output stream * * @param out the output stream * @throws FuseMapFillerException FuseMapFillerException * @throws IOException IOException * @throws PinMapException PinMapException */ void writeTo(OutputStream out) throws FuseMapFillerException, IOException, PinMapException; }
gpl-3.0
YixingHuang/CONRAD
src/edu/stanford/rsl/conrad/phantom/xcat/TessellationThread.java
2178
package edu.stanford.rsl.conrad.phantom.xcat; import java.util.Iterator; import edu.stanford.rsl.conrad.geometry.AbstractShape; import edu.stanford.rsl.conrad.geometry.AbstractSurface; import edu.stanford.rsl.conrad.geometry.shapes.compound.CompoundShape; import edu.stanford.rsl.conrad.geometry.shapes.simple.PointND; import edu.stanford.rsl.conrad.geometry.splines.SurfaceBSpline; import edu.stanford.rsl.conrad.geometry.splines.TimeVariantSurfaceBSpline; import edu.stanford.rsl.conrad.parallel.ParallelThread; import edu.stanford.rsl.conrad.utils.TessellationUtil; /** * Thread to tessellate a SurfaceBSpline or TimeVariantSurfaceBSpline. * * @author akmaier * */ public class TessellationThread extends ParallelThread { private Object tessellationObject; private double time; private CompoundShape scene; /** * @return the mesh */ public CompoundShape getObjects() { return scene; } public TessellationThread (Object tessellationObject, double time){ this.tessellationObject = tessellationObject; this.time = time; } @SuppressWarnings("rawtypes") @Override public void execute(){ Object tObject = this; scene = new CompoundShape(); while (tObject != null){ if (((Iterator)this.tessellationObject).hasNext()){ tObject = ((Iterator)this.tessellationObject).next(); int elementCountU = (int)TessellationUtil.getSamplingU((AbstractSurface) tObject); int elementCountV = (int)TessellationUtil.getSamplingV((AbstractSurface) tObject); if (tObject instanceof SurfaceBSpline){ SurfaceBSpline spline = (SurfaceBSpline)tObject; scene.add(spline.tessellateMesh(elementCountU, elementCountV)); } if (tObject instanceof TimeVariantSurfaceBSpline){ TimeVariantSurfaceBSpline spline = (TimeVariantSurfaceBSpline)tObject; AbstractShape mesh = spline.tessellateMesh(elementCountU, elementCountV, time); scene.add(mesh); } } else { tObject = null; } } } @Override public String getProcessName() { return "Tessellation Thread"; } } /* * Copyright (C) 2010-2014 Andreas Maier * CONRAD is developed as an Open Source project under the GNU General Public License (GPL). */
gpl-3.0
TheSecretLife/DR-API
game/src/main/java/net/dungeonrealms/game/listener/TabCompleteCommands.java
1747
package net.dungeonrealms.game.listener; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.events.PacketListener; import net.dungeonrealms.DungeonRealms; import net.dungeonrealms.common.game.database.player.rank.Rank; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; /** * Created by Brad on 09/06/2016. */ public class TabCompleteCommands implements Listener { private static PacketListener listener; public void onEnable() { listener = new PacketAdapter(DungeonRealms.getInstance(), PacketType.Play.Client.TAB_COMPLETE) { public void onPacketReceiving(PacketEvent event) { if (event.getPacketType() == PacketType.Play.Client.TAB_COMPLETE) { // Allow GMs/OPs/DEVs to access tab completion. if (Rank.isGM(event.getPlayer())) return; PacketContainer packet = event.getPacket(); String message = (packet.getSpecificModifier(String.class).read(0)).toLowerCase(); if ((message.startsWith("/") || message.startsWith("@"))) event.setCancelled(true); } } }; ProtocolLibrary.getProtocolManager().addPacketListener(listener); Bukkit.getServer().getPluginManager().registerEvents(this, DungeonRealms.getInstance()); } public void onDisable() { ProtocolLibrary.getProtocolManager().removePacketListener(listener); HandlerList.unregisterAll(this); } }
gpl-3.0
kontext-e/jqassistant-plugins
jacoco/src/test/java/de/kontext_e/jqassistant/plugin/jacoco/scanner/JacocoScannerPluginTest.java
2557
package de.kontext_e.jqassistant.plugin.jacoco.scanner; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class JacocoScannerPluginTest { @Test public void aValidPathShouldBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "/jacoco/test/jacocoTestReport.xml"; final boolean accepted = plugin.acceptsPath(path); assertTrue("A valid path should be accepted", accepted); } @Test public void aValidPathAsRootShouldBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "/jacocoTestReport.xml"; final boolean accepted = plugin.acceptsPath(path); assertTrue("A valid path should be accepted", accepted); } @Test public void anInvValidPathAsRootShouldNotBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "/jacocoTestReport.foo"; final boolean accepted = plugin.acceptsPath(path); assertFalse("An invalid path should not be accepted", accepted); } @Test public void aValidSingleFileNameShouldBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "jacocoTestReport.xml"; final boolean accepted = plugin.acceptsPath(path); assertTrue("A valid path should be accepted", accepted); } @Test public void aValidParentDirectoryShouldBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "/jacoco/report.xml"; final boolean accepted = plugin.acceptsPath(path); assertTrue("A valid parent directory should be accepted", accepted); } @Test public void anInvalidPathGetsNotAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = "/pmd/report.xml"; final boolean accepted = plugin.acceptsPath(path); assertFalse("An invalid parent directory should not be accepted", accepted); } @Test public void pathNullShouldNotBeAccepted() throws IOException { JacocoScannerPlugin plugin = new JacocoScannerPlugin(); String path = null; final boolean accepted = plugin.accepts(null, path, null); assertFalse("Path NULL should not be accepted", accepted); } }
gpl-3.0
gdconde/la2008
app/src/main/java/app/la2008/com/ar/la2008/interfaces/ObjectSelected.java
114
package app.la2008.com.ar.la2008.interfaces; public interface ObjectSelected { void select(Object object); }
gpl-3.0
wjaneal/liastem
SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java
3396
package org.usfirst.frc.team6162.robot; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * This is a demo program showing the use of the RobotDrive class. The * SampleRobot class is the base of a robot application that will automatically * call your Autonomous and OperatorControl methods at the right time as * controlled by the switches on the driver station or the field controls. * * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SampleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. * * WARNING: While it may look like a good choice to use for your code if you're * inexperienced, don't. Unless you know what you are doing, complex code will * be much more difficult under this system. Use IterativeRobot or Command-Based * instead if you're new. */ public class Robot extends SampleRobot { RobotDrive myRobot = new RobotDrive(0, 1,2,3); Joystick stick = new Joystick(0); final String defaultAuto = "Default"; final String customAuto = "My Auto"; SendableChooser<String> chooser = new SendableChooser<>(); public Robot() { myRobot.setExpiration(0.1); } @Override public void robotInit() { chooser.addDefault("Default Auto", defaultAuto); chooser.addObject("My Auto", customAuto); SmartDashboard.putData("Auto modes", chooser); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString line to get the auto name from the text box below the Gyro * * You can add additional auto modes by adding additional comparisons to the * if-else structure below with additional strings. If using the * SendableChooser make sure to add them to the chooser code above as well. */ @Override public void autonomous() { String autoSelected = chooser.getSelected(); // String autoSelected = SmartDashboard.getString("Auto Selector", // defaultAuto); System.out.println("Auto selected: " + autoSelected); switch (autoSelected) { case customAuto: myRobot.setSafetyEnabled(false); myRobot.drive(0.1, 0.1); // spin at half speed Timer.delay(2.0); // for 2 seconds myRobot.drive(0.2, -0.2); // stop robot break; case defaultAuto: default: myRobot.setSafetyEnabled(false); myRobot.drive(0.1, 0.1); // drive forwards half speed Timer.delay(2.0); // for 2 seconds myRobot.drive(0.2, -0.2); // stop robot break; } } /** * Runs the motors with arcade steering. */ @Override public void operatorControl() { myRobot.setSafetyEnabled(true); while (isOperatorControl() && isEnabled()) { myRobot.arcadeDrive(stick); // drive with arcade style (use right // stick) Timer.delay(0.005); // wait for a motor update time } } /** * Runs during test mode */ @Override public void test() { } }
gpl-3.0
nvllsvm/Audinaut
app/src/main/java/net/nullsum/audinaut/util/SilentBackgroundTask.java
1204
/* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 (C) Sindre Mehus */ package net.nullsum.audinaut.util; import android.content.Context; /** * @author Sindre Mehus */ public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> { public SilentBackgroundTask(Context context) { super(context); } @Override public void execute() { queue.offer(task = new Task()); } @Override protected void done(T result) { // Don't do anything unless overriden } @Override public void updateProgress(String message) { } }
gpl-3.0
pahans/Kichibichiya
src/com/pahans/kichibichiya/model/ListAction.java
1111
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pahans.kichibichiya.model; public abstract class ListAction { public abstract long getId(); public abstract String getName(); public String getSummary() { return null; } public void onClick() { } public boolean onLongClick() { return false; } @Override public final String toString() { return getName(); } }
gpl-3.0
st0ck53y/Sudoku_Solver
app/src/main/java/com/st0ck53y/testsudokuapplication/classes/GridArea.java
1644
package com.st0ck53y.testsudokuapplication.classes; public class GridArea { private int value; public GridArea(int v) { this(); if (v != 0) { setValue(v); } } public GridArea() { value = 8185; // 4 bit for remaining possible (9), 9 bit for flags of each, and 1 bit for value flag (is value or check?) } public boolean isValue() { return (value >> 15) == 1; //value flag set when number is certain } public int getValue() { return (value & 15); //either the number in grid, or possibilities remaining } //creates list of integers from binary flags public int[] getPossibles() { int[] p = new int[getValue()]; int pointer = 0; for (int i = 4; i <= 12; i++) { if (((value >> i) & 1) == 1) { p[pointer++] = i - 3; } } return p; } //switches from check to value public void checkGrid() { if ((getValue()) == 1) { setValue(getPossibles()[0]); } } //turns off flag of number and decrements remaining counter public void setImpossible(int i) { int pos = i + 3; int curSet = (value >> pos) & 1; if (curSet == 1) { //Have to check to stop decrement if multiple passes are done value &= (65535 - (1 << (i + 3))); value--; checkGrid(); } } public void setValue(int v) { if (v == 0) value = 8185; else value = (v | (1 << 15)); } }
gpl-3.0
trackplus/Genji
src/main/java/com/aurel/track/persist/BaseTCardGroupingFieldPeer.java
42159
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $Id:$ */ package com.aurel.track.persist; import java.math.BigDecimal; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.torque.NoRowsException; import org.apache.torque.TooManyRowsException; import org.apache.torque.Torque; import org.apache.torque.TorqueException; import org.apache.torque.TorqueRuntimeException; import org.apache.torque.map.MapBuilder; import org.apache.torque.map.TableMap; import org.apache.torque.om.DateKey; import org.apache.torque.om.NumberKey; import org.apache.torque.om.StringKey; import org.apache.torque.om.ObjectKey; import org.apache.torque.om.SimpleKey; import org.apache.torque.util.BasePeer; import org.apache.torque.util.Criteria; import com.workingdogs.village.DataSetException; import com.workingdogs.village.QueryDataSet; import com.workingdogs.village.Record; // Local classes import com.aurel.track.persist.map.*; /** * grouping field for card * */ public abstract class BaseTCardGroupingFieldPeer extends BasePeer { /** the default database name for this class */ public static final String DATABASE_NAME; /** the table name for this class */ public static final String TABLE_NAME; /** * @return the map builder for this peer * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @deprecated Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME) instead */ public static MapBuilder getMapBuilder() throws TorqueException { return Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME); } /** the column name for the OBJECTID field */ public static final String OBJECTID; /** the column name for the NAVIGATORLAYOUT field */ public static final String NAVIGATORLAYOUT; /** the column name for the CARDFIELD field */ public static final String CARDFIELD; /** the column name for the ISACTIV field */ public static final String ISACTIV; /** the column name for the SORTFIELD field */ public static final String SORTFIELD; /** the column name for the ISDESCENDING field */ public static final String ISDESCENDING; /** the column name for the TPUUID field */ public static final String TPUUID; static { DATABASE_NAME = "track"; TABLE_NAME = "TCARDGROUPINGFIELD"; OBJECTID = "TCARDGROUPINGFIELD.OBJECTID"; NAVIGATORLAYOUT = "TCARDGROUPINGFIELD.NAVIGATORLAYOUT"; CARDFIELD = "TCARDGROUPINGFIELD.CARDFIELD"; ISACTIV = "TCARDGROUPINGFIELD.ISACTIV"; SORTFIELD = "TCARDGROUPINGFIELD.SORTFIELD"; ISDESCENDING = "TCARDGROUPINGFIELD.ISDESCENDING"; TPUUID = "TCARDGROUPINGFIELD.TPUUID"; if (Torque.isInit()) { try { Torque.getMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME); } catch (TorqueException e) { log.error("Could not initialize Peer", e); throw new TorqueRuntimeException(e); } } else { Torque.registerMapBuilder(TCardGroupingFieldMapBuilder.CLASS_NAME); } } /** number of columns for this peer */ public static final int numColumns = 7; /** A class that can be returned by this peer. */ protected static final String CLASSNAME_DEFAULT = "com.aurel.track.persist.TCardGroupingField"; /** A class that can be returned by this peer. */ protected static final Class CLASS_DEFAULT = initClass(CLASSNAME_DEFAULT); /** * Class object initialization method. * * @param className name of the class to initialize * @return the initialized class */ private static Class initClass(String className) { Class c = null; try { c = Class.forName(className); } catch (Throwable t) { log.error("A FATAL ERROR has occurred which should not " + "have happened under any circumstance. Please notify " + "the Torque developers <torque-dev@db.apache.org> " + "and give as many details as possible (including the error " + "stack trace).", t); // Error objects should always be propagated. if (t instanceof Error) { throw (Error) t.fillInStackTrace(); } } return c; } /** * Get the list of objects for a ResultSet. Please not that your * resultset MUST return columns in the right order. You can use * getFieldNames() in BaseObject to get the correct sequence. * * @param results the ResultSet * @return the list of objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> resultSet2Objects(java.sql.ResultSet results) throws TorqueException { try { QueryDataSet qds = null; List<Record> rows = null; try { qds = new QueryDataSet(results); rows = getSelectResults(qds); } finally { if (qds != null) { qds.close(); } } return populateObjects(rows); } catch (SQLException e) { throw new TorqueException(e); } catch (DataSetException e) { throw new TorqueException(e); } } /** * Method to do inserts. * * @param criteria object used to create the INSERT statement. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static ObjectKey doInsert(Criteria criteria) throws TorqueException { return BaseTCardGroupingFieldPeer .doInsert(criteria, (Connection) null); } /** * Method to do inserts. This method is to be used during a transaction, * otherwise use the doInsert(Criteria) method. It will take care of * the connection details internally. * * @param criteria object used to create the INSERT statement. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static ObjectKey doInsert(Criteria criteria, Connection con) throws TorqueException { correctBooleans(criteria); setDbName(criteria); if (con == null) { return BasePeer.doInsert(criteria); } else { return BasePeer.doInsert(criteria, con); } } /** * Add all the columns needed to create a new object. * * @param criteria object containing the columns to add. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void addSelectColumns(Criteria criteria) throws TorqueException { criteria.addSelectColumn(OBJECTID); criteria.addSelectColumn(NAVIGATORLAYOUT); criteria.addSelectColumn(CARDFIELD); criteria.addSelectColumn(ISACTIV); criteria.addSelectColumn(SORTFIELD); criteria.addSelectColumn(ISDESCENDING); criteria.addSelectColumn(TPUUID); } /** * changes the boolean values in the criteria to the appropriate type, * whenever a booleanchar or booleanint column is involved. * This enables the user to create criteria using Boolean values * for booleanchar or booleanint columns * @param criteria the criteria in which the boolean values should be corrected * @throws TorqueException if the database map for the criteria cannot be obtained. */ public static void correctBooleans(Criteria criteria) throws TorqueException { correctBooleans(criteria, getTableMap()); } /** * Create a new object of type cls from a resultset row starting * from a specified offset. This is done so that you can select * other rows than just those needed for this object. You may * for example want to create two objects from the same row. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static TCardGroupingField row2Object(Record row, int offset, Class cls) throws TorqueException { try { TCardGroupingField obj = (TCardGroupingField) cls.newInstance(); TCardGroupingFieldPeer.populateObject(row, offset, obj); obj.setModified(false); obj.setNew(false); return obj; } catch (InstantiationException e) { throw new TorqueException(e); } catch (IllegalAccessException e) { throw new TorqueException(e); } } /** * Populates an object from a resultset row starting * from a specified offset. This is done so that you can select * other rows than just those needed for this object. You may * for example want to create two objects from the same row. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void populateObject(Record row, int offset, TCardGroupingField obj) throws TorqueException { try { obj.setObjectID(row.getValue(offset + 0).asIntegerObj()); obj.setNavigatorLayout(row.getValue(offset + 1).asIntegerObj()); obj.setCardField(row.getValue(offset + 2).asIntegerObj()); obj.setIsActiv(row.getValue(offset + 3).asString()); obj.setSortField(row.getValue(offset + 4).asIntegerObj()); obj.setIsDescending(row.getValue(offset + 5).asString()); obj.setUuid(row.getValue(offset + 6).asString()); } catch (DataSetException e) { throw new TorqueException(e); } } /** * Method to do selects. * * @param criteria object used to create the SELECT statement. * @return List of selected Objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> doSelect(Criteria criteria) throws TorqueException { return populateObjects(doSelectVillageRecords(criteria)); } /** * Method to do selects within a transaction. * * @param criteria object used to create the SELECT statement. * @param con the connection to use * @return List of selected Objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> doSelect(Criteria criteria, Connection con) throws TorqueException { return populateObjects(doSelectVillageRecords(criteria, con)); } /** * Grabs the raw Village records to be formed into objects. * This method handles connections internally. The Record objects * returned by this method should be considered readonly. Do not * alter the data and call save(), your results may vary, but are * certainly likely to result in hard to track MT bugs. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<Record> doSelectVillageRecords(Criteria criteria) throws TorqueException { return BaseTCardGroupingFieldPeer .doSelectVillageRecords(criteria, (Connection) null); } /** * Grabs the raw Village records to be formed into objects. * This method should be used for transactions * * @param criteria object used to create the SELECT statement. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<Record> doSelectVillageRecords(Criteria criteria, Connection con) throws TorqueException { if (criteria.getSelectColumns().size() == 0) { addSelectColumns(criteria); } correctBooleans(criteria); setDbName(criteria); // BasePeer returns a List of Value (Village) arrays. The array // order follows the order columns were placed in the Select clause. if (con == null) { return BasePeer.doSelect(criteria); } else { return BasePeer.doSelect(criteria, con); } } /** * The returned List will contain objects of the default type or * objects that inherit from the default. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> populateObjects(List<Record> records) throws TorqueException { List<TCardGroupingField> results = new ArrayList<TCardGroupingField>(records.size()); // populate the object(s) for (int i = 0; i < records.size(); i++) { Record row = records.get(i); results.add(TCardGroupingFieldPeer.row2Object(row, 1, TCardGroupingFieldPeer.getOMClass())); } return results; } /** * The class that the Peer will make instances of. * If the BO is abstract then you must implement this method * in the BO. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static Class getOMClass() throws TorqueException { return CLASS_DEFAULT; } /** * Method to do updates. * * @param criteria object containing data that is used to create the UPDATE * statement. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doUpdate(Criteria criteria) throws TorqueException { BaseTCardGroupingFieldPeer .doUpdate(criteria, (Connection) null); } /** * Method to do updates. This method is to be used during a transaction, * otherwise use the doUpdate(Criteria) method. It will take care of * the connection details internally. * * @param criteria object containing data that is used to create the UPDATE * statement. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doUpdate(Criteria criteria, Connection con) throws TorqueException { Criteria selectCriteria = new Criteria(DATABASE_NAME, 2); correctBooleans(criteria); selectCriteria.put(OBJECTID, criteria.remove(OBJECTID)); setDbName(criteria); if (con == null) { BasePeer.doUpdate(selectCriteria, criteria); } else { BasePeer.doUpdate(selectCriteria, criteria, con); } } /** * Method to do deletes. * * @param criteria object containing data that is used DELETE from database. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(Criteria criteria) throws TorqueException { TCardGroupingFieldPeer .doDelete(criteria, (Connection) null); } /** * Method to do deletes. This method is to be used during a transaction, * otherwise use the doDelete(Criteria) method. It will take care of * the connection details internally. * * @param criteria object containing data that is used DELETE from database. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(Criteria criteria, Connection con) throws TorqueException { correctBooleans(criteria); setDbName(criteria); if (con == null) { BasePeer.doDelete(criteria, TABLE_NAME); } else { BasePeer.doDelete(criteria, TABLE_NAME, con); } } /** * Method to do selects * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> doSelect(TCardGroupingField obj) throws TorqueException { return doSelect(buildSelectCriteria(obj)); } /** * Method to do inserts * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doInsert(TCardGroupingField obj) throws TorqueException { obj.setPrimaryKey(doInsert(buildCriteria(obj))); obj.setNew(false); obj.setModified(false); } /** * @param obj the data object to update in the database. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doUpdate(TCardGroupingField obj) throws TorqueException { doUpdate(buildCriteria(obj)); obj.setModified(false); } /** * @param obj the data object to delete in the database. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(TCardGroupingField obj) throws TorqueException { doDelete(buildSelectCriteria(obj)); } /** * Method to do inserts. This method is to be used during a transaction, * otherwise use the doInsert(TCardGroupingField) method. It will take * care of the connection details internally. * * @param obj the data object to insert into the database. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doInsert(TCardGroupingField obj, Connection con) throws TorqueException { obj.setPrimaryKey(doInsert(buildCriteria(obj), con)); obj.setNew(false); obj.setModified(false); } /** * Method to do update. This method is to be used during a transaction, * otherwise use the doUpdate(TCardGroupingField) method. It will take * care of the connection details internally. * * @param obj the data object to update in the database. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doUpdate(TCardGroupingField obj, Connection con) throws TorqueException { doUpdate(buildCriteria(obj), con); obj.setModified(false); } /** * Method to delete. This method is to be used during a transaction, * otherwise use the doDelete(TCardGroupingField) method. It will take * care of the connection details internally. * * @param obj the data object to delete in the database. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(TCardGroupingField obj, Connection con) throws TorqueException { doDelete(buildSelectCriteria(obj), con); } /** * Method to do deletes. * * @param pk ObjectKey that is used DELETE from database. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(ObjectKey pk) throws TorqueException { BaseTCardGroupingFieldPeer .doDelete(pk, (Connection) null); } /** * Method to delete. This method is to be used during a transaction, * otherwise use the doDelete(ObjectKey) method. It will take * care of the connection details internally. * * @param pk the primary key for the object to delete in the database. * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void doDelete(ObjectKey pk, Connection con) throws TorqueException { doDelete(buildCriteria(pk), con); } /** Build a Criteria object from an ObjectKey */ public static Criteria buildCriteria( ObjectKey pk ) { Criteria criteria = new Criteria(); criteria.add(OBJECTID, pk); return criteria; } /** Build a Criteria object from the data object for this peer */ public static Criteria buildCriteria( TCardGroupingField obj ) { Criteria criteria = new Criteria(DATABASE_NAME); if (!obj.isNew()) criteria.add(OBJECTID, obj.getObjectID()); criteria.add(NAVIGATORLAYOUT, obj.getNavigatorLayout()); criteria.add(CARDFIELD, obj.getCardField()); criteria.add(ISACTIV, obj.getIsActiv()); criteria.add(SORTFIELD, obj.getSortField()); criteria.add(ISDESCENDING, obj.getIsDescending()); criteria.add(TPUUID, obj.getUuid()); return criteria; } /** Build a Criteria object from the data object for this peer, skipping all binary columns */ public static Criteria buildSelectCriteria( TCardGroupingField obj ) { Criteria criteria = new Criteria(DATABASE_NAME); if (!obj.isNew()) { criteria.add(OBJECTID, obj.getObjectID()); } criteria.add(NAVIGATORLAYOUT, obj.getNavigatorLayout()); criteria.add(CARDFIELD, obj.getCardField()); criteria.add(ISACTIV, obj.getIsActiv()); criteria.add(SORTFIELD, obj.getSortField()); criteria.add(ISDESCENDING, obj.getIsDescending()); criteria.add(TPUUID, obj.getUuid()); return criteria; } /** * Retrieve a single object by pk * * @param pk the primary key * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @throws NoRowsException Primary key was not found in database. * @throws TooManyRowsException Primary key was not found in database. */ public static TCardGroupingField retrieveByPK(Integer pk) throws TorqueException, NoRowsException, TooManyRowsException { return retrieveByPK(SimpleKey.keyFor(pk)); } /** * Retrieve a single object by pk * * @param pk the primary key * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @throws NoRowsException Primary key was not found in database. * @throws TooManyRowsException Primary key was not found in database. */ public static TCardGroupingField retrieveByPK(Integer pk, Connection con) throws TorqueException, NoRowsException, TooManyRowsException { return retrieveByPK(SimpleKey.keyFor(pk), con); } /** * Retrieve a single object by pk * * @param pk the primary key * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @throws NoRowsException Primary key was not found in database. * @throws TooManyRowsException Primary key was not found in database. */ public static TCardGroupingField retrieveByPK(ObjectKey pk) throws TorqueException, NoRowsException, TooManyRowsException { Connection db = null; TCardGroupingField retVal = null; try { db = Torque.getConnection(DATABASE_NAME); retVal = retrieveByPK(pk, db); } finally { Torque.closeConnection(db); } return retVal; } /** * Retrieve a single object by pk * * @param pk the primary key * @param con the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @throws NoRowsException Primary key was not found in database. * @throws TooManyRowsException Primary key was not found in database. */ public static TCardGroupingField retrieveByPK(ObjectKey pk, Connection con) throws TorqueException, NoRowsException, TooManyRowsException { Criteria criteria = buildCriteria(pk); List<TCardGroupingField> v = doSelect(criteria, con); if (v.size() == 0) { throw new NoRowsException("Failed to select a row."); } else if (v.size() > 1) { throw new TooManyRowsException("Failed to select only one row."); } else { return (TCardGroupingField)v.get(0); } } /** * Retrieve a multiple objects by pk * * @param pks List of primary keys * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> retrieveByPKs(List<ObjectKey> pks) throws TorqueException { Connection db = null; List<TCardGroupingField> retVal = null; try { db = Torque.getConnection(DATABASE_NAME); retVal = retrieveByPKs(pks, db); } finally { Torque.closeConnection(db); } return retVal; } /** * Retrieve a multiple objects by pk * * @param pks List of primary keys * @param dbcon the connection to use * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List<TCardGroupingField> retrieveByPKs( List<ObjectKey> pks, Connection dbcon ) throws TorqueException { List<TCardGroupingField> objs = null; if (pks == null || pks.size() == 0) { objs = new LinkedList<TCardGroupingField>(); } else { Criteria criteria = new Criteria(); criteria.addIn( OBJECTID, pks ); objs = doSelect(criteria, dbcon); } return objs; } /** * selects a collection of TCardGroupingField objects pre-filled with their * TNavigatorLayout objects. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in TCardGroupingFieldPeer. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ protected static List<TCardGroupingField> doSelectJoinTNavigatorLayout(Criteria criteria) throws TorqueException { return doSelectJoinTNavigatorLayout(criteria, null); } /** * selects a collection of TCardGroupingField objects pre-filled with their * TNavigatorLayout objects. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in TCardGroupingFieldPeer. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ protected static List<TCardGroupingField> doSelectJoinTNavigatorLayout(Criteria criteria, Connection conn) throws TorqueException { setDbName(criteria); TCardGroupingFieldPeer.addSelectColumns(criteria); int offset = numColumns + 1; TNavigatorLayoutPeer.addSelectColumns(criteria); criteria.addJoin(TCardGroupingFieldPeer.NAVIGATORLAYOUT, TNavigatorLayoutPeer.OBJECTID); correctBooleans(criteria); List<Record> rows; if (conn == null) { rows = BasePeer.doSelect(criteria); } else { rows = BasePeer.doSelect(criteria,conn); } List<TCardGroupingField> results = new ArrayList<TCardGroupingField>(); for (int i = 0; i < rows.size(); i++) { Record row = rows.get(i); Class omClass = TCardGroupingFieldPeer.getOMClass(); TCardGroupingField obj1 = (TCardGroupingField) TCardGroupingFieldPeer .row2Object(row, 1, omClass); omClass = TNavigatorLayoutPeer.getOMClass(); TNavigatorLayout obj2 = (TNavigatorLayout) TNavigatorLayoutPeer .row2Object(row, offset, omClass); boolean newObject = true; for (int j = 0; j < results.size(); j++) { TCardGroupingField temp_obj1 = results.get(j); TNavigatorLayout temp_obj2 = (TNavigatorLayout) temp_obj1.getTNavigatorLayout(); if (temp_obj2.getPrimaryKey().equals(obj2.getPrimaryKey())) { newObject = false; temp_obj2.addTCardGroupingField(obj1); break; } } if (newObject) { obj2.initTCardGroupingFields(); obj2.addTCardGroupingField(obj1); } results.add(obj1); } return results; } /** * Returns the TableMap related to this peer. * * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static TableMap getTableMap() throws TorqueException { return Torque.getDatabaseMap(DATABASE_NAME).getTable(TABLE_NAME); } private static void setDbName(Criteria crit) { // Set the correct dbName if it has not been overridden // crit.getDbName will return the same object if not set to // another value so == check is okay and faster if (crit.getDbName() == Torque.getDefaultDB()) { crit.setDbName(DATABASE_NAME); } } // The following methods wrap some methods in BasePeer // to have more support for Java5 generic types in the Peer /** * Utility method which executes a given sql statement. This * method should be used for select statements only. Use * executeStatement for update, insert, and delete operations. * * @param queryString A String with the sql statement to execute. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String) */ public static List<Record> executeQuery(String queryString) throws TorqueException { return BasePeer.executeQuery(queryString); } /** * Utility method which executes a given sql statement. This * method should be used for select statements only. Use * executeStatement for update, insert, and delete operations. * * @param queryString A String with the sql statement to execute. * @param dbName The database to connect to. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String,String) */ public static List<Record> executeQuery(String queryString, String dbName) throws TorqueException { return BasePeer.executeQuery(queryString,dbName); } /** * Method for performing a SELECT. Returns all results. * * @param queryString A String with the sql statement to execute. * @param dbName The database to connect to. * @param singleRecord Whether or not we want to select only a * single record. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String,String,boolean) */ public static List<Record> executeQuery( String queryString, String dbName, boolean singleRecord) throws TorqueException { return BasePeer.executeQuery(queryString,dbName,singleRecord); } /** * Method for performing a SELECT. Returns all results. * * @param queryString A String with the sql statement to execute. * @param singleRecord Whether or not we want to select only a * single record. * @param con A Connection. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String,boolean,Connection) */ public static List<Record> executeQuery( String queryString, boolean singleRecord, Connection con) throws TorqueException { return BasePeer.executeQuery(queryString,singleRecord,con); } /** * Method for performing a SELECT. * * @param queryString A String with the sql statement to execute. * @param start The first row to return. * @param numberOfResults The number of rows to return. * @param dbName The database to connect to. * @param singleRecord Whether or not we want to select only a * single record. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean) */ public static List<Record> executeQuery( String queryString, int start, int numberOfResults, String dbName, boolean singleRecord) throws TorqueException { return BasePeer.executeQuery(queryString,start,numberOfResults,dbName,singleRecord); } /** * Method for performing a SELECT. Returns all results. * * @param queryString A String with the sql statement to execute. * @param start The first row to return. * @param numberOfResults The number of rows to return. * @param singleRecord Whether or not we want to select only a * single record. * @param con A Connection. * @return List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean,Connection) */ public static List<Record> executeQuery( String queryString, int start, int numberOfResults, boolean singleRecord, Connection con) throws TorqueException { return BasePeer.executeQuery(queryString,start,numberOfResults,singleRecord,con); } /** * Returns all records in a QueryDataSet as a List of Record * objects. Used for functionality like util.LargeSelect. * * @see #getSelectResults(QueryDataSet, int, int, boolean) * @param qds the QueryDataSet * @return a List of Record objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet) */ public static List<Record> getSelectResults(QueryDataSet qds) throws TorqueException { return BasePeer.getSelectResults(qds); } /** * Returns all records in a QueryDataSet as a List of Record * objects. Used for functionality like util.LargeSelect. * * @see #getSelectResults(QueryDataSet, int, int, boolean) * @param qds the QueryDataSet * @param singleRecord * @return a List of Record objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,boolean) */ public static List<Record> getSelectResults(QueryDataSet qds, boolean singleRecord) throws TorqueException { return BasePeer.getSelectResults(qds,singleRecord); } /** * Returns numberOfResults records in a QueryDataSet as a List * of Record objects. Starting at record 0. Used for * functionality like util.LargeSelect. * * @see #getSelectResults(QueryDataSet, int, int, boolean) * @param qds the QueryDataSet * @param numberOfResults * @param singleRecord * @return a List of Record objects * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,boolean) */ public static List<Record> getSelectResults( QueryDataSet qds, int numberOfResults, boolean singleRecord) throws TorqueException { return BasePeer.getSelectResults(qds,numberOfResults,singleRecord); } /** * Returns numberOfResults records in a QueryDataSet as a List * of Record objects. Starting at record start. Used for * functionality like util.LargeSelect. * * @param qds The <code>QueryDataSet</code> to extract results * from. * @param start The index from which to start retrieving * <code>Record</code> objects from the data set. * @param numberOfResults The number of results to return (or * <code> -1</code> for all results). * @param singleRecord Whether or not we want to select only a * single record. * @return A <code>List</code> of <code>Record</code> objects. * @exception TorqueException If any <code>Exception</code> occurs. * @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,int,boolean) */ public static List getSelectResults( QueryDataSet qds, int start, int numberOfResults, boolean singleRecord) throws TorqueException { return BasePeer.getSelectResults(qds,start,numberOfResults,singleRecord); } /** * Performs a SQL <code>select</code> using a PreparedStatement. * Note: this method does not handle null criteria values. * * @param criteria * @param con * @return a List of Record objects. * @throws TorqueException Error performing database query. * @see org.apache.torque.util.BasePeer#doPSSelect(Criteria,Connection) */ public static List<Record> doPSSelect(Criteria criteria, Connection con) throws TorqueException { return BasePeer.doPSSelect(criteria,con); } /** * Do a Prepared Statement select according to the given criteria * * @param criteria * @return a List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. * @see org.apache.torque.util.BasePeer#doPSSelect(Criteria) */ public static List<Record> doPSSelect(Criteria criteria) throws TorqueException { return BasePeer.doPSSelect(criteria); } }
gpl-3.0
Plain-Simple/GalaxyDraw
java/src/plainsimple/galaxydraw/DrawSpace.java
4687
package plainsimple.space; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; /** * Renders an image of a starry sky based on several parameters. * Copyright(C) Plain Simple Apps 2015 * See github.com/Plain-Simple/GalaxyDraw for more information. * Licensed under GPL GNU Version 3 (see license.txt) */ public class DrawSpace { // color of stars private Color starColor; // color of background private Color backgroundColor; // whether or not to use gradient private boolean useGradient; // gradient to use, if backgroundGradient = true private GradientPaint backgroundGradient; // stars per 2500 px (50*50 square) private double density; // alpha value used when drawing stars private int brightness; // radius of stars, in px private int starSize; // random variance from given values private double variance; // used for random number generation private Random random; public Color getStarColor() { return starColor; } public void setStarColor(Color starColor) { this.starColor = starColor; } public Color getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; } public double getDensity() { return density; } public void setDensity(double density) { this.density = density; } public int getBrightness() { return brightness; } public void setBrightness(int brightness) { this.brightness = brightness; } public int getStarSize() { return starSize; } public void setStarSize(int starSize) { this.starSize = starSize; } public boolean usesGradient() { return useGradient; } public void setUseGradient(boolean useGradient) { this.useGradient = useGradient; } public GradientPaint getBackgroundGradient() { return backgroundGradient; } public void setBackgroundGradient(GradientPaint backgroundGradient) { this.backgroundGradient = backgroundGradient; } public double getVariance() { return variance; } public void setVariance(double variance) { this.variance = variance; } // init with default values public DrawSpace() { density = 5; brightness = 150; starSize = 3; variance = 0.4; starColor = new Color(255, 255, 238); backgroundColor = Color.BLACK; useGradient = false; random = new Random(); } // creates BufferedImage of given dimensions and renders space on it public BufferedImage drawSpace(int imgWidth, int imgHeight) { BufferedImage generated = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); drawSpace(generated); return generated; } // renders space on given BufferedImage public void drawSpace(BufferedImage canvas) { Graphics2D graphics = canvas.createGraphics(); drawBackground(graphics, canvas.getWidth(), canvas.getHeight()); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int num_stars = (int) (canvas.getWidth() * canvas.getHeight() / 2500.0 * density); for (int i = 0; i < num_stars; i++) { drawStar(graphics, random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), varyBrightness(brightness, variance), varySize(starSize, variance)); } } private void drawBackground(Graphics2D graphics, int imgWidth, int imgHeight) { if (useGradient) { graphics.setPaint(backgroundGradient); graphics.fillRect(0, 0, imgWidth, imgHeight); } else { graphics.setColor(backgroundColor); graphics.fillRect(0, 0, imgWidth, imgHeight); } } private void drawStar(Graphics2D graphics, int x, int y, int brightness, int size) { graphics.setColor(starColor); graphics.setColor(new Color(starColor.getRed(), starColor.getBlue(), starColor.getGreen(), brightness)); graphics.fillOval(x, y, size, size); } private int varyBrightness(int value, double variance) { int varied = value + random.nextInt((int) (value * variance * 100)) / 100; if (varied > 255) { return 255; } else { return varied; } } private int varySize(int value, double variance) { return value + random.nextInt((int) (value * variance * 100)) / 100; } }
gpl-3.0
Lanchon/DexPatcher-tool
tool/src/main/java/lanchon/dexpatcher/transform/util/wrapper/WrapperAnnotationElement.java
1021
/* * DexPatcher - Copyright 2015-2020 Rodrigo Balerdi * (GNU General Public License version 3 or later) * * DexPatcher 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. */ package lanchon.dexpatcher.transform.util.wrapper; import org.jf.dexlib2.base.BaseAnnotationElement; import org.jf.dexlib2.iface.AnnotationElement; import org.jf.dexlib2.iface.value.EncodedValue; public class WrapperAnnotationElement extends BaseAnnotationElement { protected final AnnotationElement wrappedAnnotationElement; public WrapperAnnotationElement(AnnotationElement wrappedAnnotationElement) { this.wrappedAnnotationElement = wrappedAnnotationElement; } @Override public String getName() { return wrappedAnnotationElement.getName(); } @Override public EncodedValue getValue() { return wrappedAnnotationElement.getValue(); } }
gpl-3.0
trejkaz/haqua
src/org/trypticon/haqua/HaquaMenuItemUI.java
3093
package org.trypticon.haqua; import com.apple.laf.AquaMenuItemUI; import org.jetbrains.annotations.NotNull; import javax.accessibility.Accessible; import javax.swing.JComponent; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.MenuItemUI; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; /** * @author trejkaz */ public class HaquaMenuItemUI extends MenuItemUI { private final AquaMenuItemUI delegate; public HaquaMenuItemUI(AquaMenuItemUI delegate) { this.delegate = delegate; } @NotNull @SuppressWarnings("UnusedDeclaration") // called via reflection public static ComponentUI createUI(JComponent component) { // Unfortunately the constructor for AquaMenuItemUI is package local, so we can't just inherit from it. :( return new HaquaMenuItemUI((AquaMenuItemUI) AquaMenuItemUI.createUI(component)); } @Override public void update(Graphics g, JComponent c) { if (!c.getComponentOrientation().isLeftToRight()) { Graphics2D gCopy = (Graphics2D) g.create(); try { // By painting 9 pixels to the right, 9 pixels on the left of the background are not painted, // so we work around that here. delegate.paintBackground(g, c, c.getWidth(), c.getHeight()); // AquaMenuUI paints the item 9 pixels too far left in right-to-left orientation. gCopy.translate(9, 0); delegate.update(gCopy, c); } finally { gCopy.dispose(); } } else { delegate.update(g, c); } } // Not overriding (nor delegating) paint() at the moment but we overrode update() and that seems to suffice. // Everything below is straight delegation. @Override public void installUI(JComponent c) { delegate.installUI(c); } @Override public void uninstallUI(JComponent c) { delegate.uninstallUI(c); } @Override public Dimension getPreferredSize(JComponent c) { return delegate.getPreferredSize(c); } @Override public Dimension getMinimumSize(JComponent c) { return delegate.getMinimumSize(c); } @Override public Dimension getMaximumSize(JComponent c) { return delegate.getMaximumSize(c); } @Override public boolean contains(JComponent c, int x, int y) { return delegate.contains(c, x, y); } @Override public int getBaseline(JComponent c, int width, int height) { return delegate.getBaseline(c, width, height); } @Override public Component.BaselineResizeBehavior getBaselineResizeBehavior(JComponent c) { return delegate.getBaselineResizeBehavior(c); } @Override public int getAccessibleChildrenCount(JComponent c) { return delegate.getAccessibleChildrenCount(c); } @Override public Accessible getAccessibleChild(JComponent c, int i) { return delegate.getAccessibleChild(c, i); } }
gpl-3.0
lgulyas/MEME
src/ai/aitia/meme/paramsweep/gui/Page_EMILPrefs.java
4536
/******************************************************************************* * Copyright (C) 2006-2013 AITIA International, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package ai.aitia.meme.paramsweep.gui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import ai.aitia.meme.gui.Preferences; import ai.aitia.meme.gui.PreferencesPage; import ai.aitia.meme.gui.Preferences.Button; import ai.aitia.meme.paramsweep.gui.WizardPreferences.IReinitalizeable; import ai.aitia.meme.paramsweep.platform.PlatformManager; import ai.aitia.meme.paramsweep.platform.PlatformManager.PlatformType; import ai.aitia.meme.paramsweep.utils.Utilities; import ai.aitia.meme.utils.FormsUtils; import ai.aitia.meme.utils.GUIUtils; import ai.aitia.meme.utils.FormsUtils.Separator; public class Page_EMILPrefs extends PreferencesPage implements IReinitalizeable, ActionListener { //===================================================================================== //members private static final long serialVersionUID = 1L; /** The owner component of the page. */ private WizardPreferences owner = null; //===================================================================================== // GUI members private JPanel content = null; private JButton registerButton = new JButton("Register"); private JButton deRegisterButton = new JButton("Deregister"); //===================================================================================== // methods //------------------------------------------------------------------------------------- /** Constructor. * @param owner the owner component of the page */ public Page_EMILPrefs(WizardPreferences owner) { super("EMIL-S Repast"); this.owner = owner; layoutGUI(); reinitialize(); } //===================================================================================== // implemented interfaces //------------------------------------------------------------------------------------- @Override public String getInfoText(Preferences p) { return "EMIL-S Repast properties."; } @Override public boolean onButtonPress(Button b) { return true; } //------------------------------------------------------------------------------------- public void reinitialize() {} //---------------------------------------------------------------------------------------------------- public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if ("REGISTER".equals(cmd)) { PlatformManager.registerPlatform(PlatformType.EMIL,"."); owner.warning(true,"Registration successful!",Preferences.MESSAGE,true); } else if ("DEREGISTER".equals(cmd)) { int result = Utilities.askUser(owner,false,"Confirmation","Are you sure?"); if (result == 1) { PlatformManager.removePlatform(PlatformType.EMIL); owner.warning(true,"Deregistration successful!",Preferences.MESSAGE,true); } } } //===================================================================================== // GUI methods //------------------------------------------------------------------------------------- private void layoutGUI() { JPanel tmp = FormsUtils.build("p ~ p ~ p:g", "01_", registerButton,deRegisterButton).getPanel(); content = FormsUtils.build("p ~ p:g ~ p ", "[DialogBorder]000||" + "111||" + "222|" + "___", "A platform for Trass models", tmp, new Separator("")).getPanel(); this.setLayout(new BorderLayout()); this.add(content,BorderLayout.CENTER); registerButton.setActionCommand("REGISTER"); deRegisterButton.setActionCommand("DEREGISTER"); GUIUtils.addActionListener(this,registerButton,deRegisterButton); } }
gpl-3.0
rfortti/PRS_rfortti
src/aula01/Exemplo1.java
912
/* * 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 aula01; import java.util.Scanner; /** * * @author Aluno */ public class Exemplo1 { public static void main(String[] args) { /* Objeto Scan vai auxiliar na entrada de dados via teclado */ Scanner scan = new Scanner(System.in); System.out.println("Qual o seu nome ?"); /* Metodo nextLine lê uma string do teclado */ String nome = scan.nextLine(); System.out.println("Seja Bem-Vindo" + nome); System.out.println("Qual a sua idade ?"); /* Metodo nextInt lê um inteiro do teclado */ int idade = scan.nextInt(); System.out.println("Sua idade eh " + idade + " anos."); } }
gpl-3.0
applifireAlgo/appDemoApps201115
surveyportal/src/main/java/com/survey/app/server/repository/CountryRepository.java
1169
package com.survey.app.server.repository; import com.athena.server.repository.SearchInterface; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import java.util.List; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; @SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Country Master table Entity", complexity = Complexity.LOW) public interface CountryRepository<T> extends SearchInterface { public List<T> findAll() throws SpartanPersistenceException; public T save(T entity) throws SpartanPersistenceException; public List<T> save(List<T> entity) throws SpartanPersistenceException; public void delete(String id) throws SpartanPersistenceException; public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException; public void update(List<T> entity) throws SpartanPersistenceException; public T findById(String countryId) throws Exception, SpartanPersistenceException; }
gpl-3.0
tdgunes/music-box
core/src/main/java/Utils.java
1662
/** * Taha Dogan Gunes * <tdgunes@gmail.com> * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * <p/> * 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. */ public class Utils { public static String cleanStringForOnto(String string){ string = string.replace("[",""); string = string.replace("]",""); string = string.replace("#",""); string = string.replace(">",""); string = string.replace("%",""); string = string.replace("\"",""); //string = string.replace(" ",""); string = string.replace(".",""); string = string.replace("'",""); // string = string.replace("I","i"); return string; } }
gpl-3.0
atrezubov/GShadowServiceUniversal
app/build/generated/source/r/release/com/google/android/gms/panorama/R.java
15078
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms.panorama; public final class R { public static final class attr { public static final int adSize = 0x7f010055; public static final int adSizes = 0x7f010056; public static final int adUnitId = 0x7f010057; public static final int appTheme = 0x7f010081; public static final int buyButtonAppearance = 0x7f010088; public static final int buyButtonHeight = 0x7f010085; public static final int buyButtonText = 0x7f010087; public static final int buyButtonWidth = 0x7f010086; public static final int cameraBearing = 0x7f010060; public static final int cameraTargetLat = 0x7f010061; public static final int cameraTargetLng = 0x7f010062; public static final int cameraTilt = 0x7f010063; public static final int cameraZoom = 0x7f010064; public static final int circleCrop = 0x7f01005e; public static final int environment = 0x7f010082; public static final int fragmentMode = 0x7f010084; public static final int fragmentStyle = 0x7f010083; public static final int imageAspectRatio = 0x7f01005d; public static final int imageAspectRatioAdjust = 0x7f01005c; public static final int liteMode = 0x7f010065; public static final int mapType = 0x7f01005f; public static final int maskedWalletDetailsBackground = 0x7f01008b; public static final int maskedWalletDetailsButtonBackground = 0x7f01008d; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f01008c; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f01008a; public static final int maskedWalletDetailsLogoImageType = 0x7f01008f; public static final int maskedWalletDetailsLogoTextColor = 0x7f01008e; public static final int maskedWalletDetailsTextAppearance = 0x7f010089; public static final int uiCompass = 0x7f010066; public static final int uiMapToolbar = 0x7f01006e; public static final int uiRotateGestures = 0x7f010067; public static final int uiScrollGestures = 0x7f010068; public static final int uiTiltGestures = 0x7f010069; public static final int uiZoomControls = 0x7f01006a; public static final int uiZoomGestures = 0x7f01006b; public static final int useViewLifecycle = 0x7f01006c; public static final int windowTransitionStyle = 0x7f010059; public static final int zOrderOnTop = 0x7f01006d; } public static final class color { public static final int common_action_bar_splitter = 0x7f070003; public static final int common_signin_btn_dark_text_default = 0x7f070004; public static final int common_signin_btn_dark_text_disabled = 0x7f070005; public static final int common_signin_btn_dark_text_focused = 0x7f070006; public static final int common_signin_btn_dark_text_pressed = 0x7f070007; public static final int common_signin_btn_default_background = 0x7f070008; public static final int common_signin_btn_light_text_default = 0x7f070009; public static final int common_signin_btn_light_text_disabled = 0x7f07000a; public static final int common_signin_btn_light_text_focused = 0x7f07000b; public static final int common_signin_btn_light_text_pressed = 0x7f07000c; public static final int common_signin_btn_text_dark = 0x7f07001b; public static final int common_signin_btn_text_light = 0x7f07001c; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f07000d; public static final int wallet_bright_foreground_holo_dark = 0x7f07000e; public static final int wallet_bright_foreground_holo_light = 0x7f07000f; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f070010; public static final int wallet_dim_foreground_holo_dark = 0x7f070011; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f070012; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f070013; public static final int wallet_highlighted_text_holo_dark = 0x7f070014; public static final int wallet_highlighted_text_holo_light = 0x7f070015; public static final int wallet_hint_foreground_holo_dark = 0x7f070016; public static final int wallet_hint_foreground_holo_light = 0x7f070017; public static final int wallet_holo_blue_light = 0x7f070018; public static final int wallet_link_text_light = 0x7f070019; public static final int wallet_primary_text_holo_light = 0x7f07001d; public static final int wallet_secondary_text_holo_dark = 0x7f07001e; } public static final class drawable { public static final int common_full_open_on_phone = 0x7f020057; public static final int common_ic_googleplayservices = 0x7f020058; public static final int common_signin_btn_icon_dark = 0x7f020059; public static final int common_signin_btn_icon_disabled_dark = 0x7f02005a; public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f02005b; public static final int common_signin_btn_icon_disabled_focus_light = 0x7f02005c; public static final int common_signin_btn_icon_disabled_light = 0x7f02005d; public static final int common_signin_btn_icon_focus_dark = 0x7f02005e; public static final int common_signin_btn_icon_focus_light = 0x7f02005f; public static final int common_signin_btn_icon_light = 0x7f020060; public static final int common_signin_btn_icon_normal_dark = 0x7f020061; public static final int common_signin_btn_icon_normal_light = 0x7f020062; public static final int common_signin_btn_icon_pressed_dark = 0x7f020063; public static final int common_signin_btn_icon_pressed_light = 0x7f020064; public static final int common_signin_btn_text_dark = 0x7f020065; public static final int common_signin_btn_text_disabled_dark = 0x7f020066; public static final int common_signin_btn_text_disabled_focus_dark = 0x7f020067; public static final int common_signin_btn_text_disabled_focus_light = 0x7f020068; public static final int common_signin_btn_text_disabled_light = 0x7f020069; public static final int common_signin_btn_text_focus_dark = 0x7f02006a; public static final int common_signin_btn_text_focus_light = 0x7f02006b; public static final int common_signin_btn_text_light = 0x7f02006c; public static final int common_signin_btn_text_normal_dark = 0x7f02006d; public static final int common_signin_btn_text_normal_light = 0x7f02006e; public static final int common_signin_btn_text_pressed_dark = 0x7f02006f; public static final int common_signin_btn_text_pressed_light = 0x7f020070; public static final int ic_plusone_medium_off_client = 0x7f020072; public static final int ic_plusone_small_off_client = 0x7f020073; public static final int ic_plusone_standard_off_client = 0x7f020074; public static final int ic_plusone_tall_off_client = 0x7f020075; public static final int powered_by_google_dark = 0x7f020078; public static final int powered_by_google_light = 0x7f020079; } public static final class id { public static final int adjust_height = 0x7f090012; public static final int adjust_width = 0x7f090013; public static final int book_now = 0x7f090027; public static final int buyButton = 0x7f090023; public static final int buy_now = 0x7f090028; public static final int buy_with_google = 0x7f090029; public static final int classic = 0x7f09002b; public static final int donate_with_google = 0x7f09002a; public static final int grayscale = 0x7f09002c; public static final int holo_dark = 0x7f09001e; public static final int holo_light = 0x7f09001f; public static final int hybrid = 0x7f090014; public static final int match_parent = 0x7f090025; public static final int monochrome = 0x7f09002d; public static final int none = 0x7f09000d; public static final int normal = 0x7f090005; public static final int production = 0x7f090020; public static final int sandbox = 0x7f090021; public static final int satellite = 0x7f090015; public static final int selectionDetails = 0x7f090024; public static final int slide = 0x7f09000e; public static final int strict_sandbox = 0x7f090022; public static final int terrain = 0x7f090016; public static final int wrap_content = 0x7f090026; } public static final class integer { public static final int google_play_services_version = 0x7f0a0001; } public static final class raw { public static final int gtm_analytics = 0x7f050000; } public static final class string { public static final int accept = 0x7f0b0010; public static final int common_android_wear_notification_needs_update_text = 0x7f0b0014; public static final int common_android_wear_update_text = 0x7f0b0015; public static final int common_android_wear_update_title = 0x7f0b0016; public static final int common_google_play_services_enable_button = 0x7f0b0017; public static final int common_google_play_services_enable_text = 0x7f0b0018; public static final int common_google_play_services_enable_title = 0x7f0b0019; public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f0b001a; public static final int common_google_play_services_install_button = 0x7f0b001b; public static final int common_google_play_services_install_text_phone = 0x7f0b001c; public static final int common_google_play_services_install_text_tablet = 0x7f0b001d; public static final int common_google_play_services_install_title = 0x7f0b001e; public static final int common_google_play_services_invalid_account_text = 0x7f0b001f; public static final int common_google_play_services_invalid_account_title = 0x7f0b0020; public static final int common_google_play_services_needs_enabling_title = 0x7f0b0021; public static final int common_google_play_services_network_error_text = 0x7f0b0022; public static final int common_google_play_services_network_error_title = 0x7f0b0023; public static final int common_google_play_services_notification_needs_installation_title = 0x7f0b0024; public static final int common_google_play_services_notification_needs_update_title = 0x7f0b0025; public static final int common_google_play_services_notification_ticker = 0x7f0b0026; public static final int common_google_play_services_sign_in_failed_text = 0x7f0b0027; public static final int common_google_play_services_sign_in_failed_title = 0x7f0b0028; public static final int common_google_play_services_unknown_issue = 0x7f0b0029; public static final int common_google_play_services_unsupported_text = 0x7f0b002a; public static final int common_google_play_services_unsupported_title = 0x7f0b002b; public static final int common_google_play_services_update_button = 0x7f0b002c; public static final int common_google_play_services_update_text = 0x7f0b002d; public static final int common_google_play_services_update_title = 0x7f0b002e; public static final int common_open_on_phone = 0x7f0b002f; public static final int common_signin_button_text = 0x7f0b0030; public static final int common_signin_button_text_long = 0x7f0b0031; public static final int commono_google_play_services_api_unavailable_text = 0x7f0b0032; public static final int create_calendar_message = 0x7f0b0033; public static final int create_calendar_title = 0x7f0b0034; public static final int decline = 0x7f0b0035; public static final int store_picture_message = 0x7f0b0038; public static final int store_picture_title = 0x7f0b0039; public static final int wallet_buy_button_place_holder = 0x7f0b003b; } public static final class style { public static final int Theme_IAPTheme = 0x7f0c0035; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0c0036; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0c0037; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0c0038; public static final int WalletFragmentDefaultStyle = 0x7f0c0039; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010055, 0x7f010056, 0x7f010057 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] CustomWalletTheme = { 0x7f010059 }; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] LoadingImageView = { 0x7f01005c, 0x7f01005d, 0x7f01005e }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f01005f, 0x7f010060, 0x7f010061, 0x7f010062, 0x7f010063, 0x7f010064, 0x7f010065, 0x7f010066, 0x7f010067, 0x7f010068, 0x7f010069, 0x7f01006a, 0x7f01006b, 0x7f01006c, 0x7f01006d, 0x7f01006e }; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] WalletFragmentOptions = { 0x7f010081, 0x7f010082, 0x7f010083, 0x7f010084 }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f010085, 0x7f010086, 0x7f010087, 0x7f010088, 0x7f010089, 0x7f01008a, 0x7f01008b, 0x7f01008c, 0x7f01008d, 0x7f01008e, 0x7f01008f }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
gpl-3.0
karamelchef/kandy
CloudServiceRecommender/src/main/java/se/kth/kandy/ejb/restservice/ApplicationConfig.java
1020
/* * 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 se.kth.kandy.ejb.restservice; import java.util.Set; import javax.ws.rs.core.Application; /** * * @author Hossein */ @javax.ws.rs.ApplicationPath("api") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); addRestResourceClasses(resources); return resources; } /** * Do not modify addRestResourceClasses() method. It is automatically populated with all resources defined in the * project. If required, comment out calling this method in getClasses(). */ private void addRestResourceClasses( Set<Class<?>> resources) { resources.add(se.kth.kandy.ejb.restservice.ClusterCostFacadeREST.class); resources.add(se.kth.kandy.ejb.restservice.KaramelStatisticsFacadeREST.class); } }
gpl-3.0
larseknu/android_programmering_2014
Lecture 08/src/com/capgemini/playingwithsqlite/ShowListAdapter.java
1116
package com.capgemini.playingwithsqlite; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ShowListAdapter extends ArrayAdapter<Show> { public ShowListAdapter(Context context, int resource) { super(context, resource); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater viewInflater = LayoutInflater.from(getContext()); view = viewInflater.inflate(R.layout.show_list_row, null); } Show show = getItem(position); if (show != null) { TextView title = (TextView) view.findViewById(R.id.show_title); TextView year = (TextView) view.findViewById(R.id.year); if (title != null) { title.setText(show.getTitle()); } if (year != null) { year.setText(show.getYear() + ""); } } return view; } }
gpl-3.0
proninyaroslav/libretorrent
app/src/main/java/org/proninyaroslav/libretorrent/core/model/session/TorrentSessionImpl.java
53404
/* * Copyright (C) 2016-2022 Yaroslav Pronin <proninyaroslav@mail.ru> * * This file is part of LibreTorrent. * * LibreTorrent 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. * * LibreTorrent 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 LibreTorrent. If not, see <http://www.gnu.org/licenses/>. */ package org.proninyaroslav.libretorrent.core.model.session; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; import org.apache.commons.io.FileUtils; import org.libtorrent4j.AlertListener; import org.libtorrent4j.AnnounceEntry; import org.libtorrent4j.ErrorCode; import org.libtorrent4j.Pair; import org.libtorrent4j.SessionHandle; import org.libtorrent4j.SessionManager; import org.libtorrent4j.SessionParams; import org.libtorrent4j.SettingsPack; import org.libtorrent4j.Sha1Hash; import org.libtorrent4j.TcpEndpoint; import org.libtorrent4j.TorrentFlags; import org.libtorrent4j.TorrentHandle; import org.libtorrent4j.TorrentInfo; import org.libtorrent4j.Vectors; import org.libtorrent4j.WebSeedEntry; import org.libtorrent4j.alerts.Alert; import org.libtorrent4j.alerts.AlertType; import org.libtorrent4j.alerts.ListenFailedAlert; import org.libtorrent4j.alerts.MetadataReceivedAlert; import org.libtorrent4j.alerts.PortmapErrorAlert; import org.libtorrent4j.alerts.SessionErrorAlert; import org.libtorrent4j.alerts.TorrentAlert; import org.libtorrent4j.swig.add_torrent_params; import org.libtorrent4j.swig.alert; import org.libtorrent4j.swig.alert_category_t; import org.libtorrent4j.swig.bdecode_node; import org.libtorrent4j.swig.byte_vector; import org.libtorrent4j.swig.create_torrent; import org.libtorrent4j.swig.entry; import org.libtorrent4j.swig.error_code; import org.libtorrent4j.swig.int_vector; import org.libtorrent4j.swig.ip_filter; import org.libtorrent4j.swig.libtorrent; import org.libtorrent4j.swig.session_params; import org.libtorrent4j.swig.settings_pack; import org.libtorrent4j.swig.sha1_hash; import org.libtorrent4j.swig.string_vector; import org.libtorrent4j.swig.tcp_endpoint_vector; import org.libtorrent4j.swig.torrent_flags_t; import org.libtorrent4j.swig.torrent_handle; import org.libtorrent4j.swig.torrent_info; import org.proninyaroslav.libretorrent.core.exception.DecodeException; import org.proninyaroslav.libretorrent.core.exception.TorrentAlreadyExistsException; import org.proninyaroslav.libretorrent.core.exception.UnknownUriException; import org.proninyaroslav.libretorrent.core.model.AddTorrentParams; import org.proninyaroslav.libretorrent.core.model.TorrentEngineListener; import org.proninyaroslav.libretorrent.core.model.data.MagnetInfo; import org.proninyaroslav.libretorrent.core.model.data.Priority; import org.proninyaroslav.libretorrent.core.model.data.SessionStats; import org.proninyaroslav.libretorrent.core.model.data.entity.FastResume; import org.proninyaroslav.libretorrent.core.model.data.entity.Torrent; import org.proninyaroslav.libretorrent.core.model.data.metainfo.TorrentMetaInfo; import org.proninyaroslav.libretorrent.core.settings.SessionSettings; import org.proninyaroslav.libretorrent.core.storage.TorrentRepository; import org.proninyaroslav.libretorrent.core.system.FileDescriptorWrapper; import org.proninyaroslav.libretorrent.core.system.FileSystemFacade; import org.proninyaroslav.libretorrent.core.system.SystemFacade; import org.proninyaroslav.libretorrent.core.utils.Utils; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class TorrentSessionImpl extends SessionManager implements TorrentSession { private static final String TAG = TorrentSession.class.getSimpleName(); private static final int[] INNER_LISTENER_TYPES = new int[] { AlertType.ADD_TORRENT.swig(), AlertType.METADATA_RECEIVED.swig(), AlertType.SESSION_ERROR.swig(), AlertType.PORTMAP_ERROR.swig(), AlertType.LISTEN_FAILED.swig(), AlertType.LOG.swig(), AlertType.DHT_LOG.swig(), AlertType.PEER_LOG.swig(), AlertType.PORTMAP_LOG.swig(), AlertType.TORRENT_LOG.swig(), AlertType.SESSION_STATS.swig() }; /* Base unit in KiB. Used for create torrent */ private static final int[] pieceSize = {0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; private static final String PEER_FINGERPRINT = "Lr"; /* called peer id */ private static final String USER_AGENT = "LibreTorrent %s"; private InnerListener innerListener; private ConcurrentLinkedQueue<TorrentEngineListener> listeners = new ConcurrentLinkedQueue<>(); private SessionSettings settings = new SessionSettings(); private ReentrantLock settingsLock = new ReentrantLock(); private Queue<LoadTorrentTask> restoreTorrentsQueue = new LinkedList<>(); private ExecutorService loadTorrentsExec; private ConcurrentHashMap<String, TorrentDownload> torrentTasks = new ConcurrentHashMap<>(); /* Wait list for non added magnets */ private HashSet<String> magnets = new HashSet<>(); private ConcurrentHashMap<String, byte[]> loadedMagnets = new ConcurrentHashMap<>(); private ArrayList<String> addTorrentsList = new ArrayList<>(); private ReentrantLock syncMagnet = new ReentrantLock(); private CompositeDisposable disposables = new CompositeDisposable(); private TorrentRepository repo; private FileSystemFacade fs; private SystemFacade system; private SessionLogger sessionLogger; private boolean started; private AtomicBoolean stopRequested; private Thread parseIpFilterThread; public TorrentSessionImpl(@NonNull TorrentRepository repo, @NonNull FileSystemFacade fs, @NonNull SystemFacade system) { super(false); this.stopRequested = new AtomicBoolean(false); this.started = false; this.sessionLogger = new SessionLogger(); this.repo = repo; this.fs = fs; this.system = system; innerListener = new InnerListener(); loadTorrentsExec = Executors.newCachedThreadPool(); } @Override public SessionLogger getLogger() { return sessionLogger; } @Override public void addListener(TorrentEngineListener listener) { listeners.add(listener); } @Override public void removeListener(TorrentEngineListener listener) { listeners.remove(listener); } @Override public TorrentDownload getTask(String id) { return torrentTasks.get(id); } public void setSettings(@NonNull SessionSettings settings) { setSettings(settings, true); } @Override public void setSettings(@NonNull SessionSettings settings, boolean keepPort) { settingsLock.lock(); try { this.settings = settings; applySettings(settings, keepPort); } finally { settingsLock.unlock(); } } @Override public SessionSettings getSettings() { settingsLock.lock(); try { return new SessionSettings(settings); } finally { settingsLock.unlock(); } } @Override public byte[] getLoadedMagnet(String hash) { return loadedMagnets.get(hash); } @Override public void removeLoadedMagnet(String hash) { loadedMagnets.remove(hash); } private boolean operationNotAllowed() { return swig() == null || stopRequested.get(); } @Override public Torrent addTorrent( @NonNull AddTorrentParams params, boolean removeFile ) throws IOException, TorrentAlreadyExistsException, DecodeException, UnknownUriException { if (operationNotAllowed()) return null; Torrent torrent = new Torrent( params.sha1hash, params.downloadPath, params.name, params.addPaused, System.currentTimeMillis(), params.sequentialDownload, params.firstLastPiecePriority ); byte[] bencode = null; if (params.fromMagnet) { bencode = getLoadedMagnet(params.sha1hash); removeLoadedMagnet(params.sha1hash); if (bencode == null) torrent.setMagnetUri(params.source); } if (repo.getTorrentById(torrent.id) != null) { mergeTorrent(torrent.id, params, bencode); throw new TorrentAlreadyExistsException(); } repo.addTorrent(torrent); if (!params.tags.isEmpty()) { repo.replaceTags(torrent.id, params.tags); } if (!torrent.isDownloadingMetadata()) { /* * This is possible if the magnet data came after Torrent object * has already been created and nothing is known about the received data */ if (params.filePriorities.length == 0) { try (FileDescriptorWrapper w = fs.getFD(Uri.parse(params.source))) { FileDescriptor outFd = w.open("r"); try (FileInputStream is = new FileInputStream(outFd)) { TorrentMetaInfo info = new TorrentMetaInfo(is); params.filePriorities = new Priority[info.fileCount]; Arrays.fill(params.filePriorities, Priority.DEFAULT); } } catch (FileNotFoundException e) { /* Ignore */ } } } try { download(torrent.id, params, bencode); } catch (Exception e) { repo.deleteTorrent(torrent); throw e; } finally { if (removeFile && !params.fromMagnet) { try { fs.deleteFile(Uri.parse(params.source)); } catch (UnknownUriException e) { // Ignore } } } return torrent; } private void download(String id, AddTorrentParams params, byte[] bencode) throws IOException, UnknownUriException { if (operationNotAllowed()) return; cancelFetchMagnet(id); Torrent torrent = repo.getTorrentById(id); if (torrent == null) throw new IOException("Torrent " + id + " is null"); addTorrentsList.add(params.sha1hash); String path = fs.makeFileSystemPath(params.downloadPath); File saveDir = new File(path); if (torrent.isDownloadingMetadata()) { download(params.source, saveDir, params.addPaused, params.sequentialDownload); return; } TorrentDownload task = torrentTasks.get(torrent.id); if (task != null) task.remove(false); if (params.fromMagnet) { download(bencode, saveDir, params.filePriorities, params.sequentialDownload, params.addPaused, null); } else { try (FileDescriptorWrapper w = fs.getFD(Uri.parse(params.source))) { FileDescriptor fd = w.open("r"); try (FileInputStream fin = new FileInputStream(fd)) { FileChannel chan = fin.getChannel(); download(new TorrentInfo(chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size())), saveDir, params.filePriorities, params.sequentialDownload, params.addPaused, null); } } } } @Override public void deleteTorrent(@NonNull String id, boolean withFiles) { if (operationNotAllowed()) return; TorrentDownload task = getTask(id); if (task == null) { Torrent torrent = repo.getTorrentById(id); if (torrent != null) repo.deleteTorrent(torrent); notifyListeners((listener) -> listener.onTorrentRemoved(id)); } else { task.remove(withFiles); } } @Override public void restoreTorrents() { if (operationNotAllowed()) return; for (Torrent torrent : repo.getAllTorrents()) { if (torrent == null || isTorrentAlreadyRunning(torrent.id)) continue; String path = null; try { path = fs.makeFileSystemPath(torrent.downloadPath); } catch (UnknownUriException e) { Log.e(TAG, "Unable to restore torrent:"); Log.e(TAG, Log.getStackTraceString(e)); } LoadTorrentTask loadTask = new LoadTorrentTask(torrent.id); if (path != null && torrent.isDownloadingMetadata()) { loadTask.putMagnet( torrent.getMagnet(), new File(path), torrent.manuallyPaused, torrent.sequentialDownload ); } restoreTorrentsQueue.add(loadTask); } runNextLoadTorrentTask(); } @Override public MagnetInfo fetchMagnet(@NonNull String uri) throws Exception { if (operationNotAllowed()) return null; org.libtorrent4j.AddTorrentParams params = parseMagnetUri(uri); org.libtorrent4j.AddTorrentParams resParams = fetchMagnet(params); if (resParams == null) return null; List<Priority> priorities = Arrays.asList(PriorityConverter.convert(resParams.filePriorities())); return new MagnetInfo(uri, resParams.getInfoHashes().getBest().toHex(), resParams.getName(), priorities); } @Override public MagnetInfo parseMagnet(@NonNull String uri) { org.libtorrent4j.AddTorrentParams p = org.libtorrent4j.AddTorrentParams.parseMagnetUri(uri); String sha1hash = p.getInfoHashes().getBest().toHex(); String name = (TextUtils.isEmpty(p.getName()) ? sha1hash : p.getName()); return new MagnetInfo(uri, sha1hash, name, Arrays.asList(PriorityConverter.convert(p.filePriorities()))); } private org.libtorrent4j.AddTorrentParams fetchMagnet(org.libtorrent4j.AddTorrentParams params) throws Exception { if (operationNotAllowed()) return null; add_torrent_params p = params.swig(); sha1_hash hash = p.getInfo_hashes().get_best(); if (hash == null) return null; String strHash = hash.to_hex(); torrent_handle th = null; boolean add = false; try { syncMagnet.lock(); try { th = swig().find_torrent(hash); if (th != null && th.is_valid()) { torrent_info ti = th.torrent_file_ptr(); if (ti != null && ti.is_valid()) { byte[] b = createTorrent(p, ti); if (b != null) loadedMagnets.put(hash.to_hex(), b); } notifyListeners((listener) -> listener.onMagnetLoaded(strHash, ti != null ? new TorrentInfo(ti).bencode() : null)); } else { add = true; } if (add) { magnets.add(strHash); if (TextUtils.isEmpty(p.getName())) p.setName(strHash); torrent_flags_t flags = p.getFlags(); flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); flags = flags.or_(TorrentFlags.UPLOAD_MODE); flags = flags.or_(TorrentFlags.STOP_WHEN_READY); p.setFlags(flags); addDefaultTrackers(p); error_code ec = new error_code(); th = swig().add_torrent(p, ec); if (!th.is_valid() || ec.failed()) magnets.remove(strHash); th.resume(); } } finally { syncMagnet.unlock(); } } catch (Exception e) { if (add && th != null && th.is_valid()) swig().remove_torrent(th); throw new Exception(e); } return new org.libtorrent4j.AddTorrentParams(p); } private org.libtorrent4j.AddTorrentParams parseMagnetUri(String uri) { error_code ec = new error_code(); add_torrent_params p = libtorrent.parse_magnet_uri(uri, ec); if (ec.value() != 0) throw new IllegalArgumentException(ec.message()); return new org.libtorrent4j.AddTorrentParams(p); } @Override public void cancelFetchMagnet(@NonNull String infoHash) { if (operationNotAllowed() || !magnets.contains(infoHash)) return; magnets.remove(infoHash); TorrentHandle th = find(Sha1Hash.parseHex(infoHash)); if (th != null && th.isValid()) remove(th, SessionHandle.DELETE_FILES); } private void mergeTorrent(String id, AddTorrentParams params, byte[] bencode) { if (operationNotAllowed()) { return; } var task = torrentTasks.get(id); if (task == null) { return; } task.setSequentialDownload(params.sequentialDownload); if (params.filePriorities != null) { task.prioritizeFiles(params.filePriorities); } task.setFirstLastPiecePriority(params.firstLastPiecePriority); try { var ti = (bencode == null ? new TorrentInfo(new File(Uri.parse(params.source).getPath())) : new TorrentInfo(bencode)); var th = find(Sha1Hash.parseHex(id)); if (th != null) { for (var tracker : ti.trackers()) { th.addTracker(tracker); } for (var webSeed : ti.webSeeds()) { th.addUrlSeed(webSeed.url()); } } task.saveResumeData(true); } catch (Exception e) { /* Ignore */ } if (params.addPaused) { task.pauseManually(); } else { task.resumeManually(); } } @Override public long getDownloadSpeed() { return stats().downloadRate(); } @Override public long getUploadSpeed() { return stats().uploadRate(); } @Override public long getTotalDownload() { return stats().totalDownload(); } @Override public long getTotalUpload() { return stats().totalUpload(); } @Override public int getDownloadSpeedLimit() { SettingsPack settingsPack = settings(); return (settingsPack == null ? -1 : settingsPack.downloadRateLimit()); } @Override public int getUploadSpeedLimit() { SettingsPack settingsPack = settings(); return (settingsPack == null ? -1 : settingsPack.uploadRateLimit()); } @Override public int getListenPort() { return (swig() == null ? -1 : swig().listen_port()); } @Override public long getDhtNodes() { return stats().dhtNodes(); } @Override public void enableIpFilter(@NonNull Uri path) { if (operationNotAllowed()) return; if (parseIpFilterThread != null && !parseIpFilterThread.isInterrupted()) parseIpFilterThread.interrupt(); parseIpFilterThread = new Thread(() -> { if (operationNotAllowed() || Thread.interrupted()) return; IPFilterImpl filter = new IPFilterImpl(); int ruleCount = new IPFilterParser().parseFile(path, fs, filter); if (Thread.interrupted()) return; if (ruleCount != 0 && swig() != null && !operationNotAllowed()) swig().set_ip_filter(filter.getFilter()); notifyListeners((listener) -> listener.onIpFilterParsed(ruleCount)); }); parseIpFilterThread.start(); } @Override public void disableIpFilter() { if (operationNotAllowed()) return; if (parseIpFilterThread != null && !parseIpFilterThread.isInterrupted()) parseIpFilterThread.interrupt(); swig().set_ip_filter(new ip_filter()); } @Override public void pauseAll() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.pause(); } } @Override public void resumeAll() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.resume(); } } @Override public void pauseAllManually() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.pauseManually(); } } @Override public void resumeAllManually() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.resumeManually(); } } @Override public void setMaxConnectionsPerTorrent(int connections) { if (operationNotAllowed()) return; settings.connectionsLimitPerTorrent = connections; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.setMaxConnections(connections); } } @Override public void setMaxUploadsPerTorrent(int uploads) { if (operationNotAllowed()) return; settings.uploadsLimitPerTorrent = uploads; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.setMaxUploads(uploads); } } @Override public void setAutoManaged(boolean autoManaged) { if (operationNotAllowed()) return; settings.autoManaged = autoManaged; for (TorrentDownload task : torrentTasks.values()) task.setAutoManaged(autoManaged); } @Override public boolean isDHTEnabled() { SettingsPack sp = settings(); return sp != null && sp.isEnableDht(); } @Override public boolean isPeXEnabled() { /* PeX enabled by default in session_handle.session_flags_t::add_default_plugins */ return true; } @Override public void start() { if (isRunning()) return; SessionParams params = loadSettings(); SettingsPack settingsPack = params.getSettings(); settings_pack sp = settingsPack.swig(); sp.set_str(settings_pack.string_types.dht_bootstrap_nodes.swigValue(), dhtBootstrapNodes()); sp.set_bool(settings_pack.bool_types.enable_ip_notifier.swigValue(), false); sp.set_int(settings_pack.int_types.alert_queue_size.swigValue(), 5000); sp.set_bool(settings_pack.bool_types.announce_to_all_trackers.swigValue(), true); sp.set_bool(settings_pack.bool_types.announce_to_all_tiers.swigValue(), true); String versionName = system.getAppVersionName(); if (versionName != null) { int[] version = Utils.getVersionComponents(versionName); String fingerprint = libtorrent.generate_fingerprint(PEER_FINGERPRINT, version[0], version[1], version[2], 0); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), fingerprint); String userAgent = String.format(USER_AGENT, Utils.getAppVersionNumber(versionName)); sp.set_str(settings_pack.string_types.user_agent.swigValue(), userAgent); Log.i(TAG, "Peer fingerprint: " + sp.get_str(settings_pack.string_types.peer_fingerprint.swigValue())); Log.i(TAG, "User agent: " + sp.get_str(settings_pack.string_types.user_agent.swigValue())); } if (settings.useRandomPort) { setRandomPort(settings); } settingsToSettingsPack(settings, params.getSettings()); super.start(params); } @Override public void requestStop() { if (stopRequested.getAndSet(true)) return; saveAllResumeData(); stopTasks(); } private void stopTasks() { disposables.add(Observable.fromIterable(torrentTasks.values()) .filter(Objects::nonNull) .map(TorrentDownload::requestStop) .toList() .flatMapCompletable(Completable::merge) /* Wait for all torrents */ .subscribe( this::handleStoppingTasks, (err) -> { Log.e(TAG, "Error stopping torrents: " + Log.getStackTraceString(err)); handleStoppingTasks(); } )); } private void handleStoppingTasks() { /* Handles must be destructed before the session is destructed */ torrentTasks.clear(); checkStop(); } private void checkStop() { if (stopRequested.get() && torrentTasks.isEmpty() && addTorrentsList.isEmpty()) super.stop(); } private void saveAllResumeData() { for (TorrentDownload task : torrentTasks.values()) { if (task == null || task.hasMissingFiles()) continue; task.saveResumeData(false); } } @Override public boolean isRunning() { return super.isRunning() && started; } @Override public long dhtNodes() { return super.dhtNodes(); } @Override public int[] getPieceSizeList() { return pieceSize; } @Override protected void onBeforeStart() { addListener(torrentTaskListener); addListener(innerListener); } @Override protected void onAfterStart() { /* * Overwrite default behaviour of super.start() * and enable logging in onAfterStart() */ if (settings.logging) { SettingsPack sp = settings(); if (sp == null) return; sp.setInteger(settings_pack.int_types.alert_mask.swigValue(), getAlertMask(settings).to_int()); applySettingsPack(sp); enableSessionLogger(true); } saveSettings(); started = true; disposables.add(Completable.fromRunnable(() -> notifyListeners(TorrentEngineListener::onSessionStarted)) .subscribeOn(Schedulers.io()) .subscribe()); } private void enableSessionLogger(boolean enable) { if (enable) { sessionLogger.resume(); } else { sessionLogger.stopRecording(); sessionLogger.pause(); sessionLogger.clean(); } } @Override protected void onBeforeStop() { disposables.clear(); started = false; enableSessionLogger(false); parseIpFilterThread = null; magnets.clear(); loadedMagnets.clear(); removeListener(torrentTaskListener); removeListener(innerListener); } @Override protected void onAfterStop() { notifyListeners(TorrentEngineListener::onSessionStopped); stopRequested.set(false); } @Override protected void onApplySettings(SettingsPack sp) { saveSettings(); } private final TorrentEngineListener torrentTaskListener = new TorrentEngineListener() { @Override public void onTorrentRemoved(@NonNull String id) { torrentTasks.remove(id); } }; private final class InnerListener implements AlertListener { @Override public int[] types() { return INNER_LISTENER_TYPES; } @Override public void alert(Alert<?> alert) { switch (alert.type()) { case ADD_TORRENT: TorrentAlert<?> torrentAlert = (TorrentAlert<?>)alert; TorrentHandle th = find(torrentAlert.handle().infoHash()); if (th == null) break; String hash = th.infoHash().toHex(); if (magnets.contains(hash)) break; torrentTasks.put(hash, newTask(th, hash)); if (addTorrentsList.contains(hash)) notifyListeners((listener) -> listener.onTorrentAdded(hash)); else notifyListeners((listener) -> listener.onTorrentLoaded(hash)); addTorrentsList.remove(hash); checkStop(); runNextLoadTorrentTask(); break; case METADATA_RECEIVED: handleMetadata(((MetadataReceivedAlert)alert)); break; case SESSION_STATS: handleStats(); break; default: checkError(alert); if (settings.logging) sessionLogger.send(alert); break; } } } private void checkError(Alert<?> alert) { notifyListeners((listener) -> { String msg = null; switch (alert.type()) { case SESSION_ERROR: { SessionErrorAlert sessionErrorAlert = (SessionErrorAlert)alert; ErrorCode error = sessionErrorAlert.error(); msg = SessionErrors.getErrorMsg(error); if (!SessionErrors.isNonCritical(error)) listener.onSessionError(msg); break; } case LISTEN_FAILED: { ListenFailedAlert listenFailedAlert = (ListenFailedAlert)alert; msg = SessionErrors.getErrorMsg(listenFailedAlert.error()); ErrorCode error = listenFailedAlert.error(); if (!SessionErrors.isNonCritical(error)) listener.onSessionError(msg); break; } case PORTMAP_ERROR: { PortmapErrorAlert portmapErrorAlert = (PortmapErrorAlert)alert; ErrorCode error = portmapErrorAlert.error(); msg = SessionErrors.getErrorMsg(error); if (!SessionErrors.isNonCritical(error)) listener.onNatError(msg); break; } } if (msg != null) Log.e(TAG, "Session error: " + msg); }); } private void handleMetadata(MetadataReceivedAlert metadataAlert) { TorrentHandle th = metadataAlert.handle(); String hash = th.infoHash().toHex(); if (!magnets.contains(hash)) return; TorrentInfo ti = th.torrentFile(); if (ti != null) loadedMagnets.put(hash, ti.bencode()); remove(th, SessionHandle.DELETE_FILES); notifyListeners((listener) -> listener.onMagnetLoaded(hash, loadedMagnets.get(hash))); } private void handleStats() { if (operationNotAllowed()) return; notifyListeners((listener) -> listener.onSessionStats( new SessionStats(dhtNodes(), getTotalDownload(), getTotalUpload(), getDownloadSpeed(), getUploadSpeed(), getListenPort())) ); } private static String dhtBootstrapNodes() { return "dht.libtorrent.org:25401" + "," + "router.bittorrent.com:6881" + "," + "dht.transmissionbt.com:6881" + "," + /* For IPv6 DHT */ "outer.silotis.us:6881"; } private SessionParams loadSettings() { try { String sessionPath = repo.getSessionFile(); if (sessionPath == null) return new SessionParams(defaultSettingsPack()); File sessionFile = new File(sessionPath); if (sessionFile.exists()) { byte[] data = FileUtils.readFileToByteArray(sessionFile); byte_vector buffer = Vectors.bytes2byte_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { session_params params = session_params.read_session_params(n); /* Prevents GC */ buffer.clear(); return new SessionParams(params); } else { throw new IllegalArgumentException("Can't decode data: " + ec.message()); } } else { return new SessionParams(defaultSettingsPack()); } } catch (Exception e) { Log.e(TAG, "Error loading session state: "); Log.e(TAG, Log.getStackTraceString(e)); return new SessionParams(defaultSettingsPack()); } } private void saveSettings() { try { session_params params = swig().session_state(); entry e = session_params.write_session_params(params); byte[] b = Vectors.byte_vector2bytes(e.bencode()); repo.saveSession(b); } catch (Exception e) { Log.e(TAG, "Error saving session state: "); Log.e(TAG, Log.getStackTraceString(e)); } } private SettingsPack defaultSettingsPack() { SettingsPack sp = new SettingsPack(); settingsToSettingsPack(settings, sp); return sp; } private void settingsToSettingsPack(SessionSettings settings, SettingsPack sp) { sp.activeDownloads(settings.activeDownloads); sp.activeSeeds(settings.activeSeeds); sp.activeLimit(settings.activeLimit); sp.maxPeerlistSize(settings.maxPeerListSize); sp.tickInterval(settings.tickInterval); sp.inactivityTimeout(settings.inactivityTimeout); sp.connectionsLimit(settings.connectionsLimit); sp.listenInterfaces(getIface(settings.inetAddress, settings.portRangeFirst)); sp.setInteger(settings_pack.int_types.max_retry_port_bind.swigValue(), settings.portRangeSecond - settings.portRangeFirst); sp.setEnableDht(settings.dhtEnabled); sp.setBoolean(settings_pack.bool_types.enable_lsd.swigValue(), settings.lsdEnabled); sp.setBoolean(settings_pack.bool_types.enable_incoming_utp.swigValue(), settings.utpEnabled); sp.setBoolean(settings_pack.bool_types.enable_outgoing_utp.swigValue(), settings.utpEnabled); sp.setBoolean(settings_pack.bool_types.enable_upnp.swigValue(), settings.upnpEnabled); sp.setBoolean(settings_pack.bool_types.enable_natpmp.swigValue(), settings.natPmpEnabled); var encryptMode = convertEncryptMode(settings.encryptMode); var encLevel = getAllowedEncryptLevel(settings.encryptMode); sp.setInteger(settings_pack.int_types.in_enc_policy.swigValue(), encryptMode); sp.setInteger(settings_pack.int_types.out_enc_policy.swigValue(), encryptMode); sp.setInteger(settings_pack.int_types.allowed_enc_level.swigValue(), encLevel); sp.uploadRateLimit(settings.uploadRateLimit); sp.downloadRateLimit(settings.downloadRateLimit); sp.anonymousMode(settings.anonymousMode); sp.seedingOutgoingConnections(settings.seedingOutgoingConnections); sp.setInteger(settings_pack.int_types.alert_mask.swigValue(), getAlertMask(settings).to_int()); sp.setBoolean(settings_pack.bool_types.validate_https_trackers.swigValue(), settings.validateHttpsTrackers); applyProxy(settings, sp); } private void applyProxy(SessionSettings settings, SettingsPack sp) { int proxyType = convertProxyType(settings.proxyType, settings.proxyRequiresAuth); sp.setInteger(settings_pack.int_types.proxy_type.swigValue(), proxyType); if (settings.proxyType != SessionSettings.ProxyType.NONE) { sp.setInteger(settings_pack.int_types.proxy_port.swigValue(), settings.proxyPort); sp.setString(settings_pack.string_types.proxy_hostname.swigValue(), settings.proxyAddress); if (settings.proxyRequiresAuth) { sp.setString(settings_pack.string_types.proxy_username.swigValue(), settings.proxyLogin); sp.setString(settings_pack.string_types.proxy_password.swigValue(), settings.proxyPassword); } sp.setBoolean(settings_pack.bool_types.proxy_peer_connections.swigValue(), settings.proxyPeersToo); sp.setBoolean(settings_pack.bool_types.proxy_tracker_connections.swigValue(), true); sp.setBoolean(settings_pack.bool_types.proxy_hostnames.swigValue(), true); } } private alert_category_t getAlertMask(SessionSettings settings) { alert_category_t mask = alert.all_categories; if (!settings.logging) { alert_category_t log_mask = alert.session_log_notification; log_mask = log_mask.or_(alert.torrent_log_notification); log_mask = log_mask.or_(alert.peer_log_notification); log_mask = log_mask.or_(alert.dht_log_notification); log_mask = log_mask.or_(alert.port_mapping_log_notification); log_mask = log_mask.or_(alert.picker_log_notification); mask = mask.and_(log_mask.inv()); } return mask; } private int convertEncryptMode(SessionSettings.EncryptMode mode) { switch (mode) { case ENABLED: return settings_pack.enc_policy.pe_enabled.swigValue(); case FORCED: return settings_pack.enc_policy.pe_forced.swigValue(); default: return settings_pack.enc_policy.pe_disabled.swigValue(); } } private int getAllowedEncryptLevel(SessionSettings.EncryptMode mode) { if (mode == SessionSettings.EncryptMode.FORCED) { return settings_pack.enc_level.pe_rc4.swigValue(); } else { return settings_pack.enc_level.pe_both.swigValue(); } } private int convertProxyType(SessionSettings.ProxyType mode, boolean authRequired) { switch (mode) { case SOCKS4: return settings_pack.proxy_type_t.socks4.swigValue(); case SOCKS5: return (authRequired ? settings_pack.proxy_type_t.socks5_pw.swigValue() : settings_pack.proxy_type_t.socks5.swigValue()); case HTTP: return (authRequired ? settings_pack.proxy_type_t.http_pw.swigValue() : settings_pack.proxy_type_t.http.swigValue()); default: return settings_pack.proxy_type_t.none.swigValue(); } } private String getIface(String inetAddress, int portRangeFirst) { String iface; if (inetAddress.equals(SessionSettings.DEFAULT_INETADDRESS)) { iface = "0.0.0.0:%1$d,[::]:%1$d"; } else { /* IPv6 test */ if (inetAddress.contains(":")) iface = "[" + inetAddress + "]"; else iface = inetAddress; iface = iface + ":%1$d"; } return String.format(iface, portRangeFirst); } private void applySettingsPack(SettingsPack sp) { applySettings(sp); saveSettings(); } private void applySettings(SessionSettings settings, boolean keepPort) { applyMaxStoredLogs(settings); applySessionLoggerFilters(settings); enableSessionLogger(settings.logging); if (!keepPort && settings.useRandomPort) { setRandomPort(settings); } SettingsPack sp = settings(); if (sp != null) { settingsToSettingsPack(settings, sp); applySettingsPack(sp); } } private void setRandomPort(SessionSettings settings) { Pair<Integer, Integer> range = SessionSettings.getRandomRangePort(); settings.portRangeFirst = range.first; settings.portRangeSecond = range.second; } private void applyMaxStoredLogs(SessionSettings settings) { if (settings.maxLogSize == sessionLogger.getMaxStoredLogs()) return; sessionLogger.setMaxStoredLogs(settings.maxLogSize); } private void applySessionLoggerFilters(SessionSettings settings) { disposables.add(Completable.fromRunnable(() -> sessionLogger.applyFilterParams(new SessionLogger.SessionFilterParams( settings.logSessionFilter, settings.logDhtFilter, settings.logPeerFilter, settings.logPortmapFilter, settings.logTorrentFilter ))) .subscribeOn(Schedulers.computation()) .subscribe()); } private byte[] createTorrent(add_torrent_params params, torrent_info ti) { if (operationNotAllowed()) return null; create_torrent ct = new create_torrent(ti); string_vector v = params.getUrl_seeds(); for (int i = 0; i < v.size(); i++) ct.add_url_seed(v.get(i)); string_vector trackers = params.getTrackers(); int_vector tiers = params.getTracker_tiers(); for (int i = 0; i < trackers.size(); i++) ct.add_tracker(trackers.get(i), tiers.get(i)); entry e = ct.generate(); return Vectors.byte_vector2bytes(e.bencode()); } private TorrentDownload newTask(TorrentHandle th, String id) { TorrentDownload task = new TorrentDownloadImpl(this, repo, fs, listeners, id, th, settings.autoManaged); task.setMaxConnections(settings.connectionsLimitPerTorrent); task.setMaxUploads(settings.uploadsLimitPerTorrent); return task; } private interface CallListener { void apply(TorrentEngineListener listener); } private void notifyListeners(@NonNull CallListener l) { for (TorrentEngineListener listener : listeners) { if (listener != null) l.apply(listener); } } private void runNextLoadTorrentTask() { if (operationNotAllowed()) { restoreTorrentsQueue.clear(); return; } LoadTorrentTask task; try { task = restoreTorrentsQueue.poll(); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); return; } if (task != null) loadTorrentsExec.execute(task); } private boolean isTorrentAlreadyRunning(String torrentId) { return torrentTasks.containsKey(torrentId) || addTorrentsList.contains(torrentId); } private final class LoadTorrentTask implements Runnable { private String torrentId; private File saveDir = null; private String magnetUri = null; private boolean isMagnet = false; private boolean magnetPaused = false; private boolean magnetSequentialDownload = false; LoadTorrentTask(String torrentId) { this.torrentId = torrentId; } public void putMagnet( String magnetUri, File saveDir, boolean magnetPaused, boolean magnetSequentialDownload ) { this.magnetUri = magnetUri; this.saveDir = saveDir; this.magnetPaused = magnetPaused; this.magnetSequentialDownload = magnetSequentialDownload; isMagnet = true; } @Override public void run() { try { if (isTorrentAlreadyRunning(torrentId)) return; if (isMagnet) download(magnetUri, saveDir, magnetPaused, magnetSequentialDownload); else restoreDownload(torrentId); } catch (Exception e) { Log.e(TAG, "Unable to restore torrent from previous session: " + torrentId, e); Torrent torrent = repo.getTorrentById(torrentId); if (torrent != null) { torrent.error = e.toString(); repo.updateTorrent(torrent); } notifyListeners((listener) -> listener.onRestoreSessionError(torrentId)); } } } private void download(byte[] bencode, File saveDir, Priority[] priorities, boolean sequentialDownload, boolean paused, List<TcpEndpoint> peers) { download((bencode == null ? null : new TorrentInfo(bencode)), saveDir, priorities, sequentialDownload, paused, peers); } private void download(TorrentInfo ti, File saveDir, Priority[] priorities, boolean sequentialDownload, boolean paused, List<TcpEndpoint> peers) { if (operationNotAllowed()) return; if (ti == null) throw new IllegalArgumentException("Torrent info is null"); if (!ti.isValid()) throw new IllegalArgumentException("Torrent info not valid"); torrent_handle th = swig().find_torrent(ti.swig().info_hash()); if (th != null && th.is_valid()) { /* Found a download with the same hash */ return; } add_torrent_params p = new add_torrent_params(); p.set_ti(ti.swig()); if (saveDir != null) p.setSave_path(saveDir.getAbsolutePath()); if (priorities != null) { if (ti.files().numFiles() != priorities.length) throw new IllegalArgumentException("Priorities count should be equals to the number of files"); byte_vector v = new byte_vector(); for (Priority priority : priorities) { if (priority == null) v.add(org.libtorrent4j.Priority.IGNORE.swig()); else v.add(PriorityConverter.convert(priority).swig()); } p.set_file_priorities(v); } if (peers != null && !peers.isEmpty()) { tcp_endpoint_vector v = new tcp_endpoint_vector(); for (TcpEndpoint endp : peers) v.add(endp.swig()); p.setPeers(v); } torrent_flags_t flags = p.getFlags(); /* Force saving resume data */ flags = flags.or_(TorrentFlags.NEED_SAVE_RESUME); if (settings.autoManaged) flags = flags.or_(TorrentFlags.AUTO_MANAGED); else flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); if (sequentialDownload) flags = flags.or_(TorrentFlags.SEQUENTIAL_DOWNLOAD); else flags = flags.and_(TorrentFlags.SEQUENTIAL_DOWNLOAD.inv()); if (paused) flags = flags.or_(TorrentFlags.PAUSED); else flags = flags.and_(TorrentFlags.PAUSED.inv()); p.setFlags(flags); addDefaultTrackers(p); swig().async_add_torrent(p); } @Override public void download( @NonNull String magnetUri, File saveDir, boolean paused, boolean sequentialDownload ) { if (operationNotAllowed()) return; error_code ec = new error_code(); add_torrent_params p = libtorrent.parse_magnet_uri(magnetUri, ec); if (ec.value() != 0) throw new IllegalArgumentException(ec.message()); sha1_hash info_hash = p.getInfo_hashes().get_best(); if (info_hash == null) return; torrent_handle th = swig().find_torrent(info_hash); if (th != null && th.is_valid()) { /* Found a download with the same hash */ return; } if (saveDir != null) p.setSave_path(saveDir.getAbsolutePath()); if (TextUtils.isEmpty(p.getName())) p.setName(info_hash.to_hex()); torrent_flags_t flags = p.getFlags(); flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); if (paused) flags = flags.or_(TorrentFlags.PAUSED); else flags = flags.and_(TorrentFlags.PAUSED.inv()); if (sequentialDownload) flags = flags.or_(TorrentFlags.SEQUENTIAL_DOWNLOAD); else flags = flags.and_(TorrentFlags.SEQUENTIAL_DOWNLOAD.inv()); p.setFlags(flags); addDefaultTrackers(p); swig().async_add_torrent(p); } private void addDefaultTrackers(add_torrent_params p) { String[] defaultTrackers = getSettings().defaultTrackersList; if (defaultTrackers != null && defaultTrackers.length > 0) { string_vector v = p.getTrackers(); if (v == null) { v = new string_vector(); } v.addAll(Arrays.asList(defaultTrackers)); p.setTrackers(v); } } @Override public void setDefaultTrackersList(@NonNull String[] trackersList) { settings.defaultTrackersList = trackersList; } private void restoreDownload(String id) throws IOException { if (operationNotAllowed()) return; FastResume fastResume = repo.getFastResumeById(id); if (fastResume == null) throw new IOException("Fast resume data not found"); error_code ec = new error_code(); byte_vector buffer = Vectors.bytes2byte_vector(fastResume.data); bdecode_node n = new bdecode_node(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret != 0) throw new IllegalArgumentException("Can't decode data: " + ec.message()); ec.clear(); add_torrent_params p = libtorrent.read_resume_data(n, ec); if (ec.value() != 0) throw new IllegalArgumentException("Unable to read the resume data: " + ec.message()); torrent_flags_t flags = p.getFlags(); /* Disable force saving resume data, because they already have */ flags = flags.and_(TorrentFlags.NEED_SAVE_RESUME.inv()); if (settings.autoManaged) flags = flags.or_(TorrentFlags.AUTO_MANAGED); else flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); p.setFlags(flags); /* After reading the metadata some time may have passed */ if (operationNotAllowed()) return; swig().async_add_torrent(p); } }
gpl-3.0
Guerra24/NanoUI
nanoui-core/src/main/java/net/luxvacuos/nanoui/rendering/shaders/data/Attribute.java
1020
/* * This file is part of NanoUI * * Copyright (C) 2016-2018 Guerra24 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.luxvacuos.nanoui.rendering.shaders.data; public class Attribute { private int id; private String name; public Attribute(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } }
gpl-3.0
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/persistence/connection/DefaultConnectionProfileData.java
4695
package net.thevpc.upa.impl.persistence.connection; /** * Created by vpc on 8/7/15. */ public class DefaultConnectionProfileData { private String databaseProductName ; private String databaseProductVersion ; private String connectionDriverName ; private String connectionDriverVersion ; private String server ; private String port ; private String pathAndName ; private String paramsString; @Override public String toString() { return "DefaultConnectionProfileData{" + "databaseProductName='" + databaseProductName + '\'' + ", databaseProductVersion='" + databaseProductVersion + '\'' + ", connectionDriverName='" + connectionDriverName + '\'' + ", connectionDriverVersion='" + connectionDriverVersion + '\'' + ", server='" + server + '\'' + ", port='" + port + '\'' + ", pathAndName='" + pathAndName + '\'' + ", params='" + paramsString + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DefaultConnectionProfileData that = (DefaultConnectionProfileData) o; if (databaseProductName != null ? !databaseProductName.equals(that.databaseProductName) : that.databaseProductName != null) return false; if (databaseProductVersion != null ? !databaseProductVersion.equals(that.databaseProductVersion) : that.databaseProductVersion != null) return false; if (connectionDriverName != null ? !connectionDriverName.equals(that.connectionDriverName) : that.connectionDriverName != null) return false; if (connectionDriverVersion != null ? !connectionDriverVersion.equals(that.connectionDriverVersion) : that.connectionDriverVersion != null) return false; if (server != null ? !server.equals(that.server) : that.server != null) return false; if (port != null ? !port.equals(that.port) : that.port != null) return false; if (pathAndName != null ? !pathAndName.equals(that.pathAndName) : that.pathAndName != null) return false; return paramsString != null ? paramsString.equals(that.paramsString) : that.paramsString == null; } @Override public int hashCode() { int result = databaseProductName != null ? databaseProductName.hashCode() : 0; result = 31 * result + (databaseProductVersion != null ? databaseProductVersion.hashCode() : 0); result = 31 * result + (connectionDriverName != null ? connectionDriverName.hashCode() : 0); result = 31 * result + (connectionDriverVersion != null ? connectionDriverVersion.hashCode() : 0); result = 31 * result + (server != null ? server.hashCode() : 0); result = 31 * result + (port != null ? port.hashCode() : 0); result = 31 * result + (pathAndName != null ? pathAndName.hashCode() : 0); result = 31 * result + (paramsString != null ? paramsString.hashCode() : 0); return result; } public String getDatabaseProductName() { return databaseProductName; } public void setDatabaseProductName(String databaseProductName) { this.databaseProductName = databaseProductName; } public String getDatabaseProductVersion() { return databaseProductVersion; } public void setDatabaseProductVersion(String databaseProductVersion) { this.databaseProductVersion = databaseProductVersion; } public String getConnectionDriverName() { return connectionDriverName; } public void setConnectionDriverName(String connectionDriverName) { this.connectionDriverName = connectionDriverName; } public String getConnectionDriverVersion() { return connectionDriverVersion; } public void setConnectionDriverVersion(String connectionDriverVersion) { this.connectionDriverVersion = connectionDriverVersion; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getPathAndName() { return pathAndName; } public void setPathAndName(String pathAndName) { this.pathAndName = pathAndName; } public String getParamsString() { return paramsString; } public void setParamsString(String paramsString) { this.paramsString = paramsString; } }
gpl-3.0
ISA-tools/Automacron
src/main/java/org/isatools/macros/utils/MotifProcessingUtils.java
8126
package org.isatools.macros.utils; import org.apache.commons.collections15.map.ListOrderedMap; import org.isatools.macros.motiffinder.Motif; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by the ISA team * * @author Eamonn Maguire (eamonnmag@gmail.com) * <p/> * Date: 31/10/2012 * Time: 07:57 */ public class MotifProcessingUtils { private static final String SINGLE_MOTIF_PATTERN = "((:|\\*)*\\{*[\\w\\s]*#[\\w\\s]*(:|,|>)*[\\w\\s]*:*[\\w\\s]*\\}*)"; private static final String WORD_PATTERN = "[ref]*_*(\\w+\\s*)+_*(\\d+)*"; private static final String ALT_SINGLE_MOTIF_PATTERN = "((:|\\*|,)*\\{*[\\w\\s]*#[\\w\\s]*(:|,|>)*(\\w+:*)*\\d*(\\(\\w+\\))*(_)*:*\\}*)"; private static final String NODE_PATTERN = "([\\w\\s_]+:\\d+)"; private static Pattern motifGroupPattern = Pattern.compile(SINGLE_MOTIF_PATTERN + "+"); private static Pattern singleMotifPattern = Pattern.compile(ALT_SINGLE_MOTIF_PATTERN); private static Pattern mergePattern = Pattern.compile(NODE_PATTERN); private static Pattern singleWordPattern = Pattern.compile(WORD_PATTERN); private static Pattern number = Pattern.compile(":\\d+"); public static String findAndCollapseMergeEvents(String representation) { Matcher m = mergePattern.matcher(representation); Map<String, List<Integer>> idToStartIndex = new ListOrderedMap<String, List<Integer>>(); while (m.find()) { String group = representation.substring(m.start(), m.end()); if (!idToStartIndex.containsKey(group)) { idToStartIndex.put(group, new ArrayList<Integer>()); } idToStartIndex.get(group).add(m.start()); } for (String key : idToStartIndex.keySet()) { if (idToStartIndex.get(key).size() > 1) { String reference = "ref_" + key.substring(0, key.lastIndexOf(":")) + "_" + key.substring(key.lastIndexOf(":") + 1); representation = representation.replace(key, reference); representation = representation.replaceFirst(reference, key.substring(0, key.lastIndexOf(":")) + ">" + reference); } } representation = representation.replaceAll("\\(\\d+\\)", ""); representation = representation.replaceAll(":\\d+", ""); return representation; } public static int getNumberOfGroupsInMotifString(Motif motif) { return getNumberOfGroupsInMotifString(motif.getStringRepresentation()); } public static int getNumberOfGroupsInMotifString(String representation) { List<String> branches = getBranchesInMotif(representation); int maxSize = 0; for (String branch : branches) { List<String> nodesInBranch = getNodesInBranch(branch); if (nodesInBranch.size() > maxSize) { maxSize = nodesInBranch.size(); } } return maxSize; } /** * Returns an ordered set of Branches found in the motif. * * @param representation - Motif String representation * @return OrderedSet of branches as found in the String representation. */ public static List<String> getBranchesInMotif(String representation) { List<String> branches = new ArrayList<String>(); Matcher motifGroupMatcher = motifGroupPattern.matcher(representation); while (motifGroupMatcher.find()) { String targetGroup = representation.substring(motifGroupMatcher.start(), motifGroupMatcher.end()); branches.add(targetGroup); } return branches; } /** * Returns an ordered set of nodes found in a branch. * * @param branch - String representation of branch to be processed * @return - OrderedSet of nodes within the branch. */ public static List<String> getNodesInBranch(String branch) { Matcher singleBracketMatcher = singleMotifPattern.matcher(branch); List<String> nodes = new ArrayList<String>(); while (singleBracketMatcher.find()) { nodes.add(branch.substring(singleBracketMatcher.start(), singleBracketMatcher.end())); } return nodes; } /** * Returns the parts of the node, usually of size 3 where 1:Relationship Type 2: Node Type 3:Count */ public static List<String> getPartsOfNode(String node) { Matcher wordMatcher = singleWordPattern.matcher(node); // we want the 2nd word. This is always the node type in our motif representation. List<String> nodeParts = new ArrayList<String>(); while (wordMatcher.find()) { nodeParts.add(node.substring(wordMatcher.start(), wordMatcher.end())); } return nodeParts; } /** * Returns all node ids contained in a motif's String representation. * * @param representation - Motif String representation * @return - Set of node ids as Longs. */ public static Set<Long> getNodeIdsInString(String representation) { Matcher m = number.matcher(representation); Set<Long> nodeIds = new HashSet<Long>(); while (m.find()) { nodeIds.add(Long.valueOf(representation.substring(m.start() + 1, m.end()))); } return nodeIds; } /** * isMotifGood(String representation) * A good motif is one with the same start and end nodes. The code will be similar to that of the code * used to detect the group counts, except for each group, we process the last motif and determine * whether or not the node type is the same. * * @param representation - String representation of motif to be processed * @return true if the end nodes match, false otherwise. */ public static boolean isMotifGood(String representation) { List<String> branches = getBranchesInMotif(representation); Set<String> endNodeTypes = new HashSet<String>(); for (String branch : branches) { List<String> nodesInBranch = getNodesInBranch(branch); String lastNode = ""; for (String node : nodesInBranch) { lastNode = node; } if (!lastNode.isEmpty()) { List<String> motifParts = getPartsOfNode(lastNode); // we want the 2nd word. This is always the node type in our motif representation. String type = motifParts.size() > 1 ? motifParts.get(1) : motifParts.get(0); if (type.startsWith("ref")) { type = type.replaceAll("ref|_|(\\d+)", ""); } if (!type.isEmpty()) { endNodeTypes.add(type.trim()); } } } // if this set is bigger than 1, then we have a 'bad' motif since there is more than one end node type. return endNodeTypes.size() == 1; } private static String removeSoloKeys(String representation, Map<String, List<Integer>> idToStartIndex) { // we do the replacement in reverse to avoid problems with indexes. Set<String> toRemove = new HashSet<String>(); for (String key : idToStartIndex.keySet()) { if (idToStartIndex.get(key).size() == 1) { representation = representation.replaceAll(key, key.substring(0, key.indexOf(":"))); toRemove.add(key); } } for (String key : toRemove) { idToStartIndex.remove(key); } return representation; } public static Set<Long> flattenNodeIds(Collection<Set<Long>> nodesInMotif) { Set<Long> nodes = new HashSet<Long>(); synchronized (nodesInMotif) { try { for (Set<Long> motifNodes : nodesInMotif) { nodes.addAll(motifNodes); } } catch (ConcurrentModificationException cme) { System.err.println("Error occurred " + cme.getMessage()); // don't do anything } } return nodes; } }
gpl-3.0
craftercms/studio
src/main/java/org/craftercms/studio/impl/v2/upgrade/operations/site/ConfigEncryptionUpgradeOperation.java
3108
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.impl.v2.upgrade.operations.site; import org.craftercms.commons.crypto.TextEncryptor; import org.craftercms.commons.upgrade.exception.UpgradeException; import org.craftercms.studio.api.v2.utils.StudioConfiguration; import org.craftercms.studio.impl.v2.upgrade.StudioUpgradeContext; import java.beans.ConstructorProperties; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Implementation of {@link AbstractContentUpgradeOperation} that upgrades encrypted properties in configuration files. * * @author joseross * @since 3.1.9 */ public class ConfigEncryptionUpgradeOperation extends AbstractContentUpgradeOperation { protected static String DEFAULT_ENCRYPTED_PATTERN = "\\$\\{enc:([^}#]+)}"; protected Pattern encryptedPattern = Pattern.compile(DEFAULT_ENCRYPTED_PATTERN); protected TextEncryptor textEncryptor; @ConstructorProperties({"studioConfiguration", "textEncryptor"}) public ConfigEncryptionUpgradeOperation(StudioConfiguration studioConfiguration, TextEncryptor textEncryptor) { super(studioConfiguration); this.textEncryptor = textEncryptor; } @Override protected boolean shouldBeUpdated(StudioUpgradeContext context, Path file) { return true; } @Override protected void updateFile(StudioUpgradeContext context, Path path) throws UpgradeException { try { // read the whole file String content = readFile(path); // find all encrypted values Matcher matcher = encryptedPattern.matcher(content); boolean updateFile = matcher.matches(); // for each one while(matcher.find()) { String encryptedValue = matcher.group(1); // decrypt it String originalValue = textEncryptor.decrypt(encryptedValue); // encrypt it again String newValue = textEncryptor.encrypt(originalValue); // replace it content = content.replaceAll(encryptedValue, newValue); updateFile = true; } // update the file if needed if (updateFile) { writeFile(path, content); } } catch (Exception e) { throw new UpgradeException("Error updating file " + path + " for site " + context, e); } } }
gpl-3.0
Tomucha/coordinator
coordinator-server/src/main/java/cz/clovekvtisni/coordinator/server/web/controller/EventListController.java
2011
package cz.clovekvtisni.coordinator.server.web.controller; import cz.clovekvtisni.coordinator.server.domain.EventEntity; import cz.clovekvtisni.coordinator.server.domain.PoiEntity; import cz.clovekvtisni.coordinator.server.domain.UserEntity; import cz.clovekvtisni.coordinator.server.filter.EventFilter; import cz.clovekvtisni.coordinator.server.filter.OrganizationInEventFilter; import cz.clovekvtisni.coordinator.server.service.EventService; import cz.clovekvtisni.coordinator.server.tool.objectify.ResultList; import cz.clovekvtisni.coordinator.server.web.util.Breadcrumb; 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.RequestParam; import java.util.ArrayList; import java.util.Calendar; import java.util.List; @Controller @RequestMapping("/superadmin/event/list") public class EventListController extends AbstractSuperadminController { @Autowired private EventService eventService; @RequestMapping public String list(@RequestParam(value = "bookmark", required = false) String bookmark, Model model) { UserEntity loggedUser = getLoggedUser(); ResultList<EventEntity> events; if (loggedUser.isSuperadmin()) { events = eventService.findByFilter(new EventFilter(), DEFAULT_LIST_LENGTH, bookmark, EventService.FLAG_FETCH_LOCATIONS); } else { OrganizationInEventFilter inEventFilter = new OrganizationInEventFilter(); inEventFilter.setOrganizationIdVal(loggedUser.getOrganizationId()); events = eventService.findByOrganizationFilter(inEventFilter, DEFAULT_LIST_LENGTH, bookmark, EventService.FLAG_FETCH_LOCATIONS); } model.addAttribute("events", events.getResult()); return "superadmin/event-list"; } }
gpl-3.0
masach/FaceWhat
FacewhatDroid/src/com/chat/DB/provider/ContactProvider.java
5381
package com.chat.db.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; public class ContactProvider extends ContentProvider{ private final static String AUTHORITY = ContactProvider.class.getCanonicalName(); /**ÁªÏµÈËÊý¾Ý¿â*/ private final static String DB_NAME = "contact.db"; /**ÁªÏµÈË*/ private final static String CONTACT_TABLE = "contact"; /**ÁªÏµÈË×é*/ private final static String CONTACT_GROUP_TABLE = "group"; /**Êý¾Ý¿â°æ±¾*/ private final static int DB_VERSION = 1; /**ÁªÏµÈË uri*/ public final static Uri CONTACT_URI = Uri.parse("content://"+AUTHORITY+"/"+CONTACT_TABLE); /**ÁªÏµ×é uri*/ public final static Uri CONTACT_GROUP_URI = Uri.parse("content://"+AUTHORITY+"/"+CONTACT_GROUP_TABLE); private SQLiteOpenHelper dbHelper; private SQLiteDatabase db; private static final UriMatcher URI_MATCHER; /**UriMatcherÆ¥ÅäÖµ*/ public static final int CONTACTS = 1; public static final int GROUPS = 2; static{ URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(AUTHORITY, CONTACT_TABLE, CONTACTS); URI_MATCHER.addURI(AUTHORITY, CONTACT_GROUP_TABLE, GROUPS); } @Override public boolean onCreate() { dbHelper = new ContactDatabaseHelper(getContext()); return (dbHelper == null) ?false:true; } /**¸ù¾Ýuri²éѯ³öselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼ÆäÖÐprojection¾ÍÊÇÒ»¸öÁÐÃûÁÐ±í£¬±íÃ÷ֻѡÔñÖ¸¶¨µÄÊý¾ÝÁÐ*/ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder) { Log.e("SQLite£º","½øÈë²éѯ "); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); db = dbHelper.getReadableDatabase(); Cursor ret = null; switch(URI_MATCHER.match(uri)){ case CONTACTS: qb.setTables(CONTACT_TABLE); ret = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); break; case GROUPS: break; } ret.setNotificationUri(getContext().getContentResolver(), uri); return ret; } /**¸ù¾ÝuriËù²åÈëvalues*/ @Override public Uri insert(Uri uri, ContentValues values) { Log.e("SQLite£º","½øÈë²åÈë "); db = dbHelper.getWritableDatabase(); Uri result = null; switch(URI_MATCHER.match(uri)){ case CONTACTS: long rowId = db.insert(CONTACT_TABLE, ContactColumns.ACCOUNT, values); result = ContentUris.withAppendedId(uri, rowId); break; default:break; } if(result!=null){ getContext().getContentResolver().notifyChange(result,null); } return result; } /** ¸ù¾ÝUriɾ³ýselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼ */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { db = dbHelper.getWritableDatabase(); int count = 0; Log.e("SQLite£º","½øÈëɾ³ý "); switch(URI_MATCHER.match(uri)){ case CONTACTS: count = db.delete(CONTACT_TABLE, selection, selectionArgs); break; default:break; } if (count != 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /**¸ù¾ÝuriÐÞ¸ÄselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼*/ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { db = dbHelper.getWritableDatabase(); int count = 0; Log.e("SQLite£º","½øÈë¸üР"); switch(URI_MATCHER.match(uri)){ case CONTACTS: count = db.update(CONTACT_TABLE, values, selection, selectionArgs); break; default:break; } Log.e("SQLite£º","¸üнá¹û " + count); if (count != 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /** *¸Ã·½·¨ÓÃÓÚ·µ»Øµ±Ç°UriËù´ú±íµÄÊý¾ÝµÄMIMEÀàÐÍ */ @Override public String getType(Uri uri) { return null; } /**ÁªÏµÈËÐÅÏ¢Êý¾Ý¿â*/ private class ContactDatabaseHelper extends SQLiteOpenHelper{ public ContactDatabaseHelper(Context context){ super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + CONTACT_TABLE + "(" + ContactColumns._ID+ " INTEGER PRIMARY KEY," + ContactColumns.AVATAR + " BLOB," +ContactColumns.SORT + " TEXT," +ContactColumns.NAME + " TEXT," +ContactColumns.JID + " TEXT," +ContactColumns.TYPE + " TEXT," +ContactColumns.STATUS + " TEXT," +ContactColumns.ACCOUNT + " TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+ CONTACT_TABLE); onCreate(db); } } /** * ÁªÏµÈËÊôÐÔ *BaseColumnsÊÇ×Ô¶¨ÒåÁÐÃû£¬ ÀïÃæÓÐÁ½¸ö×Ö¶Î _id,_count,ÏÂÃæÊÇÀ©Õ¹ */ public static class ContactColumns implements BaseColumns{ //Óû§Í·Ïñ public static final String AVATAR = "avatar"; //Óû§±¸×¢ public static final String NAME = "name"; //Ö÷È˵ĺÃÓÑ public static final String ACCOUNT = "account"; //ºÃÓѵÄÊ××Öĸ public static final String SORT = "sort"; //Ö÷ÈË public static final String JID = "jid"; //ºÃÓÑÀàÐÍ(Ìí¼ÓºÃÓÑʱ£ºboth£¬to£¬from) public static final String TYPE = "type"; //ºÃÓÑ״̬£¨ÔÚÏß»¹ÊÇÀëÏß £© public static final String STATUS = "status"; } }
gpl-3.0
MummyDing/Awesome-Campus
app/src/main/java/cn/edu/jxnu/awesome_campus/database/table/education/ExamTimeTable.java
1445
package cn.edu.jxnu.awesome_campus.database.table.education; /** * Created by MummyDing on 16-1-26. * GitHub: https://github.com/MummyDing * Blog: http://blog.csdn.net/mummyding */ public class ExamTimeTable { /*** * 考试安排表 */ public static final String NAME = "ExamTimeTable"; /** * 考试安排表 * 不设主键 * 说明: 注销需清空此表 否则新账号登陆考试安排信息将发生冲突 */ public static final String COURSE_ID = "CourseID"; public static final String COURSE_NAME = "CourseName"; public static final String EXAM_TIME = "ExamTime"; public static final String EXAM_ROOM = "ExamRoom"; public static final String EXAM_SEAT = "ExamSeat"; // 备注信息 public static final String REMARK = "Remark"; /** * 字段ID 数据库操作建立字段对应关系 从0开始 */ public static final int ID_COURSE_ID = 0; public static final int ID_COURSE_NAME =1; public static final int ID_EXAM_TIME = 2; public static final int ID_EXAM_ROOM = 3; public static final int ID_EXAM_SEAT = 4; public static final int ID_REMARK = 5; public static final String CREATE_TABLE = "create table "+NAME+"("+ COURSE_ID+" text, "+ COURSE_NAME+" text, "+ EXAM_TIME+" text, "+ EXAM_ROOM+" text, "+ EXAM_SEAT+" text, "+ REMARK+" text)"; }
gpl-3.0
jorson/excalibur
excalibur-frame/src/main/java/com/excalibur/frame/exception/DataException.java
1486
package com.excalibur.frame.exception; import com.excalibur.core.base.ExcaliburException; /** * Thrown to indicate that a compulsory parameter is missing. * * @author Foxykeep */ public final class DataException extends ExcaliburException { private static final long serialVersionUID = -6031863210486494461L; /** * Constructs a new {@link DataException} that includes the current stack trace. */ public DataException() { super(); } /** * Constructs a new {@link DataException} that includes the current stack trace, the * specified detail message and the specified cause. * * @param detailMessage The detail message for this exception. * @param throwable The cause of this exception. */ public DataException(final String detailMessage, final Throwable throwable) { super(detailMessage, throwable); } /** * Constructs a new {@link DataException} that includes the current stack trace and the * specified detail message. * * @param detailMessage The detail message for this exception. */ public DataException(final String detailMessage) { super(detailMessage); } /** * Constructs a new {@link DataException} that includes the current stack trace and the * specified cause. * * @param throwable The cause of this exception. */ public DataException(final Throwable throwable) { super(throwable); } }
gpl-3.0
kostovhg/SoftUni
Java Fundamentals-Sep17/Java_OOP_Advanced/h_InterfaceSegregationDependencyInversion/src/lab/p03_employee_info/models/ConsoleClient.java
689
package lab.p03_employee_info.models; import lab.p03_employee_info.contracts.Formatter; import lab.p03_employee_info.contracts.InfoProvider; public class ConsoleClient { private Formatter formatter; private InfoProvider infoProvider; public ConsoleClient(Formatter formatter, InfoProvider infoProvider) { this.formatter = formatter; this.infoProvider = infoProvider; } public void printEmployeesByName(){ System.out.println(this.formatter.format(this.infoProvider.getEmployeesByName())); } public void printEmployeesBySalary() { System.out.println(this.formatter.format(this.infoProvider.getEmployeesBySalary())); } }
gpl-3.0
sandakith/TRRuSST
TrReviewScraper/src/main/java/org/trusst/utils/DBUtils.java
8980
package org.trusst.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Properties; import org.trusst.market.MarketItem; import org.trusst.market.item.AppItem; public class DBUtils { private static Connection conn = null; private static Statement stmt = null; private static String dbLocation = "droidReviewDB"; private static String dbURL = "jdbc:derby://localhost:1527/"; private static String driverName = "org.apache.derby.jdbc.ClientDriver"; private static Connection getConnInstance() { if (conn == null) { conn = createConnection("admin","admin"); } return conn; } public static boolean populateMarketItemToDB(MarketItem marketItem) { boolean result = false; conn = getConnInstance(); if (conn!= null){ result = incertMarketItem(conn, marketItem); result = incertMarketItemReviews(conn, marketItem); }else { System.out.print("Could not connect to the database"); System.out.println("Check that the Derby Network Server is running on localhost."); } return result; } private static boolean incertMarketItem(Connection conn, MarketItem item ){ // Create Star ratings array String sql = "insert into APP.MarketItem " + "(id, " + "recordDate, " + "ItemId, " + "ItemName, " + "ItemDeveloper, " + "ItemDeveloperRating, " + "ItemAvgRating, " + "RatingCount, " + "LastUpdate, " + "NumOfInstalls, " + "ItemPrice, " + "ItemSize, " + "CurrentVersion, " + "ContentRating, " + "fiveStars, " + "fourStars, " + "threeStarts, " + "twoStars, " + "oneStar)" + "values " + "("+getNextID("APP.MarketItem")+"," + "'" + (getCurrentDateTime()) + "', " + "'" + (item.getItemId()).replaceAll("[^a-zA-Z0-9. ]+","") + "', " + "'" + (item.getItemName()).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (item.getItemDeveloper()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemDeveloperRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemAvgRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getRatingCount()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getLastUpdate()).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (item.getNumOfDownloads()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemPrice()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemSize()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getCurrentVersion()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getContentRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getFiveStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getFourStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getThreeStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getTwoStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getOneStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "')"; int numRows = executeUpdate(conn,sql); return ((numRows == 1) ? true : false ); } private static boolean incertMarketItemReviews(Connection conn, MarketItem item ){ boolean result = false; // Create Star ratings array String splittableString = item.getItemUserReviews(); String[] reviewList = splittableString.split(" :::: "); for (int i = 0; i < reviewList.length; i++) { String[] review = reviewList[i].split(" :: "); if (review.length <= 1){ review = new String[]{"none","none","none","none","none","none"}; } String sql = "insert into APP.MarketItemReviews " + "(id, " + "recordDate, " + "reviewItemId, " + "reviewUserId, " + "reviewUser, " + "reviewDate, " + "reviewStarValue, " + "reviewHeading, " + "reviewBody)" + "values " + "("+getNextID("APP.MarketItemReviews")+"," + "'" + (getCurrentDateTime()) + "', " + +(getNextID("APP.MarketItem")-1)+"," + "'" + (review[0]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[1]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[2]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[3]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[4]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[5]).replaceAll("[^a-zA-Z0-9 ]++","") + "')"; int numRows = executeUpdate(conn,sql); result = (numRows == 1) ? true : false ; } return result ; } private static Connection createConnection(String userName, String password) { try { Class.forName(driverName); Properties dbProps = new Properties(); dbProps.put("user", userName); dbProps.put("password", password); conn = DriverManager.getConnection(dbURL + dbLocation, dbProps); } catch (Exception except){ System.out.print("Could not connect to the database with username: " + userName); System.out.println(" password " + password); System.out.println("Check that the Derby Network Server is running on localhost."); except.printStackTrace(); } return conn; } private static int executeUpdate(Connection conn, String sql) { // the number of rows affected by the update or insert int numRows = 0; try { stmt = conn.createStatement(); numRows = stmt.executeUpdate(sql); stmt.close(); } catch (SQLException sqlExcept) { sqlExcept.printStackTrace(); } return numRows; } private static String[] runQuery(Connection conn, String sql) { List<String> list = Collections.synchronizedList(new ArrayList<String>(10)); try { stmt = conn.createStatement(); ResultSet results = stmt.executeQuery(sql); ResultSetMetaData rsmd = results.getMetaData(); int numberCols = rsmd.getColumnCount(); while(results.next()) { StringBuffer sbuf = new StringBuffer(200); for (int i = 1; i <= numberCols; i++){ sbuf.append(results.getString(i)); sbuf.append(", "); } list.add(sbuf.toString()); } results.close(); stmt.close(); } catch (SQLException sqlExcept) { sqlExcept.printStackTrace(); } return list.toArray(new String[list.size()]); } private static boolean dropAllReceordsFromTable(Connection conn, String table) { String sql = "delete from " + table ; int numRows = executeUpdate(conn,sql); if (numRows >= 0){ return true; } return false; } private static String getCurrentDateTime(){ Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); String dateNow = formatter.format(currentDate.getTime()); return dateNow; } private static int getNextID(String table){ Connection conn = getConnInstance(); StringBuffer sqlStringBuffer = new StringBuffer(); sqlStringBuffer.append("select max(id) from "); sqlStringBuffer.append(table); String[] runQueryResult = runQuery(conn, sqlStringBuffer.toString()); if (runQueryResult.length == 0){ return 0; } else if (runQueryResult[0].equals("null, ")) { return 1; }else{ Integer result = Integer.parseInt(runQueryResult[0].split(",")[0]); return result.intValue()+1; } } }
gpl-3.0
darrivau/GOOL
src/main/java/gool/ast/core/EnhancedForLoop.java
2878
/* * Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1. * Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2. * * This file is part of GOOL. * * GOOL is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, version 3. * * GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License version 3 for more details. * * You should have received a copy of the GNU General Public License along with GOOL, * in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>. */ package gool.ast.core; import gool.ast.type.TypeNone; import gool.generator.GoolGeneratorController; import gool.generator.common.CodeGenerator; /** * This class captures an enhanced for loop in the intermediate language. * Hence it inherits of Expression. * For example, this class captures * {@code * for( String s : array){ * ... * } */ public class EnhancedForLoop extends Expression { /** * The variable declaration in the enhanced for loop. */ private VarDeclaration varDec; /** * The expression used in the enhanced for loop. */ private Expression expr; /** * The statement used in the enhanced for loop. */ private Statement statements; /** * The simple constructor of an enhanced for loop representation. */ private EnhancedForLoop() { super(TypeNone.INSTANCE); } /** * The constructor of an enhanced for loop representation. * @param varDec * : The variable declaration in the enhanced for loop. * @param expr * : The expression used in the enhanced for loop. * @param statements * : The statement used in the enhanced for loop. */ public EnhancedForLoop(VarDeclaration varDec, Expression expr, Statement statements) { this(); this.varDec = varDec; this.expr = expr; this.statements = statements; } /** * Gets the variable declaration in the enhanced for loop. * @return * The variable declaration in the enhanced for loop. */ public VarDeclaration getVarDec() { return varDec; } /** * Gets the expression used in the enhanced for loop. * @return * The expression used in the enhanced for loop. */ public Expression getExpression() { return expr; } /** * Gets the statement used in the enhanced for loop. * @return * The statement used in the enhanced for loop. */ public Statement getStatements() { return statements; } @Override public String callGetCode() { CodeGenerator cg; try{ cg = GoolGeneratorController.generator(); }catch (IllegalStateException e){ return this.getClass().getSimpleName(); } return cg.getCode(this); } }
gpl-3.0
jusabatier/georchestra
ldapadmin/src/main/java/org/georchestra/ldapadmin/mailservice/MailService.java
4258
/* * Copyright (C) 2009-2016 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * geOrchestra is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ package org.georchestra.ldapadmin.mailservice; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.georchestra.commons.configuration.GeorchestraConfiguration; import org.springframework.beans.factory.annotation.Autowired; /** * Facade of mail service. * * @author Mauricio Pazos * */ public final class MailService { protected static final Log LOG = LogFactory.getLog(MailService.class.getName()); private EmailFactoryImpl emailFactory; @Autowired private GeorchestraConfiguration georchestraConfiguration; @Autowired public MailService(EmailFactoryImpl emailFactory) { this.emailFactory = emailFactory; } public void sendNewAccountRequiresModeration(ServletContext servletContext, final String uid, final String userName, final String userEmail, final String moderatorEmail) { try { NewAccountRequiresModerationEmail email = this.emailFactory.createNewAccountRequiresModerationEmail(servletContext, userEmail, new String[]{moderatorEmail}); email.sendMsg(userName, uid); } catch (Exception e) { LOG.error(e); } } public void sendAccountCreationInProcess( final ServletContext servletContext, final String uid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - email: " + userEmail); } try{ AccountCreationInProcessEmail email = this.emailFactory.createAccountCreationInProcessEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid ); } catch (Exception e) { LOG.error(e); } } public void sendAccountUidRenamed(final ServletContext servletContext, final String newUid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("Send mail to warn user [email: " + userEmail + "] for its new identifier: " + newUid); } try{ AccountUidRenamedEmail email = this.emailFactory.createAccountUidRenamedEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, newUid ); } catch (Exception e) { LOG.error(e); } } public void sendAccountWasCreated(final ServletContext servletContext, final String uid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - email: " + userEmail); } try{ AccountWasCreatedEmail email = this.emailFactory.createAccountWasCreatedEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid ); } catch (Exception e) { LOG.error(e); } } /** * Sent an email to the user whit the unique URL required to change his password. * @param servletContext * @param servletContext * * @param uid user id * @param commonName user full name * @param url url where the user can change his password * @param userEmail user email * */ public void sendChangePasswordURL(ServletContext servletContext, final String uid, final String commonName, final String url, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - url: " + url + " - email: " + userEmail); } try{ ChangePasswordEmail email = this.emailFactory.createChangePasswordEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid, url); } catch (Exception e) { LOG.error(e); } } }
gpl-3.0
netuh/DecodePlatformPlugin
br.ufpe.ines.decode/bundles/br.ufpe.ines.decode.observer/src/br/ufpe/ines/decode/observer/control/ExperimentManager.java
2240
package br.ufpe.ines.decode.observer.control; import java.io.File; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import br.ufpe.ines.decode.decode.CodingExperiment; import br.ufpe.ines.decode.decode.DecodePackage; public class ExperimentManager { protected static ExperimentManager singleton = new ExperimentManager(); private Set<CodingExperiment> loadedExperiments2 = new HashSet<CodingExperiment>(); private List<String> filePaths = new LinkedList<String>(); static final Logger logger = Logger.getLogger(ExperimentManager.class); // private CountDownLatch latchAction = new CountDownLatch(1); public static ExperimentManager getInstance() { if (singleton == null) singleton = new ExperimentManager(); return singleton; } protected ExperimentManager() { } public Set<CodingExperiment> getLoadedExperiments() { return loadedExperiments2; } public void loadDecodeModel(File filePath) { loadedExperiments2.add(load(filePath)); filePaths.add(filePath.getAbsolutePath()); } protected CodingExperiment load(File filePath) { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("decode", new XMIResourceFactoryImpl()); DecodePackage.eINSTANCE.eClass(); URI fileURI = URI.createFileURI(filePath.getAbsolutePath()); Resource resource = resourceSet.getResource(fileURI, true); EObject myModelObject = resource.getContents().get(0); CodingExperiment myWeb = null; if (myModelObject instanceof CodingExperiment) { myWeb = (CodingExperiment) myModelObject; } return myWeb; } public List<String> getFiles() { return filePaths; } public CodingExperiment getLoadedExperiment(String experimentID) { return loadedExperiments2.stream() .filter(e -> e.getElementId().equals(experimentID)) .findFirst().get(); } }
gpl-3.0
marcosemiao/log4jdbc
core/log4jdbc-utils/log4jdbc-commons/src/main/java/fr/ms/log4jdbc/util/logging/impl/DefaultLogger.java
5410
/* * This file is part of Log4Jdbc. * * Log4Jdbc 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. * * Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>. * */ package fr.ms.log4jdbc.util.logging.impl; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Date; import fr.ms.log4jdbc.lang.delegate.DefaultStringMakerFactory; import fr.ms.log4jdbc.lang.delegate.StringMakerFactory; import fr.ms.log4jdbc.lang.stringmaker.impl.StringMaker; import fr.ms.log4jdbc.util.logging.Logger; /** * * @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a> * * * @author Marco Semiao * */ public class DefaultLogger implements Logger { private final static String nl = System.getProperty("line.separator"); private final static StringMakerFactory stringMakerFactory = DefaultStringMakerFactory.getInstance(); private final PrintHandler printHandler; private final String name; private String level; private boolean trace; private boolean debug; private boolean info; private boolean warn; private boolean error; private boolean fatal; public DefaultLogger(final PrintHandler printHandler, final String level, final String name) { this.printHandler = printHandler; if (level != null) { if (level.equals("trace")) { trace = true; debug = true; info = true; error = true; } else if (level.equals("debug")) { debug = true; info = true; error = true; } else if (level.equals("info")) { info = true; error = true; } else if (level.equals("warn")) { warn = true; error = true; } else if (level.equals("error")) { error = true; } else if (level.equals("fatal")) { fatal = true; } this.level = level.toUpperCase(); } this.name = name; } public boolean isTraceEnabled() { return trace; } public boolean isDebugEnabled() { return debug; } public boolean isInfoEnabled() { return info; } public boolean isWarnEnabled() { return warn; } public boolean isErrorEnabled() { return error; } public boolean isFatalEnabled() { return fatal; } public void trace(final String message) { trace(message, null); } public void trace(final String message, final Throwable t) { if (isTraceEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.trace(formatMessage); } } public void debug(final String message) { debug(message, null); } public void debug(final String message, final Throwable t) { if (isDebugEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.debug(formatMessage); } } public void info(final String message) { info(message, null); } public void info(final String message, final Throwable t) { if (isInfoEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.info(formatMessage); } } public void warn(final String message) { warn(message, null); } public void warn(final String message, final Throwable t) { if (isWarnEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.warn(formatMessage); } } public void error(final String message) { error(message, null); } public void error(final String message, final Throwable t) { if (isErrorEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.error(formatMessage); } } public void fatal(final String message) { fatal(message, null); } public void fatal(final String message, final Throwable t) { if (isFatalEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.fatal(formatMessage); } } private String getException(final Throwable t) { String exception = ""; if (t != null) { final StringWriter errors = new StringWriter(); t.printStackTrace(new PrintWriter(errors)); exception = nl + t.getMessage() + nl + errors.toString(); } return exception; } private String formatMessage(final String message) { final Date now = new Date(); final StringMaker newMessage = stringMakerFactory.newString(); newMessage.append("["); newMessage.append(now); newMessage.append("]"); newMessage.append(" ["); newMessage.append(level); newMessage.append("]"); newMessage.append(" ["); newMessage.append(name); newMessage.append("] "); newMessage.append(message); return newMessage.toString(); } public PrintWriter getPrintWriter() { final Writer writerLogger = new WriterLogger(this); // PrintWriter (println) est synchronized et si le logger est desactivé, // cela detruit les perfs :( à revoir return new PrintWriter(writerLogger); } @Override public String toString() { return "DefaultLogger [name=" + name + ", level=" + level + "]"; } }
gpl-3.0
joseoliv/Cyan
meta/WrImportStatement.java
528
package meta; import ast.ExprIdentStar; public class WrImportStatement extends WrStatement { public WrImportStatement(WrExprIdentStar importPackage) { super(importPackage.hidden); } @Override public Object eval(WrEvalEnv ee) { ee.hidden.importPackage( ((ExprIdentStar ) hidden).asString()); return null; } @Override ExprIdentStar getHidden() { return (ExprIdentStar ) hidden; } @Override public void accept(WrASTVisitor visitor, WrEnv env) { ((ExprIdentStar ) hidden).getI().accept(visitor, env); } }
gpl-3.0
repoxIST/repoxEuropeana
repox-gui/src/main/java/harvesterUI/client/panels/forms/dataSources/DataSourceTagContainer.java
7296
package harvesterUI.client.panels.forms.dataSources; import com.extjs.gxt.ui.client.Style; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.SelectionChangedEvent; import com.extjs.gxt.ui.client.event.SelectionChangedListener; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.util.Margins; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel; import com.extjs.gxt.ui.client.widget.grid.ColumnConfig; import com.extjs.gxt.ui.client.widget.grid.ColumnModel; import com.extjs.gxt.ui.client.widget.grid.Grid; import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; import com.extjs.gxt.ui.client.widget.layout.FlowLayout; import com.extjs.gxt.ui.client.widget.layout.HBoxLayout; import com.extjs.gxt.ui.client.widget.layout.HBoxLayoutData; import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem; import com.extjs.gxt.ui.client.widget.toolbar.ToolBar; import harvesterUI.client.HarvesterUI; import harvesterUI.client.util.UtilManager; import harvesterUI.shared.dataTypes.dataSet.DataSetTagUI; import harvesterUI.shared.dataTypes.dataSet.DataSourceUI; import java.util.ArrayList; import java.util.List; /** * Created to Project REPOX * User: Edmundo * Date: 13-07-2012 * Time: 12:28 */ public class DataSourceTagContainer extends LayoutContainer { private ContentPanel tagsDSPanel; private Grid<DataSetTagUI> tagsChosenList; private DataSourceTagsDialog dataSourceTagsDialog; public DataSourceTagContainer() { createTaggingLists(); } private void createTaggingLists(){ HBoxLayout transformContainerLayout = new HBoxLayout(); transformContainerLayout.setHBoxLayoutAlign(HBoxLayout.HBoxLayoutAlign.MIDDLE); setLayout(transformContainerLayout); tagsDSPanel = new ContentPanel(); tagsDSPanel.setHeaderVisible(false); tagsDSPanel.setLayout(new FlowLayout(0)); final ToolBar topToolbar = new ToolBar(); tagsDSPanel.setTopComponent(topToolbar); Button addTransformationButton = new Button(); addTransformationButton.setText("&nbsp&nbspAdd"); addTransformationButton.setIcon(HarvesterUI.ICONS.tag_add_icon()); addTransformationButton.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { dataSourceTagsDialog = new DataSourceTagsDialog(tagsChosenList); dataSourceTagsDialog.showAndCenter(); } }); topToolbar.add(addTransformationButton); final Button deleteButton = new Button(); deleteButton.setText("&nbsp&nbspDelete"); deleteButton.setIcon(HarvesterUI.ICONS.tag_remove_icon()); deleteButton.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { for(DataSetTagUI dataSetTagUI : tagsChosenList.getSelectionModel().getSelectedItems()) tagsChosenList.getStore().remove(dataSetTagUI); } }); List<ColumnConfig> configs = new ArrayList<ColumnConfig>(); CheckBoxSelectionModel<DataSetTagUI> sm = new CheckBoxSelectionModel<DataSetTagUI>(); sm.setSelectionMode(Style.SelectionMode.MULTI); configs.add(sm.getColumn()); ColumnConfig column = new ColumnConfig("name", HarvesterUI.CONSTANTS.name(),50); column.setAlignment(Style.HorizontalAlignment.LEFT); configs.add(column); ColumnModel cm = new ColumnModel(configs); ListStore<DataSetTagUI> store = new ListStore<DataSetTagUI>(); tagsChosenList = new Grid<DataSetTagUI>(store, cm); tagsChosenList.setBorders(false); tagsChosenList.setAutoExpandColumn("name"); tagsChosenList.setLoadMask(true); tagsChosenList.setSelectionModel(sm); tagsChosenList.addPlugin(sm); tagsChosenList.setStripeRows(true); tagsChosenList.getView().setForceFit(true); tagsChosenList.setHeight(100); tagsChosenList.disableTextSelection(false); tagsChosenList.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<DataSetTagUI>() { @Override public void selectionChanged(SelectionChangedEvent<DataSetTagUI> se) { if (se.getSelectedItem() != null) { topToolbar.insert(deleteButton,1); } else { topToolbar.remove(deleteButton); } } }); LabelToolItem label = new LabelToolItem("Tags"); label.setStyleName("alignTop"); label.setWidth(DataSourceForm.SPECIAL_FIELDS_LABEL_WIDTH); label.addStyleName("defaultFormFieldLabel"); add(label, new HBoxLayoutData(new Margins(0, 2, UtilManager.DEFAULT_HBOX_BOTTOM_MARGIN, 0))); HBoxLayoutData flex = new HBoxLayoutData(new Margins(0, 0, UtilManager.DEFAULT_HBOX_BOTTOM_MARGIN, 0)); flex.setFlex(1); BorderLayoutData centerData = new BorderLayoutData(Style.LayoutRegion.CENTER); centerData.setMargins(new Margins(0)); tagsDSPanel.add(tagsChosenList); add(tagsDSPanel, flex); } public List<DataSetTagUI> getTags(){ return tagsChosenList.getStore().getModels(); } // public void reload(final DataSourceUI dataSourceUI, final boolean reset){ // sourceList.getStore().removeAll(); // if(targetList.getStore().getModels().size() <= 0 || reset) // targetList.getStore().removeAll(); // // AsyncCallback<List<DataSetTagUI>> callback = new AsyncCallback<List<DataSetTagUI>>() { // public void onFailure(Throwable caught) { // new ServerExceptionDialog("Failed to get response from server",caught.getMessage()).show(); // } // public void onSuccess(List<DataSetTagUI> tags) { // if(sourceList.getStore().getModels().size() <= 0) // sourceList.getStore().add(tags); // // if(dataSourceUI != null) // loadEditData(dataSourceUI,tags,reset); // // for(DataSetTagUI dataSetTagUI : targetList.getStore().getModels()){ // for(DataSetTagUI sourceDSTagUI : sourceList.getStore().getModels()){ // if(sourceDSTagUI.getName().equals(dataSetTagUI.getName())) // sourceList.getStore().remove(sourceDSTagUI); // } // } // } // }; // TagsServiceAsync service = (TagsServiceAsync) Registry.get(HarvesterUI.TAGS_SERVICE); // service.getAllTags(callback); // } public void reset(){ tagsChosenList.getStore().removeAll(); } public void loadEditData(DataSourceUI dataSourceUI){ tagsChosenList.getStore().removeAll(); tagsChosenList.getStore().add(dataSourceUI.getTags()); } public DataSourceTagsDialog getDataSourceTagsDialog() { return dataSourceTagsDialog; } }
gpl-3.0
dermotblair/Sipper
android-ngn-stack/src/org/doubango/tinyWRAP/CallSession.java
8341
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.9 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.doubango.tinyWRAP; public class CallSession extends InviteSession { private long swigCPtr; protected CallSession(long cPtr, boolean cMemoryOwn) { super(tinyWRAPJNI.CallSession_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } protected static long getCPtr(CallSession obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; tinyWRAPJNI.delete_CallSession(swigCPtr); } swigCPtr = 0; } super.delete(); } public CallSession(SipStack pStack) { this(tinyWRAPJNI.new_CallSession(SipStack.getCPtr(pStack), pStack), true); } public boolean callAudio(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudio__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callAudio(String remoteUriString) { return tinyWRAPJNI.CallSession_callAudio__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callAudio(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudio__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callAudio(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callAudio__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean callAudioVideo(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callAudioVideo(String remoteUriString) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callAudioVideo(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callAudioVideo(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean callVideo(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callVideo__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callVideo(String remoteUriString) { return tinyWRAPJNI.CallSession_callVideo__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callVideo(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callVideo__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callVideo(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callVideo__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean call(String remoteUriString, twrap_media_type_t media, ActionConfig config) { return tinyWRAPJNI.CallSession_call__SWIG_0(swigCPtr, this, remoteUriString, media.swigValue(), ActionConfig.getCPtr(config), config); } public boolean call(String remoteUriString, twrap_media_type_t media) { return tinyWRAPJNI.CallSession_call__SWIG_1(swigCPtr, this, remoteUriString, media.swigValue()); } public boolean call(SipUri remoteUri, twrap_media_type_t media, ActionConfig config) { return tinyWRAPJNI.CallSession_call__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, media.swigValue(), ActionConfig.getCPtr(config), config); } public boolean call(SipUri remoteUri, twrap_media_type_t media) { return tinyWRAPJNI.CallSession_call__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, media.swigValue()); } public boolean setSessionTimer(long timeout, String refresher) { return tinyWRAPJNI.CallSession_setSessionTimer(swigCPtr, this, timeout, refresher); } public boolean set100rel(boolean enabled) { return tinyWRAPJNI.CallSession_set100rel(swigCPtr, this, enabled); } public boolean setRtcp(boolean enabled) { return tinyWRAPJNI.CallSession_setRtcp(swigCPtr, this, enabled); } public boolean setRtcpMux(boolean enabled) { return tinyWRAPJNI.CallSession_setRtcpMux(swigCPtr, this, enabled); } public boolean setSRtpMode(tmedia_srtp_mode_t mode) { return tinyWRAPJNI.CallSession_setSRtpMode(swigCPtr, this, mode.swigValue()); } public boolean setAvpfMode(tmedia_mode_t mode) { return tinyWRAPJNI.CallSession_setAvpfMode(swigCPtr, this, mode.swigValue()); } public boolean setICE(boolean enabled) { return tinyWRAPJNI.CallSession_setICE(swigCPtr, this, enabled); } public boolean setICEStun(boolean enabled) { return tinyWRAPJNI.CallSession_setICEStun(swigCPtr, this, enabled); } public boolean setICETurn(boolean enabled) { return tinyWRAPJNI.CallSession_setICETurn(swigCPtr, this, enabled); } public boolean setSTUNServer(String hostname, int port) { return tinyWRAPJNI.CallSession_setSTUNServer(swigCPtr, this, hostname, port); } public boolean setSTUNCred(String username, String password) { return tinyWRAPJNI.CallSession_setSTUNCred(swigCPtr, this, username, password); } public boolean setQoS(tmedia_qos_stype_t type, tmedia_qos_strength_t strength) { return tinyWRAPJNI.CallSession_setQoS(swigCPtr, this, type.swigValue(), strength.swigValue()); } public boolean hold(ActionConfig config) { return tinyWRAPJNI.CallSession_hold__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean hold() { return tinyWRAPJNI.CallSession_hold__SWIG_1(swigCPtr, this); } public boolean resume(ActionConfig config) { return tinyWRAPJNI.CallSession_resume__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean resume() { return tinyWRAPJNI.CallSession_resume__SWIG_1(swigCPtr, this); } public boolean transfer(String referToUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_transfer__SWIG_0(swigCPtr, this, referToUriString, ActionConfig.getCPtr(config), config); } public boolean transfer(String referToUriString) { return tinyWRAPJNI.CallSession_transfer__SWIG_1(swigCPtr, this, referToUriString); } public boolean acceptTransfer(ActionConfig config) { return tinyWRAPJNI.CallSession_acceptTransfer__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean acceptTransfer() { return tinyWRAPJNI.CallSession_acceptTransfer__SWIG_1(swigCPtr, this); } public boolean rejectTransfer(ActionConfig config) { return tinyWRAPJNI.CallSession_rejectTransfer__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean rejectTransfer() { return tinyWRAPJNI.CallSession_rejectTransfer__SWIG_1(swigCPtr, this); } public boolean sendDTMF(int number) { return tinyWRAPJNI.CallSession_sendDTMF(swigCPtr, this, number); } public long getSessionTransferId() { return tinyWRAPJNI.CallSession_getSessionTransferId(swigCPtr, this); } public boolean sendT140Data(tmedia_t140_data_type_t data_type, java.nio.ByteBuffer data_ptr, long data_size) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_0(swigCPtr, this, data_type.swigValue(), data_ptr, data_size); } public boolean sendT140Data(tmedia_t140_data_type_t data_type, java.nio.ByteBuffer data_ptr) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_1(swigCPtr, this, data_type.swigValue(), data_ptr); } public boolean sendT140Data(tmedia_t140_data_type_t data_type) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_2(swigCPtr, this, data_type.swigValue()); } public boolean setT140Callback(T140Callback pT140Callback) { return tinyWRAPJNI.CallSession_setT140Callback(swigCPtr, this, T140Callback.getCPtr(pT140Callback), pT140Callback); } }
gpl-3.0
sankha93/java2r
source/src/sngforge/java2r/RFactoryException.java
1182
/* * Java2R: A library to connect Java and R * Copyright (C) 2009 Sankha Narayan Guria * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package sngforge.java2r; /** * Exception due to error in initialization of <code>RFactory</code> * @author Sankha Narayan Guria * @version 1.0 */ public class RFactoryException extends Exception { /** * Constructs an instance of <code>RFactoryException</code> with the specified detail message. * @param msg The detail message. */ public RFactoryException(String msg) { super(msg); } }
gpl-3.0
srpgit/hb
hb/src/main/java/pers/wzq/hb/util/table/CellFormatter.java
473
package pers.wzq.hb.util.table; import org.apache.poi.ss.usermodel.Cell; /** * excel表格格式化接口 * * @author RP_S * @since 2017年9月28日 */ public interface CellFormatter { /** * 使用自定义方式,格式化表格内容<br> * 可在table表格上自定义属性,编程转换成excel单元格样式 * * @param tableCell table表格 * @param cell excel表格 */ void formatCell(TableCell tableCell, Cell cell); }
gpl-3.0
dmrub/kiara-java
KIARA/src/main/java/de/dfki/kiara/tcp/TcpBlockAddress.java
4424
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages * * Copyright (C) 2014 German Research Center for Artificial Intelligence (DFKI) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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, see <http://www.gnu.org/licenses/>. */ package de.dfki.kiara.tcp; import de.dfki.kiara.InvalidAddressException; import de.dfki.kiara.Transport; import de.dfki.kiara.TransportAddress; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; /** * * @author Dmitri Rubinstein <dmitri.rubinstein@dfki.de> */ public class TcpBlockAddress implements TransportAddress { private final TcpBlockTransport transport; private final String hostName; private final int port; private final InetAddress address; public TcpBlockAddress(TcpBlockTransport transport, URI uri) throws InvalidAddressException, UnknownHostException { if (transport == null) { throw new NullPointerException("transport"); } if (uri == null) { throw new NullPointerException("uri"); } if (!"tcp".equals(uri.getScheme()) && !"tcps".equals(uri.getScheme())) { throw new InvalidAddressException("only tcp and tcps scheme is allowed"); } this.transport = transport; this.hostName = uri.getHost(); this.port = uri.getPort(); this.address = InetAddress.getByName(this.hostName); } public TcpBlockAddress(TcpBlockTransport transport, String hostName, int port) throws UnknownHostException { if (transport == null) { throw new NullPointerException("transport"); } if (hostName == null) { throw new NullPointerException("hostName"); } this.transport = transport; this.hostName = hostName; this.port = port; this.address = InetAddress.getByName(hostName); } @Override public Transport getTransport() { return transport; } @Override public int getPort() { return port; } @Override public String getHostName() { return hostName; } @Override public boolean acceptsTransportConnection(TransportAddress transportAddress) { if (transportAddress == null) { throw new NullPointerException("transportAddress"); } if (!(transportAddress instanceof TcpBlockAddress)) { return false; } TcpBlockAddress other = (TcpBlockAddress) transportAddress; if (!other.address.equals(this.address)) { final String otherHostName = other.getHostName(); final String thisHostName = getHostName(); if (!otherHostName.equals(thisHostName) && !"0.0.0.0".equals(thisHostName)) { return false; } } if (other.getPort() != getPort()) { return false; } return true; } @Override public boolean acceptsConnection(TransportAddress transportAddress) { return acceptsTransportConnection(transportAddress); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof TcpBlockAddress)) { return false; } TcpBlockAddress other = (TcpBlockAddress) obj; // FIXME is following always correct ? if (other.getTransport() != getTransport()) { return false; } return (other.address.equals(this.address) || other.hostName.equals(this.hostName)) && other.port == this.port; } @Override public String toString() { // FIXME what to do with different flavors of tcp (tcp, tcps) ? return getTransport().getName() + "://" + hostName + ":" + port; } }
gpl-3.0
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/AttributeBase.java
1057
package net.minecraft.server; import javax.annotation.Nullable; public abstract class AttributeBase implements IAttribute { private final IAttribute a; private final String b; private final double c; private boolean d; protected AttributeBase(@Nullable IAttribute iattribute, String s, double d0) { this.a = iattribute; this.b = s; this.c = d0; if (s == null) { throw new IllegalArgumentException("Name cannot be null!"); } } public String getName() { return this.b; } public double b() { return this.c; } public boolean c() { return this.d; } public AttributeBase a(boolean flag) { this.d = flag; return this; } @Nullable public IAttribute d() { return this.a; } public int hashCode() { return this.b.hashCode(); } public boolean equals(Object object) { return object instanceof IAttribute && this.b.equals(((IAttribute) object).getName()); } }
gpl-3.0
sinantie/PLTAG
src/pltag/parser/semantics/discriminative/Feature.java
2104
/* * Copyright (C) 2015 ikonstas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pltag.parser.semantics.discriminative; import pltag.parser.params.Vec; /** * * @author konstas */ public class Feature { private final Vec vec; private final int index; public Feature(Vec probVec, int index) { this.vec = probVec; this.index = index; } public int getIndex() { return index; } public double getValue() { return vec.getCount(index); } public void setValue(double value) { vec.setUnsafe(index, value); } public void increment(double value) { setValue(getValue() + value); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Feature other = (Feature) obj; if (this.vec != other.vec && (this.vec == null || !this.vec.equals(other.vec))) { return false; } return this.index == other.index; } @Override public int hashCode() { int hash = 7; hash = 83 * hash + (this.vec != null ? this.vec.hashCode() : 0); hash = 83 * hash + this.index; return hash; } @Override public String toString() { return String.valueOf(index); } }
gpl-3.0
jakobadam/rdp
src/net/propero/rdp/Glyph.java
3279
/* Glyph.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Represents data for individual glyphs, used for drawing text * * 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 * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; // import java.awt.*; // import java.awt.image.*; public class Glyph { private int font = 0; private int character = 0; private int offset = 0; private int baseline = 0; private int width = 0; private int height = 0; private byte[] fontdata = null; /** * Construct a Glyph object * * @param font * Font ID for Glyph * @param character * Character ID for Glyph * @param offset * x-offset of Glyph data for drawing * @param baseline * y-offset of Glyph data for drawing * @param width * Width of Glyph, in pixels * @param height * Height of Glyph, in pixels * @param fontdata * Data detailing Glyph's graphical representation */ public Glyph(int font, int character, int offset, int baseline, int width, int height, byte[] fontdata) { this.font = font; this.character = character; this.offset = offset; this.baseline = baseline; this.width = width; this.height = height; this.fontdata = fontdata; } /** * Retrieve the font ID for this Glyph * * @return Font ID */ public int getFont() { return this.font; } /** * Retrive y-offset of Glyph data * * @return y-offset */ public int getBaseLine() { return this.baseline; } /** * Return character ID of this Glyph * * @return ID of character represented by this Glyph */ public int getCharacter() { return this.character; } /** * Retrive x-offset of Glyph data * * @return x-offset */ public int getOffset() { return this.offset; } /** * Return width of Glyph * * @return Glyph width, in pixels */ public int getWidth() { return this.width; } /** * Return height of Glyph * * @return Glyph height, in pixels */ public int getHeight() { return this.height; } /** * Graphical data for this Glyph * * @return Data defining graphical representation of this Glyph */ public byte[] getFontData() { return this.fontdata; } }
gpl-3.0
apocist/eMafiaServer
src/com/inverseinnovations/eMafiaServer/includes/classes/Settings.java
6028
/* eMafiaServer - Settings.java GNU GENERAL PUBLIC LICENSE V3 Copyright (C) 2012 Matthew 'Apocist' Davis */ package com.inverseinnovations.eMafiaServer.includes.classes; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.Properties; import com.inverseinnovations.eMafiaServer.*; import com.inverseinnovations.eMafiaServer.includes.StringFunctions; /**Server user-definable settings to be loaded from file*/ public class Settings { public Base Base; Properties p = new Properties(); boolean loadError = false; // Server config variables //Keep in mind that on a live host, you'll want to bind to the outbound IP or host name, not localhost or 127.0.0.1, etc. 0 should work just fine public String SERVER_HOST; public int SERVER_PORT; public String SERVER_ADDRESS;//default is "localhost" public int SERVER_MAX_CLIENTS;//default is "256" is is how many players can connect at once public int CLIENT_BUILD; // Connection timeout for activity-less connections (in seconds) public int CONN_TIMEOUT; //MySql Config public String MYSQL_URL; public String MYSQL_USER; public String MYSQL_PASS; public String APIKEY; public String APIURL; public String GAMEMASTERNAME; public String GAMEMASTERPASS; public int LOGGING; /** Initialize and attempting to load server settings from settings.ini. * If setting or file doesn't exist, will make file and choose default settings during this session. */ public Settings(Base base){ this.Base = base; try {p.load(new FileInputStream("settings.ini"));} catch (Exception e) { loadError = true; Base.Console.config("Unable to read from settings.ini, attempting to make a new one."); PrintWriter writer; try { writer = new PrintWriter("settings.ini", "UTF-8"); writer.println("# Server config variables"); writer.println("#SERVER_HOST is the ip address other users connect to the server with."); writer.println("#Keep in mind that on a live host, you'll want to bind to the outbound IP or host name, not localhost or 127.0.0.1, etc."); writer.println("SERVER_HOST= 0"); writer.println("SERVER_PORT= 1234");//1234 is dev server - 3689 is public server(Apo normally keeps public server up and running) writer.println("SERVER_ADDRESS= localhost"); writer.println("SERVER_MAX_CLIENTS= 256"); writer.println("CLIENT_BUILD= 1");//Used for Client update control writer.println(); writer.println("# Connection timeout for activity-less connections (in seconds)"); writer.println("CONN_TIMEOUT= 1200"); writer.println(); writer.println("MYSQL_ADDR= 127.0.0.1"); writer.println("MYSQL_PORT= 3306"); writer.println("MYSQL_DBNAME= mafiamud"); writer.println("MYSQL_USER= *****"); writer.println("MYSQL_PASS= *****"); writer.println(); writer.println("# SC2Mafia Forum Settings"); writer.println("APIKEY= *****");//Getting permission for Oops to release the key publicly writer.println("APIURL= http://sc2mafia.com/forum/api.php"); writer.println("GAMEMASTERNAME= eMafia Game Master");//Any account really works..this is just a dedicated bot writer.println("GAMEMASTERPASS= *****"); writer.println(); writer.println("# Logging Level:"); writer.println("#OMIT = Only log Severe errors, Warnings, and Config settings"); writer.println("#NORMAL = Log everything but the small details"); writer.println("#EXPAND = Log everything including the small details"); writer.println("#DEBUG= Every tid bit is displayed, may include sensitive data such as encrypted passwords and cause exessive garbage."); writer.println("LOGGING= DEBUG"); writer.close(); } catch (Exception e2) { Base.Console.warning("Error: Unable to create a settings file, will continue to run with default"); } } SERVER_HOST = loadVariableFromSettings("SERVER_HOST","0"); SERVER_PORT = loadVariableFromSettings("SERVER_PORT",1234); SERVER_ADDRESS = loadVariableFromSettings("SERVER_ADDRESS","localhost"); SERVER_MAX_CLIENTS = loadVariableFromSettings("SERVER_MAX_CLIENTS",256); CLIENT_BUILD = loadVariableFromSettings("CLIENT_BUILD",5); CONN_TIMEOUT = loadVariableFromSettings("CONN_TIMEOUT",1200); //"jdbc:mysql://192.168.1.80:3306/mafiamud"; MYSQL_URL = "jdbc:mysql://"+loadVariableFromSettings("MYSQL_ADDR","127.0.0.1")+":"+loadVariableFromSettings("MYSQL_PORT",3306)+"/"+loadVariableFromSettings("MYSQL_DBNAME","mafiamud"); MYSQL_USER = loadVariableFromSettings("MYSQL_USER","*****"); MYSQL_PASS = loadVariableFromSettings("MYSQL_PASS","*****"); APIKEY = loadVariableFromSettings("APIKEY","g9nZkHeE"); APIURL = loadVariableFromSettings("APIURL","http://sc2mafia.com/forum/api.php"); GAMEMASTERNAME = loadVariableFromSettings("GAMEMASTERNAME","eMafia Game Master"); GAMEMASTERPASS = loadVariableFromSettings("GAMEMASTERPASS","*****"); switch(loadVariableFromSettings("LOGGING","NORMAL").toUpperCase()){ case "OMIT":LOGGING = 0;break; case "NORMAL":LOGGING = 1;break; case "EXPAND":LOGGING = 2;break; case "DEBUG":LOGGING = 3;break; default:LOGGING = 1;break; } } /** Attempt to retrieve the set String from settings.ini * @param varName * @param defaultValue * @return settings or defaultValue if non-exisitant */ private String loadVariableFromSettings(String varName, String defaultValue){ if(!loadError){ String var = p.getProperty(varName); if(var != null && !var.equals("")){ return var; } } return defaultValue; } /** Attempt to retrieve the set int from settings.ini * @param varName * @param defaultValue * @return settings or defaultValue if non-exisitant */ private int loadVariableFromSettings(String varName, int defaultValue){ if(!loadError){ String var = p.getProperty(varName); if(var != null && !var.equals("")){ if(StringFunctions.isInteger(var)){ return Integer.parseInt(var); } } } return defaultValue; } }
gpl-3.0
Etherous/Emerge
manager/src/main/java/net/etherous/emerge/manager/config/NativeNode.java
2483
/* * Copyright (c) 2015 Brandon Lyon * * This file is part of Emerge Game Engine (Emerge) * * Emerge is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Emerge 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 Emerge. If not, see <http://www.gnu.org/licenses/>. */ package net.etherous.emerge.manager.config; import java.io.File; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @XmlAccessorType (XmlAccessType.FIELD) public class NativeNode { // Name of the native file (Required) @XmlAttribute (name = "name", required = true) String name; // The native's target platform (Optional. Can be inferred. May not be needed) @XmlAttribute (name = "plat", required = false) String platform; // The native's target architecture (Optional. Can be inferred. May not be needed) @XmlAttribute (name = "arch", required = false) String architecture; // File path to the native. Can be either absolute or relative to EMERGE_HOME (Optional. Can be inferred) @XmlAttribute (name = "path", required = false) String path; public NativeNode () { } public String getName () { return this.name; } public void setName (final String name) { this.name = name; } public String getPlatform () { return this.platform; } public void setPlatform (final String platform) { this.platform = platform; } public String getArchitecture () { return this.architecture; } public void setArchitecture (final String architecture) { this.architecture = architecture; } public String getPath () { return this.path; } public void setPath (final String path) { this.path = path; } public File getFile (final File defaultPath) { final String path = this.getPath (); if (path != null) return new File (path); return new File (defaultPath, this.name); } }
gpl-3.0
trackplus/Genji
src/main/java/com/aurel/track/fieldType/runtime/callbackInterfaces/IExternalLookupLucene.java
1615
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $Id:$ */ package com.aurel.track.fieldType.runtime.callbackInterfaces; import java.util.List; import java.util.Map; /** * Fields whose datasource is remotely filtered * @author Tamas Ruff * */ public interface IExternalLookupLucene { /** * Gets all external lookup objects to index * @return */ List getAllExternalLookups(); /** * Gets the searchable lucene (sub)field names */ String[] getSearchableFieldNames(); /** * Gets the field names to values map for an external lookup instance * @param externalLookupObject * @return */ Map<String, String> getUnfoldedSearchFields(Object externalLookupObject); /** * Gets the lookup object ID * @param externalLookupObject * @return */ Integer getLookupObjectID(Object externalLookupObject); }
gpl-3.0
a254629486/mis-readinglife
src/main/java/com/system/controller/SysLoktpeController.java
3011
/** * <b>项目名:</b><br/> * <b>包名:</b>com.readinglife.b2b.sys.controller<br/> * <b>文件名:</b>SysLoktpeController.java<br/> * <b>描述:</b>TODO<br/> * <b>版本信息:</b>v1.0.0<br/> * <b>Copyright (c)</b> 2013新经典文化有限公司-版权所有<br/> * */ package com.system.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.annotation.ForBean; import com.readinglife.framework.web.BaseController; import com.readinglife.framework.web.JsonPager; import com.readinglife.tools.json.Jacksons; import com.system.model.po.SysLoktpePO; import com.system.service.InitService; import com.system.service.SysLoktpeService; /** * <b>类名称:</b>SysLoktpeController<br/> * <b>类描述:</b><br/> * <b>创建人:</b>B2B framework by <a href="mailto:Q12_35@163.com">zhaosy</a><br/> * <b>修改人:</b><br/> * <b>修改备注:</b><br/> * <b>版本信息:</b>v1.0.0<br/> * */ @Controller @RequestMapping("/sysLoktpeController") public class SysLoktpeController extends BaseController{ @Autowired SysLoktpeService sysLoktpeService; @Autowired InitService initService; @SuppressWarnings({ "unchecked" }) @RequestMapping("/save") @ResponseBody public String save(@ForBean SysLoktpePO record) { sysLoktpeService.deleteByPrimaryKey(record.getLoktpe()); sysLoktpeService.insert(record); //刷新缓存服务 initService.initBaseCode(); return result(true, SAVE_SUCCESS); } @SuppressWarnings("rawtypes") @RequestMapping("/remove") @ResponseBody public String remove(HttpServletRequest request) { Map param = formatParam(request); sysLoktpeService.deleteByPrimaryKeys(param.get("pkId").toString(),String.class); //刷新缓存服务 initService.initBaseCode(); return result(true, DELETE_SUCCESS); } @RequestMapping("/toSearchList") public String toSearchList(HttpServletRequest request) { return "//sys/lok/sys_loktpe_list"; } @SuppressWarnings({ "rawtypes" }) @RequestMapping("/searchList") @ResponseBody public String searchList(HttpServletRequest request,Model model) { Map param = formatParam(request); JsonPager jPager = getJsonPager(param); jPager = sysLoktpeService.selectByPageMap(jPager,param); return jPager.toJsonString(Jacksons.DATE_TIME_FORMAT); } @SuppressWarnings({ "rawtypes" }) @RequestMapping("/getLokcode") @ResponseBody public String getLokcode(HttpServletRequest request,Model model) { Map param = formatParam(request); JsonPager jPager = getJsonPager(param); jPager.setSize(Integer.MAX_VALUE); jPager = sysLoktpeService.selectByPageMap(jPager,param); return Jacksons.json().fromObjectToJson(jPager.getRows()); } }
gpl-3.0
hgs1217/Paper-Melody
tapdetect/src/main/java/tapdetect/facade/Tap.java
11860
/* * @Author: zhouben * @Date: 2017-05-10 22:47:18 * @Last Modified by: zhouben * @Last Modified time: 2017-06-15 10:58:43 */ package tapdetect.facade; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.List; import tapdetect.ColorRange; import tapdetect.Config; import tapdetect.FingerDetector; import tapdetect.HandDetector; import tapdetect.ImgLogger; import tapdetect.Sampler; import tapdetect.TapDetector; import tapdetect.TapDetector.TapDetectPoint; import tapdetect.Util; // import java.util.stream.Collectors; public class Tap { /** * Facade for outside to use the tap detector * * @param im: a Image in the type of org.opencv.core.Mat * required to be in <strong>YCrCb</strong> color mode! * @return : a <code>List</code> of <code>Points</code> * which takes the left top point as (0, 0) point * <p> * <br> Usage: * <code> * <br> Mat im = Imgcodecs.imread("samples/foo.jpg"); * <br> List<Point> taps = Tap.getTaps(im); * <br> Point pt = taps.get(0); * <br> System.out.println("Hurrah, someone taps at (" + pt.x + ", " + pt.y + ")"); * </code> */ static { // with opencv java, use Core.NATIVE_LIBRARY_NAME, // with opencv android, use "opencv_java3" System.loadLibrary("opencv_java3"); // this line only need to be carried out once ImgLogger.silent(); } public static long getProcessInterval() { return processInterval; } public static boolean readyForNextFrame() { return System.currentTimeMillis() - lastProcess > Config.PROCESS_INTERVAL_MS; } public static void reset() { ColorRange.reset(); } public static boolean sampleCompleted() { /** * Once this returns `True`, sampling process should be completed, * sampling function will not be called anymore. * However you can call `Tap.sample` manually if you really want */ return Sampler.sampleCompleted(); } public static List<Point> getTaps(Mat im) { /** * Searching tapping points from `im` * This is the most used func in this facade * @param im: one frame from a video * @return : A list of `Point` indicating the points which * (1) is regarded as the finger tip * (2) is regarded as being tapping */ if (!preprocess(im)) { return resultCache; } Mat hand = HandDetector.getHand(im); List<Point> fingers = FingerDetector.getFingers(im, hand); List<Point> taps = TapDetector.getTapping(im, fingers); scaleResult(taps); updateResultCache(taps); return taps; } public static List<Point> getPress(Mat im) { /** * Searching pressing finger tips from `im` * @param im: one frame from a video * @return : A list of `Point` indicating the points which * (1) is regarded as the finger tip * (2) is regarded as being pressing * * @warning: do not use getPress and getTaps in a row for the sake of performance. * Use `getAll` to get every finger tips instead */ if (!preprocess(im)) { return resultCache; } Mat hand = HandDetector.getHand(im); List<Point> fingers = FingerDetector.getFingers(im, hand); List<Point> press = TapDetector.getPressing(im, fingers); scaleResult(press); updateResultCache(press); return press; } public static List<Point> getAll(Mat im, List<List<Point>> contoursOutput, List<TapDetectPoint> tapDetectPointsOutput ) { /** * @param: im: A image in color space BGR * @param: contoursOutput * if is not null, apexes of the contour of hand will be saved * @param: tapDetectPointsOutput * if is not null, all results of detected points will be saved * @retrun: * A list of points detected as being tapping * (nothing but `TapDetectPoint` with status `FALLING` in `tapDetectPointsOutput`) * This function will modify `im` into YCrCb as well as a smaller size */ if (!preprocess(im)) { return resultCache; } Mat hand = HandDetector.getHand(im); List<MatOfPoint> contour = new ArrayList<>(); List<Point> fingers = FingerDetector.getFingers(im, hand, contour); List<TapDetectPoint> taps = TapDetector.getTappingAll(im, fingers); if (contoursOutput != null) { contoursOutput.clear(); for (MatOfPoint cnt : contour) { List<Point> cntPt = cnt.toList(); scaleResult(cntPt); contoursOutput.add(cntPt); } } for (TapDetectPoint pt : taps) { pt.x *= recoverRatio; pt.y *= recoverRatio; } if (contoursOutput != null) { tapDetectPointsOutput.clear(); tapDetectPointsOutput.addAll(taps); } List<Point> ret = new ArrayList<>(); for (TapDetectPoint pt : taps) { if (pt.isTapping()) { ret.add(pt); } } updateResultCache(ret); return ret; } public static List<Point> getPressAll(Mat im, List<List<Point>> contoursOutput, List<TapDetectPoint> tapDetectPointsOutput ) { /** * Same with `getAll` but returns a list of `pressing` points */ if (!preprocess(im)) { return resultCache; } Mat hand = HandDetector.getHand(im); List<MatOfPoint> contour = new ArrayList<>(); List<Point> fingers = FingerDetector.getFingers(im, hand, contour); List<TapDetectPoint> taps = TapDetector.getTappingAll(im, fingers); if (contoursOutput != null) { contoursOutput.clear(); for (MatOfPoint cnt : contour) { List<Point> cntPt = cnt.toList(); scaleResult(cntPt); contoursOutput.add(cntPt); } } for (TapDetectPoint pt : taps) { pt.x *= recoverRatio; pt.y *= recoverRatio; } if (contoursOutput != null) { tapDetectPointsOutput.clear(); tapDetectPointsOutput.addAll(taps); } List<Point> ret = new ArrayList<>(); for (TapDetectPoint pt : taps) { if (pt.isPressing()) { ret.add(pt); } } updateResultCache(ret); return ret; } public static List<Point> getSampleWindowContour() { if (sampleWindowContour == null && recoverRatio > 0.0) { sampleWindowContour = new ArrayList<>(); for (Point p : Sampler.getSampleWindowContour()) { sampleWindowContour.add(new Point(p.x * recoverRatio, p.y * recoverRatio)); } } return sampleWindowContour; } private static boolean checkTime() { long t = System.currentTimeMillis(); if (t - lastProcess < Config.PROCESS_INTERVAL_MS) { // too higher the camera fps return false; } else { processInterval = t - lastProcess; lastProcess = t; return true; } } private static boolean sample(Mat mat) { /** * Sampling pixels from mat to get a appropriate hand color * This will be called automatically before tapping detection being carried out */ if (!Sampler.isInited()) { Sampler.initSampleMask(mat.height(), mat.width()); } Sampler.sample(mat); return Sampler.sampleCompleted(); } private static boolean preprocess(Mat im) { // check time if (!checkTime()) { return false; } // resize to the standard size recoverRatio = 1.0 / Util.resize(im); Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2YCrCb); Imgproc.blur(im, im, new Size(Config.IM_BLUR_SIZE, Config.IM_BLUR_SIZE)); if (!Sampler.sampleCompleted()) { sample(im); return false; } return true; } private static void scaleResult(List<Point> result) { for (Point pt : result) { pt.x *= recoverRatio; pt.y *= recoverRatio; } } private static void updateResultCache(List<Point> result) { resultCache.clear(); for (Point pt : result) { resultCache.add(pt); } } private static double recoverRatio = 0.0; private static long lastProcess = 0; private static long processInterval; private static List<Point> resultCache = new ArrayList<>(); private static List<Point> sampleWindowContour = null; // Configs public static void setHighPerformance(boolean highPerformance) { if (highPerformance) { Config.PROCESS_INTERVAL_MS = 50; } else { Config.PROCESS_INTERVAL_MS = 100; } } public static void setMotionSensibility(int motionSensibility) { switch (motionSensibility) { case 0: // sensitive to small move Config.FINGER_TIP_MOVE_DIST_MAX = 20; Config.FINGER_TIP_LINGER_DIST_MAX = 1; break; case 1: Config.FINGER_TIP_MOVE_DIST_MAX = 25; Config.FINGER_TIP_LINGER_DIST_MAX = 2; break; case 2: // sensitive to big move Config.FINGER_TIP_MOVE_DIST_MAX = 35; Config.FINGER_TIP_LINGER_DIST_MAX = 4; break; } } public static void setSkinColorSensibility(int colorSensibility) { switch (colorSensibility) { case 0: // a small range of color is considered as skin color Config.COLOR_RANGE_EXPAND[0] = 2; Config.COLOR_RANGE_EXPAND[1] = 1.4; Config.COLOR_RANGE_EXPAND[2] = 2; break; case 1: Config.COLOR_RANGE_EXPAND[0] = 3; Config.COLOR_RANGE_EXPAND[1] = 1.6; Config.COLOR_RANGE_EXPAND[2] = 3; break; case 2: // a large range of color is considered as skin color Config.COLOR_RANGE_EXPAND[0] = 3; Config.COLOR_RANGE_EXPAND[1] = 1.8; Config.COLOR_RANGE_EXPAND[2] = 3; break; } } public static void setCalibritionColorSensibility(int calibritionColorSensibility) { switch (calibritionColorSensibility) { case 0: // have a coarse sampling Config.SAMPLE_PASS_THRESHOLD = 0.75; Config.FINGER_COLOR_TOLERANCE[1] = 25; Config.FINGER_COLOR_TOLERANCE[2] = 25; break; case 1: Config.SAMPLE_PASS_THRESHOLD = 0.85; Config.FINGER_COLOR_TOLERANCE[1] = 17; Config.FINGER_COLOR_TOLERANCE[2] = 20; break; case 2: // have a precise sampling Config.SAMPLE_PASS_THRESHOLD = 0.9; Config.FINGER_COLOR_TOLERANCE[1] = 15; Config.FINGER_COLOR_TOLERANCE[2] = 15; break; } } }
gpl-3.0
itachi1706/Applied-Energistics-2
src/main/java/appeng/container/slot/SlotFakeBlacklist.java
1363
/* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. * * Applied Energistics 2 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>. */ package appeng.container.slot; import net.minecraft.inventory.IInventory; public class SlotFakeBlacklist extends SlotFakeTypeOnly { public SlotFakeBlacklist( final IInventory inv, final int idx, final int x, final int y ) { super( inv, idx, x, y ); } @Override public float getOpacityOfIcon() { return 0.8f; } @Override public boolean renderIconWithItem() { return true; } @Override public int getIcon() { if( this.getHasStack() ) { return this.getStack().stackSize > 0 ? 16 + 14 : 14; } return -1; } }
gpl-3.0
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/util/CountUpDownLatch.java
1481
/* Copyright 2017 Andrew Dawson * * This file is a part of Tusky. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky.util; /** * This is a synchronization primitive related to {@link java.util.concurrent.CountDownLatch} * except that it starts at zero and can count upward. * <p> * The intended use case is for waiting for all tasks to be finished when the number of tasks isn't * known ahead of time, or may change while waiting. */ public class CountUpDownLatch { private int count; public CountUpDownLatch() { this.count = 0; } public synchronized void countDown() { count--; notifyAll(); } public synchronized void countUp() { count++; notifyAll(); } public synchronized void await() throws InterruptedException { while (count != 0) { wait(); } } }
gpl-3.0
wizjany/craftbook
src/main/java/com/sk89q/craftbook/circuits/gates/world/blocks/CombineHarvesterST.java
1257
package com.sk89q.craftbook.circuits.gates.world.blocks; import org.bukkit.Server; import com.sk89q.craftbook.ChangedSign; import com.sk89q.craftbook.circuits.ic.ChipState; import com.sk89q.craftbook.circuits.ic.IC; import com.sk89q.craftbook.circuits.ic.ICFactory; import com.sk89q.craftbook.circuits.ic.SelfTriggeredIC; public class CombineHarvesterST extends CombineHarvester implements SelfTriggeredIC { public CombineHarvesterST(Server server, ChangedSign sign, ICFactory factory) { super(server, sign, factory); } @Override public String getTitle() { return "Self-Triggered Combine Harvester"; } @Override public String getSignTitle() { return "HARVEST ST"; } @Override public boolean isActive() { return true; } @Override public void think(ChipState chip) { chip.setOutput(0, harvest()); } public static class Factory extends CombineHarvester.Factory { public Factory(Server server) { super(server); } @Override public IC create(ChangedSign sign) { return new CombineHarvesterST(getServer(), sign, this); } } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/iface/src/ar/gov/rosario/siat/cyq/iface/service/ICyqDefinicionService.java
3540
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.cyq.iface.service; import ar.gov.rosario.siat.cyq.iface.model.AbogadoAdapter; import ar.gov.rosario.siat.cyq.iface.model.AbogadoSearchPage; import ar.gov.rosario.siat.cyq.iface.model.AbogadoVO; import ar.gov.rosario.siat.cyq.iface.model.JuzgadoAdapter; import ar.gov.rosario.siat.cyq.iface.model.JuzgadoSearchPage; import ar.gov.rosario.siat.cyq.iface.model.JuzgadoVO; import coop.tecso.demoda.iface.DemodaServiceException; import coop.tecso.demoda.iface.model.CommonKey; import coop.tecso.demoda.iface.model.UserContext; public interface ICyqDefinicionService { // ---> ABM Abogado public AbogadoSearchPage getAbogadoSearchPageInit(UserContext usercontext) throws DemodaServiceException; public AbogadoSearchPage getAbogadoSearchPageResult(UserContext usercontext, AbogadoSearchPage abogadoSearchPage) throws DemodaServiceException; public AbogadoAdapter getAbogadoAdapterForView(UserContext userContext, CommonKey commonKey) throws DemodaServiceException; public AbogadoAdapter getAbogadoAdapterForCreate(UserContext userContext) throws DemodaServiceException; public AbogadoAdapter getAbogadoAdapterForUpdate(UserContext userContext, CommonKey commonKey) throws DemodaServiceException; public AbogadoVO createAbogado(UserContext userContext, AbogadoVO abogadoVO ) throws DemodaServiceException; public AbogadoVO updateAbogado(UserContext userContext, AbogadoVO abogadoVO ) throws DemodaServiceException; public AbogadoVO deleteAbogado(UserContext userContext, AbogadoVO abogadoVO ) throws DemodaServiceException; public AbogadoVO activarAbogado(UserContext userContext, AbogadoVO abogadoVO ) throws DemodaServiceException; public AbogadoVO desactivarAbogado(UserContext userContext, AbogadoVO abogadoVO ) throws DemodaServiceException; public AbogadoAdapter imprimirAbogado(UserContext userContext, AbogadoAdapter abogadoAdapter ) throws DemodaServiceException; // <--- ABM Abogado // ---> ABM Juzgado public JuzgadoSearchPage getJuzgadoSearchPageInit(UserContext usercontext) throws DemodaServiceException; public JuzgadoSearchPage getJuzgadoSearchPageResult(UserContext usercontext, JuzgadoSearchPage juzgadoSearchPage) throws DemodaServiceException; public JuzgadoAdapter getJuzgadoAdapterForView(UserContext userContext, CommonKey commonKey) throws DemodaServiceException; public JuzgadoAdapter getJuzgadoAdapterForCreate(UserContext userContext) throws DemodaServiceException; public JuzgadoAdapter getJuzgadoAdapterForUpdate(UserContext userContext, CommonKey commonKey) throws DemodaServiceException; public JuzgadoVO createJuzgado(UserContext userContext, JuzgadoVO juzgadoVO ) throws DemodaServiceException; public JuzgadoVO updateJuzgado(UserContext userContext, JuzgadoVO juzgadoVO ) throws DemodaServiceException; public JuzgadoVO deleteJuzgado(UserContext userContext, JuzgadoVO juzgadoVO ) throws DemodaServiceException; public JuzgadoVO activarJuzgado(UserContext userContext, JuzgadoVO juzgadoVO ) throws DemodaServiceException; public JuzgadoVO desactivarJuzgado(UserContext userContext, JuzgadoVO juzgadoVO ) throws DemodaServiceException; public JuzgadoAdapter imprimirJuzgado(UserContext userContext, JuzgadoAdapter juzgadoAdapter ) throws DemodaServiceException; // <--- ABM Juzgado }
gpl-3.0