repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
zuonima/sql-utils
src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleDDLStatement.java
815
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.dialect.oracle.ast.stmt; import com.alibaba.druid.sql.ast.statement.SQLDDLStatement; public interface OracleDDLStatement extends SQLDDLStatement, OracleStatement { }
gpl-3.0
Elolawyn/UPV-Curso-Android
Unidad 1/src/ejercicioLugar/Lugar.java
2293
package ejercicioLugar; public class Lugar { private String nombre; private String direccion; private GeoPunto posicion; private String foto; private int telefono; private String url; private String comentario; private long fecha; private float valoracion; public Lugar(String nombre, String direccion, double longitud, double latitud, int telefono, String url, String comentario, int valoracion) { fecha = System.currentTimeMillis(); posicion = new GeoPunto(longitud, latitud); this.nombre = nombre; this.direccion = direccion; this.telefono = telefono; this.url = url; this.comentario = comentario; this.valoracion = valoracion; } public String getNombre() { return nombre; } public String getDireccion() { return direccion; } public GeoPunto getPosicion() { return posicion; } public String getFoto() { return foto; } public int getTelefono() { return telefono; } public String getUrl() { return url; } public String getComentario() { return comentario; } public long getFecha() { return fecha; } public float getValoracion() { return valoracion; } public void setNombre(String nombre) { this.nombre = nombre; } public void setDireccion(String direccion) { this.direccion = direccion; } public void setPosicion(GeoPunto posicion) { this.posicion = posicion; } public void setFoto(String foto) { this.foto = foto; } public void setTelefono(int telefono) { this.telefono = telefono; } public void setUrl(String url) { this.url = url; } public void setComentario(String comentario) { this.comentario = comentario; } public void setFecha(long fecha) { this.fecha = fecha; } public void setValoracion(float valoracion) { this.valoracion = valoracion; } @Override public String toString() { return "Lugar [nombre=" + nombre + ", direccion=" + direccion + ", posicion=" + posicion + ", foto=" + foto + ", telefono=" + telefono + ", url=" + url + ", comentario=" + comentario + ", fecha=" + fecha + ", valoracion=" + valoracion + "]"; } }
gpl-3.0
Maxels88/openxls
src/main/java/org/openxls/formats/XLS/SXDBEx.java
3417
/* * --------- BEGIN COPYRIGHT NOTICE --------- * Copyright 2002-2012 Extentech Inc. * Copyright 2013 Infoteria America Corp. * * This file is part of OpenXLS. * * OpenXLS 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. * * OpenXLS 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 OpenXLS. If not, see * <http://www.gnu.org/licenses/>. * ---------- END COPYRIGHT NOTICE ---------- */ package org.openxls.formats.XLS; /** * The SXDBEx record specifies additional PivotCache properties. * * numDate (8 bytes): A DateAsNum structure that specifies the date and time on which the PivotCache was created or last refreshed. cSxFormula (4 bytes): An unsigned integer that specifies the count of SXFormula records for this cache. */ import org.openxls.ExtenXLS.DateConverter; import org.openxls.toolkit.ByteTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Locale; public class SXDBEx extends XLSRecord implements XLSConstants, PivotCacheRecord { private static final Logger log = LoggerFactory.getLogger( SXDBEx.class ); private static final long serialVersionUID = 9027599480633995587L; int nformulas; double lastdate; @Override public void init() { super.init(); log.debug( "SXDBEx - {}", Arrays.toString( getData() ) ); // numDate 0-8 last refresh date lastdate = ByteTools.eightBytetoLEDouble( getBytesAt( 0, 8 ) ); nformulas = ByteTools.readInt( getBytesAt( 8, 4 ) ); // # SXFormula records } public String toString() { java.util.Date ld = DateConverter.getDateFromNumber( lastdate ); java.text.DateFormat dateFormatter = java.text.DateFormat.getDateInstance( java.text.DateFormat.DEFAULT, Locale.getDefault() ); try { return "SXDBEx: nFormulas:" + nformulas + " last Date:" + dateFormatter.format( ld ) + Arrays.toString( getRecord() ); } catch( Exception e ) { } return "SXDBEx: nFormulas:" + nformulas + " last Date: undefined"; } /** * create a new minimum SXDBEx * * @return */ public static XLSRecord getPrototype() { SXDBEx sxdbex = new SXDBEx(); sxdbex.setOpcode( SXDBEX ); byte[] data = new byte[12]; double d = DateConverter.getXLSDateVal( new java.util.Date() ); System.arraycopy( ByteTools.doubleToLEByteArray( d ), 0, data, 0, 8 ); sxdbex.setData( data ); sxdbex.init(); return sxdbex; } public void setnFormulas( int n ) { nformulas = n; byte[] b = ByteTools.cLongToLEBytes( n ); System.arraycopy( b, 0, getData(), 8, 4 ); } public int getnFormulas() { return nformulas; } /** * return the bytes describing this record, including the header * * @return */ @Override public byte[] getRecord() { byte[] b = new byte[4]; System.arraycopy( ByteTools.shortToLEBytes( getOpcode() ), 0, b, 0, 2 ); System.arraycopy( ByteTools.shortToLEBytes( (short) getData().length ), 0, b, 2, 2 ); return ByteTools.append( getData(), b ); } }
gpl-3.0
AlmuHS/Practicas_PCD
examenes/Examen2018_Textil-2/src/examen2018_textil/Generador.java
1493
/* * 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 examen2018_textil; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author almu */ public class Generador extends Thread { Thread[] prenda; Linea lin; int numprendas; public Generador(Linea lin) { this.lin = lin; numprendas = 10; prenda = new Thread[numprendas]; } public void lanzarHilos() { Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); try { for (int i = 0; i < numprendas; i++) { if (rand.nextInt(10) < 3) { Pantalon pant = new Pantalon(i, lin); prenda[i] = new Thread(pant); prenda[i].start(); } else { Camisa camisa = new Camisa(i, lin); prenda[i] = new Thread(camisa); camisa.start(); } sleep(rand.nextInt(1000) + 3000); } for (int i = 0; i < numprendas; i++) { prenda[i].join(); } } catch (InterruptedException ex) { Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex); } } public void run() { lanzarHilos(); } }
gpl-3.0
fantesy84/EasyPay
easypay-commons/commons-jdbc/src/main/java/net/fantesy84/sys/jdbc/support/DefaultListRowMapper.java
1675
/** * Project commons-dao * CreateTime: 2016年4月13日 * Creator: junjie.ge * Copyright ©2016 葛俊杰 */ package net.fantesy84.sys.jdbc.support; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.RowMapper; import net.fantesy84.util.reflect.ReflectUtils; /** * TypeName: DefaultRowMapper * * <P> * CreateTime: 2016年4月13日 * <P> * UpdateTime: * * @author junjie.ge * @param <T> * */ public class DefaultListRowMapper<T> implements RowMapper<List<T>> { private Class<T> valueType; /** * @param valueType */ public DefaultListRowMapper(Class<T> valueType) { super(); this.valueType = valueType; } /* * (non-Javadoc) * * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, * int) */ @Override public List<T> mapRow(ResultSet rs, int rowNum) throws SQLException { List<T> list = new ArrayList<>(); while (rs.next()) { T entity = null; try { entity = valueType.getConstructor(new Class<?>[] {}).newInstance(new Object[] {}); ResultSetMetaData metaData = rs.getMetaData(); for (int i = 0; i < metaData.getColumnCount(); i++) { Object obj = rs.getObject(i); String columnName = metaData.getColumnLabel(i + 1); Object javaValue = ReflectUtils.searchField(entity, columnName).getType().cast(obj); ReflectUtils.setter(entity, columnName, javaValue); } } catch (Exception e) { throw new SQLException(e); } list.add(entity); } return list; } }
gpl-3.0
Senney/CPSC599-RPG
src/cpsc599/ai/HitAndRunAI.java
1744
package cpsc599.ai; import com.badlogic.gdx.math.Vector2; import cpsc599.assets.Actor; import cpsc599.assets.Level; import cpsc599.assets.Player; import cpsc599.managers.PlayerManager; import java.util.Random; public class HitAndRunAI extends AIActor { public HitAndRunAI(PlayerManager playerManager, AStarPathfinder pathfinder, Actor actor) { super(playerManager, pathfinder, actor); } private Vector2 findLocationInRange(Vector2 position, Level level, int range) { int iterations = 0; Random rand = new Random(System.currentTimeMillis()); while (iterations < 10) { int xr = rand.nextInt(range) + 1, yr = rand.nextInt(range); int nx = (int)position.x + xr, ny = (int)position.y + yr; if (!level.collide(nx, ny)) { return new Vector2(nx, ny); } iterations++; } return null; } @Override public boolean decideTurn() { Vector2 myPos = new Vector2(this.actor.x, this.actor.y); Player closest = playerManager.getNearest(myPos); if (closest == null) return skipTurn(); // If they're within striking range, we do a hit and run attack. Vector2 theirPos = new Vector2(closest.x, closest.y); if (myPos.dst(theirPos) < (this.actor.range + 1)) { attack(closest); Vector2 pos = findLocationInRange(myPos, pathfinder.getLevel(), this.actor.maxMove); if (pos != null) { moveTo((int)pos.x, (int)pos.y); return true; } else { return skipTurn(); } } else { attackTo(closest.x, closest.y); } return true; } }
gpl-3.0
mbshopM/openconcerto
OpenConcerto/src/org/openconcerto/erp/core/common/component/TransfertGroupSQLComponent.java
8752
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ package org.openconcerto.erp.core.common.component; import org.openconcerto.erp.config.Gestion; import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable; import org.openconcerto.sql.Configuration; import org.openconcerto.sql.element.GroupSQLComponent; import org.openconcerto.sql.element.SQLComponent; import org.openconcerto.sql.element.SQLElement; import org.openconcerto.sql.model.SQLField; import org.openconcerto.sql.model.SQLInjector; import org.openconcerto.sql.model.SQLRow; import org.openconcerto.sql.model.SQLRowAccessor; import org.openconcerto.sql.model.SQLRowValues; import org.openconcerto.sql.model.SQLRowValues.ForeignCopyMode; import org.openconcerto.sql.model.SQLRowValuesListFetcher; import org.openconcerto.sql.model.SQLSelect; import org.openconcerto.sql.model.Where; import org.openconcerto.sql.view.EditFrame; import org.openconcerto.sql.view.EditPanel.EditMode; import org.openconcerto.sql.view.list.RowValuesTable; import org.openconcerto.ui.FrameUtil; import org.openconcerto.ui.group.Group; import org.openconcerto.utils.ExceptionHandler; import org.openconcerto.utils.cc.ITransformer; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.swing.ImageIcon; public abstract class TransfertGroupSQLComponent extends GroupSQLComponent { protected SQLRowAccessor selectedRow; private List<SQLRowValues> sourceRows; public TransfertGroupSQLComponent(SQLElement element, Group group) { super(element, group); } /** * Chargement d'élément à partir d'une autre table ex : les éléments d'un BL dans une facture * * @param table ItemTable du component de destination (ex : tableFacture) * @param elt element source (ex : BL) * @param id id de la row source * @param itemsElt elements des items de la source (ex : BL_ELEMENT) */ public void loadItem(AbstractArticleItemTable table, SQLElement elt, int id, SQLElement itemsElt) { loadItem(table, elt, id, itemsElt, true); } public void loadItem(AbstractArticleItemTable table, SQLElement elt, int id, SQLElement itemsElt, boolean clear) { List<SQLRow> myListItem = elt.getTable().getRow(id).getReferentRows(itemsElt.getTable()); if (myListItem.size() != 0) { SQLInjector injector = SQLInjector.getInjector(itemsElt.getTable(), table.getSQLElement().getTable()); if (clear) { table.getModel().clearRows(); } for (SQLRow rowElt : myListItem) { SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(rowElt); if (createRowValuesFrom.getTable().getFieldsName().contains("POURCENT_ACOMPTE")) { if (createRowValuesFrom.getObject("POURCENT_ACOMPTE") == null) { createRowValuesFrom.put("POURCENT_ACOMPTE", new BigDecimal(100.0)); } } table.getModel().addRow(createRowValuesFrom); int rowIndex = table.getModel().getRowCount() - 1; table.getModel().fireTableModelModified(rowIndex); } } else { if (clear) { table.getModel().clearRows(); table.getModel().addNewRowAt(0); } } table.getModel().fireTableDataChanged(); table.repaint(); } public void importFrom(List<SQLRowValues> rows) { this.sourceRows = rows; if (rows.size() > 0) { final SQLInjector injector = SQLInjector.getInjector(rows.get(0).getTable(), this.getTable()); final SQLRowValues rValues = injector.createRowValuesFrom(rows); select(rValues); } else { select(null); } } @Override public int insert(SQLRow order) { // TODO: Pour l'instant appelé dans Swing, mais cela va changer... final int insertedId = super.insert(order); if (insertedId != SQLRow.NONEXISTANT_ID && sourceRows != null && !sourceRows.isEmpty()) { final SQLInjector injector = SQLInjector.getInjector(sourceRows.get(0).getTable(), this.getTable()); try { injector.commitTransfert(sourceRows, insertedId); } catch (Exception e) { ExceptionHandler.handle("Unable to insert transfert", e); } } return insertedId; } @Override public void select(SQLRowAccessor r) { if (r == null) { super.select(null); return; } // remove foreign and replace rowvalues by id final SQLRowValues singleRowValues = new SQLRowValues(r.asRowValues(), ForeignCopyMode.COPY_ID_OR_RM); super.select(singleRowValues); final RowValuesTable table = this.getRowValuesTable(); if (table != null) { table.clear(); table.insertFrom(r); } } protected RowValuesTable getRowValuesTable() { return null; } public static void openTransfertFrame(List<SQLRowValues> sourceRows, String destTableName, String groupID) { final SQLElement elt = Configuration.getInstance().getDirectory().getElement(destTableName); final EditFrame editFrame = new EditFrame(elt.createComponent(groupID), EditMode.CREATION); editFrame.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage()); final SQLComponent sqlComponent = editFrame.getSQLComponent(); if (sqlComponent instanceof TransfertGroupSQLComponent) { final TransfertGroupSQLComponent comp = (TransfertGroupSQLComponent) sqlComponent; if (!sourceRows.isEmpty()) { // fetch all fields of all table to avoid 1 request by referent row final List<Number> ids = new ArrayList<Number>(sourceRows.size()); for (SQLRowValues sqlRowValues : sourceRows) { ids.add(sqlRowValues.getIDNumber()); } final SQLRowValues row = sourceRows.get(0).deepCopy(); // FIXME don't work in the general case for (final SQLField rk : row.getTable().getDBSystemRoot().getGraph().getReferentKeys(row.getTable())) { final Set<SQLRowValues> referentRows = row.getReferentRows(rk); if (referentRows.size() > 1) { final Iterator<SQLRowValues> iter = new ArrayList<SQLRowValues>(referentRows).iterator(); // keep the first iter.next(); while (iter.hasNext()) { final SQLRowValues ref = iter.next(); ref.remove(rk.getName()); } } } for (SQLRowValues r : row.getGraph().getItems()) { final Set<String> fields = new HashSet<String>(r.getTable().getFieldsName()); fields.removeAll(r.getFields()); r.putNulls(fields, false); } final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(row); fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() { @Override public SQLSelect transformChecked(SQLSelect input) { input.setWhere(new Where(row.getTable().getKey(), ids)); return input; } }); final List<SQLRowValues> result = fetcher.fetch(); comp.importFrom(result); FrameUtil.show(editFrame); } } else { throw new IllegalArgumentException("Table " + destTableName + " SQLComponent is not a TransfertBaseSQLComponent"); } } }
gpl-3.0
cs-au-dk/Artemis
contrib/Kaluza/hampi/lib/stp-jni/stp/Type.java
1434
/** The MIT License Copyright (c) 2007 Adam Kiezun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package stp; public final class Type extends STPObject{ public Type(long handle) { super(handle); } @Override public String toString() { return typeString(); } /** * Return a string representation of the Type t. */ public String typeString() { return STPJNI.typeString(handle); } }
gpl-3.0
epam/Wilma
wilma-application/modules/wilma-webapp/src/main/java/com/epam/wilma/webapp/config/servlet/operation/mode/OperationModeStatusServlet.java
2948
package com.epam.wilma.webapp.config.servlet.operation.mode; /*========================================================================== Copyright since 2013, EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.epam.wilma.core.toggle.mode.ProxyModeToggle; import com.epam.wilma.router.RoutingService; /** * This servlet is used to get the status of the operation mode (wilma/proxy/stub), * and returns the information in JSON format. * @author Tunde_Kovacs */ @Component public class OperationModeStatusServlet extends HttpServlet { private final ProxyModeToggle proxyModeToggle; private final RoutingService routingService; /** * Constructor using spring framework to initialize the class. * @param proxyModeToggle is used to get information about the proxy mode * @param routingService is used to get information about the stub mode */ @Autowired public OperationModeStatusServlet(ProxyModeToggle proxyModeToggle, RoutingService routingService) { this.proxyModeToggle = proxyModeToggle; this.routingService = routingService; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); boolean proxyModeOn = proxyModeToggle.isProxyModeOn(); boolean stubModeOn = routingService.isStubModeOn(); boolean wilmaModeOn = !proxyModeOn && !stubModeOn; out.write("{\"proxyMode\":" + proxyModeOn + ",\"stubMode\":" + stubModeOn + ",\"wilmaMode\":" + wilmaModeOn + "}"); out.flush(); out.close(); } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
gpl-3.0
BennoGAP/notification-forwarder
SMS/src/main/java/org/groebl/sms/common/ListviewHelper.java
1784
package org.groebl.sms.common; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.ListView; import org.groebl.sms.R; import org.groebl.sms.ui.ThemeManager; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ListviewHelper { public static void applyCustomScrollbar(Context context, ListView listView) { if (context != null && listView != null) { try { Drawable drawable = ContextCompat.getDrawable(context, R.drawable.scrollbar); drawable.setColorFilter(Color.argb(64, Color.red(ThemeManager.getTextOnBackgroundSecondary()), Color.green(ThemeManager.getTextOnBackgroundSecondary()), Color.blue(ThemeManager.getTextOnBackgroundSecondary())), PorterDuff.Mode.SRC_ATOP); Field mScrollCacheField = View.class.getDeclaredField("mScrollCache"); mScrollCacheField.setAccessible(true); Object mScrollCache = mScrollCacheField.get(listView); Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar"); scrollBarField.setAccessible(true); Object scrollBar = scrollBarField.get(mScrollCache); Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class); method.setAccessible(true); method.invoke(scrollBar, drawable); } catch (Exception e) { e.printStackTrace(); } } } }
gpl-3.0
kevinwang/wedit
WEditServer/src/wedit/server/WEditServer.java
650
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package wedit.server; import wedit.net.SessionManager; /** * * @author Kevin Wang */ public class WEditServer { public static StringBuffer document = new StringBuffer(); public WEditServer() { RequestHandler.getInstance().start(); SessionManager.getInstance().start(); } /** * @param args the command line arguments */ public static void main(String[] args) { ServerFrame.getInstance().setVisible(true); ServerFrame.getInstance().consoleWrite("WEdit server started."); } }
gpl-3.0
DeerMichel/trafficsim
src/de/mh/trafficsim/engine/SimulationObject.java
318
package de.mh.trafficsim.engine; /** * Represents a simulated object */ public abstract class SimulationObject extends StaticObject { /** * Simulates for given (time) ticks * * @param ticks number of ticks to be simulated */ public abstract void simulate(int ticks); }
gpl-3.0
paulobcosta/ClassSimilarityAnalizer
src/br/com/localhost/utils/Tool.java
4560
package br.com.localhost.utils; import java.util.ArrayList; import br.com.localhost.similarity.ClassContent; import br.com.localhost.similarity.PackageContent; public class Tool { public Tool() { } public static boolean isDigit(String s) { return s.matches("[0-9]*"); } public static Double intToDouble(int value) { String s = String.valueOf(value); return Double.parseDouble(s); } public static double getEuclidianSimilarityTax(PackageContent pA, PackageContent pB) { ArrayList<Double> lA = new ArrayList<Double>(); ArrayList<Double> lB = new ArrayList<Double>(); ArrayList<String> auxiliarList = new ArrayList<String>(); for (int i = 0; i < pA.size(); i++) { auxiliarList.add(pA.get(i).getName()); } for (int k = 0; k < pB.size(); k++) { if (!auxiliarList.contains(pB.get(k).getName())) { auxiliarList.add(pB.get(k).getName()); } } for (String iterator : auxiliarList) { if (pA.containsWord(iterator) && pB.containsWord(iterator)) { lA.add(Tool.intToDouble(pA.get(pA.getIndexOfWord(iterator)) .getTimes())); lB.add(Tool.intToDouble(pB.get(pB.getIndexOfWord(iterator)) .getTimes())); } else if (!pA.containsWord(iterator) && pB.containsWord(iterator)) { lA.add(0.0); lB.add(Tool.intToDouble(pB.get(pB.getIndexOfWord(iterator)) .getTimes())); } else if (pA.containsWord(iterator) && !pB.containsWord(iterator)) { lA.add(Tool.intToDouble(pA.get(pA.getIndexOfWord(iterator)) .getTimes())); lB.add(0.0); } else { lA.add(0.0); lB.add(0.0); } } return (1.0 - Tool.getEuclidianDistance(lA, lB)); } public static double getEuclidianSimilarityTax(ClassContent cA, ClassContent cB) { ArrayList<Double> lA = new ArrayList<Double>(); ArrayList<Double> lB = new ArrayList<Double>(); ArrayList<String> auxiliarList = new ArrayList<String>(); for (int i = 0; i < cA.size(); i++) { auxiliarList.add(cA.get(i).getName()); } for (int k = 0; k < cB.size(); k++) { if (!auxiliarList.contains(cB.get(k).getName())) { auxiliarList.add(cB.get(k).getName()); } } for (String iterator : auxiliarList) { if (cA.containsWord(iterator) && cB.containsWord(iterator)) { lA.add(Tool.intToDouble(cA.get(cA.getIndexOfWord(iterator)) .getTimes())); lB.add(Tool.intToDouble(cB.get(cB.getIndexOfWord(iterator)) .getTimes())); } else if (!cA.containsWord(iterator) && cB.containsWord(iterator)) { lA.add(0.0); lB.add(Tool.intToDouble(cB.get(cB.getIndexOfWord(iterator)) .getTimes())); } else if (cA.containsWord(iterator) && !cB.containsWord(iterator)) { lA.add(Tool.intToDouble(cA.get(cA.getIndexOfWord(iterator)) .getTimes())); lB.add(0.0); } else { lA.add(0.0); lB.add(0.0); } } return 1.0 - Tool.getEuclidianDistance(lA, lB); } public static double getCamberraDistance(ArrayList<Double> lA, ArrayList<Double> lB) { ArrayList<Double> sum = new ArrayList<Double>(); ArrayList<Double> minus = new ArrayList<Double>(); ArrayList<Double> normalizedLA = new ArrayList<Double>(); ArrayList<Double> normalizedLB = new ArrayList<Double>(); ArrayList<Double> quot = new ArrayList<Double>(); double result = 0.0; double size = intToDouble(lA.size()); for (int i = 0; i < lA.size(); i++) { normalizedLA.add(lA.get(i) / (lA.get(i) + lB.get(i))); normalizedLB.add(lB.get(i) / (lA.get(i) + lB.get(i))); sum.add(normalizedLA.get(i) + normalizedLB.get(i)); minus.add(Math.abs((normalizedLA.get(i) - normalizedLB.get(i)))); quot.add((minus.get(i) / sum.get(i)) / size); result += quot.get(i); } return result; } public static Double getEuclidianDistance(ArrayList<Double> lA, ArrayList<Double> lB) { ArrayList<Double> normalizedLA = new ArrayList<Double>(); ArrayList<Double> normalizedLB = new ArrayList<Double>(); ArrayList<Double> totalData = new ArrayList<Double>(); ArrayList<Double> distances = new ArrayList<Double>(); ArrayList<Double> positiveDistances = new ArrayList<Double>(); double result = 0.0; double size = intToDouble(lA.size()); for (int k = 0; k < lA.size(); k++) { totalData.add(lA.get(k) + lB.get(k)); normalizedLA.add(lA.get(k) / totalData.get(k)); normalizedLB.add(lB.get(k) / totalData.get(k)); distances.add((normalizedLA.get(k) - normalizedLB.get(k))); positiveDistances.add(Math.pow(distances.get(k), 2)); result += (positiveDistances.get(k) / size); } result = Math.sqrt(result); if(result > 1.0) return 1.0; else return result; } }
gpl-3.0
stachu540/PhantomBot
source/tv/phantombot/discord/util/DiscordUtil.java
15169
/* * Copyright (C) 2016-2017 phantombot.tv * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tv.phantombot.discord; import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.handle.obj.IRole; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.MessageBuilder; import sx.blah.discord.util.RequestBuffer; import sx.blah.discord.util.EmbedBuilder; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.List; import java.io.FileNotFoundException; import java.io.File; import java.time.LocalDateTime; import java.awt.Color; /* * Has all of the methods to work with Discord4J. * * @author Illusionaryone * @author ScaniaTV */ public class DiscordUtil { /* * Method to send a message to a channel. * * @param {IChannel} channel * @param {String} message */ public void sendMessage(IChannel channel, String message) { RequestBuffer.request(() -> { try { if (channel != null) { com.gmt2001.Console.out.println("[DISCORD] [#" + channel.getName() + "] [CHAT] " + message); channel.sendMessage(message); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to send a message: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to send a message to a channel. * * @param {String} channelName * @param {String} message */ public void sendMessage(String channelName, String message) { sendMessage(getChannel(channelName), message); } /* * Method to send private messages to a user. * * @param {IUser} user * @param {String} message */ public void sendPrivateMessage(IUser user, String message) { RequestBuffer.request(() -> { try { if (user != null) { com.gmt2001.Console.out.println("[DISCORD] [@" + user.getName().toLowerCase() + "#" + user.getDiscriminator() + "] [DM] " + message); user.getOrCreatePMChannel().sendMessage(message); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to send a private message: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to send private messages to a user. * * @param {String} userName * @param {String} message */ public void sendPrivateMessage(String userName, String message) { sendPrivateMessage(getUser(userName), message); } /* * Method to send embed messages. * * @param {IChannel} channel * @param {String} message * @param {String} color */ public void sendMessageEmbed(IChannel channel, String message, String color) { EmbedObject builder = new EmbedBuilder().withDescription(message).withColor(getColor(color)).build(); RequestBuffer.request(() -> { try { if (channel != null) { com.gmt2001.Console.out.println("[DISCORD] [#" + channel.getName() + "] [EMBED] " + message); channel.sendMessage(builder); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to send an embed message: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to send embed messages. * * @param {String} channelName * @param {String} message * @param {String} color */ public void sendMessageEmbed(String channelName, String message, String color) { sendMessageEmbed(getChannel(channelName), message, color); } /* * Method to send a file to a channel. * * @param {IChannel} channel * @param {String} message * @param {String} fileLocation */ public void sendFile(IChannel channel, String message, String fileLocation) { RequestBuffer.request(() -> { try { if (channel != null) { com.gmt2001.Console.out.println("[DISCORD] [#" + channel.getName() + "] [UPLOAD] [" + fileLocation + "] " + message); if (message.isEmpty()) { channel.sendFile(new File(fileLocation)); } else { channel.sendFile(message, new File(fileLocation)); } } } catch (MissingPermissionsException | DiscordException | FileNotFoundException ex) { com.gmt2001.Console.err.println("Failed to upload a file: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to send a file to a channel. * * @param {String} channelName * @param {String} message * @param {String} fileLocation */ public void sendFile(String channelName, String message, String fileLocation) { sendFile(getChannel(channelName), message, fileLocation); } /* * Method to send a file to a channel. * * @param {String} channelName * @param {String} fileLocation */ public void sendFile(String channelName, String fileLocation) { sendFile(getChannel(channelName), "", fileLocation); } /* * Method to return a channel object by its name. * * @param {String} channelName * @return {IChannel} */ public IChannel getChannel(String channelName) { List<IChannel> channels = DiscordAPI.guild.getChannelsByName(channelName); for (IChannel channel : channels) { if (channel.getName().equals(channelName)) { return channel; } } return null; } /* * Method to return a user object by its name. * * @param {String} userName * @return {IUser} */ public IUser getUser(String userName) { List<IUser> users = DiscordAPI.guild.getUsersByName(userName, true); for (IUser user : users) { if (user.getDisplayName(DiscordAPI.guild).equals(userName)) { return user; } } return null; } /* * Method to return a user object by its name and its discriminator. * * @param {String} userName * @param {String} discriminator * @return {IUser} */ public IUser getUserWithDiscriminator(String userName, String discriminator) { List<IUser> users = DiscordAPI.guild.getUsersByName(userName, true); for (IUser user : users) { if (user.getDisplayName(DiscordAPI.guild).equals(userName) && user.getDiscriminator().equals(discriminator)) { return user; } } return null; } /* * Method to return a role object by its name. * * @param {String} roleName * @return {IRole} */ public IRole getRole(String roleName) { List<IRole> roles = DiscordAPI.guild.getRolesByName(roleName); for (IRole role : roles) { if (role.getName().equals(roleName)) { return role; } } return null; } /* * Method to set a role on a user. * * @param {IRole} role * @param {IUser} user */ public void addRole(IRole role, IUser user) { RequestBuffer.request(() -> { try { if (role != null && user != null) { user.addRole(role); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to add role on user: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to set a role on a user. * * @param {String} roleName * @param {String} userName */ public void addRole(String roleName, String userName) { addRole(getRole(roleName), getUser(userName)); } /* * Method to remove a role on a user. * * @param {IRole} role * @param {IUser} user */ public void removeRole(IRole role, IUser user) { RequestBuffer.request(() -> { try { if (role != null && user != null) { user.removeRole(role); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to remove role on user: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to remove a role on a user. * * @param {String} roleName * @param {String} userName */ public void removeRole(String roleName, String userName) { removeRole(getRole(roleName), getUser(userName)); } /* * Method to create a new role. * * @param {String} roleName */ public void createRole(String roleName) { RequestBuffer.request(() -> { try { DiscordAPI.guild.createRole().changeName(roleName); } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to create role: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to delete a role. * * @param {IRole} role */ public void deleteRole(IRole role) { RequestBuffer.request(() -> { try { if (role != null) { role.delete(); } } catch (MissingPermissionsException | DiscordException ex) { com.gmt2001.Console.err.println("Failed to delete role: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } /* * Method to delete a role. * * @param {String} roleName */ public void deleteRole(String roleName) { deleteRole(getRole(roleName)); } /* * Method to check if someone is an administrator. * * @param {IUser} user * @return {Boolean} */ public boolean isAdministrator(IUser user) { if (user != null) { return user.getPermissionsForGuild(DiscordAPI.guild).contains(Permissions.ADMINISTRATOR); } return false; } /* * Method to check if someone is an administrator. * * @param {String} userName * @return {Boolean} */ public boolean isAdministrator(String userName) { return isAdministrator(getUser(userName)); } /* * Method to bulk delete messages from a channel. * * @param {IChannel} channel * @param {Number} amount */ public void bulkDelete(IChannel channel, int amount) { // Discord4J says that getting messages can block the current thread if they need to be requested from Discord's API. // So start this on a new thread to avoid that. Please note that you need to delete at least 2 messages. if (channel != null) { Thread thread = new Thread(new Runnable() { @Override public void run() { RequestBuffer.request(() -> { try { List<IMessage> messages = channel.getMessageHistoryFrom(LocalDateTime.now(), (amount < 2 ? 2 : amount)); channel.bulkDelete(messages); } catch (DiscordException ex) { com.gmt2001.Console.err.println("Failed to bulk delete messages: [" + ex.getClass().getSimpleName() + "] " + ex.getMessage()); } }); } }, "tv.phantombot.discord.util.DiscordUtil::bulkDelete"); thread.start(); } } /* * Method to bulk delete messages from a channel. * * @param {String} channelName * @param {Number} amount */ public void bulkDelete(String channelName, int amount) { bulkDelete(getChannel(channelName), amount); } /* * Method to set the current game. * * @param {String} game */ public void setGame(String game) { DiscordAPI.shard.changePlayingText(game); } /* * Method to set the current game and stream. * * @param {String} game * @param {String} url */ public void setStream(String game, String url) { DiscordAPI.shard.streaming(game, url); } /* * Method to remove the current game or reset the streaming status. * */ public void removeGame() { DiscordAPI.shard.online(); } /* * Method to get a color object. * * @param {String} color * @return {Color} */ public Color getColor(String color) { Matcher match = Pattern.compile("(\\d{1,3}),?\\s?(\\d{1,3}),?\\s?(\\d{1,3})").matcher(color); if (match.find()) { return new Color(Integer.parseInt(match.group(1)), Integer.parseInt(match.group(2)), Integer.parseInt(match.group(3))); } else { switch (color) { case "black": return Color.black; case "blue": return Color.blue; case "cyan": return Color.cyan; case "gray": return Color.gray; case "green": return Color.green; case "magenta": return Color.magenta; case "orange": return Color.orange; case "pink": return Color.pink; case "red": return Color.red; case "white": return Color.white; case "yellow": return Color.yellow; default: return Color.gray; } } } }
gpl-3.0
AKSW/AutoSPARQL
commons/src/main/java/org/aksw/autosparql/commons/nlp/token/Tokenizer.java
119
package org.aksw.autosparql.commons.nlp.token; public interface Tokenizer { String[] tokenize(String sentence); }
gpl-3.0
gbrencic/apitZk
common/tests/hr.pleasantnightmare/network/simplegame/stage/SimpleCharacter.java
1233
package hr.pleasantnightmare.network.simplegame.stage; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; /** * User: gbrencic * Date: 29.08.12. * Time: 13:26 */ public class SimpleCharacter { private final Integer id; private float posX = 0; private float posY = 0; private transient int direction = 1; //1u2d3l4r private Rectangle shape = null; public SimpleCharacter(Integer id, int posX, int posY) { this.id = id; this.posX = posX; this.posY = posY; shape = new Rectangle(posX, posY, 10, 10); } public Shape getShape() { return shape; } public float getPosX() { return posX; } public void setPosX(float posX) { this.posX = posX; shape.setX(posX); } public float getPosY() { return posY; } public void setPosY(float posY) { this.posY = posY; shape.setY(posY); } public Integer getId() { return id; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } }
gpl-3.0
marvertin/geokuk
src/main/java/cz/geokuk/core/coordinates/Mercator.java
5651
package cz.geokuk.core.coordinates; /** * Merkátorové souřadnice jsou v metrech. Střed souřadnic [0,0] je na průsečíku rovníku a nultého poledníku. Osa X směřuje k východu, osa Y k severu. * * * TMS Global Mercator Profile --------------------------- * * Functions necessary for generation of tiles in Spherical Mercator projection, EPSG:900913 (EPSG:gOOglE, Google Maps Global Mercator), EPSG:3785, OSGEO:41001. * * Such tiles are compatible with Google Maps, Microsoft Virtual Earth, Yahoo Maps, UK Ordnance Survey OpenSpace API, ... and you can overlay them on top of base maps of those web mapping applications. * * Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left). * * What coordinate conversions do we need for TMS Global Mercator tiles:: * * LatLon <-> Meters <-> Pixels <-> Tile * * WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid lat/lon XY in metres XY pixels Z zoom XYZ from TMS EPSG:4326 EPSG:900913 .----. --------- -- TMS / \ <-> | | <-> /----/ <-> Google \ / | | /--------/ QuadTree ----- --------- /------------/ KML, public WebMapService Web * Clients TileMapService * * What is the coordinate extent of Earth in EPSG:900913? * * [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244] Constant 20037508.342789244 comes from the circumference of the Earth in meters, which is 40 thousand kilometers, the coordinate origin is in the middle of extent. In fact you can calculate the constant as: 2 * * math.pi * 6378137 / 2.0 $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:900913 Polar areas with abs(latitude) bigger then 85.05112878 are clipped off. * * What are zoom level constants (pixels/meter) for pyramid with EPSG:900913? * * whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile, every lower zoom level resolution is always divided by two initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062 * * What is the difference between TMS and Google Maps/QuadTree tile name convention? * * The tile raster itself is the same (equal extent, projection, pixel size), there is just different identification of the same raster tile. Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ. Google placed the origin [0,0] to the top-left corner, reference is XYZ. Microsoft * is referencing tiles by a QuadTree name, defined on the website: http://msdn2.microsoft.com/en-us/library/bb259689.aspx * * The lat/lon coordinates are using WGS84 datum, yeh? * * Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum. Well, the web clients like Google Maps are projecting those coordinates by Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if the were on the WGS84 ellipsoid. * * From MSDN documentation: To simplify the calculations, we use the spherical form of projection, not the ellipsoidal form. Since the projection is used only for map display, and not for displaying numeric coordinates, we don't need the extra precision of an ellipsoidal projection. The spherical * projection causes approximately 0.33 percent scale distortion in the Y direction, which is not visually noticable. * * How do I create a raster in EPSG:900913 and convert coordinates with PROJ.4? * * You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform. All of the tools supports -t_srs 'epsg:900913'. * * For other GIS programs check the exact definition of the projection: More info at http://spatialreference.org/ref/user/google-projection/ The same projection is degined as EPSG:3785. WKT definition is in the official EPSG database. * * Proj4 Text: +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs * * Human readable WKT format of EPGS:900913: PROJCS["Google Maps Global Mercator", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.2572235630016, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433], * AUTHORITY["EPSG","4326"]], PROJECTION["Mercator_1SP"], PARAMETER["central_meridian",0], PARAMETER["scale_factor",1], PARAMETER["false_easting",0], PARAMETER["false_northing",0], UNIT["metre",1, AUTHORITY["EPSG","9001"]]]* */ public class Mercator extends Misto0 { /** Poloměr země v metrech */ public final double mx; public final double my; public Mercator(final double aMx, final double aMy) { mx = aMx; my = aMy; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Mercator other = (Mercator) obj; if (Double.doubleToLongBits(mx) != Double.doubleToLongBits(other.mx)) { return false; } if (Double.doubleToLongBits(my) != Double.doubleToLongBits(other.my)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(mx); result = prime * result + (int) (temp ^ temp >>> 32); temp = Double.doubleToLongBits(my); result = prime * result + (int) (temp ^ temp >>> 32); return result; } @Override public Mercator toMercator() { return this; } @Override public Mou toMou() { return FGeoKonvertor.toMou(this); } @Override public String toString() { return String.format("Mercator[%f ; %f]", mx, my); } @Override public Utm toUtm() { return FGeoKonvertor.toUtm(this); } @Override public Wgs toWgs() { return FGeoKonvertor.toWgs(this); } }
gpl-3.0
MassAtLeeds/Cluster-Hunter
ClusterHunter/src/org/gavaghan/geodesy/GlobalCoordinates.java
4988
/* Geodesy by Mike Gavaghan * * http://www.gavaghan.org/blog/free-source-code/geodesy-library-vincentys-formula/ * * This code may be freely used and modified on any personal or professional * project. It comes with no warranty. */ package org.gavaghan.geodesy; import java.io.Serializable; /** * <p> * Encapsulation of latitude and longitude coordinates on a globe. Negative * latitude is southern hemisphere. Negative longitude is western hemisphere. * </p> * <p> * Any angle may be specified for longtiude and latitude, but all angles will be * canonicalized such that: * </p> * * <pre> * -90 &lt;= latitude &lt;= +90 - 180 &lt; longitude &lt;= +180 * </pre> * * @author Mike Gavaghan */ public class GlobalCoordinates implements Comparable<GlobalCoordinates>, Serializable { /** Latitude in degrees. Negative latitude is southern hemisphere. */ private double mLatitude; /** Longitude in degrees. Negative longitude is western hemisphere. */ private double mLongitude; /** * Canonicalize the current latitude and longitude values such that: * * <pre> * -90 &lt;= latitude &lt;= +90 - 180 &lt; longitude &lt;= +180 * </pre> */ private void canonicalize() { mLatitude = (mLatitude + 180) % 360; if (mLatitude < 0) { mLatitude += 360; } mLatitude -= 180; if (mLatitude > 90) { mLatitude = 180 - mLatitude; mLongitude += 180; } else if (mLatitude < -90) { mLatitude = -180 - mLatitude; mLongitude += 180; } mLongitude = ((mLongitude + 180) % 360); if (mLongitude <= 0) { mLongitude += 360; } mLongitude -= 180; } /** * Construct a new GlobalCoordinates. Angles will be canonicalized. * * @param latitude latitude in degrees * @param longitude longitude in degrees */ public GlobalCoordinates(double latitude, double longitude) { mLatitude = latitude; mLongitude = longitude; canonicalize(); } /** * Get latitude. * * @return latitude in degrees */ public double getLatitude() { return mLatitude; } /** * Set latitude. The latitude value will be canonicalized (which might result * in a change to the longitude). Negative latitude is southern hemisphere. * * @param latitude in degrees */ public void setLatitude(double latitude) { mLatitude = latitude; canonicalize(); } /** * Get longitude. * * @return longitude in degrees */ public double getLongitude() { return mLongitude; } /** * Set longitude. The longitude value will be canonicalized. Negative * longitude is western hemisphere. * * @param longitude in degrees */ public void setLongitude(double longitude) { mLongitude = longitude; canonicalize(); } /** * Compare these coordinates to another set of coordiates. Western longitudes * are less than eastern logitudes. If longitudes are equal, then southern * latitudes are less than northern latitudes. * * @param other instance to compare to * @return -1, 0, or +1 as per Comparable contract */ @Override public int compareTo(GlobalCoordinates other) { int retval; if (mLongitude < other.mLongitude) { retval = -1; } else if (mLongitude > other.mLongitude) { retval = +1; } else if (mLatitude < other.mLatitude) { retval = -1; } else if (mLatitude > other.mLatitude) { retval = +1; } else { retval = 0; } return retval; } /** * Get a hash code for these coordinates. * * @return */ @Override public int hashCode() { return ((int) (mLongitude * mLatitude * 1000000 + 1021)) * 1000033; } /** * Compare these coordinates to another object for equality. * * @param other * @return */ @Override public boolean equals(Object obj) { if (!(obj instanceof GlobalCoordinates)) { return false; } GlobalCoordinates other = (GlobalCoordinates) obj; return (mLongitude == other.mLongitude) && (mLatitude == other.mLatitude); } /** * Get coordinates as a string. */ @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(Math.abs(mLatitude)); buffer.append((mLatitude >= 0) ? 'N' : 'S'); buffer.append(';'); buffer.append(Math.abs(mLongitude)); buffer.append((mLongitude >= 0) ? 'E' : 'W'); buffer.append(';'); return buffer.toString(); } }
gpl-3.0
DScripting/DCows
DTools/DGrandExchange.java
4290
package scripts.DTools; import java.awt.Image; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DGrandExchange { public Item getData(final int itemID) { try { URL u = new URL("http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" + itemID); URLConnection c = u.openConnection(); BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream())); try { String text = r.readLine(); if (text == null || text.length() == 0) return null; Image icon = null; Image icon_large = null; int id = -1; String name = ""; String description = ""; int price = -1; boolean members = true; String regex = "http(\\D+)(\\d+)(\\D+)(\\d+)"; Matcher matcher = Pattern.compile(regex).matcher(text); for (int i = 1; i <= 2; i++) { if (matcher.find()) { if (i == 1) { //icon = getImage(matcher.group().replaceAll("itemdb_rs", "itemdb_oldschool")); } else { //icon_large = getImage(matcher.group().replaceAll("itemdb_rs", "itemdb_oldschool")); } } } regex = "id\":(\\d+)"; matcher = Pattern.compile(regex).matcher(text); if (matcher.find()) id = Integer.parseInt(matcher.group().replaceAll("\\D+", "")); regex = "name\":\"[^\"]+"; matcher = Pattern.compile(regex).matcher(text); if (matcher.find()) name = matcher.group().substring(7); regex = "description\":\"[^\"]+"; matcher = Pattern.compile(regex).matcher(text); if (matcher.find()) description = matcher.group().substring(14); regex = "current\"\\:\\{(.*?)\\}"; matcher = Pattern.compile(regex).matcher(text); if (matcher.find()) { regex = matcher.group().replaceAll("\"|:|}|\\{|,", "").replaceAll("^(.*?)price", ""); if (regex.contains("m")) { price = Integer.parseInt(String.format("%.0f", Double.parseDouble(regex.replaceAll("[^\\d.]", "")) * 1000000)); } else if (regex.contains("k")) { price = Integer.parseInt( String.format("%.0f", Double.parseDouble(regex.replaceAll("[^\\d.]", "")) * 1000)); } else { price = Integer.parseInt(regex); } } regex = "members\":\"[^\"]+"; matcher = Pattern.compile(regex).matcher(text); if (matcher.find()) if (matcher.group().substring(10).contains("false")) members = false; return new Item(icon, icon_large, id, name, description, price, members); } finally { r.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public class Item { private Image icon; private Image icon_large; private int id; private String name; private String description; private int price; private boolean members; private Item(Image icon, Image icon_large, int id, String name, String description, int price, boolean members) { this.icon = icon; this.icon_large = icon_large; this.id = id; this.name = name; this.description = description; this.price = price; this.members = members; } private Image getIcon() { return icon; } private Image getIconLarge() { return icon_large; } private int getID() { return id; } private String getName() { return name; } private String getDescription() { return description; } public int getPrice() { return price; } private boolean isMembers() { return members; } } }
gpl-3.0
LKylin/DatingMoments
app/src/main/java/com/kylin/datingmoments/activity/VoidActivity.java
380
package com.kylin.datingmoments.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.kylin.datingmoments.R; public class VoidActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_void); } }
gpl-3.0
kuros/random-jpa
src/main/java/com/github/kuros/random/jpa/annotation/VisibleForTesting.java
812
package com.github.kuros.random.jpa.annotation; /* * Copyright (c) 2015 Kumar Rohit * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License or any * later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public @interface VisibleForTesting { }
gpl-3.0
sugarpramana/JHRM
Module-Parent/Module-Hr/src/main/java/org/module/hr/model/MstLeavePeriod.java
4532
package org.module.hr.model; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlTransient; /** * * @author formulateko@admin.com */ @Entity @Table(name = "mst_leave_period", catalog = "dbhr", schema = "schema_hr") public class MstLeavePeriod implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id_leave_period") @SequenceGenerator(name="MstLeavePeriod_idLeavePeriod_GENERATOR", sequenceName="SCHEMA_HR.MstLeavePeriod_idLeavePeriod_SEQ") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "MstLeavePeriod_idLeavePeriod_GENERATOR") private Integer idLeavePeriod; @Column(name = "from_date") @Temporal(javax.persistence.TemporalType.DATE) private Date fromDate; @Column(name = "to_date") @Temporal(javax.persistence.TemporalType.DATE) private Date toDate; @Column(name = "options_from_date") @Temporal(javax.persistence.TemporalType.DATE) private Date optionsFromDate; @OneToMany(mappedBy = "idLeavePeriod") private List<TrsEntitlement> trsEntitlementList; @Transient Calendar cal = Calendar.getInstance(); public MstLeavePeriod() { cal.set(Calendar.MONTH, 0); cal.set(Calendar.DATE, 1); this.setOptionsFromDate(cal.getTime()); cal.add(Calendar.YEAR, 1); cal.add(Calendar.DATE, -1); this.setToDate(cal.getTime()); } public MstLeavePeriod(Integer idLeavePeriod) { this.idLeavePeriod = idLeavePeriod; } public Integer getIdLeavePeriod() { return idLeavePeriod; } public void setIdLeavePeriod(Integer idLeavePeriod) { this.idLeavePeriod = idLeavePeriod; } public Date getFromDate() { return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } public Date getToDate() { return toDate; } public void setToDate(Date toDate) { this.toDate = toDate; } public Date getOptionsFromDate() { return optionsFromDate; } public void setOptionsFromDate(Date optionsFromDate) { this.optionsFromDate = optionsFromDate; } @XmlTransient public List<TrsEntitlement> getTrsEntitlementList() { return trsEntitlementList; } public void setTrsEntitlementList(List<TrsEntitlement> trsEntitlementList) { this.trsEntitlementList = trsEntitlementList; } //For UI public Integer getSelectedFromDateMonth() { cal.setTime(this.optionsFromDate); return cal.get(Calendar.MONTH); } public void setSelectedFromDateMonth(Integer selectedFromDateMonth) { cal.setTime(this.optionsFromDate); cal.set(Calendar.MONTH, selectedFromDateMonth); this.optionsFromDate = cal.getTime(); cal.add(Calendar.YEAR, 1); cal.add(Calendar.DATE, -1); this.toDate = cal.getTime(); } public Integer getSelectedFromDateDate() { cal.setTime(this.optionsFromDate); return cal.get(Calendar.DAY_OF_MONTH); } public void setSelectedFromDateDate(Integer selectedFromDateDate) { cal.setTime(this.optionsFromDate); cal.set(Calendar.DAY_OF_MONTH, selectedFromDateDate); this.optionsFromDate = cal.getTime(); cal.add(Calendar.YEAR, 1); cal.add(Calendar.DATE, -1); this.toDate = cal.getTime(); } public String getSelectedToDate() { cal.setTime(this.toDate); String strToDate = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + " " + cal.get(Calendar.DATE); if(cal.get(Calendar.YEAR) > Calendar.getInstance().get(Calendar.YEAR)){ strToDate += " (Following Year)"; } return strToDate; } }
gpl-3.0
lecousin/net.lecousin.dataorganizer-0.1
net.lecousin.dataorganizer/src/net/lecousin/dataorganizer/ui/control/RateControl.java
4880
package net.lecousin.dataorganizer.ui.control; import net.lecousin.dataorganizer.Local; import net.lecousin.framework.event.Event; import net.lecousin.framework.event.Event.Listener; import net.lecousin.framework.ui.eclipse.SharedImages; import net.lecousin.framework.ui.eclipse.UIUtil; import net.lecousin.framework.ui.eclipse.control.UIControlUtil; import net.lecousin.framework.ui.eclipse.dialog.CalloutToolTip; import net.lecousin.framework.ui.eclipse.dialog.FlatPopupMenu; import net.lecousin.framework.ui.eclipse.graphics.ColorUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; public class RateControl extends Composite { public RateControl(Composite parent, byte rate, boolean editable) { super(parent, SWT.NONE); super.setBackground(parent.getBackground()); etoile[0] = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_EMPTY); etoile[1] = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_QUART); etoile[2] = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_HALF); etoile[3] = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_3QUART); etoile[4] = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_FULL); disabled = SharedImages.getImage(SharedImages.icons.x16.basic.STAR_YELLOW_DISABLED); UIUtil.gridLayout(this, 5, 2, 2).horizontalSpacing = 0; l1 = UIUtil.newImage(this, disabled); l2 = UIUtil.newImage(this, disabled); l3 = UIUtil.newImage(this, disabled); l4 = UIUtil.newImage(this, disabled); l5 = UIUtil.newImage(this, disabled); l1.setBackground(ColorUtil.getWhite()); l2.setBackground(ColorUtil.getWhite()); l3.setBackground(ColorUtil.getWhite()); l4.setBackground(ColorUtil.getWhite()); l5.setBackground(ColorUtil.getWhite()); setRate(rate); if (editable) UIControlUtil.recursiveMouseListener(this, new Mouse(), true); UIControlUtil.recursiveMouseTrackListener(this, new MouseTrack(), true); } private Image[] etoile = new Image[5]; private Image disabled; private Label l1, l2, l3, l4, l5; private Event<Byte> rateChanged = new Event<Byte>(); public Event<Byte> rateChanged() { return rateChanged; } @Override public Point computeSize(int hint, int hint2, boolean changed) { Point size = new Point(hint, hint2); if (hint == SWT.DEFAULT) size.x = 5*12+2*2; if (hint2 == SWT.DEFAULT) size.y = 12+2*2; return size; } @Override public void setBackground(Color color) { // l1.setBackground(color); // l2.setBackground(color); // l3.setBackground(color); // l4.setBackground(color); // l5.setBackground(color); super.setBackground(color); } private byte rate = -1; public void setRate(byte rate) { if (rate == this.rate) return; this.rate = rate; if (rate < 0) { l1.setImage(disabled); l2.setImage(disabled); l3.setImage(disabled); l4.setImage(disabled); l5.setImage(disabled); } else { if (rate < 5) l1.setImage(etoile[rate]); else l1.setImage(etoile[4]); if (rate < 5) l2.setImage(etoile[0]); else if (rate > 7) l2.setImage(etoile[4]); else l2.setImage(etoile[rate-4]); if (rate < 9) l3.setImage(etoile[0]); else if (rate > 11) l3.setImage(etoile[4]); else l3.setImage(etoile[rate-8]); if (rate < 13) l4.setImage(etoile[0]); else if (rate > 15) l4.setImage(etoile[4]); else l4.setImage(etoile[rate-12]); if (rate < 17) l5.setImage(etoile[0]); else if (rate > 19) l5.setImage(etoile[4]); else l5.setImage(etoile[rate-16]); } rateChanged.fire(rate); } private class Mouse implements MouseListener { public void mouseDown(MouseEvent e) { } public void mouseUp(MouseEvent e) { edit(); } public void mouseDoubleClick(MouseEvent e) { edit(); } } public void edit() { FlatPopupMenu dlg = new FlatPopupMenu(this, Local.Select_your_rating.toString(), true, true, false, false); RateEditPanel rateControl = new RateEditPanel(dlg.getControl(), rate); rateControl.rateChanged().addListener(new Listener<Byte>() { public void fire(Byte event) { setRate(event); } }); dlg.show(this, FlatPopupMenu.Orientation.BOTTOM_RIGHT, true); } private class MouseTrack implements MouseTrackListener { public void mouseEnter(MouseEvent e) { } public void mouseExit(MouseEvent e) { } public void mouseHover(MouseEvent e) { String text; if (rate < 0) text = Local.Not_rated.toString(); else text = ""+rate+"/20"; CalloutToolTip.open(RateControl.this, CalloutToolTip.Orientation.BOTTOM_RIGHT, text, 1500, -1); } } }
gpl-3.0
marvisan/HadesFIX
Model/src/main/java/net/hades/fix/message/group/impl/v43/MDReqGroup43.java
5070
/* * Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved. * Use is subject to license terms. */ /* * MDReqGroup43.java * * $Id: MDReqGroup43.java,v 1.7 2011-04-14 23:44:48 vrotaru Exp $ */ package net.hades.fix.message.group.impl.v43; import net.hades.fix.message.struct.Tag; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import net.hades.fix.message.FragmentContext; import net.hades.fix.message.comp.Instrument; import net.hades.fix.message.comp.impl.v43.Instrument43; import net.hades.fix.message.exception.BadFormatMsgException; import net.hades.fix.message.exception.InvalidMsgException; import net.hades.fix.message.exception.TagNotPresentException; import net.hades.fix.message.group.MDReqGroup; /** * FIX 4.3 implementation of MDReqGroup group. * * @author <a href="mailto:support@marvisan.com">Support Team</a> * @version $Revision: 1.7 $ * @created 05/04/2009, 11:39:24 AM */ public class MDReqGroup43 extends MDReqGroup { // <editor-fold defaultstate="collapsed" desc="Constants"> private static final long serialVersionUID = -8371079496852507203L; protected static final Set<Integer> START_COMP_TAGS; protected static final Set<Integer> ALL_TAGS; protected static final Set<Integer> INSTRUMENT_COMP_TAGS = new Instrument43().getFragmentAllTags(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Static Block"> static { ALL_TAGS = new HashSet<Integer>(TAGS); ALL_TAGS.addAll(INSTRUMENT_COMP_TAGS); START_COMP_TAGS = new HashSet<Integer>(INSTRUMENT_COMP_TAGS); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Attributes"> protected Set<Integer> STANDARD_SECURED_TAGS = ALL_TAGS; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> public MDReqGroup43() { SECURED_TAGS = STANDARD_SECURED_TAGS; FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired); instrument = new Instrument43(context); } public MDReqGroup43(FragmentContext context) { super(context); SECURED_TAGS = STANDARD_SECURED_TAGS; instrument = new Instrument43(context); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Public Methods"> @Override public Set<Integer> getFragmentAllTags() { return ALL_TAGS; } // ACCESSORS ////////////////////////////////////////// @Override public Instrument getInstrument() { return instrument; } @Override public void setInstrument() { this.instrument = new Instrument43(new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired)); } public void setInstrument(Instrument instrument) { this.instrument = instrument; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected Methods"> @Override protected byte[] encodeFragmentSecured(boolean secured) throws TagNotPresentException, BadFormatMsgException { if (validateRequired) { validateRequiredTags(); } byte[] result = new byte[0]; ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { bao.write(instrument.encode(getMsgSecureTypeForFlag(secured))); result = bao.toByteArray(); } catch (IOException ex) { String error = "Error writing to the byte array."; LOGGER.log(Level.SEVERE, "{0} Error was : {1}", new Object[] { error, ex.toString() }); throw new BadFormatMsgException(error, ex); } return result; } @Override protected void setFragmentCompTagValue(Tag tag, ByteBuffer message) throws BadFormatMsgException, InvalidMsgException, TagNotPresentException { FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired); if (INSTRUMENT_COMP_TAGS.contains(tag.tagNum)) { if (instrument == null) { instrument = new Instrument43(context); } instrument.decode(tag, message); } } @Override protected String getUnsupportedTagMessage() { return "This tag is not supported in [MDReqGroup] group version [4.3]."; } @Override protected Set<Integer> getFragmentCompTags() { return START_COMP_TAGS; } @Override protected Set<Integer> getFragmentSecuredTags() { return SECURED_TAGS; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Package Methods"> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Private Methods"> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Inner Classes"> // </editor-fold> }
gpl-3.0
F1rst-Unicorn/stocks
server/src/main/java/de/njsm/stocks/server/v2/business/LocationManager.java
3218
/* stocks is client-server program to manage a household's food stock * Copyright (C) 2019 The stocks developers * * This file is part of the stocks program suite. * * stocks is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * stocks is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.njsm.stocks.server.v2.business; import de.njsm.stocks.common.api.Location; import de.njsm.stocks.common.api.StatusCode; import de.njsm.stocks.common.api.LocationForDeletion; import de.njsm.stocks.common.api.LocationForInsertion; import de.njsm.stocks.common.api.LocationForRenaming; import de.njsm.stocks.common.api.LocationForSetDescription; import de.njsm.stocks.server.util.Principals; import de.njsm.stocks.server.v2.db.FoodHandler; import de.njsm.stocks.server.v2.db.FoodItemHandler; import de.njsm.stocks.server.v2.db.LocationHandler; import de.njsm.stocks.server.v2.db.jooq.tables.records.LocationRecord; public class LocationManager extends BusinessObject<LocationRecord, Location> implements BusinessGettable<LocationRecord, Location>, BusinessAddable<LocationRecord, Location>, BusinessDeletable<LocationForDeletion, Location> { private final LocationHandler locationHandler; private final FoodItemHandler foodItemHandler; private final FoodHandler foodHandler; public LocationManager(LocationHandler locationHandler, FoodHandler foodHandler, FoodItemHandler foodItemHandler) { super(locationHandler); this.locationHandler = locationHandler; this.foodHandler = foodHandler; this.foodItemHandler = foodItemHandler; } public StatusCode put(LocationForInsertion location) { return add(location); } public StatusCode rename(LocationForRenaming item) { return runOperation(() -> locationHandler.rename(item)); } public StatusCode delete(LocationForDeletion l) { return runOperation(() -> { if (l.cascade()) { StatusCode deleteFoodResult = foodItemHandler.deleteItemsStoredIn(l); if (deleteFoodResult != StatusCode.SUCCESS) return deleteFoodResult; } return foodHandler.unregisterDefaultLocation(l) .bind(() -> locationHandler.delete(l)); }); } @Override public void setPrincipals(Principals principals) { super.setPrincipals(principals); foodHandler.setPrincipals(principals); foodItemHandler.setPrincipals(principals); } public StatusCode setDescription(LocationForSetDescription data) { return runOperation(() -> locationHandler.setDescription(data)); } }
gpl-3.0
arneboe/PixelController
pixelcontroller-core/src/main/java/com/neophob/sematrix/core/visual/effect/Options/FloatValueOption.java
927
package com.neophob.sematrix.core.visual.effect.Options; public class FloatValueOption implements IOption { private final String name; private final float min; private final float max; private float value; private boolean hasChanged = false; public FloatValueOption(final String name, final float min, final float max, final float value) { this.name = name; this.min = min; this.max = max; this.value = value; } @Override public String getName() { return name; } public float getLower() { return min; } public float getUpper() { return max; } public float getValue() { return value; } public void setValue(final float v) { value = v; hasChanged = true; } public boolean changed() { boolean ret = hasChanged; hasChanged = false; return ret; } }
gpl-3.0
ijlalhussain/LogGenerator
DeclareDesigner/src/net/sourceforge/jeval/VariableStore.java
280
package net.sourceforge.jeval; public interface VariableStore { /** * Gets the value of a variable, the variable will include the * * @param variable * @return * @throws MalformedExpression */ public double getValue(String variable) throws MalformedExpression; }
gpl-3.0
libdeos/deos-rsksmart
lib/rskj/rskj-core/src/main/java/co/rsk/core/RskFactory.java
4839
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.core; import co.rsk.blocks.FileBlockPlayer; import co.rsk.blocks.FileBlockRecorder; import co.rsk.config.RskSystemProperties; import co.rsk.net.BlockProcessResult; import org.ethereum.config.DefaultConfig; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.Blockchain; import org.ethereum.core.ImportResult; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.server.ChannelManager; import org.ethereum.util.BuildInfo; import org.ethereum.util.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; /** * Created by ajlopez on 3/3/2016. */ @Component public class RskFactory { private static final Logger logger = LoggerFactory.getLogger("general"); private static ApplicationContext context; private RskFactory(){ } public static Rsk createRsk() { return createRsk((Class) null); } public static ApplicationContext getContext(){ return context; } public static Rsk createRsk(Class userSpringConfig) { return createRsk(SystemProperties.CONFIG, userSpringConfig); } public static Rsk createRsk(SystemProperties config, Class userSpringConfig) { logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier()); BuildInfo.printInfo(); if (config.databaseReset()){ FileUtil.recursiveDelete(config.databaseDir()); logger.info("Database reset done"); } return userSpringConfig == null ? createRsk(new Class[] {DefaultConfig.class}) : createRsk(DefaultConfig.class, userSpringConfig); } public static Rsk createRsk(Class ... springConfigs) { if (logger.isInfoEnabled()) { StringBuilder versions = new StringBuilder(); for (EthVersion v : EthVersion.supported()) { versions.append(v.getCode()).append(", "); } versions.delete(versions.length() - 2, versions.length()); logger.info("capability eth version: [{}]", versions); } context = new AnnotationConfigApplicationContext(springConfigs); final Rsk rs = context.getBean(Rsk.class); rs.getBlockchain().setRsk(true); if (RskSystemProperties.RSKCONFIG.isBlocksEnabled()) { String recorder = RskSystemProperties.RSKCONFIG.blocksRecorder(); if (recorder != null) { String filename = recorder; rs.getBlockchain().setBlockRecorder(new FileBlockRecorder(filename)); } final String player = RskSystemProperties.RSKCONFIG.blocksPlayer(); if (player != null) { new Thread() { @Override public void run() { try (FileBlockPlayer bplayer = new FileBlockPlayer(player)) { ((RskImpl)rs).setIsPlayingBlocks(true); Blockchain bc = rs.getWorldManager().getBlockchain(); ChannelManager cm = rs.getChannelManager(); for (Block block = bplayer.readBlock(); block != null; block = bplayer.readBlock()) { ImportResult tryToConnectResult = bc.tryToConnect(block); if (BlockProcessResult.importOk(tryToConnectResult)) { cm.broadcastBlock(block, null); } } } catch (Exception e) { logger.error("Error", e); } finally { ((RskImpl)rs).setIsPlayingBlocks(false); } } }.start(); } } return rs; } }
gpl-3.0
andrezma/ProbandoAga
src/entidades/TercerosresolucionesJpaController.java
12337
package entidades; import clases.ClaseBaseDatos; import clases.ClaseGeneral; import clases.ClaseInformacion; import clases.ClaseMensaje; import java.math.BigDecimal; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel; public class TercerosresolucionesJpaController { private ClaseBaseDatos datos = new ClaseBaseDatos(); private ClaseInformacion informacion = new ClaseInformacion(); public TercerosresolucionesJpaController() { } public void create(Tercerosresoluciones tercerosresoluciones) { try { datos.query("INSERT INTO " + tercerosresoluciones.tabla + " VALUES (" // + tercerosresoluciones.getId() + ", " + tercerosresoluciones.getAno() + ", " + tercerosresoluciones.getFkresolucion() + ", " + "'" + tercerosresoluciones.getFktercero() + "', " + tercerosresoluciones.getValor() + ", " + "'" + tercerosresoluciones.getDestino() + "', " + "'" + tercerosresoluciones.getObjetivo() + "', " + "'" + tercerosresoluciones.getSoporte() + "', " + "'" + tercerosresoluciones.getTarifa() + "', " + tercerosresoluciones.getSalario() + ", " + tercerosresoluciones.getDiario() + ", " + "'" + tercerosresoluciones.getFkcomprobante() + "', " + "'" + tercerosresoluciones.getFkcuenta() + "') RETURNING id"); while (ClaseBaseDatos.resultado.next()) { ClaseGeneral.idTercerosresolucion = ClaseBaseDatos.resultado.getInt("ID"); } if (!datos.isError) { ClaseMensaje.informacionGuardarBD("Articulos - Resolucion"); } } catch (Exception ex) { ClaseMensaje.errorGuardarBD(); } finally { } } public void edit(Tercerosresoluciones tercerosresoluciones, Tercerosresoluciones id) { try { datos.update("UPDATE TERCEROSRESOLUCION SET " // + "ID = " + tercerosresoluciones.getId() + ", " + "ANO = " + tercerosresoluciones.getAno() + ", " + "FKRESOLUCION = " + tercerosresoluciones.getFkresolucion() + ", " + "FKTERCERO = '" + tercerosresoluciones.getFktercero() + "', " + "VALOR = " + tercerosresoluciones.getValor() + ", " + "DESTINO = '" + tercerosresoluciones.getDestino() + "', " + "OBJETIVO = '" + tercerosresoluciones.getObjetivo() + "', " + "SOPORTE = '" + tercerosresoluciones.getSoporte() + "', " + "TARIFA = '" + tercerosresoluciones.getTarifa() + "', " + "SALARIO = " + tercerosresoluciones.getSalario() + ", " + "DIARIO = " + tercerosresoluciones.getDiario() + ", " + "FKCOMPROBANTE = '" + tercerosresoluciones.getFkcomprobante()+ "', " + "FKCUENTA = '" + tercerosresoluciones.getFkcuenta() + "' " + "WHERE " + "ID = " + id.getId() + " " + "AND ANO = " + id.getAno()); if (!datos.isError) { ClaseMensaje.informacionActualizarBD("Articulos - Resolucion"); } } catch (Exception ex) { ClaseMensaje.errorActualizarBD(); } finally { } } public void editFktercero(String fktercero, String id) { try { datos.update("UPDATE TERCEROSRESOLUCION SET " + "FKTERCERO = '" + fktercero + "' " + "WHERE " + "FKTERCERO LIKE '" + id + " - %'"); } catch (Exception ex) { ClaseMensaje.errorActualizarBD(); } finally { } } public void destroy(Tercerosresoluciones id) { try { datos.update("DELETE FROM TERCEROSRESOLUCION " + "WHERE " + "ID = " + id.getId() + " " + "AND ANO = " + id.getAno()); if (!datos.isError) { ClaseMensaje.informacionEliminarBD("Articulos - Resolucion"); } } catch (Exception ex) { ClaseMensaje.errorEliminarBD(); } finally { } } public void destroyFkresolucionAno(Resoluciones id) { try { datos.update("DELETE FROM TERCEROSRESOLUCION " + "WHERE " + "FKRESOLUCION = " + id.getResolucionPK().getId() + " AND " + "ANO = " + id.getResolucionPK().getAno()); if (!datos.isError) { ClaseMensaje.informacionEliminarBD("Articulos - Resolucion"); } } catch (Exception ex) { ClaseMensaje.errorEliminarBD(); } finally { } } public List<Tercerosresoluciones> findAllInTercerosresolucionesBy() { List<Tercerosresoluciones> listTercerosresoluciones = new ArrayList<Tercerosresoluciones>(); Tercerosresoluciones tercerosresoluciones = new Tercerosresoluciones(); try { datos.query("SELECT * FROM TERCEROSRESOLUCION " + "WHERE " + ClaseGeneral.parametro + " LIKE '%" + ClaseGeneral.valor + "%'");//ORDER BY while (ClaseBaseDatos.resultado.next()) { tercerosresoluciones = new Tercerosresoluciones(); tercerosresoluciones.setId(ClaseBaseDatos.resultado.getInt("ID")); tercerosresoluciones.setAno(ClaseBaseDatos.resultado.getInt("ANO")); tercerosresoluciones.setFkresolucion(ClaseBaseDatos.resultado.getInt("FKRESOLUCION")); tercerosresoluciones.setFktercero(ClaseBaseDatos.resultado.getString("FKTERCERO")); tercerosresoluciones.setValor(BigDecimal.valueOf(Long.parseLong("" + ClaseBaseDatos.resultado.getBigDecimal("VALOR")))); tercerosresoluciones.setDestino(ClaseBaseDatos.resultado.getString("DESTINO")); tercerosresoluciones.setObjetivo(ClaseBaseDatos.resultado.getString("OBJETIVO")); tercerosresoluciones.setSoporte(ClaseBaseDatos.resultado.getString("SOPORTE")); tercerosresoluciones.setTarifa(ClaseBaseDatos.resultado.getString("TARIFA")); tercerosresoluciones.setSalario(BigDecimal.valueOf(Long.parseLong("" + ClaseBaseDatos.resultado.getBigDecimal("SALARIO")))); tercerosresoluciones.setDiario(ClaseBaseDatos.resultado.getDouble("DIARIO")); tercerosresoluciones.setFkcomprobante(ClaseBaseDatos.resultado.getString("FKCOMPROBANTE")); tercerosresoluciones.setFkcuenta(ClaseBaseDatos.resultado.getString("FKCUENTA")); listTercerosresoluciones.add(tercerosresoluciones); } return listTercerosresoluciones; } catch (SQLException ex) { ClaseMensaje.errorFind(this.toString(), ex.toString()); return null; } } public List<Tercerosresoluciones> findAllInTercerosresolucionesByFkresolucionAno(int fkresolucion, int ano) { List<Tercerosresoluciones> listTercerosresoluciones = new ArrayList<Tercerosresoluciones>(); Tercerosresoluciones tercerosresoluciones = new Tercerosresoluciones(); try { datos.query("SELECT * FROM TERCEROSRESOLUCION " + "WHERE " + "fkresolucion = " + fkresolucion + " " + "AND ano = " + ano + "");//ORDER BY while (ClaseBaseDatos.resultado.next()) { tercerosresoluciones = new Tercerosresoluciones(); tercerosresoluciones.setId(ClaseBaseDatos.resultado.getInt("ID")); tercerosresoluciones.setAno(ClaseBaseDatos.resultado.getInt("ANO")); tercerosresoluciones.setFkresolucion(ClaseBaseDatos.resultado.getInt("FKRESOLUCION")); tercerosresoluciones.setFktercero(ClaseBaseDatos.resultado.getString("FKTERCERO")); tercerosresoluciones.setValor(BigDecimal.valueOf(Long.parseLong("" + ClaseBaseDatos.resultado.getBigDecimal("VALOR")))); tercerosresoluciones.setDestino(ClaseBaseDatos.resultado.getString("DESTINO")); tercerosresoluciones.setObjetivo(ClaseBaseDatos.resultado.getString("OBJETIVO")); tercerosresoluciones.setSoporte(ClaseBaseDatos.resultado.getString("SOPORTE")); tercerosresoluciones.setTarifa(ClaseBaseDatos.resultado.getString("TARIFA")); tercerosresoluciones.setSalario(BigDecimal.valueOf(Long.parseLong("" + ClaseBaseDatos.resultado.getBigDecimal("SALARIO")))); tercerosresoluciones.setDiario(ClaseBaseDatos.resultado.getDouble("DIARIO")); tercerosresoluciones.setFkcomprobante(ClaseBaseDatos.resultado.getString("FKCOMPROBANTE")); tercerosresoluciones.setFkcuenta(ClaseBaseDatos.resultado.getString("FKCUENTA")); listTercerosresoluciones.add(tercerosresoluciones); } return listTercerosresoluciones; } catch (SQLException ex) { ClaseMensaje.errorFind(this.toString(), ex.toString()); return null; } } // public int findFkresolucionInTercerosresolucionesBySoporte(String soporte) { // int fkresolucion = 0; // // try { // datos.query("SELECT * FROM TERCEROSRESOLUCION " // + "WHERE " // + "soporte = '" + soporte + "'");//ORDER BY // while (ClaseBaseDatos.resultado.next()) { // fkresolucion = ClaseBaseDatos.resultado.getInt("FKRESOLUCION"); // } // return fkresolucion; // } catch (SQLException ex) { // ClaseMensaje.errorFind(this.toString(), ex.toString()); // return fkresolucion; // } // } public int findFkresolucionInTercerosresolucionesByFkcomprobanteAno(String fkcomprobante, int ano) { int fkresolucion = 0; try { datos.query("SELECT * FROM TERCEROSRESOLUCION " + "WHERE " + "fkcomprobante = '" + fkcomprobante + "' " + "AND ano = " + ano + ""); while (ClaseBaseDatos.resultado.next()) { fkresolucion = ClaseBaseDatos.resultado.getInt("FKRESOLUCION"); } return fkresolucion; } catch (SQLException ex) { ClaseMensaje.errorFind(this.toString(), ex.toString()); return fkresolucion; } } public double CALCLiquidacionviaticosresoluciontercero(String tarifa, int fkresolucion, int ano, String fktercero) { double valor = 0; try { datos.query("SELECT f_liquidacionviaticosresoluciontercero(" + "'" + tarifa + "', " + fkresolucion + ", " + ano + ", " + "'" + fktercero.substring(0, fktercero.indexOf(" - ")) + "') FROM TERCEROSRESOLUCION"); while (ClaseBaseDatos.resultado.next()) { valor = ClaseBaseDatos.resultado.getDouble("f_liquidacionviaticosresoluciontercero"); } return valor; } catch (SQLException ex) { ClaseMensaje.errorFind(this.toString(), ex.toString()); return 0; } } public DefaultComboBoxModel COMBOIdNombreInTercerosresolucionesBy() { DefaultComboBoxModel<String> modeloCombo = new DefaultComboBoxModel<String>(); try { modeloCombo.addElement("Seleccione - "); datos.query("SELECT DISTINCT(ID), FKRESOLUCION FROM TERCEROSRESOLUCION");// ORDER BY id while (ClaseBaseDatos.resultado.next()) { modeloCombo.addElement(ClaseBaseDatos.resultado.getInt("ID") + " - " + ClaseBaseDatos.resultado.getInt("FKRESOLUCION")); } return modeloCombo; } catch (SQLException ex) { ClaseMensaje.errorFind(this.toString(), ex.toString()); return modeloCombo; } } }
gpl-3.0
xuxueli/xxl-rpc
xxl-rpc-core/src/main/java/com/xxl/rpc/core/util/ClassUtil.java
1029
package com.xxl.rpc.core.util; import java.util.HashMap; /** * @author xuxueli 2019-02-19 */ public class ClassUtil { private static final HashMap<String, Class<?>> primClasses = new HashMap<>(); static { primClasses.put("boolean", boolean.class); primClasses.put("byte", byte.class); primClasses.put("char", char.class); primClasses.put("short", short.class); primClasses.put("int", int.class); primClasses.put("long", long.class); primClasses.put("float", float.class); primClasses.put("double", double.class); primClasses.put("void", void.class); } public static Class<?> resolveClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { Class<?> cl = primClasses.get(className); if (cl != null) { return cl; } else { throw ex; } } } }
gpl-3.0
kleiinnn/LinkJVM
src/java/linkjvm/sensors/digital/IDigitalSensor.java
1078
/* * This file is part of LinkJVM. * * Java Framework for the KIPR Link * Copyright (C) 2013 Markus Klein<m@mklein.co.at> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package linkjvm.sensors.digital; /** * This interface contains all required methods of an digital sensor. * @author Markus Klein * @version 2.1.0 * @since 2.0.0 */ public interface IDigitalSensor { /** * Return the sensor's current value. * @return sensor value */ public abstract boolean getValue(); }
gpl-3.0
blankaspect/patternGenerator
src/main/java/uk/blankaspect/patterngenerator/DocumentKind.java
3670
/*====================================================================*\ DocumentKind.java Document kind enumeration. \*====================================================================*/ // PACKAGE package uk.blankaspect.patterngenerator; //---------------------------------------------------------------------- // IMPORTS import uk.blankaspect.common.misc.FilenameSuffixFilter; import uk.blankaspect.common.misc.IStringKeyed; import uk.blankaspect.common.string.StringUtils; //---------------------------------------------------------------------- // DOCUMENT KIND ENUMERATION enum DocumentKind implements IStringKeyed { //////////////////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////////////////// DEFINITION ( "definition", AppConstants.PG_DEF_FILE_SUFFIX, AppConstants.PG_DEF_FILES_STR ), PARAMETERS ( "parameters", AppConstants.PG_PAR_FILE_SUFFIX, AppConstants.PG_PAR_FILES_STR ); //////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////// private DocumentKind(String key, String suffix, String description) { this.key = key; filter = new FilenameSuffixFilter(description, suffix); } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Class methods //////////////////////////////////////////////////////////////////////// public static DocumentKind forKey(String key) { for (DocumentKind value : values()) { if (value.key.equals(key)) return value; } return null; } //------------------------------------------------------------------ public static DocumentKind forDescription(String description) { for (DocumentKind value : values()) { if (value.filter.getDescription().equals(description)) return value; } return null; } //------------------------------------------------------------------ public static DocumentKind forFilename(String filename) { if (filename != null) { for (DocumentKind value : values()) { if (filename.endsWith(value.filter.getSuffix(0))) return value; } } return null; } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance methods : IStringKeyed interface //////////////////////////////////////////////////////////////////////// public String getKey() { return key; } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance methods : overriding methods //////////////////////////////////////////////////////////////////////// @Override public String toString() { return StringUtils.firstCharToUpperCase(key); } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance methods //////////////////////////////////////////////////////////////////////// public FilenameSuffixFilter getFilter() { return filter; } //------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////// // Instance variables //////////////////////////////////////////////////////////////////////// private String key; private FilenameSuffixFilter filter; } //----------------------------------------------------------------------
gpl-3.0
kuros/random-jpa
src/test/java/com/github/kuros/random/jpa/provider/oracle/OracleCharacterLengthProviderTest.java
4054
package com.github.kuros.random.jpa.provider.oracle; import com.github.kuros.random.jpa.metamodel.AttributeProvider; import com.github.kuros.random.jpa.metamodel.model.ColumnNameType; import com.github.kuros.random.jpa.metamodel.model.EntityTableMapping; import com.github.kuros.random.jpa.provider.SQLCharacterLengthProvider; import com.github.kuros.random.jpa.testUtil.entity.Department; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.persistence.EntityManager; import javax.persistence.Query; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; /* * Copyright (c) 2015 Kumar Rohit * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License or any * later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class OracleCharacterLengthProviderTest { @Mock private EntityManager entityManager; @Mock private AttributeProvider attributeProvider; @Mock private Query query; private SQLCharacterLengthProvider sqlCharacterLengthProvider; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mockEntityManager(); mockAttributeProvider(); sqlCharacterLengthProvider = new OracleCharacterLengthProvider(entityManager, attributeProvider); } @Test public void testApplyLengthConstraint() { assertEquals("abcde", sqlCharacterLengthProvider.applyLengthConstraint(Department.class.getName(), "departmentName", "abcdefghijkl")); assertEquals(789, sqlCharacterLengthProvider.applyLengthConstraint(Department.class.getName(), "departmentId", 123456789)); assertEquals(345.68, sqlCharacterLengthProvider.applyLengthConstraint(Department.class.getName(), "departmentAmount", 12345.6789)); } private void mockAttributeProvider() { final EntityTableMapping departmentTableMapping = new EntityTableMapping(Department.class); departmentTableMapping.addAttributeColumnMapping("departmentId", new ColumnNameType("department_id", ColumnNameType.Type.BASIC)); departmentTableMapping.addAttributeColumnMapping("departmentName", new ColumnNameType("department_name", ColumnNameType.Type.BASIC)); departmentTableMapping.addAttributeColumnMapping("departmentAmount", new ColumnNameType("department_amount", ColumnNameType.Type.BASIC)); final List<EntityTableMapping> entityTableMappings = new ArrayList<>(); entityTableMappings.add(departmentTableMapping); when(attributeProvider.get(eq("department"))).thenReturn(entityTableMappings); } private void mockEntityManager() { final Object[] row1 = {"department", "department_name", BigDecimal.valueOf(5), null, null, "NVARCHAR"}; final Object[] row2 = {"department", "department_id", null, BigDecimal.valueOf(3), null, "NUMBER"}; final Object[] row3 = {"department", "department_amount", null, BigDecimal.valueOf(3), BigDecimal.valueOf(2), "NUMBER"}; final List<Object[]> resultList = new ArrayList<>(); resultList.add(row1); resultList.add(row2); resultList.add(row3); when(entityManager.createNativeQuery(anyString())).thenReturn(query); when(query.getResultList()).thenReturn(resultList); } }
gpl-3.0
Gabrui/ces28_2017_gabriel-adriano
Labs/Lab3/src/ex4e5/ModeloComercial.java
454
/** * LAB-3 / CES-28 * @author Dylan N. Sugimoto e Gabriel Adriano de Melo * Data da criação: 08/10/2017 */ package ex4e5; /** * @author Dylan N. Sugimoto e Gabriel Adriano de Melo * Representa o modelo da carta comercial. */ public abstract class ModeloComercial extends Modelo{ @Override public String corpo(Idioma idioma, Pessoa destinatario) { return idioma.vocativo() + " " + destinatario.getNome()+": " +"\n\n" +"\n\n"; } }
gpl-3.0
srnsw/xena
plugins/pdf/ext/src/jpedal_lgpl-3.83b38/src/org/jpedal/examples/simpleviewer/MultiViewListener.java
4146
package org.jpedal.examples.simpleviewer; import java.io.File; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import org.jpedal.PdfDecoder; import org.jpedal.examples.simpleviewer.gui.SwingGUI; public class MultiViewListener implements InternalFrameListener { Object pageScaling = null, pageRotation = null; private PdfDecoder decode_pdf; private SwingGUI currentGUI; private Values commonValues; private Commands currentCommands; public MultiViewListener(PdfDecoder decode_pdf, SwingGUI currentGUI, Values commonValues, Commands currentCommands){ this.decode_pdf = decode_pdf; this.currentGUI = currentGUI; this.commonValues = commonValues; this.currentCommands = currentCommands; // pageScaling = "Window"; // pageRotation = currentGUI.getRotation(); // System.out.println("constructor"+ " "+pageScaling+" " +pageRotation); } public void internalFrameOpened(InternalFrameEvent e) { //To change body of implemented methods use File | Settings | File Templates. } public void internalFrameClosing(InternalFrameEvent e) { currentGUI.setBackNavigationButtonsEnabled(false); currentGUI.setForwardNavigationButtonsEnabled(false); currentGUI.resetPageNav(); } public void internalFrameClosed(InternalFrameEvent e) { decode_pdf.flushObjectValues(true); decode_pdf.closePdfFile(); } public void internalFrameIconified(InternalFrameEvent e) { //To change body of implemented methods use File | Settings | File Templates. } public void internalFrameDeiconified(InternalFrameEvent e) { // To change body of implemented methods use File | Settings | File // Templates. } /** * switch to active PDF * @param e */ public void internalFrameActivated(InternalFrameEvent e) { //System.out.println("activated pdf = "+decode_pdf.getClass().getName() + "@" + Integer.toHexString(decode_pdf.hashCode())); // choose selected PDF currentGUI.setPdfDecoder(decode_pdf); currentCommands.setPdfDecoder(decode_pdf); /** * align details in Viewer and variables */ int page=decode_pdf.getlastPageDecoded(); commonValues.setPageCount(decode_pdf.getPageCount()); commonValues.setCurrentPage(page); String fileName = decode_pdf.getFileName(); if(fileName!=null){ commonValues.setSelectedFile(fileName); File file = new File(fileName); commonValues.setInputDir(file.getParent()); commonValues.setFileSize(file.length() >> 10); } // System.err.println("ACTIVATED "+pageScaling+" "+pageRotation+" // count="+decode_pdf.getPageCount()/*+" // "+localPdf.getDisplayRotation()+" "+localPdf.getDisplayScaling()*/); commonValues.setPDF(decode_pdf.isPDF()); commonValues.setMultiTiff(decode_pdf.isMultiPageTiff()); //System.err.println("ACTIVATED "+pageScaling+" "+pageRotation+" count="+decode_pdf.getPageCount()/*+" "+localPdf.getDisplayRotation()+" "+localPdf.getDisplayScaling()*/); if (pageScaling != null) currentGUI.setSelectedComboItem(Commands.SCALING, pageScaling.toString()); if (pageRotation != null) currentGUI.setSelectedComboItem(Commands.ROTATION, pageRotation.toString()); // currentGUI.setPage(page); // //pageCounter2.setText(""+page); // pageCounter3.setText(""+decode_pdf.getPageCount()); currentGUI.setPageNumber(); decode_pdf.updateUI(); currentGUI.removeSearchWindow(false); // searchFrame.removeSearchWindow(false); //Only show navigation buttons required for newly activated frame currentGUI.hideRedundentNavButtons(); } public void internalFrameDeactivated(InternalFrameEvent e) { // save current settings if (pageScaling != null) { pageScaling = currentGUI.getSelectedComboItem(Commands.SCALING); } if (pageRotation != null) { pageRotation = currentGUI.getSelectedComboItem(Commands.ROTATION); } // System.err.println("DEACTIVATED "+pageScaling+" "+pageRotation); } public void setPageProperties(Object rotation, Object scaling) { pageRotation = rotation; pageScaling = scaling; } }
gpl-3.0
saulvargas/ebro
src/main/java/es/saulvargas/ebro/Ebro.java
6713
/* * Copyright (C) 2015 Saúl Vargas (saul@vargassandoval.es) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.saulvargas.ebro; import es.saulvargas.ebro.Ebro.Vertex; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.ints.Int2ByteMap; import it.unimi.dsi.fastutil.ints.Int2ByteOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * The Pregel-like engine of the system. * * @author Saúl Vargas (saul@vargassandoval.es) * @param <M> message type */ public class Ebro<M> { private static final byte NOHALT = (byte) 0; private static final byte HALT = (byte) 1; private int superstep; private final Int2ObjectMap<Vertex<M>> vertices; private final Int2ObjectMap<Aggregator> aggregators; private Int2ObjectMap<List<M>> currentMessages; private Int2ObjectMap<List<M>> futureMessages; private final Int2ByteMap votes; private int vertexCount; private int aggregatorCount; private final boolean directed; private final boolean weighted; public Ebro(int nvertices, boolean directed, boolean weighted) { this.superstep = 0; this.vertices = new Int2ObjectOpenHashMap<>(); this.aggregators = new Int2ObjectOpenHashMap<>(); this.currentMessages = new Int2ObjectOpenHashMap<>(nvertices); this.futureMessages = new Int2ObjectOpenHashMap<>(nvertices); this.votes = new Int2ByteOpenHashMap(nvertices); this.votes.defaultReturnValue(HALT); this.directed = directed; this.weighted = weighted; vertexCount = 0; aggregatorCount = 0; } public int addVertex(Vertex<M> v) { v.configure(vertexCount, this, weighted); vertices.put(v.id, v); currentMessages.put(v.id, Collections.synchronizedList(new ArrayList<>())); futureMessages.put(v.id, Collections.synchronizedList(new ArrayList<>())); votes.put(v.id, NOHALT); vertexCount++; return v.id; } public int addAgregator(Aggregator a) { a.configure(aggregatorCount, this); aggregators.put(aggregatorCount, a); aggregatorCount++; return a.id; } public Vertex<M> getVertex(int id) { return vertices.get(id); } public void addEdge(int from, int to) { addEdge(from, to, 1.0); } public void addEdge(int from, int to, double w) { vertices.get(from).addEdge(to, w); if (!directed) { vertices.get(to).addEdge(from, w); } } public void run() { while (!stop()) { System.out.println(superstep() + "\t" + numMessages()); doSuperstep(); } } private int numMessages() { return currentMessages.values().stream().mapToInt(List::size).sum(); } private boolean hasMessages() { return !currentMessages.values().stream().allMatch(List::isEmpty); } private boolean allToHalt() { return !votes.containsValue(NOHALT); } public boolean stop() { return allToHalt() && !hasMessages(); } public void doSuperstep() { vertices.int2ObjectEntrySet().parallelStream().forEach(e -> { int id = e.getIntKey(); Vertex<M> vertex = e.getValue(); List<M> messages = currentMessages.get(e.getKey()); if (votes.get(id) == NOHALT || !messages.isEmpty()) { votes.put(id, NOHALT); vertex.compute(messages); } messages.clear(); }); aggregators.values().stream().forEach(Aggregator::nextStep); superstep++; Int2ObjectMap<List<M>> aux; aux = currentMessages; currentMessages = futureMessages; futureMessages = aux; } public int superstep() { return superstep; } protected void voteToHalt(int id) { votes.put(id, HALT); } protected void sendMessage(int dst, M message) { futureMessages.get(dst).add(message); } public static abstract class Vertex<M> { protected int id; protected Ebro<M> ebro; protected final IntArrayList edgeDestList; protected DoubleArrayList edgeWeightList; public Vertex() { this.edgeDestList = new IntArrayList(); } private void configure(int id, Ebro<M> ebro, boolean weighted) { this.id = id; this.ebro = ebro; if (weighted) { edgeWeightList = new DoubleArrayList(); } else { edgeWeightList = null; } } private void addEdge(int dst, double weight) { edgeDestList.add(dst); if (edgeWeightList != null) { edgeWeightList.add(weight); } } protected abstract void compute(Collection<M> messages); protected final int superstep() { return ebro.superstep(); } protected final void voteToHalt() { ebro.voteToHalt(id); } protected final void sendMessage(int dst, M message) { ebro.sendMessage(dst, message); } } public static abstract class Aggregator<T> { protected int id; protected Ebro ebro; protected T t0; protected T t1; public Aggregator() { } private void configure(int id, Ebro ebro) { this.id = id; this.ebro = ebro; this.t1 = init(); } private void nextStep() { t0 = t1; t1 = init(); } protected abstract T init(); protected abstract T aggregate(T t1, T t); public synchronized void aggregate(T t) { t1 = aggregate(t1, t); } public T getValue() { return t0; } } }
gpl-3.0
dawg6/dawg6-d3api
src/com/dawg6/d3api/shared/D3Message.java
1207
/******************************************************************************* * Copyright (c) 2014, 2015 Scott Clarke (scott@dawg6.com). * * This file is part of Dawg6's battle.net Diablo 3 API. * * Dawg6's Demon Hunter DPS Calculator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dawg6's Demon Hunter DPS Calculator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.dawg6.d3api.shared; import java.io.Serializable; public class D3Message extends ApiData implements Serializable { private static final long serialVersionUID = 1L; public String code; public String reason; }
gpl-3.0
c0c0n3/ome-smuggler
components/server/src/main/java/ome/smuggler/config/data/DevImportConfigSource.java
1381
package ome.smuggler.config.data; import java.nio.file.Path; import java.time.Duration; import java.util.Collections; import java.util.List; import ome.smuggler.config.BaseDataDir; import ome.smuggler.core.types.ImportConfigSource; import ome.smuggler.core.types.PositiveN; import util.runtime.CommandBuilder; /** * Dev import settings. */ public class DevImportConfigSource implements ImportConfigSource { private final BaseDataDir baseDataDir; public DevImportConfigSource() { this.baseDataDir = new BaseDataDir(); } @Override public Path importLogDir() { return baseDataDir.resolve(ImportYmlFile.RelImportLogDirPath); } @Override public Duration logRetentionPeriod() { return Duration.ofSeconds(5); } @Override public List<Duration> retryIntervals() { return Collections.emptyList(); } @Override public Path failedImportLogDir() { return baseDataDir.resolve(ImportYmlFile.RelFailedImportLogDirPath); } @Override public CommandBuilder niceCommand() { return CommandBuilder.empty(); } @Override public Path batchStatusDbDir() { return baseDataDir.resolve(ImportYmlFile.RelBatchStatusDbDirPath); } @Override public PositiveN batchStatusDbLockStripes() { return DefaultBatchStatusDbLockStripes; } }
gpl-3.0
briandoconnor/my-sandbox
20171228_jhipster_prototyping/src/main/java/io/consonance/webapp/web/rest/AccountResource.java
7388
package io.consonance.webapp.web.rest; import com.codahale.metrics.annotation.Timed; import io.consonance.webapp.domain.User; import io.consonance.webapp.repository.UserRepository; import io.consonance.webapp.security.SecurityUtils; import io.consonance.webapp.service.MailService; import io.consonance.webapp.service.UserService; import io.consonance.webapp.service.dto.UserDTO; import io.consonance.webapp.web.rest.errors.*; import io.consonance.webapp.web.rest.vm.KeyAndPasswordVM; import io.consonance.webapp.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.*; /** * REST controller for managing the current user's account. */ @RestController @RequestMapping("/api") public class AccountResource { private final Logger log = LoggerFactory.getLogger(AccountResource.class); private final UserRepository userRepository; private final UserService userService; private final MailService mailService; public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) { this.userRepository = userRepository; this.userService = userService; this.mailService = mailService; } /** * POST /register : register the user. * * @param managedUserVM the managed user View Model * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already used * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already used */ @PostMapping("/register") @Timed @ResponseStatus(HttpStatus.CREATED) public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) { if (!checkPasswordLength(managedUserVM.getPassword())) { throw new InvalidPasswordException(); } userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()).ifPresent(u -> {throw new LoginAlreadyUsedException();}); userRepository.findOneByEmailIgnoreCase(managedUserVM.getEmail()).ifPresent(u -> {throw new EmailAlreadyUsedException();}); User user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); mailService.sendActivationEmail(user); } /** * GET /activate : activate the registered user. * * @param key the activation key * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be activated */ @GetMapping("/activate") @Timed public void activateAccount(@RequestParam(value = "key") String key) { Optional<User> user = userService.activateRegistration(key); if (!user.isPresent()) { throw new InternalServerErrorException("No user was found for this reset key"); } } /** * GET /authenticate : check if the user is authenticated, and return its login. * * @param request the HTTP request * @return the login if the user is authenticated */ @GetMapping("/authenticate") @Timed public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } /** * GET /account : get the current user. * * @return the current user * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be returned */ @GetMapping("/account") @Timed public UserDTO getAccount() { return userService.getUserWithAuthorities() .map(UserDTO::new) .orElseThrow(() -> new InternalServerErrorException("User could not be found")); } /** * POST /account : update the current user information. * * @param userDTO the current user information * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already used * @throws RuntimeException 500 (Internal Server Error) if the user login wasn't found */ @PostMapping("/account") @Timed public void saveAccount(@Valid @RequestBody UserDTO userDTO) { final String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new InternalServerErrorException("Current user login not found")); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); } Optional<User> user = userRepository.findOneByLogin(userLogin); if (!user.isPresent()) { throw new InternalServerErrorException("User could not be found"); } userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl()); } /** * POST /account/change-password : changes the current user's password * * @param password the new password * @throws InvalidPasswordException 400 (Bad Request) if the new password is incorrect */ @PostMapping(path = "/account/change-password") @Timed public void changePassword(@RequestBody String password) { if (!checkPasswordLength(password)) { throw new InvalidPasswordException(); } userService.changePassword(password); } /** * POST /account/reset-password/init : Send an email to reset the password of the user * * @param mail the mail of the user * @throws EmailNotFoundException 400 (Bad Request) if the email address is not registered */ @PostMapping(path = "/account/reset-password/init") @Timed public void requestPasswordReset(@RequestBody String mail) { mailService.sendPasswordResetMail( userService.requestPasswordReset(mail) .orElseThrow(EmailNotFoundException::new) ); } /** * POST /account/reset-password/finish : Finish to reset the password of the user * * @param keyAndPassword the generated key and the new password * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect * @throws RuntimeException 500 (Internal Server Error) if the password could not be reset */ @PostMapping(path = "/account/reset-password/finish") @Timed public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new InternalServerErrorException("No user was found for this reset key"); } } private static boolean checkPasswordLength(String password) { return !StringUtils.isEmpty(password) && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; } }
gpl-3.0
dotCMS/core
dotCMS/src/main/java/com/dotmarketing/portlets/personas/model/Persona.java
1555
package com.dotmarketing.portlets.personas.model; import java.util.HashMap; import java.util.List; import java.util.Map; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.personas.business.PersonaAPI; public class Persona extends Contentlet implements IPersona{ private static final long serialVersionUID = -4775734788059690797L; public static final String DOT_PERSONA_PREFIX_SCHEME = "dot:persona"; public Persona(Contentlet oldCon) { Map<String, Object> newMap = new HashMap<>(); oldCon.getMap().forEach(newMap::put); super.map = newMap; } @Override public String getName() { return getStringProperty(PersonaAPI.NAME_FIELD); } @Override public void setName(String name) { setStringProperty(PersonaAPI.NAME_FIELD, name); } @Override public String getKeyTag() { return getStringProperty(PersonaAPI.KEY_TAG_FIELD); } @Override public void setKeyTag(String keyTag) { setStringProperty(PersonaAPI.KEY_TAG_FIELD, keyTag); } @Override public String getDescription() { return getStringProperty(PersonaAPI.DESCRIPTION_FIELD); } @Override public void setDescription(String description) { setStringProperty(PersonaAPI.DESCRIPTION_FIELD, description); } @Override public String getTags() { return getStringProperty(PersonaAPI.TAGS_FIELD); } @Override public void setTags(List<String> tags) { setStringProperty(PersonaAPI.TAGS_FIELD,tags.toString()); } @Override public String toString() { return this.getName() + " : " + this.getKeyTag(); } }
gpl-3.0
felixbello/cyail
src/ch/cyail/settings/SettingsView.java
8423
package ch.cyail.settings; import java.awt.event.ActionListener; import javax.swing.JDialog; /** * * @author felix, segessemann * @version 1.0 */ public class SettingsView extends javax.swing.JFrame { /** * Creates new form Configuration */ private SettingsController settings; private JDialog firstTimeStart; public SettingsView() { initComponents(); } public SettingsView(JDialog firstTimeStart) { initComponents(); this.firstTimeStart = firstTimeStart; } // Created in Netbeans Swing Editor // Please don't change variable names // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextFieldUsername = new javax.swing.JTextField(); jLabelUsername = new javax.swing.JLabel(); jPasswordField = new javax.swing.JPasswordField(); jLabelPassword = new javax.swing.JLabel(); jButtonCancel = new javax.swing.JButton(); jButtonOk = new javax.swing.JButton(); jButtonTest = new javax.swing.JButton(); jLabelAccountDescription = new javax.swing.JLabel(); jTextFieldAccountDescription = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Account Settings"); setAlwaysOnTop(true); setMaximumSize(new java.awt.Dimension(395, 274)); setMinimumSize(new java.awt.Dimension(395, 274)); jLabelUsername.setText("Username"); jLabelPassword.setText("Password"); jButtonCancel.setText("Cancel"); jButtonOk.setText("OK"); jButtonTest.setText("Test"); jLabelAccountDescription.setText("Beschreibung"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButtonTest) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 185, Short.MAX_VALUE) .addComponent(jButtonOk) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonCancel)) .addGroup(layout.createSequentialGroup() .addComponent(jLabelAccountDescription) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldAccountDescription)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelUsername) .addComponent(jLabelPassword)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextFieldUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE) .addComponent(jPasswordField)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelAccountDescription) .addComponent(jTextFieldAccountDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelUsername)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelPassword)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonCancel) .addComponent(jButtonOk) .addComponent(jButtonTest)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonCancel; private javax.swing.JButton jButtonOk; private javax.swing.JButton jButtonTest; private javax.swing.JLabel jLabelAccountDescription; private javax.swing.JLabel jLabelPassword; private javax.swing.JLabel jLabelUsername; private javax.swing.JPasswordField jPasswordField; private javax.swing.JTextField jTextFieldAccountDescription; private javax.swing.JTextField jTextFieldUsername; // End of variables declaration//GEN-END:variables // public listener public void addOkButtonListener(ActionListener listenForOkButton) { jButtonOk.addActionListener(listenForOkButton); } public void addCancelButtonListener(ActionListener listenForCancelButton) { jButtonCancel.addActionListener(listenForCancelButton); } public void addTestButtonListener(ActionListener listenForTestButton) { jButtonTest.addActionListener(listenForTestButton); } // public Methods public String getAccountDescription() { return this.jTextFieldAccountDescription.getText(); } public String getUsername() { return this.jTextFieldUsername.getText(); } public char[] getPassword() { return this.jPasswordField.getPassword(); } public void setAccountDescription(String accountDescription) { this.jTextFieldAccountDescription.setText(accountDescription); } public void setUsername(String username) { this.jTextFieldUsername.setText(username); } public void setPassword(String password) { this.jPasswordField.setText(password); } public void setFirstTimeDialogDispose() { if (this.firstTimeStart != null) { this.firstTimeStart.dispose(); // TODO: Move this to the controller } } }
gpl-3.0
SIMON3P/supWSD
src/main/java/it/si3p/supwsd/modules/parser/ParserType.java
155
package it.si3p.supwsd.modules.parser; /** * @author papandrea * */ public enum ParserType { LEXICAL,SENSEVAL,SEMEVAL7,SEMEVAL13,SEMEVAL15,PLAIN; }
gpl-3.0
4Space/4Space-5
src/main/java/micdoodle8/mods/galacticraft/core/inventory/ContainerFuelLoader.java
3510
package micdoodle8.mods.galacticraft.core.inventory; import micdoodle8.mods.galacticraft.api.item.IItemElectric; import micdoodle8.mods.galacticraft.core.energy.tile.TileBaseElectricBlock; import micdoodle8.mods.galacticraft.core.tile.TileEntityFuelLoader; import micdoodle8.mods.galacticraft.core.util.FluidUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerFuelLoader extends Container { private TileBaseElectricBlock tileEntity; public ContainerFuelLoader(InventoryPlayer par1InventoryPlayer, TileEntityFuelLoader fuelLoader) { this.tileEntity = fuelLoader; this.addSlotToContainer(new SlotSpecific(fuelLoader, 0, 51, 55, IItemElectric.class)); this.addSlotToContainer(new Slot(fuelLoader, 1, 7, 12)); int var6; int var7; // Player inv: for (var6 = 0; var6 < 3; ++var6) { for (var7 = 0; var7 < 9; ++var7) { this.addSlotToContainer(new Slot(par1InventoryPlayer, var7 + var6 * 9 + 9, 8 + var7 * 18, 31 + 58 + var6 * 18)); } } for (var6 = 0; var6 < 9; ++var6) { this.addSlotToContainer(new Slot(par1InventoryPlayer, var6, 8 + var6 * 18, 31 + 116)); } } @Override public boolean canInteractWith(EntityPlayer var1) { return this.tileEntity.isUseableByPlayer(var1); } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack var3 = null; final Slot slot = (Slot) this.inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { final ItemStack var5 = slot.getStack(); var3 = var5.copy(); if (par2 < 2) { if (!this.mergeItemStack(var5, 2, 38, true)) { return null; } } else { if (var5.getItem() instanceof IItemElectric) { if (!this.mergeItemStack(var5, 0, 1, false)) { return null; } } else { if (FluidUtil.isFuelContainerAny(var5)) { if (!this.mergeItemStack(var5, 1, 2, false)) { return null; } } else if (par2 < 29) { if (!this.mergeItemStack(var5, 29, 38, false)) { return null; } } else if (!this.mergeItemStack(var5, 2, 29, false)) { return null; } } } if (var5.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } if (var5.stackSize == var3.stackSize) { return null; } slot.onPickupFromSlot(par1EntityPlayer, var5); } return var3; } }
gpl-3.0
Naoghuman/ABC-List
src/main/java/com/github/naoghuman/abclist/view/welcome/WelcomePresenter.java
1216
/* * Copyright (C) 2017 Naoghuman * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.naoghuman.abclist.view.welcome; import com.github.naoghuman.lib.logger.core.LoggerFacade; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; /** * * @author Naoghuman */ public class WelcomePresenter implements Initializable { @Override public void initialize(URL location, ResourceBundle resources) { LoggerFacade.getDefault().info(this.getClass(), "Initialize WelcomePresenter"); // NOI18N } }
gpl-3.0
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/internal/util/WebUtils.java
20730
package com.alipay.api.internal.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import com.alipay.api.AlipayConstants; import com.alipay.api.FileItem; /** * 网络工具类。 * * @author carver.gu * @since 1.0, Sep 12, 2009 */ public abstract class WebUtils { private static final String DEFAULT_CHARSET = AlipayConstants.CHARSET_UTF8; private static final String METHOD_POST = "POST"; private static final String METHOD_GET = "GET"; private static SSLContext ctx = null; private static HostnameVerifier verifier = null; private static SSLSocketFactory socketFactory = null; private static class DefaultTrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } static { try { ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); ctx.getClientSessionContext().setSessionTimeout(15); ctx.getClientSessionContext().setSessionCacheSize(1000); socketFactory = ctx.getSocketFactory(); } catch (Exception e) { } verifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return false;//默认认证不通过,进行证书校验。 } }; } private WebUtils() { } /** * 执行HTTP POST请求。 * * @param url 请求地址 * @param params 请求参数 * @return 响应字符串 * @throws IOException */ public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) throws IOException { return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout); } /** * 执行HTTP POST请求。 * * @param url 请求地址 * @param params 请求参数 * @param charset 字符集,如UTF-8, GBK, GB2312 * @return 响应字符串 * @throws IOException */ public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout) throws IOException { String ctype = "application/x-www-form-urlencoded;charset=" + charset; String query = buildQuery(params, charset); byte[] content = {}; if (query != null) { content = query.getBytes(charset); } return doPost(url, ctype, content, connectTimeout, readTimeout); } /** * 执行HTTP POST请求。 * * @param url 请求地址 * @param ctype 请求类型 * @param content 请求字节数组 * @return 响应字符串 * @throws IOException */ public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException { HttpURLConnection conn = null; OutputStream out = null; String rsp = null; try { try { conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, url, map.get("app_key"), map.get("method"), content); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, conn, map.get("app_key"), map.get("method"), content); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; } /** * 执行带文件上传的HTTP POST请求。 * * @param url 请求地址 * @param textParams 文本请求参数 * @param fileParams 文件请求参数 * @return 响应字符串 * @throws IOException */ public static String doPost(String url, Map<String, String> params, Map<String, FileItem> fileParams, int connectTimeout, int readTimeout) throws IOException { if (fileParams == null || fileParams.isEmpty()) { return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout); } else { return doPost(url, params, fileParams, DEFAULT_CHARSET, connectTimeout, readTimeout); } } /** * 执行带文件上传的HTTP POST请求。 * * @param url 请求地址 * @param textParams 文本请求参数 * @param fileParams 文件请求参数 * @param charset 字符集,如UTF-8, GBK, GB2312 * @return 响应字符串 * @throws IOException */ public static String doPost(String url, Map<String, String> params, Map<String, FileItem> fileParams, String charset, int connectTimeout, int readTimeout) throws IOException { if (fileParams == null || fileParams.isEmpty()) { return doPost(url, params, charset, connectTimeout, readTimeout); } String boundary = System.currentTimeMillis() + ""; // 随机分隔线 HttpURLConnection conn = null; OutputStream out = null; String rsp = null; try { try { String ctype = "multipart/form-data;boundary=" + boundary + ";charset=" + charset; conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, url, map.get("app_key"), map.get("method"), params); throw e; } try { out = conn.getOutputStream(); byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(charset); // 组装文本请求参数 Set<Entry<String, String>> textEntrySet = params.entrySet(); for (Entry<String, String> textEntry : textEntrySet) { byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(), charset); out.write(entryBoundaryBytes); out.write(textBytes); } // 组装文件请求参数 Set<Entry<String, FileItem>> fileEntrySet = fileParams.entrySet(); for (Entry<String, FileItem> fileEntry : fileEntrySet) { FileItem fileItem = fileEntry.getValue(); byte[] fileBytes = getFileEntry(fileEntry.getKey(), fileItem.getFileName(), fileItem.getMimeType(), charset); out.write(entryBoundaryBytes); out.write(fileBytes); out.write(fileItem.getContent()); } // 添加请求结束标志 byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(charset); out.write(endBoundaryBytes); rsp = getResponseAsString(conn); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, conn, map.get("app_key"), map.get("method"), params); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; } private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException { StringBuilder entry = new StringBuilder(); entry.append("Content-Disposition:form-data;name=\""); entry.append(fieldName); entry.append("\"\r\nContent-Type:text/plain\r\n\r\n"); entry.append(fieldValue); return entry.toString().getBytes(charset); } private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException { StringBuilder entry = new StringBuilder(); entry.append("Content-Disposition:form-data;name=\""); entry.append(fieldName); entry.append("\";filename=\""); entry.append(fileName); entry.append("\"\r\nContent-Type:"); entry.append(mimeType); entry.append("\r\n\r\n"); return entry.toString().getBytes(charset); } /** * 执行HTTP GET请求。 * * @param url 请求地址 * @param params 请求参数 * @return 响应字符串 * @throws IOException */ public static String doGet(String url, Map<String, String> params) throws IOException { return doGet(url, params, DEFAULT_CHARSET); } /** * 执行HTTP GET请求。 * * @param url 请求地址 * @param params 请求参数 * @param charset 字符集,如UTF-8, GBK, GB2312 * @return 响应字符串 * @throws IOException */ public static String doGet(String url, Map<String, String> params, String charset) throws IOException { HttpURLConnection conn = null; String rsp = null; try { String ctype = "application/x-www-form-urlencoded;charset=" + charset; String query = buildQuery(params, charset); try { conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, url, map.get("app_key"), map.get("method"), params); throw e; } try { rsp = getResponseAsString(conn); } catch (IOException e) { Map<String, String> map = getParamsFromUrl(url); AlipayLogger.logCommError(e, conn, map.get("app_key"), map.get("method"), params); throw e; } } finally { if (conn != null) { conn.disconnect(); } } return rsp; } private static HttpURLConnection getConnection(URL url, String method, String ctype) throws IOException { HttpURLConnection conn = null; if ("https".equals(url.getProtocol())) { HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection(); connHttps.setSSLSocketFactory(socketFactory); connHttps.setHostnameVerifier(verifier); conn = connHttps; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html"); conn.setRequestProperty("User-Agent", "aop-sdk-java"); conn.setRequestProperty("Content-Type", ctype); return conn; } private static URL buildGetUrl(String strUrl, String query) throws IOException { URL url = new URL(strUrl); if (StringUtils.isEmpty(query)) { return url; } if (StringUtils.isEmpty(url.getQuery())) { if (strUrl.endsWith("?")) { strUrl = strUrl + query; } else { strUrl = strUrl + "?" + query; } } else { if (strUrl.endsWith("&")) { strUrl = strUrl + query; } else { strUrl = strUrl + "&" + query; } } return new URL(strUrl); } public static String buildQuery(Map<String, String> params, String charset) throws IOException { if (params == null || params.isEmpty()) { return null; } StringBuilder query = new StringBuilder(); Set<Entry<String, String>> entries = params.entrySet(); boolean hasParam = false; for (Entry<String, String> entry : entries) { String name = entry.getKey(); String value = entry.getValue(); // 忽略参数名或参数值为空的参数 if (StringUtils.areNotEmpty(name, value)) { if (hasParam) { query.append("&"); } else { hasParam = true; } query.append(name).append("=").append(URLEncoder.encode(value, charset)); } } return query.toString(); } protected static String getResponseAsString(HttpURLConnection conn) throws IOException { String charset = getResponseCharset(conn.getContentType()); InputStream es = conn.getErrorStream(); if (es == null) { return getStreamAsString(conn.getInputStream(), charset); } else { String msg = getStreamAsString(es, charset); if (StringUtils.isEmpty(msg)) { throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } else { throw new IOException(msg); } } } private static String getStreamAsString(InputStream stream, String charset) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset)); StringWriter writer = new StringWriter(); char[] chars = new char[256]; int count = 0; while ((count = reader.read(chars)) > 0) { writer.write(chars, 0, count); } return writer.toString(); } finally { if (stream != null) { stream.close(); } } } private static String getResponseCharset(String ctype) { String charset = DEFAULT_CHARSET; if (!StringUtils.isEmpty(ctype)) { String[] params = ctype.split(";"); for (String param : params) { param = param.trim(); if (param.startsWith("charset")) { String[] pair = param.split("=", 2); if (pair.length == 2) { if (!StringUtils.isEmpty(pair[1])) { charset = pair[1].trim(); } } break; } } } return charset; } /** * 使用默认的UTF-8字符集反编码请求参数值。 * * @param value 参数值 * @return 反编码后的参数值 */ public static String decode(String value) { return decode(value, DEFAULT_CHARSET); } /** * 使用默认的UTF-8字符集编码请求参数值。 * * @param value 参数值 * @return 编码后的参数值 */ public static String encode(String value) { return encode(value, DEFAULT_CHARSET); } /** * 使用指定的字符集反编码请求参数值。 * * @param value 参数值 * @param charset 字符集 * @return 反编码后的参数值 */ public static String decode(String value, String charset) { String result = null; if (!StringUtils.isEmpty(value)) { try { result = URLDecoder.decode(value, charset); } catch (IOException e) { throw new RuntimeException(e); } } return result; } /** * 使用指定的字符集编码请求参数值。 * * @param value 参数值 * @param charset 字符集 * @return 编码后的参数值 */ public static String encode(String value, String charset) { String result = null; if (!StringUtils.isEmpty(value)) { try { result = URLEncoder.encode(value, charset); } catch (IOException e) { throw new RuntimeException(e); } } return result; } private static Map<String, String> getParamsFromUrl(String url) { Map<String, String> map = null; if (url != null && url.indexOf('?') != -1) { map = splitUrlQuery(url.substring(url.indexOf('?') + 1)); } if (map == null) { map = new HashMap<String, String>(); } return map; } /** * 从URL中提取所有的参数。 * * @param query URL地址 * @return 参数映射 */ public static Map<String, String> splitUrlQuery(String query) { Map<String, String> result = new HashMap<String, String>(); String[] pairs = query.split("&"); if (pairs != null && pairs.length > 0) { for (String pair : pairs) { String[] param = pair.split("=", 2); if (param != null && param.length == 2) { result.put(param[0], param[1]); } } } return result; } public String buildForm(String baseUrl, RequestParametersHolder requestHolder) { return null; } public static String buildForm(String baseUrl, Map<String, String> parameters) { java.lang.StringBuffer sb = new StringBuffer(); sb.append("<form name=\"punchout_form\" method=\"post\" action=\""); sb.append(baseUrl); sb.append("\">\n"); sb.append(buildHiddenFields(parameters)); sb.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n"); sb.append("</form>\n"); sb.append("<script>document.forms[0].submit();</script>"); java.lang.String form = sb.toString(); return form; } private static String buildHiddenFields(Map<String, String> parameters) { if (parameters == null || parameters.isEmpty()) { return ""; } java.lang.StringBuffer sb = new StringBuffer(); Set<String> keys = parameters.keySet(); for (String key : keys) { String value = parameters.get(key); // 除去参数中的空值 if (key == null || value == null) { continue; } sb.append(buildHiddenField(key, value)); } java.lang.String result = sb.toString(); return result; } private static String buildHiddenField(String key, String value) { java.lang.StringBuffer sb = new StringBuffer(); sb.append("<input type=\"hidden\" name=\""); sb.append(key); sb.append("\" value=\""); //转义双引号 String a = value.replace("\"", "&quot;"); sb.append(a).append("\">\n"); return sb.toString(); } }
gpl-3.0
senbox-org/snap-desktop
snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/AbstractInputPanel.java
2123
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.core.datamodel.Product; import org.esa.snap.graphbuilder.rcp.dialogs.SourceProductPanel; import org.esa.snap.rcp.SnapApp; import javax.swing.*; import java.awt.*; /** */ public abstract class AbstractInputPanel extends WizardPanel { protected SourceProductPanel sourcePanel; public AbstractInputPanel() { super("Input"); createPanel(); } public void returnFromLaterStep() { } public boolean canRedisplayNextPanel() { return false; } public boolean hasNextPanel() { return true; } public boolean canFinish() { return false; } public boolean validateInput() { final Product product = sourcePanel.getSelectedSourceProduct(); if (product == null) { showErrorMsg("Please select a source product"); return false; } return true; } public abstract WizardPanel getNextPanel(); protected abstract String getInstructions(); private void createPanel() { final JPanel textPanel = createTextPanel("Instructions", getInstructions()); this.add(textPanel, BorderLayout.NORTH); sourcePanel = new SourceProductPanel(SnapApp.getDefault().getAppContext()); sourcePanel.initProducts(); this.add(sourcePanel, BorderLayout.CENTER); } }
gpl-3.0
gillion/RDACP
Trunk/00.Coding/cartan/cartan-center/src/main/java/com/cartan/center/ebs/ruleTable/RuleTableServiceEbs.java
273
/** * @author 刘溪滨 (13720880048@163.com) * @version 1.0 @Date: 2015-11-18 上午9:10 */ package com.cartan.center.ebs.ruleTable; import com.rop.annotation.ServiceMethodBean; @ServiceMethodBean public class RuleTableServiceEbs extends RuleTableServiceEbsBase { }
mpl-2.0
seedstack/business
core/src/test/java/org/seedstack/business/fixtures/inmemory/product/Picture.java
1256
/* * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org> * * 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/. */ /** * */ package org.seedstack.business.fixtures.inmemory.product; import org.seedstack.business.domain.BaseEntity; import org.seedstack.business.domain.Identity; import org.seedstack.business.util.SequenceGenerator; import org.seedstack.business.util.inmemory.InMemory; public class Picture extends BaseEntity<Long> { @Identity(generator = SequenceGenerator.class) @InMemory private Long id; private PictureURL url; private Long productId; public Picture(String url, Long productId) { super(); this.url = new PictureURL(url); this.productId = productId; } @Override public Long getId() { return id; } public PictureURL getUrl() { return url; } public void setUrl(PictureURL url) { this.url = url; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } }
mpl-2.0
emartech/android-mobile-engage-sdk
mobile-engage-sdk/src/main/java/com/emarsys/mobileengage/inbox/InboxInternalProvider.java
804
package com.emarsys.mobileengage.inbox; import com.emarsys.core.request.RequestManager; import com.emarsys.core.request.RestClient; import com.emarsys.mobileengage.RequestContext; public class InboxInternalProvider { public InboxInternal provideInboxInternal(boolean experimental, RequestManager requestManager, RestClient restClient, RequestContext requestContext) { InboxInternal result; if (experimental) { result = new InboxInternal_V2(requestManager, restClient, requestContext); } else { result = new InboxInternal_V1(requestManager, restClient, requestContext); } return result; } }
mpl-2.0
jpeddicord/progcon
sample-problems/Fibonacci/doc/solution.java
386
class Fibonacci { public static void main(String args[]) { System.out.println(fib(5)); } public static long fib(int n) { long a = 0; long b = 1; long temp = 0; for (int i = 0; i < n; i++) { //System.out.println(a); temp = a + b; a = b; b = temp; } return a; } }
mpl-2.0
utybo/BST
openbst/src/main/java/utybo/branchingstorytree/swing/visuals/JumpToNodeDialog.java
6986
/** * 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 Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, v. 2.0. */ package utybo.branchingstorytree.swing.visuals; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.Vector; import java.util.function.Consumer; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import net.miginfocom.swing.MigLayout; import utybo.branchingstorytree.api.story.BranchingStory; import utybo.branchingstorytree.api.story.StoryNode; import utybo.branchingstorytree.swing.Icons; import utybo.branchingstorytree.swing.OpenBSTGUI; import utybo.branchingstorytree.swing.impl.TabClient; import utybo.branchingstorytree.swing.utils.Lang; public class JumpToNodeDialog extends JDialog { private static final long serialVersionUID = 1L; private JTextField textField; private final ButtonGroup buttonGroup = new ButtonGroup(); private JSpinner spinner; private JLabel lblNodeExistanceInfo; private JComboBox<String> comboBox; private BranchingStory mainStory; private TabClient client; /** * 0 = with index; 1 = with alias */ private int mode; private JButton btnOk; public JumpToNodeDialog(TabClient client, BranchingStory mainStory, Consumer<StoryNode> callback) { super(OpenBSTGUI.getInstance()); this.client = client; this.mainStory = mainStory; setModalityType(ModalityType.DOCUMENT_MODAL); setTitle(Lang.get("nodejump.title")); getContentPane().setLayout(new MigLayout("", "[][][][grow]", "[][][][][grow][]")); JLabel lblGoTo = new JLabel(Lang.get("nodejump.gotonode")); getContentPane().add(lblGoTo, "cell 1 0"); JRadioButton rdbtnWithId = new JRadioButton(Lang.get("nodejump.withid")); rdbtnWithId.setHorizontalAlignment(SwingConstants.TRAILING); rdbtnWithId.addActionListener(e -> { textField.setEnabled(false); spinner.setEnabled(true); mode = 0; updateExistanceInfo(); }); rdbtnWithId.setSelected(true); buttonGroup.add(rdbtnWithId); getContentPane().add(rdbtnWithId, "cell 2 0"); JLabel label = new JLabel(new ImageIcon(Icons.getImage("Easy to Find", 40))); getContentPane().add(label, "cell 0 0 1 5,aligny top"); spinner = new JSpinner(); spinner.addChangeListener(e -> updateExistanceInfo()); spinner.setModel(new SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); getContentPane().add(spinner, "cell 3 0,growx"); JRadioButton rdbtnWithAlias = new JRadioButton(Lang.get("nodejump.withalias")); rdbtnWithAlias.addActionListener(e -> { textField.setEnabled(true); spinner.setEnabled(false); mode = 1; updateExistanceInfo(); }); buttonGroup.add(rdbtnWithAlias); getContentPane().add(rdbtnWithAlias, "cell 2 1"); textField = new JTextField(); textField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { updateExistanceInfo(); } @Override public void removeUpdate(DocumentEvent e) { updateExistanceInfo(); } @Override public void changedUpdate(DocumentEvent e) { updateExistanceInfo(); } }); textField.setEnabled(false); getContentPane().add(textField, "cell 3 1,growx"); textField.setColumns(10); JLabel lblFromFile = new JLabel(Lang.get("nodejump.fromfile")); getContentPane().add(lblFromFile, "cell 1 2,alignx trailing"); comboBox = new JComboBox<>(); comboBox.addItemListener(e -> updateExistanceInfo()); Vector<String> values = new Vector<>(); values.add("<main>"); ArrayList<String> additional = new ArrayList<String>( client.getXBFHandler().getAdditionalStoryNames()); Collections.sort(additional); values.addAll(additional); comboBox.setSelectedItem("<main>"); comboBox.setModel(new DefaultComboBoxModel<>(values)); getContentPane().add(comboBox, "cell 2 2 2 1,growx"); lblNodeExistanceInfo = new JLabel(); getContentPane().add(lblNodeExistanceInfo, "cell 1 3 3 1,alignx trailing"); btnOk = new JButton(Lang.get("nodejump.go")); btnOk.addActionListener(e -> { callback.accept(updateExistanceInfo()); dispose(); }); getContentPane().add(btnOk, "flowx,cell 0 5 4 1,alignx trailing"); JButton btnCancel = new JButton(Lang.get("cancel")); btnCancel.addActionListener(e -> dispose()); getContentPane().add(btnCancel, "cell 0 5"); updateExistanceInfo(); pack(); setLocationRelativeTo(OpenBSTGUI.getInstance()); } private StoryNode updateExistanceInfo() { String storyName = comboBox.getSelectedItem().toString(); BranchingStory story; if("<main>".equals(storyName)) story = mainStory; else story = client.getXBFHandler().getAdditionalStory(storyName); // Story can't be null here. If it is, then there's a bug in XBF. boolean exists = false; StoryNode sn = null; if(mode == 0) { sn = story.getNode((Integer)spinner.getValue()); exists = sn != null; } else { for(StoryNode n : story.getAllNodes()) { if(n.hasTag("alias") && n.getTag("alias").equals(textField.getText())) { sn = n; exists = true; break; } } } btnOk.setEnabled(exists); lblNodeExistanceInfo.setText(Lang.get(exists ? "nodejump.exists" : "nodejump.notexists")); lblNodeExistanceInfo.setForeground( exists ? (OpenBSTGUI.getInstance().isDark() ? Color.GREEN : Color.GREEN.darker()) : Color.RED); return sn; } }
mpl-2.0
itesla/ipst
modules/src/main/java/eu/itesla_project/modules/contingencies/Operator.java
442
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * 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/. */ package eu.itesla_project.modules.contingencies; /** * * @author Quinary <itesla@quinary.com> */ public interface Operator { }
mpl-2.0
jph-axelor/axelor-business-suite
axelor-production/src/main/java/com/axelor/apps/production/service/ConfiguratorCreatorServiceImpl.java
916
package com.axelor.apps.production.service; import com.axelor.apps.production.db.Configurator; import com.axelor.apps.production.db.ConfiguratorCreator; import com.axelor.apps.production.db.repo.ConfiguratorRepository; import com.google.inject.Inject; import com.google.inject.persist.Transactional; public class ConfiguratorCreatorServiceImpl implements ConfiguratorCreatorService { @Inject private ConfiguratorRepository configuratorRepo; @Override @Transactional public Configurator generateConfigurator(ConfiguratorCreator creator) { if (creator == null) { return null; } Configurator configurator = configuratorRepo.all().filter("self.configuratorCreator = ?1", creator).fetchOne(); if (configurator == null) { configurator = new Configurator(); configurator.setConfiguratorCreator(creator); configuratorRepo.save(configurator); } return configurator; } }
agpl-3.0
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/module/endow/document/service/CAECodeService.java
1180
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.endow.document.service; import org.kuali.kfs.module.endow.businessobject.CAECode; public interface CAECodeService { /** * Gets a CAECode by primary key. * * @param code * @return a CAECode */ public CAECode getByPrimaryKey(String code); }
agpl-3.0
Skelril/Aurora
src/main/java/com/skelril/aurora/items/specialattack/SpecialAttack.java
1781
/* * Copyright (c) 2014 Wyatt Childers. * * This file is part of Aurora. * * Aurora is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aurora is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Aurora. If not, see <http://www.gnu.org/licenses/>. */ package com.skelril.aurora.items.specialattack; import com.sk89q.commandbook.CommandBook; import com.skelril.aurora.util.ChatUtil; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import java.util.logging.Logger; public abstract class SpecialAttack { protected static final CommandBook inst = CommandBook.inst(); protected static final Logger log = inst.getLogger(); protected static final Server server = CommandBook.server(); protected LivingEntity owner; public SpecialAttack(LivingEntity owner) { this.owner = owner; } public abstract void activate(); public abstract LivingEntity getTarget(); public abstract Location getLocation(); public LivingEntity getOwner() { return owner; } protected void inform(String message) { if (owner instanceof Player) { ChatUtil.send((Player) owner, message); } } public long getCoolDown() { return 0; } }
agpl-3.0
thiagopa/planyourexchange
app/src/main/java/com/planyourexchange/fragments/schoolcourse/SchoolCourseValueFragment.java
2990
package com.planyourexchange.fragments.schoolcourse; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.planyourexchange.R; import com.planyourexchange.fragments.base.ListViewFragment; import com.planyourexchange.pageflow.PageFlow; import com.planyourexchange.rest.model.SchoolCourseValue; import com.planyourexchange.rest.model.SchoolCourseValueKey; import com.planyourexchange.utils.MoneyUtils; import java.io.Serializable; import butterknife.Bind; import butterknife.ButterKnife; /** * Copyright (C) 2015, Thiago Pagonha, * Plan Your Exchange, easy exchange to fit your budget * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class SchoolCourseValueFragment extends ListViewFragment<SchoolCourseValueKey,SchoolCourseValue> { public SchoolCourseValueFragment() { super(R.string.school_course_value_title, R.string.school_course_value, R.layout.school_course_value_list, PageFlow.HEALTH_INSURANCE); } @Override public void callService(SchoolCourseValueKey schoolCourseValueKey) { serverApi.findCourseSchoolValue(schoolCourseValueKey, this); } @Override protected Serializable createNextKey(SchoolCourseValue schoolCourseValue) { return pageFlowContext.getCountry().getId(); } static class ViewHolder { @Bind(R.id.school_course_icon) ImageView icon; @Bind(R.id.school_course_name) TextView name; @Bind(R.id.school_course_price) TextView price; ViewHolder(View view) { ButterKnife.bind(this, view); } } @Override protected void renderSingleModel(SchoolCourseValue schoolCourseValue, View rowView) { ViewHolder viewHolder = new ViewHolder(rowView); ImageLoader.getInstance().displayImage(schoolCourseValue.getSchool().getIcon(), viewHolder.icon); viewHolder.name.setText(schoolCourseValue.getSchool().getName()); viewHolder.price.setText(MoneyUtils.newPrice( pageFlowContext.getCountry().getDefaultCurrency(), schoolCourseValue.getWeekPrice() ) ); } @Override protected void saveOption(SchoolCourseValue schoolCourseValue) { pageFlowContext.setSchoolCourseValue(schoolCourseValue); } }
agpl-3.0
rapidminer/rapidminer-studio
src/main/java/com/rapidminer/tools/encryption/exceptions/EncryptionFailedException.java
1297
/** * Copyright (C) 2001-2020 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.tools.encryption.exceptions; /** * Indicating that encryption/decryption failed. The cause can be found by calling {@link #getCause()}. * * @author Marco Boeck * @since 9.7 */ public class EncryptionFailedException extends EncryptionException { /** * Creates an EncryptionFailedException with the specified cause. * * @param cause the cause, can be {@code null} */ public EncryptionFailedException(Throwable cause) { super(cause); } }
agpl-3.0
azfalcon/xmlintl-falcon-ws
xmlintl-falcon-ws/test/com/xmlintl/falcon/util/ListEnginesTest.java
808
package com.xmlintl.falcon.util; import static org.junit.Assert.*; import java.util.ArrayList; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; public class ListEnginesTest { Logger logger = Logger.getLogger(ListEnginesTest.class); @Before public void setUp() throws Exception { } @Test public final void test() { try { ListEngines listEngines = new ListEngines("2147"); ArrayList<SMTEngine> list = listEngines.list(); for (SMTEngine engine: list) { logger.info(engine); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }
agpl-3.0
rroart/stockstat
common/config/src/main/java/roart/common/ml/NeuralNetSparkConfig.java
1526
package roart.common.ml; public class NeuralNetSparkConfig { private SparkLORConfig sparkLORConfig; private SparkMLPCConfig sparkMLPCConfig; private SparkOVRConfig sparkOVRConfig; private SparkLSVCConfig sparkLSVCConfig; public NeuralNetSparkConfig() { super(); } public NeuralNetSparkConfig(SparkLORConfig sparkLRConfig, SparkMLPCConfig sparkMLPCConfig, SparkOVRConfig sparkOVRConfig, SparkLSVCConfig sparkLSVCConfig) { super(); this.sparkLORConfig = sparkLRConfig; this.sparkMLPCConfig = sparkMLPCConfig; this.sparkOVRConfig = sparkOVRConfig; this.sparkLSVCConfig = sparkLSVCConfig; } public SparkLORConfig getSparkLORConfig() { return sparkLORConfig; } public void setSparkLORConfig(SparkLORConfig sparkLORConfig) { this.sparkLORConfig = sparkLORConfig; } public SparkMLPCConfig getSparkMLPCConfig() { return sparkMLPCConfig; } public void setSparkMLPCConfig(SparkMLPCConfig sparkMLPCConfig) { this.sparkMLPCConfig = sparkMLPCConfig; } public SparkOVRConfig getSparkOVRConfig() { return sparkOVRConfig; } public void setSparkOVRConfig(SparkOVRConfig sparkOVRConfig) { this.sparkOVRConfig = sparkOVRConfig; } public SparkLSVCConfig getSparkLSVCConfig() { return sparkLSVCConfig; } public void setSparkLSVCConfig(SparkLSVCConfig sparkLSVCConfig) { this.sparkLSVCConfig = sparkLSVCConfig; } }
agpl-3.0
chris-dvdb/dvdb.de
dvdb-external/src/main/java/com/amazon/soap/ecs/SearchInside.java
7964
package com.amazon.soap.ecs; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TotalExcerpts" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/> * &lt;element name="Excerpt" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Checksum" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PageType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PageNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SequenceNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Text" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "totalExcerpts", "excerpt" }) @XmlRootElement(name = "SearchInside") public class SearchInside { @XmlElement(name = "TotalExcerpts") @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger totalExcerpts; @XmlElement(name = "Excerpt") protected SearchInside.Excerpt excerpt; /** * Gets the value of the totalExcerpts property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getTotalExcerpts() { return totalExcerpts; } /** * Sets the value of the totalExcerpts property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTotalExcerpts(BigInteger value) { this.totalExcerpts = value; } /** * Gets the value of the excerpt property. * * @return * possible object is * {@link SearchInside.Excerpt } * */ public SearchInside.Excerpt getExcerpt() { return excerpt; } /** * Sets the value of the excerpt property. * * @param value * allowed object is * {@link SearchInside.Excerpt } * */ public void setExcerpt(SearchInside.Excerpt value) { this.excerpt = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Checksum" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PageType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PageNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SequenceNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Text" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "checksum", "pageType", "pageNumber", "sequenceNumber", "text" }) public static class Excerpt { @XmlElement(name = "Checksum") protected String checksum; @XmlElement(name = "PageType") protected String pageType; @XmlElement(name = "PageNumber") protected String pageNumber; @XmlElement(name = "SequenceNumber") protected String sequenceNumber; @XmlElement(name = "Text") protected String text; /** * Gets the value of the checksum property. * * @return * possible object is * {@link String } * */ public String getChecksum() { return checksum; } /** * Sets the value of the checksum property. * * @param value * allowed object is * {@link String } * */ public void setChecksum(String value) { this.checksum = value; } /** * Gets the value of the pageType property. * * @return * possible object is * {@link String } * */ public String getPageType() { return pageType; } /** * Sets the value of the pageType property. * * @param value * allowed object is * {@link String } * */ public void setPageType(String value) { this.pageType = value; } /** * Gets the value of the pageNumber property. * * @return * possible object is * {@link String } * */ public String getPageNumber() { return pageNumber; } /** * Sets the value of the pageNumber property. * * @param value * allowed object is * {@link String } * */ public void setPageNumber(String value) { this.pageNumber = value; } /** * Gets the value of the sequenceNumber property. * * @return * possible object is * {@link String } * */ public String getSequenceNumber() { return sequenceNumber; } /** * Sets the value of the sequenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setSequenceNumber(String value) { this.sequenceNumber = value; } /** * Gets the value of the text property. * * @return * possible object is * {@link String } * */ public String getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link String } * */ public void setText(String value) { this.text = value; } } }
agpl-3.0
rascal999/torc-gui
src/torc_gui/TabbedPane.java
69954
/* * 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 torc_gui; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.awt.Color; import java.io.*; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import javax.swing.JOptionPane; import java.util.zip.*; /** * * @author user */ public class TabbedPane extends javax.swing.JFrame { /** * Creates new form TabbedPane */ public TabbedPane() { initComponents(); // Check if we're connected to autopwn instance CheckConnection(); // Populate tool list PopulateTools(); // Populate assessment list PopulateAssessments(); // Populate tool jobs PopulateToolJobs(); } public final boolean PopulateTools() { String sURL = "http://127.0.0.1:5000/tools"; //just a string JsonArray tools; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. tools = rootobj.get("result").getAsJsonArray(); for (int i = 0; i < tools.size(); i++) { JsonObject row = tools.get(i).getAsJsonObject(); comboboxRunToolTools.addItem(row.get("name").toString().replaceAll("^\"|\"$", "")); } } catch (Exception exc) { //test System.err.println("error"); } return true; } public final boolean PopulateAssessments() { String sURL = "http://127.0.0.1:5000/assessments"; //just a string JsonArray tools; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. tools = rootobj.get("result").getAsJsonArray(); for (int i = 0; i < tools.size(); i++) { JsonObject row = tools.get(i).getAsJsonObject(); comboboxRunAssessmentAssessments.addItem(row.get("name").toString().replaceAll("^\"|\"$", "")); } } catch (Exception exc) { //test System.err.println("error"); } return true; } public final String getToolById(int tool_id) { String toolName = "error", sURL = "http://127.0.0.1:5000/tools/" + tool_id; //just a string JsonArray tools; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. tools = rootobj.get("result").getAsJsonArray(); JsonObject row = tools.get(0).getAsJsonObject(); toolName = (row.get("name").toString()); } catch (Exception exc) { //test System.err.println("error"); } return toolName; } public final boolean PopulateToolJobs() { String sURL = "http://127.0.0.1:5000/tools/jobs"; //just a string String target_name, tool_name, target, id, return_code; JsonArray tools; int k; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setUseCaches(false); request.connect(); request.disconnect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonArray rootobj = root.getAsJsonArray(); //May be an array, may be an object. System.out.println("cool"); tools = rootobj.getAsJsonArray(); System.out.println(tools); DefaultTableModel model = (DefaultTableModel) TableToolJobs.getModel(); // Remove rows if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { model.removeRow(i); } } for (int i = 0; i < tools.size(); i++) { JsonObject row = tools.get(i).getAsJsonObject(); id = row.get("id").toString().replaceAll("^\"|\"$", ""); target_name = row.get("target_name").toString().replaceAll("^\"|\"$", ""); tool_name = getToolById(row.get("tool").getAsInt()).replaceAll("^\"|\"$", ""); target = row.get("target").toString().replaceAll("^\"|\"$", ""); return_code = row.get("return_code").toString().replaceAll("^\"|\"$", ""); model.addRow(new Object[]{i}); TableToolJobs.setValueAt(id, i, 0); TableToolJobs.setValueAt(target_name, i, 1); TableToolJobs.setValueAt(tool_name, i, 2); TableToolJobs.setValueAt(target, i, 3); TableToolJobs.setValueAt(return_code, i, 4); } // Apply filters if (CheckBoxHideComplete.isSelected()) { HideComplete(); } if (CheckBoxHideIncomplete.isSelected()) { HideIncomplete(); } } catch (Exception exc) { //test System.err.println("error" + exc); } return true; } public final boolean CheckConnection() { String sURL = "http://127.0.0.1:5000/ping"; //just a string String message; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. message = rootobj.get("message").getAsString(); if (message.equals("pong")) { labelRunToolConnectionStatus.setForeground(Color.green); labelRunToolConnectionStatus.setText("Connected!"); labelRunAssessmentConnectionStatus.setForeground(Color.green); labelRunAssessmentConnectionStatus.setText("Connected!"); } } catch (Exception exc) { //test } return true; } public final int SaveToolJob(String target, int param_tool_id) { String sURL = "http://127.0.0.1:5000/tools/jobs"; //just a string int job_id = 0, tool_id = 0; String urlParameters; // Depending on which panel is visible we need the contents of the text field in that panel try { if (PanelRunTool.isVisible() == true){ urlParameters = "tool=" + comboboxRunToolTools.getSelectedIndex() + "&target=" + target + "&target_name=" + textfieldRunToolJobName.getText() + "&protocol=" + textfieldRunToolProtocol.getText() + "&port_number=" + formattedtextfieldRunToolPortNumber.getText() + "&user=" + textfieldRunToolUser.getText() + "&password=" + textfieldRunToolPassword.getText() + "&user_file=" + textfieldRunToolUserFile.getText() + "&password_file=" + textfieldRunToolPasswordFile.getText() + "&url=" + textfieldRunToolURL.getText(); } else { tool_id = param_tool_id; urlParameters = "tool=" + tool_id + "&target=" + target + "&target_name=" + textfieldRunAssessmentJobName.getText() + "&protocol=" + textfieldRunAssessmentProtocol.getText() + "&port_number=" + formattedtextfieldRunAssessmentPortNumber.getText() + "&user=" + textfieldRunAssessmentUser.getText() + "&password=" + textfieldRunAssessmentPassword.getText() + "&user_file=" + textfieldRunAssessmentUserFile.getText() + "&password_file=" + textfieldRunAssessmentPasswordFile.getText() + "&url=" + textfieldRunAssessmentURL.getText(); } byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; URL url = new URL(sURL); // Connect to the URL using java's native library HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } conn.disconnect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. job_id = rootobj.get("id").getAsInt(); System.out.println("Job id: " + job_id); } catch (Exception exc) { //test } return job_id; } public final int RunAssessmentJob(int job_id) { String sURL = "http://127.0.0.1:5000/assessments/jobs/execute"; //just a string // Connect to the URL using java's native library try { String urlParameters = "id=" + job_id; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; URL url = new URL(sURL); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } conn.disconnect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. job_id = rootobj.get("id").getAsInt(); System.out.println("Job id: " + job_id); } catch (Exception exc) { //test } return 1; } public int RunToolJob(int job_id) { String sURL = "http://127.0.0.1:5000/tools/jobs/execute"; //just a string // Connect to the URL using java's native library try { String urlParameters = "id=" + job_id; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; URL url = new URL(sURL); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } conn.disconnect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. job_id = rootobj.get("id").getAsInt(); System.out.println("Job id: " + job_id); } catch (Exception exc) { //test } return 1; } public final int ExportSingleResult(int [] selectedRow) { String defaultFileName, jobId = TableToolJobs.getValueAt(selectedRow[0], 0).toString(); String sURL = "http://127.0.0.1:5000/tools/jobs/exports/" + jobId; //just a string String message; InputStream fileContent; byte[] buffer = new byte[4096]; int n = -1; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); fileContent = request.getInputStream(); // parent component of the dialog JFrame parentFrame = new JFrame(); defaultFileName = TableToolJobs.getValueAt(TableToolJobs.getSelectedRow(), 3).toString() + "_" + TableToolJobs.getValueAt(TableToolJobs.getSelectedRow(), 2).toString() + ".zip"; // New file path File fileToSavePath = new File(System.getProperty("user.home") + "/" + defaultFileName); // New fileChooser JFileChooser fileChooser = new JFileChooser(); // Set fileChooser path to file fileChooser.setSelectedFile(fileToSavePath); fileChooser.setDialogTitle("Specify a file to save"); FileNameExtensionFilter zipType = new FileNameExtensionFilter("Zip file (.zip)", "zip"); fileChooser.addChoosableFileFilter(zipType); fileChooser.setFileFilter(zipType); int userSelection = fileChooser.showSaveDialog(parentFrame); if (userSelection == JFileChooser.APPROVE_OPTION) { File fileToSave = fileChooser.getSelectedFile(); System.out.println("Save as file: " + fileToSave.getAbsolutePath()); OutputStream output = new FileOutputStream(fileToSave); while ((n = fileContent.read(buffer)) != -1) { output.write(buffer, 0, n); } output.close(); } } catch (Exception anexc) { // something } return 0; } public final int ExportMultipleResults(int [] selectedRows) { String defaultFileName, jobId; InputStream[] fileContent; // Need to improve this fileContent = new InputStream[4096]; byte[] buffer = new byte[4096]; int n = -1; int count; System.out.println("selectedRows.length == " + selectedRows.length); // Fetch results from autopwn node for (int i = 0; i < selectedRows.length; i++){ jobId = TableToolJobs.getValueAt(selectedRows[i], 0).toString(); System.out.println("jobId == " + jobId); String sURL = "http://127.0.0.1:5000/tools/jobs/exports/" + jobId; //just a string // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); fileContent[i] = request.getInputStream(); } catch (Exception anexc) { // something } } try { File fos = new File("wtf.zip"); //FileOutputStream fos = new FileOutputStream("wtf.zip"); FileOutputStream bos = new FileOutputStream(fos); System.out.println("False???"); ZipOutputStream zos = new ZipOutputStream(bos); try { for (int i = 0; i < selectedRows.length; i++){ // not available on BufferedOutputStream zos.putNextEntry(new ZipEntry(TableToolJobs.getValueAt(selectedRows[i], 1).toString() + "_" + TableToolJobs.getValueAt(selectedRows[i], 2).toString() + "_" + TableToolJobs.getValueAt(selectedRows[i], 3).toString() + "_" + TableToolJobs.getValueAt(selectedRows[i], 0).toString() + ".zip")); while ((count = fileContent[i].read(buffer)) > 0) { System.out.println("Writing"); zos.write(buffer, 0, count); } // not available on BufferedOutputStream zos.closeEntry(); } } finally { zos.close(); } // parent component of the dialog JFrame parentFrame = new JFrame(); defaultFileName = ""; // New file path File fileToSavePath = new File(System.getProperty("user.home") + "/" + defaultFileName); // New fileChooser JFileChooser fileChooser = new JFileChooser(); // Set fileChooser path to file fileChooser.setSelectedFile(fileToSavePath); fileChooser.setDialogTitle("Specify a file to save"); FileNameExtensionFilter zipType = new FileNameExtensionFilter("Zip file (.zip)", "zip"); fileChooser.addChoosableFileFilter(zipType); fileChooser.setFileFilter(zipType); int userSelection = fileChooser.showSaveDialog(parentFrame); if (userSelection == JFileChooser.APPROVE_OPTION) { File fileToSave = fileChooser.getSelectedFile(); System.out.println("Save as file: " + fileToSave.getAbsolutePath()); OutputStream output = new FileOutputStream(fileToSave); InputStream input = new FileInputStream(fos); while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); } input.close(); } fos.delete(); } catch(Exception yaexc) { // something System.err.println(yaexc); } return 0; } public final void TableJobsSearch(String searchString){ DefaultTableModel model = (DefaultTableModel) TableToolJobs.getModel(); PopulateToolJobs(); if (searchString.equals("Search...") == false){ if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { // Can search 1 2 3 if ((model.getValueAt(i, 1).toString().contains(searchString) == false) && (model.getValueAt(i, 2).toString().contains(searchString) == false) && (model.getValueAt(i, 3).toString().contains(searchString) == false)){ model.removeRow(i); } } } } } public final void HideIncomplete(){ DefaultTableModel model = (DefaultTableModel) TableToolJobs.getModel(); if (CheckBoxHideIncomplete.isSelected() == true){ if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { System.out.println(model.getValueAt(i, 4).toString()); if (model.getValueAt(i, 4).toString().equals("null")){ model.removeRow(i); } } } } else { PopulateToolJobs(); } } public final void HideComplete(){ DefaultTableModel model = (DefaultTableModel) TableToolJobs.getModel(); if (CheckBoxHideComplete.isSelected() == true){ if (model.getRowCount() > 0) { for (int i = model.getRowCount() - 1; i > -1; i--) { if (model.getValueAt(i, 4).toString().equals("null") != true){ model.removeRow(i); } } } } else { PopulateToolJobs(); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { TabbedAutopwn = new javax.swing.JTabbedPane(); PanelRunTool = new javax.swing.JPanel(); textfieldRunToolJobName = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); textfieldRunToolPasswordFile = new javax.swing.JTextField(); textfieldRunToolUserFile = new javax.swing.JTextField(); textfieldRunToolProtocol = new javax.swing.JTextField(); textfieldRunToolURL = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); comboboxRunToolTools = new javax.swing.JComboBox<>(); jLabel9 = new javax.swing.JLabel(); buttonRunToolRun = new javax.swing.JButton(); labelRunToolConnectionStatus = new javax.swing.JLabel(); formattedtextfieldRunToolPortNumber = new javax.swing.JFormattedTextField(); textfieldRunToolUser = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); textfieldRunToolPassword = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); textAreaToolTargetList = new javax.swing.JTextArea(); PanelRunAssessment = new javax.swing.JPanel(); textfieldRunAssessmentJobName = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); textfieldRunAssessmentPasswordFile = new javax.swing.JTextField(); textfieldRunAssessmentUserFile = new javax.swing.JTextField(); textfieldRunAssessmentProtocol = new javax.swing.JTextField(); textfieldRunAssessmentURL = new javax.swing.JTextField(); jLabel19 = new javax.swing.JLabel(); buttonRunAssessmentRun = new javax.swing.JButton(); labelRunAssessmentConnectionStatus = new javax.swing.JLabel(); formattedtextfieldRunAssessmentPortNumber = new javax.swing.JFormattedTextField(); textfieldRunAssessmentUser = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); textfieldRunAssessmentPassword = new javax.swing.JTextField(); jLabel22 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); comboboxRunAssessmentAssessments = new javax.swing.JComboBox<>(); jLabel27 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel28 = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); textAreaAssessmentTargetList = new javax.swing.JTextArea(); jLabel29 = new javax.swing.JLabel(); PanelJobs = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); TableToolJobs = new javax.swing.JTable(); ButtonRefreshTable = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); ButtonToolExport = new javax.swing.JButton(); CheckBoxHideComplete = new javax.swing.JCheckBox(); CheckBoxHideIncomplete = new javax.swing.JCheckBox(); TextFieldJobsSearch = new javax.swing.JTextField(); ButtonRefreshTableBottom = new javax.swing.JButton(); ButtonToolExportBottom = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel2.setText("job_name"); jLabel5.setText("target_list"); jLabel6.setText("port_number"); jLabel7.setText("password_file"); jLabel8.setText("Torc GUI v0.1.0 - github.com/rascal999/torc-gui"); comboboxRunToolTools.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "None" })); jLabel9.setText("Tool"); buttonRunToolRun.setText("Run"); buttonRunToolRun.setToolTipText(""); buttonRunToolRun.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { buttonRunToolRunMouseClicked(evt); } }); buttonRunToolRun.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonRunToolRunActionPerformed(evt); } }); labelRunToolConnectionStatus.setForeground(new java.awt.Color(204, 51, 0)); labelRunToolConnectionStatus.setText("Not Connected!"); labelRunToolConnectionStatus.setName("labelRunToolConnectionStatus"); // NOI18N jLabel12.setText("password"); jLabel13.setText("user"); jLabel14.setText("user_file"); jLabel15.setText("protocol"); jLabel16.setText("url"); jLabel20.setText("target_file"); jButton1.setText("Upload"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel1.setText("file"); textAreaToolTargetList.setColumns(20); textAreaToolTargetList.setRows(5); jScrollPane3.setViewportView(textAreaToolTargetList); javax.swing.GroupLayout PanelRunToolLayout = new javax.swing.GroupLayout(PanelRunTool); PanelRunTool.setLayout(PanelRunToolLayout); PanelRunToolLayout.setHorizontalGroup( PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunToolLayout.createSequentialGroup() .addContainerGap() .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunToolLayout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE) .addComponent(labelRunToolConnectionStatus)) .addComponent(buttonRunToolRun, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(PanelRunToolLayout.createSequentialGroup() .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel12) .addComponent(jLabel13) .addComponent(jLabel14) .addComponent(jLabel15) .addComponent(jLabel16) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textfieldRunToolPasswordFile, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunToolPassword) .addComponent(textfieldRunToolUserFile, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunToolUser) .addComponent(textfieldRunToolURL) .addComponent(textfieldRunToolProtocol) .addComponent(formattedtextfieldRunToolPortNumber, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunToolJobName))) .addGroup(PanelRunToolLayout.createSequentialGroup() .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(PanelRunToolLayout.createSequentialGroup() .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jLabel5)) .addGap(37, 37, 37) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3) .addComponent(comboboxRunToolTools, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); PanelRunToolLayout.setVerticalGroup( PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunToolLayout.createSequentialGroup() .addContainerGap() .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(labelRunToolConnectionStatus)) .addGap(18, 18, 18) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(comboboxRunToolTools, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE) .addGroup(PanelRunToolLayout.createSequentialGroup() .addComponent(jLabel5) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jLabel1) .addComponent(jLabel20)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunToolJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(formattedtextfieldRunToolPortNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunToolPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunToolPasswordFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(textfieldRunToolUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(textfieldRunToolUserFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(textfieldRunToolProtocol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunToolLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunToolURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonRunToolRun) .addContainerGap()) ); TabbedAutopwn.addTab("Run Tool", PanelRunTool); jLabel4.setText("job_name"); jLabel17.setText("port_number"); jLabel18.setText("password_file"); jLabel19.setText("Torc GUI v0.1.0 - github.com/rascal999/torc-gui"); buttonRunAssessmentRun.setText("Run"); buttonRunAssessmentRun.setToolTipText(""); buttonRunAssessmentRun.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { buttonRunAssessmentRunMouseClicked(evt); } }); labelRunAssessmentConnectionStatus.setForeground(new java.awt.Color(204, 51, 0)); labelRunAssessmentConnectionStatus.setText("Not Connected!"); labelRunAssessmentConnectionStatus.setName("labelConnectionStatus"); // NOI18N jLabel21.setText("password"); jLabel22.setText("user"); jLabel23.setText("user_file"); jLabel24.setText("protocol"); jLabel25.setText("url"); jLabel26.setText("Assessment"); comboboxRunAssessmentAssessments.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "None" })); jLabel27.setText("target_file"); jButton2.setText("Upload"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel28.setText("file"); textAreaAssessmentTargetList.setColumns(20); textAreaAssessmentTargetList.setRows(5); jScrollPane4.setViewportView(textAreaAssessmentTargetList); jLabel29.setText("target_list"); javax.swing.GroupLayout PanelRunAssessmentLayout = new javax.swing.GroupLayout(PanelRunAssessment); PanelRunAssessment.setLayout(PanelRunAssessmentLayout); PanelRunAssessmentLayout.setHorizontalGroup( PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addContainerGap() .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addComponent(jLabel19) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE) .addComponent(labelRunAssessmentConnectionStatus)) .addComponent(buttonRunAssessmentRun, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jLabel18) .addComponent(jLabel21) .addComponent(jLabel22) .addComponent(jLabel23) .addComponent(jLabel24) .addComponent(jLabel25) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textfieldRunAssessmentJobName, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunAssessmentPassword, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(formattedtextfieldRunAssessmentPortNumber) .addComponent(textfieldRunAssessmentUser, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunAssessmentPasswordFile) .addComponent(textfieldRunAssessmentURL, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textfieldRunAssessmentProtocol) .addComponent(textfieldRunAssessmentUserFile))) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addComponent(jLabel27) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel29) .addComponent(jLabel26)) .addGap(24, 24, 24) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboboxRunAssessmentAssessments, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane4)))) .addContainerGap()) ); PanelRunAssessmentLayout.setVerticalGroup( PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addContainerGap() .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19) .addComponent(labelRunAssessmentConnectionStatus)) .addGap(18, 18, 18) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(comboboxRunAssessmentAssessments, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel26)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE) .addGroup(PanelRunAssessmentLayout.createSequentialGroup() .addComponent(jLabel29) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jLabel28) .addComponent(jLabel27)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunAssessmentJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(formattedtextfieldRunAssessmentPortNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunAssessmentPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel21)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunAssessmentPasswordFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(textfieldRunAssessmentUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel23) .addComponent(textfieldRunAssessmentUserFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel24) .addComponent(textfieldRunAssessmentProtocol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelRunAssessmentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textfieldRunAssessmentURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel25)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonRunAssessmentRun) .addContainerGap()) ); TabbedAutopwn.addTab("Run Assessment", PanelRunAssessment); TableToolJobs.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Name", "Tool", "Target", "Return Code" } )); jScrollPane1.setViewportView(TableToolJobs); ButtonRefreshTable.setText("Refresh tables"); ButtonRefreshTable.setPreferredSize(new java.awt.Dimension(80, 25)); ButtonRefreshTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ButtonRefreshTableMouseClicked(evt); } }); jLabel3.setText("Jobs"); ButtonToolExport.setText("Export"); ButtonToolExport.setPreferredSize(new java.awt.Dimension(80, 25)); ButtonToolExport.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ButtonToolExportMouseClicked(evt); } }); CheckBoxHideComplete.setText("Hide complete"); CheckBoxHideComplete.setToolTipText("Jobs which have been completed should have a return code"); CheckBoxHideComplete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CheckBoxHideCompleteActionPerformed(evt); } }); CheckBoxHideIncomplete.setText("Hide incomplete"); CheckBoxHideIncomplete.setToolTipText("Jobs which have not finished running should have a 'null' return code"); CheckBoxHideIncomplete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CheckBoxHideIncompleteActionPerformed(evt); } }); TextFieldJobsSearch.setText("Search..."); TextFieldJobsSearch.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { TextFieldJobsSearchMouseClicked(evt); } }); TextFieldJobsSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TextFieldJobsSearchActionPerformed(evt); } }); ButtonRefreshTableBottom.setText("Refresh tables"); ButtonRefreshTableBottom.setPreferredSize(new java.awt.Dimension(80, 25)); ButtonRefreshTableBottom.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ButtonRefreshTableBottomMouseClicked(evt); } }); ButtonToolExportBottom.setText("Export"); ButtonToolExportBottom.setPreferredSize(new java.awt.Dimension(80, 25)); ButtonToolExportBottom.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ButtonToolExportBottomMouseClicked(evt); } }); javax.swing.GroupLayout PanelJobsLayout = new javax.swing.GroupLayout(PanelJobs); PanelJobs.setLayout(PanelJobsLayout); PanelJobsLayout.setHorizontalGroup( PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelJobsLayout.createSequentialGroup() .addContainerGap() .addGroup(PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE) .addGroup(PanelJobsLayout.createSequentialGroup() .addGroup(PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ButtonRefreshTable, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ButtonToolExport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(PanelJobsLayout.createSequentialGroup() .addComponent(CheckBoxHideComplete) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CheckBoxHideIncomplete) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TextFieldJobsSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelJobsLayout.createSequentialGroup() .addComponent(ButtonRefreshTableBottom, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ButtonToolExportBottom, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); PanelJobsLayout.setVerticalGroup( PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelJobsLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonToolExport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ButtonRefreshTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(CheckBoxHideComplete) .addComponent(CheckBoxHideIncomplete) .addComponent(TextFieldJobsSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(PanelJobsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ButtonToolExportBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ButtonRefreshTableBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); TabbedAutopwn.addTab("Jobs", PanelJobs); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TabbedAutopwn) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TabbedAutopwn) ); pack(); }// </editor-fold>//GEN-END:initComponents private void buttonRunToolRunMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonRunToolRunMouseClicked // Run job if (comboboxRunToolTools.getSelectedIndex() == 0) { JOptionPane.showMessageDialog(null, "You need to select a tool to use.", "InfoBox: Error", JOptionPane.INFORMATION_MESSAGE); return; } if (textfieldRunToolJobName.getText().equals("")) { JOptionPane.showMessageDialog(null, "You need to specify a job name.", "InfoBox: Error", JOptionPane.INFORMATION_MESSAGE); return; } String []target = textAreaToolTargetList.getText().split(System.getProperty(("line.separator"))); for (String individualTarget: target) { int job_id = SaveToolJob(individualTarget, 0); try { Thread.sleep(100); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } RunToolJob(job_id); } }//GEN-LAST:event_buttonRunToolRunMouseClicked private void ButtonToolExportMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonToolExportMouseClicked int [] selectedRows = TableToolJobs.getSelectedRows(); if (selectedRows.length > 1) { System.out.println("About to enter ExportMultipleResults"); ExportMultipleResults(selectedRows); } else { ExportSingleResult(selectedRows); } }//GEN-LAST:event_ButtonToolExportMouseClicked private void ButtonRefreshTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonRefreshTableMouseClicked // Populate tool jobs PopulateToolJobs(); }//GEN-LAST:event_ButtonRefreshTableMouseClicked private void buttonRunAssessmentRunMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonRunAssessmentRunMouseClicked // Fetch tools from assessment if (comboboxRunAssessmentAssessments.getSelectedIndex() == 0) { JOptionPane.showMessageDialog(null, "You need to select an assessment to use.", "InfoBox: Error", JOptionPane.INFORMATION_MESSAGE); return; } if (textfieldRunAssessmentJobName.getText().equals("")) { JOptionPane.showMessageDialog(null, "You need to specify a job name.", "InfoBox: Error", JOptionPane.INFORMATION_MESSAGE); return; } int assessment_id = comboboxRunAssessmentAssessments.getSelectedIndex(); String sURL = "http://127.0.0.1:5000/assessments/" + assessment_id; //just a string JsonArray tools; // Connect to the URL using java's native library try { URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. // Get result/tool tools = rootobj.get("result").getAsJsonArray(); JsonObject row = tools.get(0).getAsJsonObject(); JsonArray tool = row.get("tools").getAsJsonArray(); String []target = textAreaAssessmentTargetList.getText().split(System.getProperty(("line.separator"))); for (String individualTarget: target) { for (int i = 0; i < tool.size(); i++) { JsonObject tool_id_json = tool.get(i).getAsJsonObject(); int tool_id = tool_id_json.get("tool").getAsInt(); // Run job int job_id = SaveToolJob(individualTarget, tool_id); try { Thread.sleep(100); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } RunToolJob(job_id); } } } catch (Exception exc) { //test System.err.println("error " + exc); System.err.println("what the fuck"); } }//GEN-LAST:event_buttonRunAssessmentRunMouseClicked private void CheckBoxHideCompleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckBoxHideCompleteActionPerformed // TODO add your handling code here: HideComplete(); }//GEN-LAST:event_CheckBoxHideCompleteActionPerformed private void CheckBoxHideIncompleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckBoxHideIncompleteActionPerformed // TODO add your handling code here: HideIncomplete(); }//GEN-LAST:event_CheckBoxHideIncompleteActionPerformed private void TextFieldJobsSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TextFieldJobsSearchMouseClicked // TODO add your handling code here: TextFieldJobsSearch.setText(""); }//GEN-LAST:event_TextFieldJobsSearchMouseClicked private void TextFieldJobsSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TextFieldJobsSearchActionPerformed // TODO add your handling code here: TableJobsSearch(TextFieldJobsSearch.getText()); }//GEN-LAST:event_TextFieldJobsSearchActionPerformed private void ButtonRefreshTableBottomMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonRefreshTableBottomMouseClicked // Populate tool jobs PopulateToolJobs(); }//GEN-LAST:event_ButtonRefreshTableBottomMouseClicked private void ButtonToolExportBottomMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonToolExportBottomMouseClicked // TODO add your handling code here: int [] selectedRows = TableToolJobs.getSelectedRows(); if (selectedRows.length > 1) { System.out.println("About to enter ExportMultipleResults"); ExportMultipleResults(selectedRows); } else { ExportSingleResult(selectedRows); } }//GEN-LAST:event_ButtonToolExportBottomMouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void buttonRunToolRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunToolRunActionPerformed // TODO add your handling code here: }//GEN-LAST:event_buttonRunToolRunActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TabbedPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TabbedPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TabbedPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TabbedPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TabbedPane().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonRefreshTable; private javax.swing.JButton ButtonRefreshTableBottom; private javax.swing.JButton ButtonToolExport; private javax.swing.JButton ButtonToolExportBottom; private javax.swing.JCheckBox CheckBoxHideComplete; private javax.swing.JCheckBox CheckBoxHideIncomplete; private javax.swing.JPanel PanelJobs; private javax.swing.JPanel PanelRunAssessment; private javax.swing.JPanel PanelRunTool; private javax.swing.JTabbedPane TabbedAutopwn; private javax.swing.JTable TableToolJobs; private javax.swing.JTextField TextFieldJobsSearch; private javax.swing.JButton buttonRunAssessmentRun; private javax.swing.JButton buttonRunToolRun; private javax.swing.JComboBox<String> comboboxRunAssessmentAssessments; private javax.swing.JComboBox<String> comboboxRunToolTools; private javax.swing.JFormattedTextField formattedtextfieldRunAssessmentPortNumber; private javax.swing.JFormattedTextField formattedtextfieldRunToolPortNumber; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JLabel labelRunAssessmentConnectionStatus; private javax.swing.JLabel labelRunToolConnectionStatus; private javax.swing.JTextArea textAreaAssessmentTargetList; private javax.swing.JTextArea textAreaToolTargetList; private javax.swing.JTextField textfieldRunAssessmentJobName; private javax.swing.JTextField textfieldRunAssessmentPassword; private javax.swing.JTextField textfieldRunAssessmentPasswordFile; private javax.swing.JTextField textfieldRunAssessmentProtocol; private javax.swing.JTextField textfieldRunAssessmentURL; private javax.swing.JTextField textfieldRunAssessmentUser; private javax.swing.JTextField textfieldRunAssessmentUserFile; private javax.swing.JTextField textfieldRunToolJobName; private javax.swing.JTextField textfieldRunToolPassword; private javax.swing.JTextField textfieldRunToolPasswordFile; private javax.swing.JTextField textfieldRunToolProtocol; private javax.swing.JTextField textfieldRunToolURL; private javax.swing.JTextField textfieldRunToolUser; private javax.swing.JTextField textfieldRunToolUserFile; // End of variables declaration//GEN-END:variables }
agpl-3.0
tyatsumi/hareka
swingclient/src/main/java/org/kareha/hareka/swingclient/gui/RegionsFrame.java
11027
package org.kareha.hareka.swingclient.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.ResourceBundle; import java.util.function.Supplier; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.WindowConstants; import org.kareha.hareka.client.Session; import org.kareha.hareka.client.field.FieldEntity; import org.kareha.hareka.client.packet.RequestRegionListPacket; import org.kareha.hareka.client.packet.SetRegionListPacket; import org.kareha.hareka.field.OneUniformTilePattern; import org.kareha.hareka.field.Placement; import org.kareha.hareka.field.Region; import org.kareha.hareka.field.SimpleRegion; import org.kareha.hareka.field.SolidTilePattern; import org.kareha.hareka.field.Tile; import org.kareha.hareka.field.TilePattern; import org.kareha.hareka.field.TilePatternType; import org.kareha.hareka.field.Vector; import org.kareha.hareka.swingclient.Strap; @SuppressWarnings("serial") public class RegionsFrame extends JInternalFrame { private static final int FRAME_WIDTH = 768; private static final int FRAME_HEIGHT = 384; private enum BundleKey { Title, NotConnected, Center, CurrentPosition, Size, Mutable, Type, Load, New, Delete, Save, LoadFirst, } private final JList<Region> list; private boolean regionsLoaded; public RegionsFrame(final Strap strap) { super("", true, true, true, true); setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); final ResourceBundle bundle = ResourceBundle.getBundle(RegionsFrame.class.getName()); setTitle(bundle.getString(BundleKey.Title.name())); final JPanel northPanel = new JPanel(); northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.Y_AXIS)); final JPanel positionPanel = new JPanel(); positionPanel.add(new JLabel(bundle.getString(BundleKey.Center.name()))); positionPanel.add(new JLabel("X")); final JTextField xField = new JTextField("0", 6); positionPanel.add(xField); positionPanel.add(new JLabel("Y")); final JTextField yField = new JTextField("0", 6); positionPanel.add(yField); final Runnable currentPositionRunnable = () -> { final Session session = strap.getSession(); if (session == null) { return; } final FieldEntity entity = session.getMirrors().getSelfMirror().getFieldEntity(); if (entity == null) { return; } final Placement placement = entity.getPlacement(); xField.setText(Integer.toString(placement.getPosition().x())); yField.setText(Integer.toString(placement.getPosition().y())); }; currentPositionRunnable.run(); final JButton currentPositionButton = new JButton(bundle.getString(BundleKey.CurrentPosition.name())); currentPositionButton.addActionListener(e -> currentPositionRunnable.run()); positionPanel.add(currentPositionButton); northPanel.add(positionPanel); final JPanel sizePanel = new JPanel(); sizePanel.add(new JLabel(bundle.getString(BundleKey.Size.name()))); final JTextField sizeField = new JTextField("4", 6); sizePanel.add(sizeField); northPanel.add(sizePanel); final JPanel mutablePanel = new JPanel(); mutablePanel.add(new JLabel(bundle.getString(BundleKey.Mutable.name()))); final JCheckBox mutableCheckBox = new JCheckBox(); mutablePanel.add(mutableCheckBox); northPanel.add(mutablePanel); final JPanel typePanel = new JPanel(); typePanel.add(new JLabel(bundle.getString(BundleKey.Type.name()))); final JComboBox<TilePatternType> typeComboBox = new JComboBox<>(TilePatternType.values()); typePanel.add(typeComboBox); final JPanel tilePanel = new JPanel(); tilePanel.setLayout(new BoxLayout(tilePanel, BoxLayout.Y_AXIS)); final JPanel tilePanelA = new JPanel(); final TileSelector tileSelectorA = new TileSelector(strap); tilePanelA.add(tileSelectorA); final JTextField elevationFieldA = new JTextField("0", 6); tilePanelA.add(elevationFieldA); tilePanel.add(tilePanelA); final JPanel tilePanelB = new JPanel(); final TileSelector tileSelectorB = new TileSelector(strap); tilePanelB.add(tileSelectorB); final JTextField elevationFieldB = new JTextField("0", 6); tilePanelB.add(elevationFieldB); tilePanel.add(tilePanelB); final JPanel tilePanelC = new JPanel(); final TileSelector tileSelectorC = new TileSelector(strap); tilePanelC.add(tileSelectorC); final JTextField elevationFieldC = new JTextField("0", 6); tilePanelC.add(elevationFieldC); tilePanel.add(tilePanelC); tilePanelB.setVisible(false); tilePanelC.setVisible(false); typeComboBox.addActionListener(e -> { switch (typeComboBox.getItemAt(typeComboBox.getSelectedIndex())) { case SOLID: tilePanelA.setVisible(true); tilePanelB.setVisible(false); tilePanelC.setVisible(false); break; case ONE_UNIFORM: tilePanelA.setVisible(true); tilePanelB.setVisible(true); tilePanelC.setVisible(true); break; } }); final JPanel centerPanel = new JPanel(); centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS)); centerPanel.add(northPanel); centerPanel.add(typePanel); centerPanel.add(tilePanel); list = new JList<>(new DefaultListModel<Region>()); list.addListSelectionListener(e -> { final int index = e.getFirstIndex(); if (index == -1) { return; } final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); if (index >= model.getSize()) { return; } final Region region = model.getElementAt(index); if (!(region instanceof SimpleRegion)) { return; } final SimpleRegion r = (SimpleRegion) region; xField.setText(Integer.toString(r.getCenter().x())); yField.setText(Integer.toString(r.getCenter().y())); sizeField.setText(Integer.toString(r.getSize())); mutableCheckBox.setSelected(r.isMutable()); final TilePattern tilePattern = r.getTilePattern(); if (tilePattern instanceof SolidTilePattern) { typeComboBox.setSelectedItem(TilePatternType.SOLID); final SolidTilePattern tp = (SolidTilePattern) tilePattern; tileSelectorA.setTile(tp.getValue().type()); } else if (tilePattern instanceof OneUniformTilePattern) { final OneUniformTilePattern tp = (OneUniformTilePattern) tilePattern; tileSelectorA.setTile(tp.getA().type()); tileSelectorB.setTile(tp.getB().type()); tileSelectorC.setTile(tp.getC().type()); } else { return; } }); final JScrollPane scrollPane = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setPreferredSize(new Dimension(256, 384)); final Supplier<TilePattern> tilePatternSupplier = () -> { final TilePatternType type = typeComboBox.getItemAt(typeComboBox.getSelectedIndex()); final int elevationA; final int elevationB; final int elevationC; try { elevationA = Integer.parseInt(elevationFieldA.getText()); elevationB = Integer.parseInt(elevationFieldB.getText()); elevationC = Integer.parseInt(elevationFieldC.getText()); } catch (final NumberFormatException ex) { JOptionPane.showInternalMessageDialog(this, ex.getMessage()); return null; } final Tile tileA = Tile.valueOf(tileSelectorA.getTile(), elevationA); final Tile tileB = Tile.valueOf(tileSelectorB.getTile(), elevationB); final Tile tileC = Tile.valueOf(tileSelectorC.getTile(), elevationC); switch (type) { default: return null; case SOLID: return new SolidTilePattern(tileA); case ONE_UNIFORM: return new OneUniformTilePattern(tileA, tileB, tileC); } }; final JPanel buttonPanel = new JPanel(); final JButton loadButton = new JButton(bundle.getString(BundleKey.Load.name())); loadButton.addActionListener(e -> { final Session session = strap.getSession(); if (session == null) { return; } session.write(new RequestRegionListPacket()); }); buttonPanel.add(loadButton); final JButton newButton = new JButton(bundle.getString(BundleKey.New.name())); newButton.addActionListener(e -> { final Vector center; final int size; try { center = Vector.valueOf(Integer.parseInt(xField.getText()), Integer.parseInt(yField.getText())); size = Integer.parseInt(sizeField.getText()); } catch (final NumberFormatException ex) { JOptionPane.showInternalMessageDialog(this, ex.getMessage()); return; } final Boolean mutable = mutableCheckBox.isSelected(); final TilePattern tilePattern = tilePatternSupplier.get(); if (tilePattern == null) { return; } final Region region = new SimpleRegion(tilePattern, mutable, center, size); final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); final int index; if (list.getSelectedIndex() == -1) { index = model.size(); } else { index = list.getSelectedIndex(); } model.add(index, region); }); buttonPanel.add(newButton); final JButton deleteButton = new JButton(bundle.getString(BundleKey.Delete.name())); deleteButton.addActionListener(e -> { final int index = list.getSelectedIndex(); if (index == -1) { return; } final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); model.remove(index); }); buttonPanel.add(deleteButton); final JButton saveButton = new JButton(bundle.getString(BundleKey.Save.name())); saveButton.addActionListener(e -> { if (!regionsLoaded) { JOptionPane.showInternalMessageDialog(this, bundle.getString(BundleKey.LoadFirst.name())); return; } final List<Region> regions = new ArrayList<>(); final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); for (final Enumeration<Region> en = model.elements(); en.hasMoreElements();) { regions.add(en.nextElement()); } final Session session = strap.getSession(); if (session == null) { return; } session.write(new SetRegionListPacket(regions)); }); buttonPanel.add(saveButton); add(centerPanel, BorderLayout.CENTER); add(scrollPane, BorderLayout.WEST); add(buttonPanel, BorderLayout.SOUTH); setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT)); pack(); } public void clearRegions() { final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); model.clear(); regionsLoaded = false; } public void setRegions(final Collection<Region> regions) { final DefaultListModel<Region> model = (DefaultListModel<Region>) list.getModel(); model.clear(); for (final Region region : regions) { model.addElement(region); } if (model.getSize() > 0) { list.setSelectedIndex(0); } regionsLoaded = true; } }
agpl-3.0
mezuro/scalability_tests
scalability_tests/src/main/java/org/mezuro/scalability_tests/REST/repositoryEndpoint/Update.java
1666
package org.mezuro.scalability_tests.REST.repositoryEndpoint; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import org.mezuro.scalability_tests.strategy.RESTStrategy; public class Update extends RESTStrategy { private String repositoryId; @Override public void beforeExperiment() throws Exception { HashMap<String, HashMap<String, String>> parameters = new HashMap<String, HashMap<String, String>>(); HashMap<String, String> repository = new HashMap<String, String>(); parameters.put("repository", repository); repository.put("address", "svn://svn.code.sf.net/p/qt-calculator/code/trunk"); repository.put("name", "name"); repository.put("scm_type", "SVN"); repository.put("kalibro_configuration_id", "1"); JSONObject jsonBody = new JSONObject(parameters); HttpResponse<JsonNode> response = post(buildUrl(REPOSITORY_PATH), jsonBody); repositoryId = ((JSONObject) (response.getBody().getObject().get("repository"))).get("id").toString(); } @Override public String request(String string) throws Exception { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("description", "updating description"); JSONObject jsonBody = new JSONObject(parameters); put(buildUrl(REPOSITORY_PATH + "/" + repositoryId), jsonBody); return repositoryId; } @Override public void afterExperiment() throws Exception { delete(buildUrl(REPOSITORY_PATH + "/" + repositoryId)); } @Override public void configure(Map<Object, Object> options) { configure(options, "kalibro_processor"); } }
agpl-3.0
cxxly/cstack
cu-core/src/main/java/cn/org/once/cstack/model/ErrorMessage.java
1246
package cn.org.once.cstack.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.fasterxml.jackson.annotation.JsonFormat; @Entity public class ErrorMessage implements Serializable { private static final long serialVersionUID = 1L; public final static Integer CHECKED_MESSAGE = 0; public final static Integer UNCHECKED_MESSAGE = 1; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "YYYY-MM-dd HH:mm") private Date date; private String message; private Integer status; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
agpl-3.0
danicadamljanovic/freya
freya/freya-annotate/src/main/java/org/freya/model/ResultGraph.java
1363
package org.freya.model; /** * @author danica */ import java.util.ArrayList; import java.util.List; public class ResultGraph { List data = new ArrayList(); String type; Integer id; private Boolean mainSubject; public Boolean isMainSubject() { return mainSubject; } public void setMainSubject(boolean mainSubject) { this.mainSubject = mainSubject; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List getAdjacencies() { return adjacencies; } public void setAdjacencies(List adjacencies) { this.adjacencies = adjacencies; } List adjacencies = new ArrayList(); public String getType() { return type; } public void setType(String type) { this.type = type; } public List getData() { return data; } public void setData(List data) { this.data = data; } String URI; public String getURI() { return URI; } public void setURI(String uri) { URI = uri; } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer result = new StringBuffer("URI:").append(this.URI).append( " ID:").append(this.id).append( " ADJACENCIES:" + this.getAdjacencies()).append("TYPE:") .append(this.getType()).append("\n"); return result.toString(); } }
agpl-3.0
MiguelSMendoza/Kunagi
WEB-INF/classes/scrum/server/sprint/SprintDao.java
2903
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.server.sprint; import ilarkesto.base.Str; import ilarkesto.base.Utl; import ilarkesto.core.scope.In; import ilarkesto.core.time.Date; import ilarkesto.fp.Predicate; import java.util.Arrays; import scrum.server.project.Project; import scrum.server.project.Requirement; import scrum.server.project.RequirementDao; public class SprintDao extends GSprintDao { @In private RequirementDao requirementDao; @In private TaskDao taskDao; public Sprint getSprintByNumber(final int number, final Project project) { return getEntity(new Predicate<Sprint>() { @Override public boolean test(Sprint sprint) { return sprint.isNumber(number) && sprint.isProject(project); } }); } @Override public Sprint newEntityInstance() { Sprint sprint = super.newEntityInstance(); sprint.setLabel("New Sprint"); return sprint; } // --- test data --- public Sprint createTestSprint(Project project) { Date begin = Date.beforeDays(15); Date end = Date.inDays(15); Sprint sprint = newEntityInstance(); sprint.setProject(project); sprint.setLabel("Our first Sprint!"); sprint.setBegin(begin); sprint.setEnd(end); if (end.isPast()) sprint.setVelocity(20f); saveEntity(sprint); project.setCurrentSprint(sprint); return sprint; } public void createTestHistorySprint(Project project, Date begin, Date end) { Sprint sprint = newEntityInstance(); sprint.setProject(project); sprint.setLabel(Str.generateRandomSentence()); sprint.setBegin(begin); sprint.setEnd(end); for (int i = 0; i < Utl.randomInt(2, 10); i++) { Requirement requirement = requirementDao.postRequirement(project, Str.generateRandomSentence(), Utl.randomElement(Arrays.asList(scrum.client.project.Requirement.WORK_ESTIMATION_FLOAT_VALUES))); requirement.setSprint(sprint); for (int j = 0; j < Utl.randomInt(2, 5); j++) { Task task = taskDao.postTask(requirement, Str.generateRandomSentence(), 0); task.setBurnedWork(Utl.randomInt(2, 10)); } if (i == 0) { taskDao.postTask(requirement, "Incomplete task", 1); } else { requirement.setClosed(true); } } sprint.close(); saveEntity(sprint); } }
agpl-3.0
haiqu/bitsquare
core/src/main/java/io/bitsquare/filter/PaymentAccountFilter.java
1090
package io.bitsquare.filter; import io.bitsquare.app.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; public class PaymentAccountFilter implements Serializable { // That object is sent over the wire, so we need to take care of version compatibility. private static final long serialVersionUID = Version.P2P_NETWORK_VERSION; private static final Logger log = LoggerFactory.getLogger(PaymentAccountFilter.class); public final String paymentMethodId; public final String getMethodName; public final String value; public PaymentAccountFilter(String paymentMethodId, String getMethodName, String value) { this.paymentMethodId = paymentMethodId; this.getMethodName = getMethodName; this.value = value; } @Override public String toString() { return "PaymentAccountFilter{" + "paymentMethodId='" + paymentMethodId + '\'' + ", getMethodName='" + getMethodName + '\'' + ", value='" + value + '\'' + '}'; } }
agpl-3.0
CecileBONIN/Silverpeas-Core
war-core/src/main/java/com/stratelia/silverpeas/silverStatisticsPeas/control/SilverStatisticsPeasDAOVolumeServer.java
4007
/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.silverpeas.silverStatisticsPeas.control; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.silverpeas.silverstatistics.volume.DirectoryVolumeService; import org.silverpeas.util.UnitUtil; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.DBUtil; import com.stratelia.webactiv.util.JNDINames; import org.silverpeas.util.memory.MemoryUnit; /** * Class declaration Get stat size directory data from database * <p/> * @author */ public class SilverStatisticsPeasDAOVolumeServer { public static final int INDICE_DATE = 0; public static final int INDICE_LIB = 1; public static final int INDICE_SIZE = 2; private static final String DB_NAME = JNDINames.SILVERSTATISTICS_DATASOURCE; private static final String selectQuery = " SELECT dateStat, fileDir, sizeDir FROM SB_Stat_SizeDirCumul ORDER BY dateStat"; /** * donne les stats global pour l'ensemble de tous les users cad 2 infos, la collection contient * donc un seul element * * @return * @throws SQLException * @see */ public static Collection<String[]> getStatsVolumeServer() throws SQLException { SilverTrace.debug("silverStatisticsPeas", "SilverStatisticsPeasDAOVolumeServer.getStatsVolumeServer", "selectQuery=" + selectQuery); Statement stmt = null; ResultSet rs = null; Connection myCon = null; try { myCon = DBUtil.makeConnection(DB_NAME); stmt = myCon.createStatement(); rs = stmt.executeQuery(selectQuery); return getStatsVolumeServerFromResultSet(rs); } finally { DBUtil.close(rs, stmt); DBUtil.close(myCon); } } /** * Method declaration * * @param rs * @return * @throws SQLException * @see */ private static Collection<String[]> getStatsVolumeServerFromResultSet(ResultSet rs) throws SQLException { List<String[]> myList = new ArrayList<String[]>(); while (rs.next()) { String[] stat = new String[3]; stat[INDICE_DATE] = rs.getString(1); stat[INDICE_LIB] = rs.getString(2); stat[INDICE_SIZE] = String.valueOf(UnitUtil.convertTo(rs.getLong(3), MemoryUnit.B, MemoryUnit.KB)); myList.add(stat); } return myList; } public static Map<String, String[]> getStatsSizeVentil(String currentUserId) throws Exception { DirectoryVolumeService service = new DirectoryVolumeService(); return service.getSizeVentilation(currentUserId); } public static Map<String, String[]> getStatsVentil(String currentUserId) throws Exception { DirectoryVolumeService service = new DirectoryVolumeService(); return service.getFileNumberVentilation(currentUserId); } }
agpl-3.0
uniteddiversity/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/mail/service/impl/ExtMailServiceImpl.java
1864
/** * This file is part of mycollab-services. * * mycollab-services 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. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.mail.service.impl; import com.esofthead.mycollab.configuration.EmailConfiguration; import com.esofthead.mycollab.configuration.SiteConfiguration; import com.esofthead.mycollab.module.mail.DefaultMailer; import com.esofthead.mycollab.module.mail.IMailer; import com.esofthead.mycollab.module.mail.NullMailer; import com.esofthead.mycollab.module.mail.service.ExtMailService; import org.springframework.stereotype.Service; /** * * @author MyCollab Ltd. * @since 1.0 */ @Service public class ExtMailServiceImpl extends AbstractMailService implements ExtMailService { @Override public boolean isMailSetupValid() { EmailConfiguration emailConfiguration = SiteConfiguration .getEmailConfiguration(); return !(emailConfiguration.getHost().equals("")); } @Override protected IMailer getMailer() { EmailConfiguration emailConfiguration = SiteConfiguration .getEmailConfiguration(); if (!isMailSetupValid()) { return new NullMailer(); } return new DefaultMailer(emailConfiguration); } }
agpl-3.0
PureSolTechnologies/parsers
parsers/src/main/java/com/puresoltechnologies/parsers/lexer/LexerFactoryException.java
245
package com.puresoltechnologies.parsers.lexer; public class LexerFactoryException extends Exception { private static final long serialVersionUID = 7336224347224196732L; public LexerFactoryException(String message) { super(message); } }
agpl-3.0
nathanialf/RIT
app/src/main/java/com/example/nate/survey/demo4.java
3560
package com.example.nate.survey; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link demo4.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link demo4#newInstance} factory method to * create an instance of this fragment. */ public class demo4 extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public demo4() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment demo4. */ // TODO: Rename and change types and number of parameters public static demo4 newInstance(String param1, String param2) { demo4 fragment = new demo4(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_demo4, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
agpl-3.0
opensourceBIM/bimql
BimQL/src/nl/wietmazairac/bimql/get/attribute/GetAttributeSubIfcNormalisedRatioMeasure.java
1633
package nl.wietmazairac.bimql.get.attribute; /****************************************************************************** * Copyright (C) 2009-2017 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import java.util.ArrayList; public class GetAttributeSubIfcNormalisedRatioMeasure { // fields private Object object; private String string; // constructors public GetAttributeSubIfcNormalisedRatioMeasure(Object object, String string) { this.object = object; this.string = string; } // methods public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getString() { return string; } public void setString(String string) { this.string = string; } public ArrayList<Object> getResult() { ArrayList<Object> resultList = new ArrayList<Object>(); return resultList; } }
agpl-3.0
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/action/layertree/LayerLabeledModalAction.java
1430
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.gwt.client.action.layertree; import org.geomajas.gwt.client.i18n.I18nProvider; import org.geomajas.gwt.client.map.layer.Layer; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.util.WidgetLayout; /** * Action that switches the labels on a layer. * * @author Frank Wynants * @author Pieter De Graef */ public class LayerLabeledModalAction extends LayerTreeModalAction { public LayerLabeledModalAction() { super(WidgetLayout.iconLabelsShow, WidgetLayout.iconLabelsHide, WidgetLayout.iconLabelsDisabled, I18nProvider.getLayerTree().labelHideAction(), I18nProvider.getLayerTree().labelAction()); } public boolean isEnabled(Layer<?> layer) { return (layer != null && layer instanceof VectorLayer); } public boolean isSelected(Layer<?> layer) { return layer != null && layer.isLabeled(); } public void onDeselect(Layer<?> layer) { layer.setLabeled(false); } public void onSelect(Layer<?> layer) { layer.setLabeled(true); } }
agpl-3.0
BrunoEberhard/open-ech
src/main/model/ch/ech/ech0011/MaritalStatus.java
191
package ch.ech.ech0011; import javax.annotation.Generated; @Generated(value="org.minimalj.metamodel.generator.ClassGenerator") public enum MaritalStatus { _1, _2, _3, _4, _5, _6, _7, _9; }
agpl-3.0
WASP-System/central
wasp-core/src/main/java/edu/yu/einstein/wasp/dao/impl/ResourceBarcodeDaoImpl.java
2403
/** * * ResourceBarcodeDaoImpl.java * @author echeng (table2type.pl) * * the ResourceBarcode Dao Impl * * **/ package edu.yu.einstein.wasp.dao.impl; import java.util.HashMap; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import edu.yu.einstein.wasp.model.ResourceBarcode; @Transactional("entityManager") @Repository public class ResourceBarcodeDaoImpl extends WaspDaoImpl<ResourceBarcode> implements edu.yu.einstein.wasp.dao.ResourceBarcodeDao { /** * ResourceBarcodeDaoImpl() Constructor * * */ public ResourceBarcodeDaoImpl() { super(); this.entityClass = ResourceBarcode.class; } /** * getResourceBarcodeByResourceBarcodeId(final Integer resourceBarcodeId) * * @param final Integer resourceBarcodeId * * @return resourceBarcode */ @Override @Transactional("entityManager") public ResourceBarcode getResourceBarcodeByResourceBarcodeId (final Integer resourceBarcodeId) { HashMap<String, Integer> m = new HashMap<String, Integer>(); m.put("id", resourceBarcodeId); List<ResourceBarcode> results = this.findByMap(m); if (results.size() == 0) { ResourceBarcode rt = new ResourceBarcode(); return rt; } return results.get(0); } /** * getResourceBarcodeByResourceId(final Integer resourceId) * * @param final Integer resourceId * * @return resourceBarcode */ @Override @Transactional("entityManager") public ResourceBarcode getResourceBarcodeByResourceId (final Integer resourceId) { HashMap<String, Integer> m = new HashMap<String, Integer>(); m.put("resourceId", resourceId); List<ResourceBarcode> results = this.findByMap(m); if (results.size() == 0) { ResourceBarcode rt = new ResourceBarcode(); return rt; } return results.get(0); } /** * getResourceBarcodeByBarcodeId(final Integer barcodeId) * * @param final Integer barcodeId * * @return resourceBarcode */ @Override @Transactional("entityManager") public ResourceBarcode getResourceBarcodeByBarcodeId (final Integer barcodeId) { HashMap<String, Integer> m = new HashMap<String, Integer>(); m.put("barcodeId", barcodeId); List<ResourceBarcode> results = this.findByMap(m); if (results.size() == 0) { ResourceBarcode rt = new ResourceBarcode(); return rt; } return results.get(0); } }
agpl-3.0
dan-passaro/logviewfx
src/main/java/sample/ColumnSaver.java
1448
package sample; import com.google.gson.Gson; import com.google.gson.JsonObject; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.control.TableColumn; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; /** * Saves column list to a preference backend. */ class ColumnSaver implements Runnable { private final ObservableList<TableColumn<JsonObject, ?>> columns; private final Consumer<String> setPrefs; private final Gson gson = new Gson(); ColumnSaver(ObservableList<TableColumn<JsonObject, ?>> columns, Consumer<String> setPrefs) { this.columns = columns; this.setPrefs = setPrefs; columns.addListener( (ListChangeListener<? super TableColumn<JsonObject, ?>>) evt -> saveColumns()); } @Override public void run() { saveColumns(); } void saveColumns() { List<SavedColumn> savedCols = columns.stream() .map(col -> { SavedColumn savedCol = new SavedColumn(); savedCol.setName(col.getText()); savedCol.setVisible(col.isVisible()); return savedCol; }) .collect(Collectors.toList()); String serialized = gson.toJson(savedCols); setPrefs.accept(serialized); } }
agpl-3.0
ging/isabel
components/gateway/GWSIP/mjsip_1.6/src/org/zoolu/sip/header/ViaHeader.java
6507
/* * Copyright (C) 2005 Luca Veltri - University of Parma - Italy * * This file is part of MjSip (http://www.mjsip.org) * * MjSip is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MjSip 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 * Affero GNU General Public License for more details. * * You should have received a copy of the Affero GNU General Public License * along with MjSip; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Luca Veltri (luca.veltri@unipr.it) */ package org.zoolu.sip.header; import org.zoolu.sip.address.SipURL; import org.zoolu.sip.provider.SipParser; /** SIP Header Via. * The Via header field indicates the transport used for the transaction * and identifies the location where the response is to be sent. * <BR> When the UAC creates a request, it MUST insert a Via into that * request. The protocol name and protocol version in the header field * is SIP and 2.0, respectively. * <BR> The Via header field value MUST * contain a branch parameter. This parameter is used to identify the * transaction created by that request. This parameter is used by both * the client and the server. * <BR> The branch parameter value MUST be unique across space and time for * all requests sent by the UA. The exceptions to this rule are CANCEL * and ACK for non-2xx responses. A CANCEL request * will have the same value of the branch parameter as the request it * cancels. An ACK for a non-2xx * response will also have the same branch ID as the INVITE whose * response it acknowledges. */ public class ViaHeader extends ParametricHeader { protected static final String received_param="received"; protected static final String rport_param="rport"; protected static final String branch_param="branch"; protected static final String maddr_param="maddr"; protected static final String ttl_param="ttl"; //public ViaHeader() //{ super(SipHeaders.Via); //} public ViaHeader(String hvalue) { super(SipHeaders.Via,hvalue); } public ViaHeader(Header hd) { super(hd); } public ViaHeader(String host, int port) { super(SipHeaders.Via,"SIP/2.0/UDP "+host+":"+port); } /*public ViaHeader(String host, int port, String branch) { super(SipHeaders.Via,"SIP/2.0/UDP "+host+":"+port+";branch="+branch); }*/ public ViaHeader(String proto, String host, int port) { super(SipHeaders.Via,"SIP/2.0/"+proto.toUpperCase()+" "+host+":"+port); } /*public ViaHeader(String proto, String host, int port, String branch) { super(SipHeaders.Via,"SIP/2.0/"+proto.toUpperCase()+" "+host+":"+port+";branch="+branch); }*/ /** Gets the transport protocol */ public String getProtocol() { SipParser par=new SipParser(value); return par.goTo('/').skipChar().goTo('/').skipChar().skipWSP().getString(); } /** Gets "sent-by" parameter */ public String getSentBy() { SipParser par=new SipParser(value); par.goTo('/').skipChar().goTo('/').skipString().skipWSP(); if (!par.hasMore()) return null; String sentby=value.substring(par.getPos(),par.indexOfSeparator()); return sentby; } /** Gets host of ViaHeader */ public String getHost() { String sentby=getSentBy(); SipParser par=new SipParser(sentby); par.goTo(':'); if (par.hasMore()) return sentby.substring(0,par.getPos()); else return sentby; } /** Returns boolean value indicating if ViaHeader has port */ public boolean hasPort() { String sentby=getSentBy(); if (sentby.indexOf(":")>0) return true; return false; } /** Gets port of ViaHeader */ public int getPort() { SipParser par=new SipParser(getSentBy()); par.goTo(':'); if (par.hasMore()) return par.skipChar().getInt(); return -1; } /** Makes a SipURL from ViaHeader */ public SipURL getSipURL() { return new SipURL(getHost(),getPort()); } /** Checks if "branch" parameter is present */ public boolean hasBranch() { return hasParameter(branch_param); } /** Gets "branch" parameter */ public String getBranch() { return getParameter(branch_param); } /** Sets "branch" parameter */ public void setBranch(String value) { setParameter(branch_param,value); } /** Checks if "received" parameter is present */ public boolean hasReceived() { return hasParameter(received_param); } /** Gets "received" parameter */ public String getReceived() { return getParameter(received_param); } /** Sets "received" parameter */ public void setReceived(String value) { setParameter(received_param,value); } /** Checks if "rport" parameter is present */ public boolean hasRport() { return hasParameter(rport_param); } /** Gets "rport" parameter */ public int getRport() { String value=getParameter(rport_param); if (value!=null) return Integer.parseInt(value); else return -1; } /** Sets "rport" parameter */ public void setRport() { setParameter(rport_param,null); } /** Sets "rport" parameter */ public void setRport(int port) { if (port<0) setParameter(rport_param,null); else setParameter(rport_param,Integer.toString(port)); } /** Checks if "maddr" parameter is present */ public boolean hasMaddr() { return hasParameter(maddr_param); } /** Gets "maddr" parameter */ public String getMaddr() { return getParameter(maddr_param); } /** Sets "maddr" parameter */ public void setMaddr(String value) { setParameter(maddr_param,value); } /** Checks if "ttl" parameter is present */ public boolean hasTtl() { return hasParameter(ttl_param); } /** Gets "ttl" parameter */ public int getTtl() { String value=getParameter(ttl_param); if (value!=null) return Integer.parseInt(value); else return -1; } /** Sets "ttl" parameter */ public void setTtl(int ttl) { setParameter(ttl_param,Integer.toString(ttl)); } }
agpl-3.0
iris-scrum-1/IRIS
interaction-commands-jdbc/src/test/java/com/temenos/interaction/jdbc/command/TestGETJdbcRecordsCommand.java
4249
package com.temenos.interaction.jdbc.command; /* * #%L * interaction-commands-jdbc * %% * Copyright (C) 2012 - 2013 Temenos Holdings N.V. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.junit.Test; import com.temenos.interaction.authorization.command.util.ODataParser; import com.temenos.interaction.core.MultivaluedMapImpl; import com.temenos.interaction.core.command.InteractionCommand; import com.temenos.interaction.core.command.InteractionCommand.Result; import com.temenos.interaction.core.command.InteractionContext; import com.temenos.interaction.core.entity.Entity; import com.temenos.interaction.core.entity.Metadata; import com.temenos.interaction.core.hypermedia.ResourceState; import com.temenos.interaction.core.resource.CollectionResource; import com.temenos.interaction.core.resource.EntityResource; import com.temenos.interaction.jdbc.producer.JdbcProducer; /** * Test the GETRawCommand class. */ public class TestGETJdbcRecordsCommand extends AbstractJdbcCommandTest { /** * Test constructor */ @Test public void testConstructor() { try { new GETJdbcRecordsCommand(mock(JdbcProducer.class)); } catch (Throwable e) { fail(); } } /* * Test command execution with valid key. */ @Test // Don't warn about the dodgy result type cast. @SuppressWarnings("unchecked") public void testExecute() { // Populate the database. populateTestTable(); // Create a producer JdbcProducer producer = null; try { producer = new JdbcProducer(dataSource); } catch (Exception e) { fail(); } // Create a command based on the producer. GETJdbcRecordsCommand command = null; try { command = new GETJdbcRecordsCommand(producer); } catch (Exception e) { fail(); } // Create an interaction context. MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl<String>(); // Select two columns. queryParams.add(ODataParser.SELECT_KEY, VARCHAR_FIELD_NAME + "," + INTEGER_FIELD_NAME); // Set up the path. MultivaluedMap<String, String> pathParams = new MultivaluedMapImpl<String>(); // Fake up a resource state. ResourceState state = new ResourceState(TEST_TABLE_NAME, "rubbish", null, "rubbish"); InteractionContext ctx = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), pathParams, queryParams, state, mock(Metadata.class)); // Execute the command try { InteractionCommand.Result result = command.execute(ctx); assertEquals(Result.SUCCESS, result); } catch (Exception e) { fail(); } // Check the results. CollectionResource<Entity> resources = (CollectionResource<Entity>) ctx.getResource(); assertFalse(null == resources); int entityCount = 0; for (EntityResource<Entity> resource : resources.getEntities()) { // Should be two results VARCHAR and INTEGER but not KEY. assertEquals(2, resource.getEntity().getProperties().getProperties().size()); // Check property values assertEquals(TEST_VARCHAR_DATA + entityCount, resource.getEntity().getProperties().getProperties().get(VARCHAR_FIELD_NAME).getValue()); assertEquals(TEST_INTEGER_DATA + entityCount, resource.getEntity().getProperties().getProperties().get(INTEGER_FIELD_NAME).getValue()); entityCount++; } // Should be one entity per row assertEquals(TEST_ROW_COUNT, entityCount); } }
agpl-3.0
qcri-social/AIDR
aidr-manager/src/main/java/qa/qcri/aidr/manager/service/TaggerService.java
7829
package qa.qcri.aidr.manager.service; import java.util.List; import java.util.Map; import qa.qcri.aidr.common.wrapper.CollectionBriefInfo; import qa.qcri.aidr.dbmanager.dto.taggerapi.TrainingDataDTO; import qa.qcri.aidr.manager.dto.ImageTaskQueueDTO; import qa.qcri.aidr.manager.dto.ModelHistoryWrapper; import qa.qcri.aidr.manager.dto.TaggerAttribute; import qa.qcri.aidr.manager.dto.TaggerCrisis; import qa.qcri.aidr.manager.dto.TaggerCrisisExist; import qa.qcri.aidr.manager.dto.TaggerCrisisRequest; import qa.qcri.aidr.manager.dto.TaggerCrisisType; import qa.qcri.aidr.manager.dto.TaggerLabel; import qa.qcri.aidr.manager.dto.TaggerLabelRequest; import qa.qcri.aidr.manager.dto.TaggerModel; import qa.qcri.aidr.manager.dto.TaggerModelFamily; import qa.qcri.aidr.manager.dto.TaggerModelNominalLabel; import qa.qcri.aidr.manager.dto.TaggerResponseWrapper; import qa.qcri.aidr.manager.dto.TaggerUser; import qa.qcri.aidr.manager.dto.TaskAnswer; import qa.qcri.aidr.manager.exception.AidrException; import qa.qcri.aidr.manager.persistence.entities.Collection; public interface TaggerService { public List<TaggerCrisisType> getAllCrisisTypes() throws AidrException; public List<TaggerCrisis> getCrisesByUserId(Integer userId) throws AidrException; public String createNewCrises(TaggerCrisisRequest crisis) throws AidrException; public java.util.Collection<TaggerAttribute> getAttributesForCrises(Integer crisisID, Integer userId) throws AidrException; public TaggerCrisisExist isCrisesExist(String code) throws AidrException; public Integer isUserExistsByUsername(String userName) throws AidrException; public Integer addNewUser(TaggerUser taggerUser) throws AidrException; public Integer addAttributeToCrisis(TaggerModelFamily modelFamily) throws AidrException; public TaggerCrisis getCrisesByCode(String code) throws AidrException; public TaggerCrisis updateCode(TaggerCrisis crisis) throws AidrException; public List<TaggerModel> getModelsForCrisis(Integer crisisID) throws AidrException; public List<TaggerModelNominalLabel> getAllLabelsForModel(Integer modelID, String crisisCode) throws AidrException; public TaggerAttribute createNewAttribute(TaggerAttribute attribute) throws AidrException; public TaggerAttribute getAttributeInfo(Integer id) throws AidrException; public TaggerLabel getLabelInfo(Integer id) throws AidrException; public boolean deleteAttribute(Integer id) throws AidrException; public boolean deleteTrainingExample(Integer id) throws AidrException; public boolean removeAttributeFromCrises(Integer modelFamilyID) throws AidrException; public TaggerAttribute updateAttribute(TaggerAttribute attribute) throws AidrException; public TaggerLabel updateLabel(TaggerLabelRequest label) throws AidrException; public TaggerLabel createNewLabel(TaggerLabelRequest label) throws AidrException; public TaggerAttribute attributeExists(String code) throws AidrException; public List<TrainingDataDTO> getTrainingDataByModelIdAndCrisisId(Integer modelFamilyId, Integer crisisId, Integer start, Integer limit, String sortColumn, String sortDirection) throws AidrException; public String getAssignableTask(Integer id, String userName) throws AidrException; public String getTemplateStatus(String code) throws AidrException; public String skipTask(Integer id, String userName) throws AidrException; public boolean saveTaskAnswer(List<TaskAnswer> taskAnswer) throws AidrException; public String loadLatestTweets(String code, String constraints) throws Exception; public ModelHistoryWrapper getModelHistoryByModelFamilyID(Integer start, Integer limit, Integer id, String sortColumn, String sortDirection) throws Exception; public Map<String, Integer> getTaggersForCollections(List<String> collectionCodes) throws Exception; public boolean pingTagger() throws AidrException; public boolean pingTrainer() throws AidrException; public boolean pingAIDROutput() throws AidrException; public boolean pingPersister() throws AidrException; public String getRetainingThreshold() throws AidrException; public String getAttributesAndLabelsByCrisisId(Integer id) throws Exception; //Added by koushik public int trashCollection(Collection collection) throws Exception; //Added by koushik public int untrashCollection(String collectionCode) throws Exception; public String loadLatestTweetsWithCount(String code, int count) throws AidrException; //Added by koushik Map<String, Integer> countCollectionsClassifiers(List<String> collectionCodes) throws AidrException; // Added by koushik public Map<String, Object> generateCSVLink(String code) throws AidrException; // Added by koushik public Map<String, Object> generateTweetIdsLink(String code) throws AidrException; //Added by koushik public Map<String, Object> generateJSONLink(String code, String jsonType) throws AidrException; //Added by koushik public Map<String, Object> generateJsonTweetIdsLink(String code, String jsonType) throws AidrException; //Added by koushik public Map<String, Object> generateJSONFilteredLink(String code, String queryString, String jsonType, String userName, Integer count, boolean removeRetweet) throws AidrException; //Added by koushik public Map<String, Object> generateJsonTweetIdsFilteredLink(String code, String queryString, String jsonType, String userName) throws AidrException; //Added by koushik public Map<String, Object> generateCSVFilteredLink(String code, String queryString, String userName, Integer count, boolean removeRetweet) throws AidrException; //Added by koushik public Map<String, Object> generateTweetIdsFilteredLink(String code, String queryString, String userName) throws AidrException; public TaggerResponseWrapper getHumanLabeledDocumentsByCrisisID(Long crisisID, Integer count) throws AidrException; public TaggerResponseWrapper getHumanLabeledDocumentsByCrisisCode(String crisisCode, Integer count) throws AidrException; public TaggerResponseWrapper getHumanLabeledDocumentsByCrisisIDUserID(Long crisisID, Long userID, Integer count) throws AidrException; public TaggerResponseWrapper getHumanLabeledDocumentsByCrisisIDUserName(Long crisisID, String userName, Integer count) throws AidrException; public Map<String, Object> downloadHumanLabeledDocumentsByCrisisUserName(String queryString, String crisisCode, String userName, Integer count, String fileType, String contentType) throws AidrException; public Map<String, Object> updateMicromapperEnabled(String code, Boolean isMicromapperEnabled) throws AidrException; public Boolean sendMailService(String subject, String body); public Long getLabelCount(Long collectionId); Map<String, Object> generateTweetIdsOnlyFilteredLink(String code, String queryString, String userName, Integer count, Boolean removeRetweet) throws AidrException; Map<String, Object> generateJsonTweetIdsOnlyFilteredLink(String code, String queryString, String jsonType, String userName, Integer exportLimit, Boolean removeRetweet) throws AidrException; Map<String, Object> generateFacebookPostDownloadLink(String code,Integer count) throws AidrException; List<CollectionBriefInfo> fetchCollectionsByAttribute(Long attributeId, Long sourceCollectionId); public String importTrainingData(Long targetCollectionId, String sourceCollectionCode, Long attributeId); public Long getImageCountForCollection(String collectionCode); public Long getTaggedImageCount(Integer crisisId); public List<ImageTaskQueueDTO> getTaggedImageDataByCrisisId(Integer crisisId, Integer start, Integer limit, String sortColumn, String sortDirection) throws AidrException; }
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/gui/attributeeditor/actions/GuessAllTypesAction.java
1585
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.attributeeditor.actions; import com.rapidminer.gui.attributeeditor.AttributeEditor; import com.rapidminer.gui.tools.ResourceAction; import java.awt.event.ActionEvent; /** * Start the corresponding action. * * @author Ingo Mierswa */ public class GuessAllTypesAction extends ResourceAction { private static final long serialVersionUID = -4550774167417692191L; private final AttributeEditor attributeEditor; public GuessAllTypesAction(AttributeEditor attributeEditor) { super("attribute_editor.guess_all_value_types"); this.attributeEditor = attributeEditor; } @Override public void actionPerformed(ActionEvent e) { this.attributeEditor.guessAllColumnTypes(); } }
agpl-3.0
GrowthcraftCE/Growthcraft-1.11
src/main/java/growthcraft/cellar/network/AbstractPacket.java
1302
package growthcraft.cellar.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import net.minecraft.entity.player.EntityPlayer; public abstract class AbstractPacket { /** * Encode the packet data into the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils}) * * @param ctx channel context * @param buffer the buffer to encode into */ public abstract void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer); /** * Decode the packet data from the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils}) * * @param ctx channel context * @param buffer the buffer to decode from */ public abstract void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer); /** * Handle a packet on the client side. Note this occurs after decoding has completed. * * @param player the player reference */ public abstract void handleClientSide(EntityPlayer player); /** * Handle a packet on the server side. Note this occurs after decoding has completed. * * @param player the player reference */ public abstract void handleServerSide(EntityPlayer player); }
agpl-3.0
Taalmonsters/WhiteLab2.0-Importer
src/main/java/nl/whitelab/dataimport/util/ProgressMonitor.java
3744
package nl.whitelab.dataimport.util; import java.util.Iterator; import nl.whitelab.dataimport.neo4j.LinkCreator; import nl.whitelab.dataimport.neo4j.NodeCreator; public final class ProgressMonitor { private long startTime = -1; private long lastReport = -1; private boolean running = false; private long reportInterval = 600000; private long dataProcessed = 0; private long docsProcessed = 0; private long tokensProcessed = 0; private static boolean permitLogging = true; public ProgressMonitor() { } public ProgressMonitor(int i) { reportInterval = i * 60000; } public void start() { running = true; startTime = System.currentTimeMillis(); } public void stop() { running = false; report(); } public boolean isRunning() { return running; } public void update(long fileSize, int documentCount, int tokenCount) { dataProcessed = dataProcessed + fileSize; docsProcessed = docsProcessed + documentCount; tokensProcessed = tokensProcessed + tokenCount; report(); } public void update(long fileSize, int documentCount, long tokenCount) { dataProcessed = dataProcessed + fileSize; docsProcessed = docsProcessed + documentCount; tokensProcessed = tokensProcessed + tokenCount; report(); } public void report() { long current = System.currentTimeMillis(); if (!running || (current - lastReport >= reportInterval)) { long elapsed = current - startTime; if (elapsed > 0) { String timestamp = HumanReadableFormatter.humanReadableTimeElapsed(elapsed); String data = HumanReadableFormatter.humanReadableByteCount(dataProcessed, true); float secs = (float) (elapsed / 1000.0); float x = dataProcessed / secs; String dataPerSecond = HumanReadableFormatter.humanReadableByteCount(x, false); String docsPerSecond = String.format("%.1f", docsProcessed / secs); String tokensPerSecond = String.format("%.1f", tokensProcessed / secs); System.out.println(timestamp+" - Processed "+tokensProcessed+" tokens ("+tokensPerSecond+" t/s), "+docsProcessed+" documents ("+docsPerSecond+" d/s), "+data+" ("+dataPerSecond+"/s)"); lastReport = current; } } } public void log(String msg) { if (permitLogging) { long elapsed = System.currentTimeMillis() - startTime; String timestamp = HumanReadableFormatter.humanReadableTimeElapsed(elapsed); System.out.println(timestamp + " - " + msg); } } public void endReport(NodeCreator nc, LinkCreator lc) { long current = System.currentTimeMillis(); long elapsed = current - startTime; String timestamp = HumanReadableFormatter.humanReadableTimeElapsed(elapsed); String data = HumanReadableFormatter.humanReadableByteCount(dataProcessed, true); float secs = elapsed / 1000; String dataPerSecond = HumanReadableFormatter.humanReadableByteCount(dataProcessed / secs, false); String docsPerSecond = String.format("%.1f", docsProcessed / secs); String tokensPerSecond = String.format("%.1f", tokensProcessed / secs); System.out.println(timestamp+" - Processed "+tokensProcessed+" tokens ("+tokensPerSecond+" t/s), "+docsProcessed+" documents ("+docsPerSecond+" d/s), "+data+" ("+dataPerSecond+"/s)"); Iterator<String> labels = nc.getCountKeys(); System.out.println(timestamp+" - Added "+nc.getNodeCount()+" nodes:"); while (labels.hasNext()) { String label = labels.next(); System.out.println(timestamp+" -\t"+label.toString()+": "+nc.getNodeCount(label)); } Iterator<String> links = lc.getCountKeys(); System.out.println(""); System.out.println(timestamp+" - Added "+lc.getLinkCount()+" links:"); while (links.hasNext()) { String label = links.next(); System.out.println(timestamp+" -\t"+label.toString()+": "+lc.getLinkCount(label)); } } }
agpl-3.0
SynthesisProject/server
moodle-master/moodle-client/src/main/java/coza/opencollab/synthesis/moodle/client/ResourcesService.java
1574
package coza.opencollab.synthesis.moodle.client; import java.util.Collection; import java.util.Date; import coza.opencollab.synthesis.moodle.client.dao.file.MoodleFile; /** * * @author OpenCollab */ public interface ResourcesService { /** * Get all resource tool data for a module (Sakai site) given the sessionId, * siteId and the fromDate. If the fromDate is null all resource tool data * will be returned * * @param defaultFormat default format * @param sessionId session id * @param siteId site id * @param fromDate filter items changed after this date * @return resources string */ public String getResourcesForSite(String defaultFormat, String sessionId, int siteId, Date fromDate); /** * Retrieves MoodleFiles from Moodle * * @param token Authentication token * @param component component * @param filearea file area * @param instanceId instance id * @param itemId item id * @return resources string */ public Collection<MoodleFile> retrieveMoodleFiles(String token, String component, String filearea, int instanceId, int itemId); public abstract byte[] downloadResource(String urlString, String sessionId); /** * Given the raw URL for the resource, add the session information in the * required format * * @param urlString base URL String * @param sessionId the session id * @return String resource URL with session id */ public String getDownloadResourceUrl(String urlString, String sessionId); }
agpl-3.0
myteer/bitsquare
gui/src/main/java/io/bitsquare/gui/main/account/content/seedwords/SeedWordsViewModel.java
1557
/* * This file is part of Bitsquare. * * Bitsquare is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bitsquare is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. */ package io.bitsquare.gui.main.account.content.seedwords; import io.bitsquare.btc.WalletService; import io.bitsquare.gui.common.model.ViewModel; import io.bitsquare.gui.util.BSFormatter; import com.google.inject.Inject; import java.util.List; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; class SeedWordsViewModel implements ViewModel { final StringProperty seedWords = new SimpleStringProperty(); @Inject public SeedWordsViewModel(WalletService walletService, BSFormatter formatter) { if (walletService.getWallet() != null) { List<String> mnemonicCode = walletService.getWallet().getKeyChainSeed().getMnemonicCode(); if (mnemonicCode != null) { seedWords.set(formatter.mnemonicCodeToString(mnemonicCode)); } } } }
agpl-3.0
publishing-systems/automated_digital_publishing
html2epub/html2epub2/ZipProcessor.java
5176
/* Copyright (C) 2014 Stephan Kreutzer * * This file is part of html2epub2. * * html2epub2 is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 or any later version, * as published by the Free Software Foundation. * * html2epub2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License 3 for more details. * * You should have received a copy of the GNU Affero General Public License 3 * along with html2epub2. If not, see <http://www.gnu.org/licenses/>. */ /** * @file $/ZipProcessor.java * @brief Processor to pack (zip) the EPUB2 file. * @author Stephan Kreutzer * @since 2014-01-05 */ import java.util.ArrayList; import java.io.File; import java.util.zip.ZipOutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.zip.Checksum; import java.util.zip.CRC32; import java.util.zip.ZipEntry; class ZipProcessor { public ZipProcessor() { } public void Run(ArrayList<File> packageFiles, File outDirectory) { try { FileOutputStream outStream = new FileOutputStream(outDirectory.getAbsolutePath() + File.separator + "out.epub"); ZipOutputStream zipStream = new ZipOutputStream(outStream); { File mimetypeFile = new File(outDirectory.getAbsolutePath() + File.separator + "mimetype"); FileInputStream inStream = new FileInputStream(mimetypeFile); String mimetype = new String("application/epub+zip"); long mimetypeFileSize = mimetypeFile.length(); if (mimetypeFileSize != new String(mimetype).length()) { System.out.print("html2epub2: '" + mimetypeFile.getAbsolutePath() + "' has an invalid file size of " + mimetypeFileSize + ", expected is " + mimetype.length() + ".\n"); System.exit(-64); } if (mimetypeFileSize > 1024) { System.out.print("html2epub2: Buffer size for mimetype file of " + mimetypeFileSize + " won't be sufficient.\n"); System.exit(-65); } byte[] buffer = new byte[1024]; int length = 0; if ((length = inStream.read(buffer)) > 0) { Checksum checksum = new CRC32(); // Calculate CRC32 checksum. checksum.update(buffer, 0, length); long crcChecksum = checksum.getValue(); ZipEntry zipEntry = new ZipEntry("mimetype"); zipEntry.setMethod(ZipEntry.STORED); zipEntry.setSize(length); zipEntry.setCompressedSize(length); zipEntry.setCrc(crcChecksum); zipStream.putNextEntry(zipEntry); zipStream.write(buffer, 0, length); inStream.close(); zipStream.closeEntry(); } else { System.out.print("html2epub2: Problem with reading the mimetype file '" + mimetypeFile.getAbsolutePath() + "'.\n"); System.exit(-66); } } /** * @todo This could be outsourced if the ZipProcessor would provide * support for a package list consisting of source/destination. */ this.AddFile(zipStream, "META-INF/container.xml", new File(outDirectory.getAbsolutePath() + File.separator + "META-INF" + File.separator + "container.xml")); for (int packageFile = 0; packageFile < packageFiles.size(); packageFile++) { File currentPackageFile = packageFiles.get(packageFile); this.AddFile(zipStream, "OPS/" + currentPackageFile.getName(), currentPackageFile); } zipStream.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(-67); } } private void AddFile(ZipOutputStream zipStream, String entryName, File file) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); zipStream.putNextEntry(zipEntry); FileInputStream inStream = new FileInputStream(file.getAbsolutePath()); byte[] buffer = new byte[1024]; int length = 0; while ((length = inStream.read(buffer)) > 0) { zipStream.write(buffer, 0, length); } inStream.close(); zipStream.closeEntry(); } }
agpl-3.0
sappho/code-heatmap
ui/src/main/java/uk/org/sappho/codeheatmap/ui/web/server/guice/FileUploadServletModule.java
372
package uk.org.sappho.codeheatmap.ui.web.server.guice; import uk.org.sappho.codeheatmap.ui.web.server.service.fileupload.FileUploadHandler; import com.google.inject.servlet.ServletModule; public class FileUploadServletModule extends ServletModule { @Override protected void configureServlets() { serve("*.gupld").with(FileUploadHandler.class); } }
agpl-3.0
StratusNetwork/ProjectAres
PGM/src/main/java/tc/oc/pgm/payload/PayloadMatchModule.java
1506
package tc.oc.pgm.payload; import org.bukkit.event.HandlerList; import tc.oc.pgm.match.Match; import tc.oc.pgm.match.MatchModule; import tc.oc.pgm.match.Repeatable; import tc.oc.time.Time; import javax.inject.Inject; import java.time.Duration; import java.util.List; import static tc.oc.commons.core.stream.Collectors.toImmutableList; public class PayloadMatchModule extends MatchModule { private static final long MILLIS = 100; private static final Duration INTERVAL = Duration.ofMillis(MILLIS); // milliseconds, two ticks private final List<Payload> payloads; private final PayloadAnnouncer announcer; @Inject private PayloadMatchModule(Match match) { this.announcer = new PayloadAnnouncer(match); this.payloads = match.featureDefinitions() .all(PayloadDefinition.class) .map(cp -> cp.getGoal(match)) .collect(toImmutableList()); } @Override public void load() { super.load(); getMatch().registerEvents(this.announcer); } @Override public void unload() { for(Payload payload : this.payloads) { payload.unregisterEvents(); } HandlerList.unregisterAll(this.announcer); super.unload(); } @Repeatable(interval = @Time(milliseconds = MILLIS)) public void tick() { for(Payload payload : payloads) { payload.tick(INTERVAL); } } }
agpl-3.0
cnery/cnery
src/main/java/com/daveoxley/cnery/actions/SceneActionConditionHome.java
4215
/** * C-Nery - A home automation web application for C-Bus. * Copyright (C) 2008,2009,2012 Dave Oxley <dave@daveoxley.co.uk>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.daveoxley.cnery.actions; import com.daveoxley.cnery.entities.AbstractCondition; import com.daveoxley.cnery.entities.SceneAction; import com.daveoxley.cnery.entities.SceneActionCondition; import com.daveoxley.seam.CNeryEntityHome; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.core.Events; /** * * @author Dave Oxley <dave@daveoxley.co.uk> */ @Name("sceneActionConditionHome") @Scope(ScopeType.CONVERSATION) public class SceneActionConditionHome extends CNeryEntityHome<SceneActionCondition> { @In private Events events; @In(required=false) private SceneAction selectedSceneAction; @In(required=false) private SceneActionCondition selectedParentSceneActionCondition; @In(required=false) private SceneActionCondition selectedSceneActionCondition; @Override public void create() { super.create(); clearInstance(); if (selectedSceneActionCondition != null) setId(selectedSceneActionCondition.getId()); } @Override protected SceneActionCondition createInstance() { SceneActionCondition sac = super.createInstance(); sac.setParent(selectedParentSceneActionCondition); sac.setSceneAction(selectedSceneAction); sac.setActionType(AbstractCondition.ActionType.TIME); return sac; } @Factory("sceneActionCondition") public SceneActionCondition getSceneActionCondition() { return getInstance(); } @Override protected void clearFactoryInstance() { create(); if (Contexts.isConversationContextActive()) Contexts.getConversationContext().remove("sceneActionCondition"); } private void clearFields() { SceneActionCondition sac = getInstance(); if (!sac.getActionType().equals(AbstractCondition.ActionType.TIME)) { sac.setTimeAfterBefore(null); sac.setTimeMinutes(0); sac.setTimePlusMinus(null); sac.setTimeWhen(null); } if (!sac.getActionType().equals(AbstractCondition.ActionType.GROUP)) sac.setDependGroup(null); if (!sac.getActionType().equals(AbstractCondition.ActionType.SCENE)) sac.setDependScene(null); if (!sac.getActionType().equals(AbstractCondition.ActionType.GROUP) && !sac.getActionType().equals(AbstractCondition.ActionType.SCENE)) sac.setSceneGroupOnOff(null); if (!sac.getActionType().equals(AbstractCondition.ActionType.LOGIC)) sac.setLogic(null); } @Override public String update() { clearFields(); return super.update(); } @Override public String persist() { clearFields(); return super.persist(); } public String persistLogic() { SceneActionCondition sac = getInstance(); sac.setActionType(AbstractCondition.ActionType.LOGIC); return persist(); } @Override public String remove() { String res = super.remove(); if (res != null && res.equals("removed")) events.raiseTransactionSuccessEvent("clearSceneActionConditionSelection"); return res; } }
agpl-3.0
akvo/akvo-flow
GAE/src/com/gallatinsystems/common/util/DateUtil.java
2363
/* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package com.gallatinsystems.common.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Collection of methods for date manipulation * * @author Christopher Fagiani */ public class DateUtil { /** * Returns a new date that is the same as the one passed in except it has a time of 00:00:00 * * @param oldDate * @return */ public static Date getDateNoTime(Date oldDate) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(oldDate); // drop the time portion cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * returns the year as a Long */ public static Long getYear(Date dt) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(dt); return new Long(cal.get(Calendar.YEAR)); } /** * takes a string containing a 4 digit year and returns a Date object that has the year * indicated and all other fields set to 0 (so jan 1 of that year at 00:00:00) * * @param year * @return * @throws NumberFormatException */ public static Date getYearOnlyDate(String year) throws NumberFormatException { Calendar cal = new GregorianCalendar(); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.MONTH, 0); cal.set(Calendar.YEAR, new Integer(year)); // sets the time portion to 00:00:00 and returns return getDateNoTime(cal.getTime()); } }
agpl-3.0
o2oa/o2oa
o2server/x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/userinfo/exception/ExceptionUserInfoWrapOut.java
394
package com.x.bbs.assemble.control.jaxrs.userinfo.exception; import com.x.base.core.project.exception.PromptException; public class ExceptionUserInfoWrapOut extends PromptException { private static final long serialVersionUID = 1859164370743532895L; public ExceptionUserInfoWrapOut( Throwable e ) { super("将查询结果转换为可以输出的数据信息时发生异常.", e ); } }
agpl-3.0
scionaltera/emergentmud
src/test/java/com/emergentmud/core/command/SubCommandTest.java
2006
/* * EmergentMUD - A modern MUD with a procedurally generated world. * Copyright (C) 2016-2017 Peter Keeler * * This file is part of EmergentMUD. * * EmergentMUD is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EmergentMUD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.emergentmud.core.command; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class SubCommandTest { private List<Parameter> parameters = new ArrayList<>(); private SubCommand subCommand; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); for (int i = 0; i < 3; i++) { Parameter parameter = mock(Parameter.class); when(parameter.getName()).thenReturn("parameter" + i); when(parameter.isRequired()).thenReturn(true); parameters.add(parameter); } subCommand = new SubCommand("test", "Tests things.", parameters); } @Test public void testGetters() throws Exception { assertEquals("test", subCommand.getName()); assertEquals("Tests things.", subCommand.getDescription()); subCommand.getParameters().forEach(p -> { assertTrue(p.getName().startsWith("parameter")); assertTrue(p.isRequired()); }); } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
war-core/src/main/java/com/silverpeas/importExportPeas/control/ExportXMLThread.java
2880
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.importExportPeas.control; import java.util.List; import com.silverpeas.importExport.control.ImportExport; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.WAAttributeValuePair; public class ExportXMLThread extends ExportThread { private final List<WAAttributeValuePair> pksToExport; private final String language; private final String rootId; private final int mode; public ExportXMLThread(ImportExportSessionController toAwake, List<WAAttributeValuePair> pks, String language, String rootId, int mode) { super(toAwake); pksToExport = pks; this.language = language; this.rootId = rootId; this.mode = mode; } @Override public void run() { SilverTrace.info("importExportPeas", "ExportXMLThread.run", "root.MSG_GEN_PARAM_VALUE", "------------DEBUT DU THREAD D'EXPORT-----------"); try { ImportExport importExport = new ImportExport(); m_ExportReport = importExport.processExport(super.m_toAwake.getUserDetail(), language, pksToExport, rootId, mode); SilverTrace.info("importExportPeas", "ExportXMLThread.run", "root.MSG_GEN_PARAM_VALUE", "------------TOUT EST OK-----------"); m_isEncours = false; m_toAwake.threadFinished(); SilverTrace.info("importExportPeas", "ExportXMLThread.run", "root.MSG_GEN_PARAM_VALUE", "------------AFTER NOTIFY-----------"); } catch (Exception e) { m_ErrorOccured = e; m_isEncours = false; m_toAwake.threadFinished(); SilverTrace.info("importExportPeas", "ExportXMLThread.run", "root.MSG_GEN_PARAM_VALUE", "------------ERREUR-----------", e); } } }
agpl-3.0
automenta/narchy
nar/src/main/java/nars/derive/Deriver.java
3742
package nars.derive; import jcog.Util; import jcog.func.TriFunction; import jcog.signal.meter.FastCounter; import nars.Emotion; import nars.NAR; import nars.Task; import nars.attention.What; import nars.control.How; import nars.control.Why; import nars.derive.premise.DeriverRules; import nars.derive.premise.PremiseDeriverCompiler; import nars.derive.premise.PremiseDeriverRuleSet; import nars.derive.premise.PremiseRuleProto; import nars.derive.timing.NonEternalTaskOccurenceOrPresentDeriverTiming; import nars.term.Term; import java.util.Set; import java.util.function.BooleanSupplier; import java.util.stream.Stream; /** * an individual deriver process: executes a particular Deriver model * specified by a set of premise rules. * <p> * runtime intensity is metered and throttled by causal feedback * <p> * this is essentially a Function<Premise, Stream<DerivedTask>> but * the current level of code complexity makes this non-obvious */ abstract public class Deriver extends How { public final DeriverRules rules; /** * determines the temporal focus of (TODO tasklink and ) belief resolution to be matched during premise formation * input: premise Task, premise belief target * output: long[2] time interval **/ public TriFunction<What, Task, Term, long[]> timing; protected Deriver(Set<PremiseRuleProto> rules, NAR nar) { this(PremiseDeriverCompiler.the(rules), nar); if (rules.isEmpty()) throw new RuntimeException("rules empty"); } protected Deriver(PremiseDeriverRuleSet rules) { this(rules, rules.nar); } protected Deriver(DeriverRules rules, NAR nar) { super(); this.rules = rules; // this.source = source; this.timing = //new TaskOrPresentTiming(nar); //new AdHocDeriverTiming(nar); //new TaskOccurenceDeriverTiming(); new NonEternalTaskOccurenceOrPresentDeriverTiming(); nar.start(this); } public static Stream<Deriver> derivers(NAR n) { return n.partStream().filter(Deriver.class::isInstance).map(Deriver.class::cast); } @Override public final void next(What w, final BooleanSupplier kontinue) { derive(Derivation.derivation.get().next(this, w), kontinue); } abstract protected void derive(Derivation d, BooleanSupplier kontinue); /** * unifier TTL used for matching in premise formation */ protected int matchTTL() { return nar.premiseUnifyTTL.intValue(); } @Override public boolean singleton() { return false; } @Override public float value() { //TODO cache this between cycles float v = Util.sum(Why::value, rules.causes()); //System.out.println(this + " " + v); return v; } final short[] what(PreDerivation d) { return rules.planner.apply(d); } public final void derive(Premise p, Derivation d, int matchTTL, int deriveTTL) { FastCounter result; Emotion e = d.nar().emotion; if (p.match(d, matchTTL)) { short[] can = d.deriver.what(d); if (can.length > 0) { d.derive( //Util.lerp(Math.max(d.priDouble, d.priSingle), Param.TTL_MIN, deriveTTL) deriveTTL, can ); result = e.premiseFire; } else { result = e.premiseUnderivable; } } else { result = e.premiseUnbudgetable; } result.increment(); } }
agpl-3.0
agibsonccc/startuphousebooking
src/main/java/com/startuphouse/booking/model/listini/Period.java
2514
/******************************************************************************* * * Copyright 2011 - Sardegna Ricerche, Distretto ICT, Pula, Italy * * Licensed under the EUPL, Version 1.1. * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://www.osor.eu/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations under the Licence. * In case of controversy the competent court is the Court of Cagliari (Italy). *******************************************************************************/ package com.startuphouse.booking.model.listini; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang3.time.DateUtils; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class Period implements Serializable{ private Integer id = null; private Date startDate; private Date endDate; private Integer id_season; public Boolean checkDates() { Boolean startDateBeforeEndDate = DateUtils.truncatedCompareTo(this.getEndDate(), this.getStartDate(), Calendar.DAY_OF_MONTH) >= 0; Boolean equalYears = this.getStartYear().equals(this.getEndYear()); Boolean ret = true; if (!startDateBeforeEndDate || !equalYears) { ret = false; } return ret; } public Integer getStartYear() { Calendar calendar = new GregorianCalendar(); calendar.setTime(this.getStartDate()); return calendar.get(Calendar.YEAR); } public Integer getEndYear() { Calendar calendar = new GregorianCalendar(); calendar.setTime(this.getEndDate()); return calendar.get(Calendar.YEAR); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Integer getId_season() { return id_season; } public void setId_season(Integer id_season) { this.id_season = id_season; } }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-core/src/main/java/org/kuali/kfs/integration/ld/LaborBenefitRateCategory.java
1650
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.integration.ld; import org.kuali.rice.krad.bo.ExternalizableBusinessObject; /** * BO for the Labor Benefit Rate Category Fringe Benefit */ public interface LaborBenefitRateCategory extends ExternalizableBusinessObject { /** * Getter method to get the laborBenefitRateCategoryCode * * @return laborBenefitRateCategoryCode */ public String getLaborBenefitRateCategoryCode(); /** * Method to set the code * * @param code */ public void setLaborBenefitRateCategoryCode(String laborBenefitRateCategoryCode); /** * Getter method for the code's description * * @return codeDesc */ public String getCodeDesc(); /** * Sets the codeDesc * * @param codeDesc */ public void setCodeDesc(String codeDesc); }
agpl-3.0
auroreallibe/Silverpeas-Core
core-web/src/main/java/org/silverpeas/core/web/util/viewgenerator/html/HtmlParagraphEncoderTag.java
2025
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.web.util.viewgenerator.html; import org.silverpeas.core.util.WebEncodeHelper; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; /** * Transform a Java String into a HTML paragraph compatible String. */ public class HtmlParagraphEncoderTag extends TagSupport { private static final long serialVersionUID = -7747695403360864218L; private String string; @Override public int doStartTag() throws JspException { try { pageContext.getOut().print(WebEncodeHelper.javaStringToHtmlParagraphe(string)); } catch (IOException ex) { throw new JspException("Silverpeas Java to html paragraph Converter Tag", ex); } return EVAL_PAGE; } public String getString() { return string; } public void setString(String string) { this.string = string; } }
agpl-3.0
automenta/narchy
util/src/main/java/jcog/data/graph/MapNodeGraph.java
6928
package jcog.data.graph; import com.google.common.graph.SuccessorsFunction; import jcog.data.graph.path.FromTo; import jcog.data.list.FasterList; import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; /** * graph rooted in a set of vertices (nodes), * providing access to edges only indirectly through them * (ie. the edges are not stored in their own index but only secondarily as part of the vertices) * <p> * TODO abstract into subclasses: * HashNodeGraph backed by HashMap node and edge containers * BagNodeGraph backed by Bag's/Bagregate's * <p> * then replace TermWidget/EDraw stuff with BagNodeGraph */ public class MapNodeGraph<N, E> extends NodeGraph<N, E> { protected final Map<N, Node<N, E>> nodes; public MapNodeGraph() { this(new LinkedHashMap<>()); } public MapNodeGraph(SuccessorsFunction<N> s, Iterable<N> start) { this(); Collection<N> traversed = new HashSet(); ArrayDeque<N> queue = new ArrayDeque(); start.forEach(queue::add); N x; while ((x = queue.poll()) != null) { MutableNode<N, E> xx = addNode(x); Iterable<? extends N> xs = s.successors(x); //System.out.println(x + " " + xs); xs.forEach(y -> { if (traversed.add(y)) queue.add(y); addEdgeByNode(xx, (E) "->" /* HACK */, addNode(y)); }); } } public MapNodeGraph(Map<N, Node<N, E>> nodes) { this.nodes = nodes; } @Override public void clear() { nodes.clear(); } public boolean removeNode(N key) { Node<N, E> removed = nodes.remove(key); if (removed != null) { removed.edges(true, false).forEach(this::edgeRemoveOut); removed.edges(false, true).forEach(this::edgeRemoveIn); onRemoved(removed); return true; } return false; } public final MutableNode<N, E> addNode(N key) { return addNode(key, true); } private MutableNode<N, E> addNode(N key, boolean returnNodeIfExisted) { final boolean[] created = {false}; MutableNode<N, E> r = (MutableNode<N, E>) nodes.computeIfAbsent(key, (x) -> { created[0] = true; return newNode(x); }); if (created[0]) { onAdd(r); return r; } else { return returnNodeIfExisted ? r : null; } } public final boolean addNewNode(N key) { return addNode(key, false) != null; } @Override protected Node<N, E> newNode(N data) { return new MutableNode<>(data); } protected void onAdd(Node<N, E> r) { } protected void onRemoved(Node<N, E> r) { } /** creates the nodes if they do not exist yet */ public boolean addEdge(N from, E data, N to) { MutableNode<N,E> f = addNode(from); MutableNode<N,E> t = addNode(to); return addEdgeByNode(f, data, t); } public boolean addEdgeIfNodesExist(N from, E data, N to) { Node<N, E> f = node(from); Node<N, E> t = node(to); return addEdgeByNode((MutableNode<N,E>) f, data, (MutableNode<N,E>) t); } public final boolean addEdgeByNode(MutableNode<N, E> from, E data, MutableNode<N, E> to) { return addEdge(from, to, new ImmutableDirectedEdge<>(from, data, to)); } public final boolean addEdge(MutableNode<N, E> from, E data, N to) { return addEdgeByNode(from, data, addNode(to)); } public final boolean addEdge(N from, E data, MutableNode<N,E> to) { return addEdgeByNode(addNode(from), data, to); } public boolean addEdge(FromTo<Node<N, E>, E> ee) { return addEdge((MutableNode<N,E>)(ee.from()), (MutableNode<N,E>)(ee.to()), ee); } static <N,E> boolean addEdge(MutableNode<N, E> from, MutableNode<N, E> to, FromTo<Node<N, E>, E> ee) { if (from.addOut(ee)) { boolean a = to.addIn(ee); assert (a); return true; } return false; } @Override public Node<N, E> node(Object key) { return nodes.get(key); } public Collection<Node<N, E>> nodes() { return nodes.values(); } @Override int nodeCount() { return nodes.size(); } @Override public void forEachNode(Consumer<Node<N, E>> n) { nodes.values().forEach(n); } public boolean edgeRemove(FromTo<Node<N, E>, E> e) { if (edgeRemoveOut(e)) { boolean removed = edgeRemoveIn(e); assert (removed); return true; } return false; } protected boolean edgeRemoveIn(FromTo<Node<N, E>, E> e) { return ((MutableNode) e.to()).removeIn(e); } protected boolean edgeRemoveOut(FromTo<Node<N, E>, E> e) { return ((MutableNode) e.from()).removeOut(e); } public Stream<FromTo<Node<N, E>, E>> edges() { return nodes().stream().flatMap(Node::streamOut); } @Override public String toString() { StringBuilder s = new StringBuilder(); s.append("Nodes: "); for (Node<N, E> n : nodes()) { s.append(n).append('\n'); } s.append("Edges: "); edges().forEach(e -> { s.append(e).append('\n'); }); return s.toString(); } public boolean containsNode(Object x) { return nodes.containsKey(x); } /** * relinks all edges in 'from' to 'to' before removing 'from' */ public boolean mergeNodes(N from, N to) { MutableNode<N, E> fromNode = (MutableNode<N, E>) nodes.get(from); MutableNode<N, E> toNode = (MutableNode<N, E>) nodes.get(to); if (fromNode != null && toNode != null) { if (fromNode != toNode) { int e = fromNode.ins() + fromNode.outs(); if (e > 0) { List<FromTo> removed = new FasterList(e); fromNode.edges(true, false).forEach(inEdge -> { removed.add(inEdge); MutableNode x = (MutableNode) (inEdge.from()); if (x != fromNode) addEdgeByNode(x, inEdge.id(), toNode); }); fromNode.edges(false, true).forEach(outEdge -> { removed.add(outEdge); MutableNode x = (MutableNode) (outEdge.to()); if (x != fromNode) addEdgeByNode(toNode, outEdge.id(), x); }); removed.forEach(this::edgeRemove); //assert (fromNode.ins() == 0 && fromNode.outs() == 0); } } removeNode(from); return true; } return false; } }
agpl-3.0
kagucho/tsubonesystem2
src/main/java/tsuboneSystem/names/TContactNames.java
4438
/* * Copyright (C) 2014-2016 Kagucho <kagucho.net@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tsuboneSystem.names; import javax.annotation.Generated; import org.seasar.extension.jdbc.name.PropertyName; import tsuboneSystem.entity.TContact; /** * {@link TContact}のプロパティ名の集合です。 * */ @Generated(value = {"S2JDBC-Gen 2.4.46", "org.seasar.extension.jdbc.gen.internal.model.NamesModelFactoryImpl"}, date = "2015/03/19 0:46:14") public class TContactNames { /** * idのプロパティ名を返します。 * * @return idのプロパティ名 */ public static PropertyName<Integer> id() { return new PropertyName<Integer>("id"); } /** * nameのプロパティ名を返します。 * * @return nameのプロパティ名 */ public static PropertyName<String> name() { return new PropertyName<String>("name"); } /** * mailのプロパティ名を返します。 * * @return mailのプロパティ名 */ public static PropertyName<String> mail() { return new PropertyName<String>("mail"); } /** * subjectのプロパティ名を返します。 * * @return subjectのプロパティ名 */ public static PropertyName<String> subject() { return new PropertyName<String>("subject"); } /** * messageのプロパティ名を返します。 * * @return messageのプロパティ名 */ public static PropertyName<String> message() { return new PropertyName<String>("message"); } /** * @author S2JDBC-Gen */ public static class _TContactNames extends PropertyName<TContact> { /** * インスタンスを構築します。 */ public _TContactNames() { } /** * インスタンスを構築します。 * * @param name * 名前 */ public _TContactNames(final String name) { super(name); } /** * インスタンスを構築します。 * * @param parent * 親 * @param name * 名前 */ public _TContactNames(final PropertyName<?> parent, final String name) { super(parent, name); } /** * idのプロパティ名を返します。 * * @return idのプロパティ名 */ public PropertyName<Integer> id() { return new PropertyName<Integer>(this, "id"); } /** * nameのプロパティ名を返します。 * * @return nameのプロパティ名 */ public PropertyName<String> name() { return new PropertyName<String>(this, "name"); } /** * mailのプロパティ名を返します。 * * @return mailのプロパティ名 */ public PropertyName<String> mail() { return new PropertyName<String>(this, "mail"); } /** * subjectのプロパティ名を返します。 * * @return subjectのプロパティ名 */ public PropertyName<String> subject() { return new PropertyName<String>(this, "subject"); } /** * messageのプロパティ名を返します。 * * @return messageのプロパティ名 */ public PropertyName<String> message() { return new PropertyName<String>(this, "message"); } } }
agpl-3.0
sozialemedienprojekt/ces-game
target/generated-sources/annotations/de/hub/cses/ces/entity/company/warehouse/Stock_.java
905
package de.hub.cses.ces.entity.company.warehouse; import de.hub.cses.ces.entity.BaseEntity_; import de.hub.cses.ces.entity.company.warehouse.StockTransaction; import de.hub.cses.ces.entity.company.warehouse.Warehouse; import de.hub.cses.ces.entity.product.Product; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2015-07-03T13:05:23") @StaticMetamodel(Stock.class) public class Stock_ extends BaseEntity_ { public static volatile SingularAttribute<Stock, Product> product; public static volatile SingularAttribute<Stock, Double> quantity; public static volatile SingularAttribute<Stock, Warehouse> warehouse; public static volatile SetAttribute<Stock, StockTransaction> transactions; }
agpl-3.0
n01077691/n01077691.github.io
Denis/src/main/java/denis/stepanov/DatePickerFragment.java
1670
/* name: Denis Stepanov student ID: n01077691 assignment #: 2 */ package denis.stepanov; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.widget.DatePicker; import android.widget.TextView; import java.util.Calendar; public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user TextView tv1= (TextView) getActivity().findViewById(R.id.date_number); //one way to show the date String day1 = getString(R.string.day); String month1 = getString(R.string.month); String year1 = getString(R.string.year); String text = (year1 +view.getYear()+ month1 +view.getMonth()+ day1 +view.getDayOfMonth()); //another way String text1 = (view.getDayOfMonth() + "/" + view.getMonth() + "/" + view.getYear()); //first way //tv1.setText(text); //second way tv1.setText(text1); } }
agpl-3.0