repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
klst-com/metasfresh
de.metas.adempiere.adempiere/client/src/main/java/org/compiere/apps/search/FindHelper.java
6372
package org.compiere.apps.search; /* * #%L * de.metas.adempiere.adempiere.client * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.adempiere.db.DBConstants; import org.adempiere.util.Check; import org.compiere.model.MQuery; import org.compiere.model.MQuery.Operator; import org.compiere.util.DB; import de.metas.adempiere.util.Permutation; /** * * @author tsa * */ public final class FindHelper { public static final String COLUMNNAME_Search = "Search"; public static void addStringRestriction(MQuery query, String columnName, String value, String infoName, boolean isIdentifier) { if (COLUMNNAME_Search.equalsIgnoreCase(columnName)) { addStringRestriction_Search(query, columnName, value, infoName, isIdentifier); return; } // // Generic implementation final String valueStr = prepareSearchString(value, false); if (valueStr == null) { query.addRestriction("UPPER(" + columnName + ")", Operator.EQUAL, null, infoName, value); } else if (valueStr.indexOf('%') == -1) { String valueSQL = "UPPER(" + DB.TO_STRING(valueStr) + ")"; query.addRestriction("UPPER(" + columnName + ")", Operator.EQUAL, valueSQL, infoName, value); } else { query.addRestriction(columnName, Operator.LIKE_I, valueStr, infoName, value); } } // metas-2009_0021_AP1_CR064 private static void addStringRestriction_Search(MQuery query, String columnName, String value, String infoName, boolean isIdentifier) { value = value.trim(); // metas: Permutationen ueber alle Search-Kombinationen // z.B. 3 Tokens ergeben 3! Moeglichkeiten als Ergebnis. if (value.contains(" ")) { StringTokenizer st = new StringTokenizer(value, " "); int tokens = st.countTokens(); String input[] = new String[tokens]; Permutation perm = new Permutation(); perm.setMaxIndex(tokens - 1); for (int token = 0; token < tokens; token++) { input[token] = st.nextToken(); } perm.permute(input, tokens - 1); Iterator<String> itr = perm.getResult().iterator(); while (itr.hasNext()) { value = ("%" + itr.next() + "%").replace(" ", "%"); query.addRestriction(COLUMNNAME_Search, Operator.LIKE_I, value, infoName, value, true); } } else { if (!value.startsWith("%")) value = "%" + value; // metas-2009_0021_AP1_CR064: end if (!value.endsWith("%")) value += "%"; query.addRestriction(COLUMNNAME_Search, Operator.LIKE_I, value, infoName, value); } } /** * When dealing with String comparison ("LIKE") use this method instead of simply building the String. * * This method provides reliability when it comes to comparison behavior * * E.G. when searching for "123" it shall match "%123%" and when searching for "123%" it shall match exactly that and NOT "%123%". * * In other words, the user receives exactly what he asks for * * @param columnSQL * @param value * @param isIdentifier * @param params * @return */ public static String buildStringRestriction(String columnSQL, Object value, boolean isIdentifier, List<Object> params) { return buildStringRestriction(null, columnSQL, value, isIdentifier, params); } /** * apply function to parameter cg: task: 02381 * * @param criteriaFunction * @param columnSQL * @param value * @param isIdentifier * @param params * @return */ public static String buildStringRestriction(String criteriaFunction, String columnSQL, Object value, boolean isIdentifier, List<Object> params) { final String valueStr = prepareSearchString(value, isIdentifier); String whereClause = null; if (Check.isEmpty(criteriaFunction, true)) { whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE" + " UPPER(" + DBConstants.FUNC_unaccent_string("?") + ")"; } else { whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE " + "UPPER(" + DBConstants.FUNC_unaccent_string(criteriaFunction.replaceFirst(columnSQL, "?")) + ")"; } params.add(valueStr); return whereClause; } public static String buildStringRestriction(String columnSQL, int displayType, Object value, Object valueTo, boolean isRange, List<Object> params) { StringBuffer where = new StringBuffer(); if (isRange) { if (value != null || valueTo != null) where.append(" ("); if (value != null) { where.append(columnSQL).append(">?"); params.add(value); } if (valueTo != null) { if (value != null) where.append(" AND "); where.append(columnSQL).append("<?"); params.add(valueTo); } if (value != null || valueTo != null) where.append(") "); } else { where.append(columnSQL).append("=?"); params.add(value); } return where.toString(); } public static String prepareSearchString(Object value) { return prepareSearchString(value, false); } public static String prepareSearchString(Object value, boolean isIdentifier) { if (value == null || value.toString().length() == 0) { return null; } String valueStr; if (isIdentifier) { // metas-2009_0021_AP1_CR064: begin valueStr = ((String)value).trim(); if (!valueStr.startsWith("%")) valueStr = "%" + value; // metas-2009_0021_AP1_CR064: end if (!valueStr.endsWith("%")) valueStr += "%"; } else { valueStr = (String)value; if (valueStr.startsWith("%")) { ; // nothing } else if (valueStr.endsWith("%")) { ; // nothing } else if (valueStr.indexOf("%") < 0) { valueStr = "%" + valueStr + "%"; } else { ; // nothing } } return valueStr; } }
gpl-2.0
HackLightly/TelePongAndroid
src/com/hacklightly/TableTennisAndroid/LaunchActivity.java
3806
package com.hacklightly.TableTennisAndroid; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class LaunchActivity extends Activity implements View.OnClickListener{ public static Typeface FONT; // In onCreate method /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { this.requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView title = (TextView)findViewById(R.id.title), finePrint = (TextView)findViewById(R.id.finePrint), info = (TextView)findViewById(R.id.info); Button scan = (Button)findViewById(R.id.qr_button), about = (Button)findViewById(R.id.about_button); FONT = Typeface.createFromAsset(getAssets(), "fonts/Nunito-Light.ttf"); title.setTypeface(FONT); about.setTypeface(FONT); scan.setTypeface(FONT); finePrint.setTypeface(FONT); info.setTypeface(FONT); scan.setOnClickListener(this); about.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.qr_button) { new Handler().postDelayed(new Runnable() { @Override public void run() { try { Intent i = new Intent ("la.droid.qr.scan"); LaunchActivity.this.startActivityForResult(i, 0); //Apply splash exit (fade out) and main entry (fade in) animation transitions. overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout); } catch (Exception e) { Log.d ("myapp", "QR Droid not installed!"); final String appPackageName = "la.droid.qr"; try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName))); } } } }, 300); } else { //about new Handler().postDelayed(new Runnable() { @Override public void run() { //Create an intent that will start the main activity. Intent i = new Intent(LaunchActivity.this, AboutActivity.class); LaunchActivity.this.startActivity(i); //Apply splash exit (fade out) and main entry (fade in) animation transitions. overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout); } }, 300); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { try { String result = data.getExtras().getString("la.droid.qr.result"); Log.d("myapp", "pass to session: " + result); Intent i = new Intent (LaunchActivity.this, SessionActivity.class); i.putExtra("id", result); LaunchActivity.this.startActivity(i); } catch (NullPointerException e) { Log.d ("myapp", "QR Droid farted"); } } }
gpl-2.0
lexml/lexml-toolkit
lexml-toolkit-common/src/main/java/br/gov/lexml/util/hibernate/SimpleHqlBuilder.java
1973
package br.gov.lexml.util.hibernate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SimpleHqlBuilder { private final String selectClause; private final List<String> whereOperators = new ArrayList<String>(); private final List<String> whereClauses = new ArrayList<String>(); private final List<Object> paramValues = new ArrayList<Object>(); private String orderByClause; public SimpleHqlBuilder(final String selectClause) { this.selectClause = selectClause; } public void orderBy(final String orderByClause) { this.orderByClause = orderByClause; } public SimpleHqlBuilder and(final String whereClause, final Object... paramValues) { return addWhereClause(" and ", whereClause, paramValues); } public SimpleHqlBuilder or(final String whereClause, final Object... paramValues) { return addWhereClause(" or ", whereClause, paramValues); } private SimpleHqlBuilder addWhereClause(final String whereOperator, final String whereClause, final Object... paramValues) { whereClauses.add(whereClause); whereOperators.add(whereOperator); this.paramValues.addAll(Arrays.asList(paramValues)); return this; } public String getHql() { StringBuilder where = new StringBuilder(); if(!whereClauses.isEmpty()) { boolean first = true; int size = whereClauses.size(); for(int i = 0; i < size; i++) { if(first) { where.append(" where "); first = false; } else { where.append(whereOperators.get(i)); } where.append(whereClauses.get(i)); } } return toJpqlStyle(selectClause + where + (orderByClause != null? " order by " + orderByClause: "")); } private static String toJpqlStyle(String query) { StringBuilder sb = new StringBuilder(query); int j = -1, count = 1; while((j = sb.indexOf("?", j + 1)) != -1) { sb.insert(j + 1, count++); } return sb.toString(); } public Object[] getParams() { return paramValues.toArray(); } }
gpl-2.0
anonymous100001/maxuse
src/main/org/tzi/use/analysis/coverage/CoverageCalculationVisitor.java
4705
/* * USE - UML based specification environment * Copyright (C) 1999-2010 Mark Richters, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // $Id$ package org.tzi.use.analysis.coverage; import org.tzi.use.uml.mm.MAssociation; import org.tzi.use.uml.mm.MAssociationEnd; import org.tzi.use.uml.mm.MAttribute; import org.tzi.use.uml.mm.MClass; import org.tzi.use.uml.mm.MNavigableElement; import org.tzi.use.uml.mm.MOperation; import org.tzi.use.uml.ocl.expr.ExpConstUnlimitedNatural; /** * This coverage visitor counts for each covered element * the number of occurrences. * <p>This visitor can be used to check how often an element is used.</p> * <p>Covered elements: * <ul> * <li>Classes</li> * <li>Associations</li> * <li>Association ends</li> * <li>Attributes</li> * </ul> * @author Lars Hamann */ public class CoverageCalculationVisitor extends AbstractCoverageVisitor { private final CoverageData coverageData = new CoverageData(); public CoverageCalculationVisitor(boolean expandOperations) { super(expandOperations); } /** * @param cls */ @Override protected void addClassCoverage(MClass cls) { if (!coverageData.getClassCoverage().containsKey(cls)) { coverageData.getClassCoverage().put(cls, 1); } else { coverageData.getClassCoverage().put(cls, coverageData.getClassCoverage().get(cls) + 1); } addCompleteClassCoverage(cls); } /** * @param cls */ protected void addCompleteClassCoverage(MClass cls) { if (!coverageData.getCompleteClassCoverage().containsKey(cls)) { coverageData.getCompleteClassCoverage().put(cls, 1); } else { coverageData.getCompleteClassCoverage().put(cls, coverageData.getCompleteClassCoverage().get(cls) + 1); } } /** * @param sourceType */ @Override protected void addAttributeCoverage(MClass sourceClass, MAttribute att) { AttributeAccessInfo info = new AttributeAccessInfo(sourceClass, att); if (!coverageData.getAttributeAccessCoverage().containsKey(info)) { coverageData.getAttributeAccessCoverage().put(info, 1); } else { coverageData.getAttributeAccessCoverage().put(info, coverageData.getAttributeAccessCoverage().get(info) + 1); } if (!coverageData.getAttributeCoverage().containsKey(att)) { coverageData.getAttributeCoverage().put(att, 1); } else { coverageData.getAttributeCoverage().put(att, coverageData.getAttributeCoverage().get(att) + 1); } addCompleteClassCoverage(sourceClass); } /** * @param sourceType */ @Override protected void addOperationCoverage(MClass sourceClass, MOperation op) { if (!coverageData.getOperationCoverage().containsKey(op)) { coverageData.getOperationCoverage().put(op, 1); } else { coverageData.getOperationCoverage().put(op, coverageData.getOperationCoverage().get(op) + 1); } addCompleteClassCoverage(sourceClass); } /** * @param sourceType */ @Override protected void addAssociationCoverage(MAssociation assoc) { if (!coverageData.getAssociationCoverage().containsKey(assoc)) { coverageData.getAssociationCoverage().put(assoc, 1); } else { coverageData.getAssociationCoverage().put(assoc, coverageData.getAssociationCoverage().get(assoc) + 1); } } /** * @param sourceType */ @Override protected void addAssociationEndCoverage(MNavigableElement dst) { //FIXME: How to handle association class? if (!(dst instanceof MAssociationEnd)) return; MAssociationEnd end = (MAssociationEnd)dst; if (!coverageData.getAssociationEndCoverage().containsKey(end)) { coverageData.getAssociationEndCoverage().put(end, 1); } else { coverageData.getAssociationEndCoverage().put(end, coverageData.getAssociationEndCoverage().get(end) + 1); } addCompleteClassCoverage(end.cls()); } /** * Returns the collected information about the coverage * @return The collected coverage data */ public CoverageData getCoverageData() { return coverageData; } @Override public void visitConstUnlimitedNatural( ExpConstUnlimitedNatural expressionConstUnlimitedNatural) { } }
gpl-2.0
donatellosantoro/freESBee
freesbeeWeb/src/it/unibas/icar/freesbee/controllo/ControlloGestionePorteApplicative.java
16806
package it.unibas.icar.freesbee.controllo; import it.unibas.icar.freesbee.modello.Azione; import it.unibas.icar.freesbee.modello.PortaApplicativa; import it.unibas.icar.freesbee.modello.Servizio; import it.unibas.icar.freesbee.modello.ServizioApplicativo; import it.unibas.icar.freesbee.modello.Utente; import it.unibas.icar.freesbee.persistenza.DAOException; import it.unibas.icar.freesbee.persistenza.IDAOAzione; import it.unibas.icar.freesbee.persistenza.IDAOConfigurazione; import it.unibas.icar.freesbee.persistenza.IDAOPortaApplicativa; import it.unibas.icar.freesbee.persistenza.IDAOServizio; import it.unibas.icar.freesbee.persistenza.IDAOServizioApplicativo; import it.unibas.icar.freesbee.vista.VistaGestionePorteApplicative; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.faces.event.ActionEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ControlloGestionePorteApplicative { private Log logger = LogFactory.getLog(this.getClass()); private VistaGestionePorteApplicative vista; private IDAOPortaApplicativa daoPortaApplicativa; private IDAOServizio daoServizio; private IDAOServizioApplicativo daoServizioApplicativo; private IDAOConfigurazione daoConfigurazione; private IDAOAzione daoAzione; private String messaggio; private String errore; private String conferma; private Utente utente; public String gestionePorteApplicative() { this.gestioneInserisciPortaApplicativa(new PortaApplicativa()); this.caricaTuttePorteApplicative(); this.vista.getNuovoPortaApplicativa().setServizio(new Servizio()); this.vista.getNuovoPortaApplicativa().setAzione(new Azione()); this.vista.getNuovoPortaApplicativa().setServizioApplicativo(new ServizioApplicativo()); try { this.vista.setNicaPresente(daoConfigurazione.find(utente).isInviaANICA()); } catch (DAOException ex) { logger.error("Impossibile leggere la configurazione " + ex); } return "gestionePorteApplicative"; } public String gestioneInserisciPortaApplicativa(PortaApplicativa nuovaPortaApplicativa) { this.vista.setInserisci(true); this.vista.setModifica(false); this.vista.setElimina(false); this.vista.setNuovoPortaApplicativa(nuovaPortaApplicativa); return null; } public String gestioneModificaPortaApplicativa(PortaApplicativa portaApplicativaDaModificare) { this.vista.setInserisci(false); this.vista.setModifica(true); this.vista.setElimina(false); this.vista.setNuovoPortaApplicativa(portaApplicativaDaModificare); return null; } public String gestioneEliminaPortaApplicativa(PortaApplicativa portaApplicativaDaEliminare) { this.vista.setInserisci(false); this.vista.setModifica(false); this.vista.setElimina(true); this.vista.setNuovoPortaApplicativa(portaApplicativaDaEliminare); return null; } public void caricaTuttePorteApplicative() { try { List<PortaApplicativa> listaPorteApplicative = daoPortaApplicativa.findAll(this.utente); List<Servizio> listaServizi = daoServizio.findAll(this.utente); List<ServizioApplicativo> listaServiziApplicativi = getDaoServizioApplicativo().findAll(this.utente); // List<Azione> listaAzioni = daoAzione.findAll(this.utente); List<Azione> listaAzioni = new ArrayList<Azione>(); Collections.sort(listaPorteApplicative); Collections.sort(listaServizi); Collections.sort(listaServiziApplicativi); Collections.sort(listaAzioni); if (listaPorteApplicative.size() == 0) { this.setMessaggio("Non ho trovato alcuna porta applicativa."); } this.vista.setListaPorteApplicative(listaPorteApplicative); this.vista.setListaServizi(listaServizi); this.vista.setListaServiziApplicativi(listaServiziApplicativi); this.vista.setListaAzioni(listaAzioni); } catch (DAOException ex) { logger.error("Impossibile leggere l'elenco delle porte applicative dalla base di dati. " + ex); this.setErrore("Impossibile leggere l'elenco delle porte applicative dalla base di dati. Controllare che freESBee sia avviato"); } } public String inserisci() { try { PortaApplicativa nuovaPortaApplicativa = this.vista.getNuovoPortaApplicativa(); PortaApplicativa portaApplicativaEsistente = daoPortaApplicativa.findByNome(this.utente, nuovaPortaApplicativa.getNome()); if (portaApplicativaEsistente != null) { this.setErrore("Impossibile aggiungere la porta applicativa. Esiste gia' una porta applicativa con il nome specificato"); return null; } long idAzione = 0; if (nuovaPortaApplicativa.getAzione() != null) { idAzione = nuovaPortaApplicativa.getAzione().getId(); } if (idAzione <= 0) { nuovaPortaApplicativa.setAzione(null); } else { Azione azione = daoAzione.findById(this.utente, idAzione, false); if (azione == null) { this.setErrore("Impossibile aggiungere la porta applicativa. Non esiste l'azione specificata"); return null; } nuovaPortaApplicativa.setAzione(azione); } long idServizio = nuovaPortaApplicativa.getServizio().getId(); if (idServizio <= 0) { nuovaPortaApplicativa.setServizio(null); PortaApplicativa portaApplicativaConServizio = daoPortaApplicativa.findByServizio(this.utente, nuovaPortaApplicativa.getStringaTipoServizio(), nuovaPortaApplicativa.getStringaServizio(), nuovaPortaApplicativa.getStringaTipoErogatore(), nuovaPortaApplicativa.getStringaErogatore(), nuovaPortaApplicativa.getStringaAzione()); if (portaApplicativaConServizio != null) { this.setErrore("Impossibile aggiungere la porta applicativa. Il servizio specificato e' gia' associato ad un'altra porta applicativa"); return null; } } else { Servizio servizio = daoServizio.findById(this.utente, idServizio, false); if (servizio == null) { this.setErrore("Impossibile aggiungere la porta applicativa. Non esiste il servizio specificato"); return null; } PortaApplicativa portaApplicativaConServizio = daoPortaApplicativa.findByServizio(this.utente, servizio, nuovaPortaApplicativa.getAzione()); if (portaApplicativaConServizio != null) { this.setErrore("Impossibile aggiungere la porta applicativa. Il servizio specificato e' gia' associato ad un'altra porta applicativa"); return null; } nuovaPortaApplicativa.setServizio(servizio); } long idServizioApplicativo = nuovaPortaApplicativa.getServizioApplicativo().getId(); if (idServizioApplicativo <= 0) { nuovaPortaApplicativa.setServizioApplicativo(null); } else { ServizioApplicativo servizioApplicativo = daoServizioApplicativo.findById(this.utente, idServizioApplicativo, false); if (servizioApplicativo == null) { this.setErrore("Impossibile aggiungere la porta applicativa. Non esiste il servizio applicativo specificato"); return null; } nuovaPortaApplicativa.setServizioApplicativo(servizioApplicativo); } daoPortaApplicativa.makePersistent(this.utente, nuovaPortaApplicativa); this.setMessaggio("Porta Applicativa inserita correttamente."); this.gestionePorteApplicative(); } catch (DAOException ex) { logger.error("Impossibile inserire la porta applicativa. " + ex); String erroreFormattato = ex.getMessage().substring(ex.getMessage().indexOf(":") + 1); this.setErrore(erroreFormattato); } return null; } public String modifica() { try { PortaApplicativa portaApplicativaDaModificare = this.vista.getNuovoPortaApplicativa(); long idServizio = 0; if (portaApplicativaDaModificare.getServizio() != null) { idServizio = portaApplicativaDaModificare.getServizio().getId(); } if (idServizio <= 0) { portaApplicativaDaModificare.setServizio(null); PortaApplicativa portaApplicativaConServizio = daoPortaApplicativa.findByServizio(this.utente, portaApplicativaDaModificare.getStringaTipoServizio(), portaApplicativaDaModificare.getStringaServizio(), portaApplicativaDaModificare.getStringaTipoErogatore(), portaApplicativaDaModificare.getStringaErogatore(), portaApplicativaDaModificare.getStringaAzione()); if (portaApplicativaConServizio != null && (portaApplicativaConServizio.getId().compareTo(portaApplicativaDaModificare.getId())) != 0) { this.setErrore("Impossibile aggiungere la porta applicativa. Il servizio specificato e' gia' associato ad un'altra porta applicativa"); return null; } } else { Servizio servizio = daoServizio.findById(this.utente, idServizio, false); if (servizio == null) { this.setErrore("Impossibile aggiungere la porta applicativa. Non esiste il servizio specificato"); return null; } long idAzione = portaApplicativaDaModificare.getAzione().getId(); Azione azione; if (idAzione <= 0) { azione = null; } else { azione = daoAzione.findById(this.utente, idAzione, false); if (azione == null) { this.setErrore("Impossibile aggiungere la porta applicativa. Non esiste l'azione specificata"); return null; } } portaApplicativaDaModificare.setAzione(azione); PortaApplicativa portaApplicativaConServizio = daoPortaApplicativa.findByServizio(this.utente, servizio, azione); if (portaApplicativaConServizio != null && (portaApplicativaConServizio.getId().compareTo(portaApplicativaDaModificare.getId())) != 0) { this.setErrore("Impossibile aggiungere la porta applicativa. Il servizio specificato e' gia' associato ad un'altra porta applicativa"); return null; } portaApplicativaDaModificare.setServizio(servizio); } daoPortaApplicativa.makePersistent(this.utente, portaApplicativaDaModificare); this.setMessaggio("Porta Applicativa modificata correttamente"); gestionePorteApplicative(); } catch (DAOException ex) { logger.error("Impossibile modificare la Porta Applicativa. " + ex); String erroreFormattato = ex.getMessage().substring(ex.getMessage().indexOf(":") + 1); this.setErrore(erroreFormattato); } return null; } public String elimina() { try { PortaApplicativa portaApplicativaDaEliminare = this.vista.getNuovoPortaApplicativa(); daoPortaApplicativa.makeTransient(this.utente, portaApplicativaDaEliminare); this.setMessaggio("Porta Applicativa eliminata correttamente."); gestionePorteApplicative(); } catch (DAOException ex) { logger.error("Impossibile eliminare la Porta Applicativa. " + ex); String erroreFormattato = ex.getMessage().substring(ex.getMessage().indexOf(":") + 1); this.setErrore(erroreFormattato); } return null; } public String schermoModificaDaTabella() { PortaApplicativa portaApplicativaDaTabella = (PortaApplicativa) this.getVista().getTabellaPorteApplicative().getRowData(); Azione azionePortaApplicativa = portaApplicativaDaTabella.getAzione(); if (azionePortaApplicativa == null) { portaApplicativaDaTabella.setAzione(new Azione()); } if (portaApplicativaDaTabella.getServizio() != null) { try { List<Azione> listaAzioni = daoAzione.findByAccordo(this.utente, portaApplicativaDaTabella.getServizio().getAccordoServizio()); this.vista.setListaAzioni(listaAzioni); } catch (DAOException ex) { logger.error("Impossibile leggere il nuovo servizio " + ex); } } this.vista.setNuovoPortaApplicativa(portaApplicativaDaTabella); gestioneModificaPortaApplicativa(portaApplicativaDaTabella); return null; } public String schermoEliminaDaTabella() { PortaApplicativa portaApplicativaDaEliminare = (PortaApplicativa) this.vista.getTabellaPorteApplicative().getRowData(); this.vista.setNuovoPortaApplicativa(portaApplicativaDaEliminare); this.setConferma("Sei sicuro di voler eliminare la Porta Applicativa?"); gestioneEliminaPortaApplicativa(portaApplicativaDaEliminare); return null; } public void servizioCambiato(ActionEvent e) { try { long idNuovoServizio = this.getVista().getNuovoPortaApplicativa().getServizio().getId(); Servizio nuovoServizio = daoServizio.findById(this.utente, idNuovoServizio, false); if (nuovoServizio == null) { return; } List<Azione> listaAzioni = daoAzione.findByAccordo(this.utente, nuovoServizio.getAccordoServizio()); this.vista.setListaAzioni(listaAzioni); } catch (DAOException ex) { logger.error("Impossibile leggere il nuovo servizio " + ex); } } public String getMessaggio() { return messaggio; } public void setMessaggio(String messaggio) { this.messaggio = messaggio; } public String getErrore() { return errore; } public void setErrore(String errore) { this.errore = errore; } public VistaGestionePorteApplicative getVista() { return vista; } public void setVista(VistaGestionePorteApplicative vista) { this.vista = vista; } public IDAOPortaApplicativa getDaoPortaApplicativa() { return daoPortaApplicativa; } public void setDaoPortaApplicativa(IDAOPortaApplicativa daoPortaApplicativa) { this.daoPortaApplicativa = daoPortaApplicativa; } public String getConferma() { return conferma; } public void setConferma(String conferma) { this.conferma = conferma; } public boolean isVisualizzaMessaggio() { return (this.messaggio != null && !this.messaggio.equalsIgnoreCase("")); } public boolean isVisualizzaErrore() { return (this.errore != null && !this.errore.equalsIgnoreCase("")); } public boolean isVisualizzaConferma() { return (this.conferma != null && !this.conferma.equalsIgnoreCase("")); } public IDAOServizio getDaoServizio() { return daoServizio; } public void setDaoServizio(IDAOServizio daoServizio) { this.daoServizio = daoServizio; } public IDAOAzione getDaoAzione() { return daoAzione; } public void setDaoAzione(IDAOAzione daoAzione) { this.daoAzione = daoAzione; } public IDAOServizioApplicativo getDaoServizioApplicativo() { return daoServizioApplicativo; } public void setDaoServizioApplicativo(IDAOServizioApplicativo daoServizioApplicativo) { this.daoServizioApplicativo = daoServizioApplicativo; } public Utente getUtente() { return utente; } public void setUtente(Utente utente) { this.utente = utente; } public IDAOConfigurazione getDaoConfigurazione() { return daoConfigurazione; } public void setDaoConfigurazione(IDAOConfigurazione daoConfigurazione) { this.daoConfigurazione = daoConfigurazione; } }
gpl-2.0
newdigicash/WSPosgrado
src/java/util/ClaseGeneral.java
11472
/* * Clase usada para las consultas SQL, para que su resultado sean devueltos * en instancias de esta clase */ package util; import java.util.List; /** * * @author ealvarez */ public class ClaseGeneral implements java.io.Serializable { private Object campo1; private Object campo2; private Object campo3; private Object campo4; private Object campo5; private Object campo6; private Object campo7; private Object campo8; private Object campo9; private Object campo10; private Object campo11; private Object campo12; private Object campo13; private Object campo14; private Object campo15; private Object campo16; private Object campo17; private Object campo18; private Object campo19; private Object campo20; private Object campo21; private Object campo22; private Object campo23; private Object campo24; private Object campo25; private Object campo26; private Object campo27; private Object campo28; private Object campo29; private Object campo30; private Object campo31; private Object campo32; private Object campo33; private Object campo34; private Object campo35; private Object campo36; private Object campo37; private Object campo38; private Object campo39; private Object campo40; private List lista1; private List lista2; private List lista3; private List lista4; private List lista5; private List lista6; private List lista7; private boolean seleccionado = false; private boolean selmultiple; public ClaseGeneral() { } public ClaseGeneral(Object campo1, Object campo2) { this.campo1 = campo1; this.campo2 = campo2; } public Object getCampo1() { return campo1; } public void setCampo1(Object campo1) { this.campo1 = campo1; } public Object getCampo2() { return campo2; } public void setCampo2(Object campo2) { this.campo2 = campo2; } public Object getCampo3() { return campo3; } public void setCampo3(Object campo3) { this.campo3 = campo3; } public Object getCampo4() { return campo4; } public void setCampo4(Object campo4) { this.campo4 = campo4; } public Object getCampo5() { return campo5; } public void setCampo5(Object campo5) { this.campo5 = campo5; } public Object getCampo6() { //public boolean isCampoJustificacionEntrada() { // if (campo10 == null) { // campoJustificacionEntrada = false; // } else { // if (campo10.equals("FALTA") || campo10.equals("ATRASO") || campo10.equals("ANTICIPADA")) { // campoJustificacionEntrada = true; // } else { // campoJustificacionEntrada = false; // } // } // return campoJustificacionEntrada; // } // // public void setCampoJustificacionEntrada(boolean campoJustificacionEntrada) { // this.campoJustificacionEntrada = campoJustificacionEntrada; // } // // public boolean isCampoJustificacionSalida() { // if (campo16 == null) { // campoJustificacionSalida = false; // } else { // if (campo16.equals("FALTA") || campo16.equals("ATRASO") || campo16.equals("ANTICIPADA")) { // campoJustificacionSalida = true; // } else { // campoJustificacionSalida = false; // } // } // return campoJustificacionSalida; // } // // public void setCampoJustificacionSalida(boolean campoJustificacionSalida) { // this.campoJustificacionSalida = campoJustificacionSalida; // } return campo6; } public void setCampo6(Object campo6) { this.campo6 = campo6; } public Object getCampo7() { return campo7; } public void setCampo7(Object campo7) { this.campo7 = campo7; } public Object getCampo8() { return campo8; } public void setCampo8(Object campo8) { this.campo8 = campo8; } public Object getCampo9() { return campo9; } public void setCampo9(Object campo9) { this.campo9 = campo9; } public Object getCampo10() { return campo10; } public void setCampo10(Object campo10) { this.campo10 = campo10; } public Object getCampo11() { return campo11; } public void setCampo11(Object campo11) { this.campo11 = campo11; } public Object getCampo12() { return campo12; } public void setCampo12(Object campo12) { this.campo12 = campo12; } public Object getCampo13() { return campo13; } public void setCampo13(Object campo13) { this.campo13 = campo13; } public Object getCampo14() { return campo14; } public void setCampo14(Object campo14) { this.campo14 = campo14; } public Object getCampo15() { return campo15; } public void setCampo15(Object campo15) { this.campo15 = campo15; } public Object getCampo16() { return campo16; } public void setCampo16(Object campo16) { this.campo16 = campo16; } public Object getCampo17() { return campo17; } public void setCampo17(Object campo17) { this.campo17 = campo17; } public Object getCampo18() { return campo18; } public void setCampo18(Object campo18) { this.campo18 = campo18; } public Object getCampo19() { return campo19; } public void setCampo19(Object campo19) { this.campo19 = campo19; } public Object getCampo20() { return campo20; } public void setCampo20(Object campo20) { this.campo20 = campo20; } public Object getCampo21() { return campo21; } public void setCampo21(Object campo21) { this.campo21 = campo21; } public Object getCampo22() { return campo22; } public void setCampo22(Object campo22) { this.campo22 = campo22; } public Object getCampo23() { return campo23; } public void setCampo23(Object campo23) { this.campo23 = campo23; } public Object getCampo24() { return campo24; } public void setCampo24(Object campo24) { this.campo24 = campo24; } public Object getCampo25() { return campo25; } public void setCampo25(Object campo25) { this.campo25 = campo25; } public boolean isSeleccionado() { return seleccionado; } public void setSeleccionado(boolean seleccionado) { this.seleccionado = seleccionado; } public boolean isSelmultiple() { return selmultiple; } public void setSelmultiple(boolean selmultiple) { this.selmultiple = selmultiple; } public List getLista1() { return lista1; } public void setLista1(List lista1) { this.lista1 = lista1; } public List getLista2() { return lista2; } public void setLista2(List lista2) { this.lista2 = lista2; } public List getLista3() { return lista3; } public void setLista3(List lista3) { this.lista3 = lista3; } public List getLista4() { return lista4; } public void setLista4(List lista4) { this.lista4 = lista4; } public List getLista5() { return lista5; } public void setLista5(List lista5) { this.lista5 = lista5; } public List getLista6() { return lista6; } public void setLista6(List lista6) { this.lista6 = lista6; } public List getLista7() { return lista7; } public void setLista7(List lista7) { this.lista7 = lista7; } public Object getCampo26() { return campo26; } public void setCampo26(Object campo26) { this.campo26 = campo26; } public Object getCampo27() { return campo27; } public void setCampo27(Object campo27) { this.campo27 = campo27; } public Object getCampo28() { return campo28; } public void setCampo28(Object campo28) { this.campo28 = campo28; } public Object getCampo29() { return campo29; } public void setCampo29(Object campo29) { this.campo29 = campo29; } public Object getCampo30() { return campo30; } public void setCampo30(Object campo30) { this.campo30 = campo30; } public Object getCampo31() { return campo31; } public void setCampo31(Object campo31) { this.campo31 = campo31; } public Object getCampo32() { return campo32; } public void setCampo32(Object campo32) { this.campo32 = campo32; } // public boolean isCampoJustificacionEntrada() { // if (campo10 == null) { // campoJustificacionEntrada = false; // } else { // if (campo10.equals("FALTA") || campo10.equals("ATRASO") || campo10.equals("ANTICIPADA")) { // campoJustificacionEntrada = true; // } else { // campoJustificacionEntrada = false; // } // } // return campoJustificacionEntrada; // } // // public void setCampoJustificacionEntrada(boolean campoJustificacionEntrada) { // this.campoJustificacionEntrada = campoJustificacionEntrada; // } // // public boolean isCampoJustificacionSalida() { // if (campo16 == null) { // campoJustificacionSalida = false; // } else { // if (campo16.equals("FALTA") || campo16.equals("ATRASO") || campo16.equals("ANTICIPADA")) { // campoJustificacionSalida = true; // } else { // campoJustificacionSalida = false; // } // } // return campoJustificacionSalida; // } // // public void setCampoJustificacionSalida(boolean campoJustificacionSalida) { // this.campoJustificacionSalida = campoJustificacionSalida; // } public Object getCampo33() { return campo33; } public void setCampo33(Object campo33) { this.campo33 = campo33; } public Object getCampo34() { return campo34; } public void setCampo34(Object campo34) { this.campo34 = campo34; } public Object getCampo35() { return campo35; } public void setCampo35(Object campo35) { this.campo35 = campo35; } public Object getCampo36() { return campo36; } public void setCampo36(Object campo36) { this.campo36 = campo36; } public Object getCampo37() { return campo37; } public void setCampo37(Object campo37) { this.campo37 = campo37; } public Object getCampo38() { return campo38; } public void setCampo38(Object campo38) { this.campo38 = campo38; } public Object getCampo39() { return campo39; } public void setCampo39(Object campo39) { this.campo39 = campo39; } public Object getCampo40() { return campo40; } public void setCampo40(Object campo40) { this.campo40 = campo40; } }
gpl-2.0
identityxx/penrose-server
common/src/java/org/safehaus/penrose/ldap/DeleteResponse.java
126
package org.safehaus.penrose.ldap; /** * @author Endi S. Dewata */ public class DeleteResponse extends Response { }
gpl-2.0
SpoonLabs/astor
src/main/java/fr/inria/astor/core/solutionsearch/ExhaustiveSearchEngine.java
4176
package fr.inria.astor.core.solutionsearch; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import com.martiansoftware.jsap.JSAPException; import fr.inria.astor.core.entities.ModificationPoint; import fr.inria.astor.core.entities.OperatorInstance; import fr.inria.astor.core.entities.ProgramVariant; import fr.inria.astor.core.entities.SuspiciousModificationPoint; import fr.inria.astor.core.manipulation.MutationSupporter; import fr.inria.astor.core.setup.ConfigurationProperties; import fr.inria.astor.core.setup.ProjectRepairFacade; import fr.inria.astor.core.solutionsearch.spaces.operators.AstorOperator; import fr.inria.main.AstorOutputStatus; /** * Exhaustive Search Engine * * @author Matias Martinez, matias.martinez@inria.fr * */ public abstract class ExhaustiveSearchEngine extends AstorCoreEngine { public ExhaustiveSearchEngine(MutationSupporter mutatorExecutor, ProjectRepairFacade projFacade) throws JSAPException { super(mutatorExecutor, projFacade); } @Override public void startEvolution() throws Exception { dateInitEvolution = new Date(); // We don't evolve variants, so the generation is always one. generationsExecuted = 1; // For each variant (one is enough) int maxMinutes = ConfigurationProperties.getPropertyInt("maxtime"); int v = 0; for (ProgramVariant parentVariant : variants) { log.debug("\n****\nanalyzing variant #" + (++v) + " out of " + variants.size()); // We analyze each modifpoint of the variant i.e. suspicious // statement for (ModificationPoint modifPoint : parentVariant.getModificationPoints()) { // We create all operators to apply in the modifpoint List<OperatorInstance> operatorInstances = createInstancesOfOperators( (SuspiciousModificationPoint) modifPoint); if (operatorInstances == null || operatorInstances.isEmpty()) continue; for (OperatorInstance pointOperation : operatorInstances) { if (!belowMaxTime(dateInitEvolution, maxMinutes)) { this.setOutputStatus(AstorOutputStatus.TIME_OUT); log.debug("Max time reached"); return; } try { log.info("mod_point " + modifPoint); log.info("-->op: " + pointOperation); } catch (Exception e) { log.error(e); } // We validate the variant after applying the operator ProgramVariant solutionVariant = variantFactory.createProgramVariantFromAnother(parentVariant, generationsExecuted); solutionVariant.getOperations().put(generationsExecuted, Arrays.asList(pointOperation)); applyNewMutationOperationToSpoonElement(pointOperation); boolean solution = processCreatedVariant(solutionVariant, generationsExecuted); // We undo the operator (for try the next one) undoOperationToSpoonElement(pointOperation); if (solution) { this.solutions.add(solutionVariant); if (ConfigurationProperties.getPropertyBool("stopfirst")) { this.setOutputStatus(AstorOutputStatus.STOP_BY_PATCH_FOUND); return; } } if (!belowMaxTime(dateInitEvolution, maxMinutes)) { this.setOutputStatus(AstorOutputStatus.TIME_OUT); log.debug("Max time reached"); return; } } } } log.debug("End exhaustive navigation"); this.setOutputStatus(AstorOutputStatus.EXHAUSTIVE_NAVIGATED); } /** * @param modificationPoint * @return */ protected List<OperatorInstance> createInstancesOfOperators(SuspiciousModificationPoint modificationPoint) { List<OperatorInstance> ops = new ArrayList<>(); AstorOperator[] operators = getOperatorSpace().values(); for (AstorOperator astorOperator : operators) { if (astorOperator.canBeAppliedToPoint(modificationPoint)) { if (!astorOperator.needIngredient()) { List<OperatorInstance> instances = astorOperator.createOperatorInstances(modificationPoint); if (instances != null && instances.size() > 0) { ops.addAll(instances); } else { log.error("Ignored operator: The approach has an operator that needs ingredients: " + astorOperator.getClass().getCanonicalName()); } } } } return ops; } }
gpl-2.0
panbasten/imeta
imeta2.x/imeta-src/imeta/src/main/java/com/panet/imeta/core/config/KettleConfig.java
5837
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package com.panet.imeta.core.config; import java.beans.Introspector; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.digester.Digester; import org.apache.commons.digester.SetNextRule; import org.apache.commons.digester.SetPropertiesRule; import org.xml.sax.Attributes; import com.panet.imeta.core.annotations.Inject; import com.panet.imeta.core.exception.KettleConfigException; /** * The gateway for all configuration operations. * * <h3>Configuration Managers Property Injection:</h3> * This class reads "<property>" elements from kettle-config.xml and attempts to * inject the value of such fields into the corresponding * <code>ConfigManager</code> implementation, following the rules established * the * * @see com.panet.imeta.core.annotations.Inject * * @author Alex Silva * */ public class KettleConfig { private static final String KETTLE_CONFIG = "kettle-config/config"; private static final String KETTLE_CONFIG_PROPERTY = KETTLE_CONFIG + "/property"; private static final String KETTLE_CONFIG_CLASS = KETTLE_CONFIG + "/config-class"; private static KettleConfig config; private Map<String, ConfigManager<?>> configs = new HashMap<String, ConfigManager<?>>(); private KettleConfig() { Digester digester = createDigester(); try { digester.parse(Thread.currentThread().getContextClassLoader().getResource( getClass().getPackage().getName().replace('.', '/') + "/kettle-config.xml")); } catch (Exception e) { e.printStackTrace(); } } public static KettleConfig getInstance() { if (config == null) { synchronized (KettleConfig.class) { config = new KettleConfig(); } } return config; } public ConfigManager<?> getManager(String name) { return configs.get(name); } /** * @return all loaders defined in kettle-config.xml. */ public Collection<ConfigManager<?>> getManagers() { return configs.values(); } private Digester createDigester() { Digester digester = new Digester(); digester.addObjectCreate(KETTLE_CONFIG, TempConfig.class); digester.addBeanPropertySetter(KETTLE_CONFIG_CLASS, "clazz"); digester.addSetProperties(KETTLE_CONFIG, "id", "id"); digester.addRule(KETTLE_CONFIG_PROPERTY, new SetPropertiesRule() { @Override public void begin(String name, String namespace, Attributes attrs) throws Exception { ((TempConfig) digester.peek()).parms.put(attrs.getValue("name"), attrs.getValue("value")); } }); digester.addRule(KETTLE_CONFIG, new SetNextRule("") { @SuppressWarnings("unchecked") public void end(String nameSpace, String name) throws Exception { TempConfig cfg = (TempConfig) digester.peek(); // do the conversion here. Class<? extends ConfigManager> cfclass = Class.forName(cfg.clazz).asSubclass( ConfigManager.class); ConfigManager parms = cfclass.newInstance(); // method injection inject(cfclass.getMethods(), cfg, parms); // field injection inject(cfclass.getDeclaredFields(), cfg, parms); KettleConfig.this.configs.put(cfg.id, parms); } }); return digester; } private <E extends AccessibleObject> void inject(E[] elems, TempConfig cfg, ConfigManager<?> parms) throws IllegalAccessException, InvocationTargetException { for (AccessibleObject elem : elems) { Inject inj = elem.getAnnotation(Inject.class); if (inj != null) { // try to inject property from map. elem.setAccessible(true); String property = inj.property(); // Can't think of any other way if (elem instanceof Method) { Method meth = (Method) elem; // find out what we are going to inject 1st property = property.equals("") ? Introspector.decapitalize(meth.getName().substring(3)) : property; meth.invoke(parms, cfg.parms.get(property)); } else if (elem instanceof Field) { Field field = (Field) elem; field.set(parms, cfg.parms.get(property.equals("") ? field.getName() : property)); } } } } /** * Adds a new manager programatically * @param name - the name of the new manager. Must not already exist * @param mgr - The mgr implementation * @throws KettleConfigException If the manager already exists in this config instance */ public void addConfig(String name,ConfigManager<?> mgr) throws KettleConfigException { ConfigManager<?> cmgr = configs.get(name); if (cmgr!=null) throw new KettleConfigException(name + " is already registered as a manager"); configs.put(name, mgr); } public static class TempConfig { private String clazz; private String id; private Map<String, String> parms = new HashMap<String, String>(); public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } } }
gpl-2.0
stephenostermiller/ostermillerutils
src/main/java/com/Ostermiller/util/ConcatInputStream.java
13411
/* * Copyright (C) 2004-2010 Stephen Ostermiller * http://ostermiller.org/contact.pl?regarding=Java+Utilities * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See LICENSE.txt for details. */ package com.Ostermiller.util; import java.io.*; import java.util.ArrayList; /** * An input stream which reads sequentially from multiple sources. * More information about this class is available from <a target="_top" href= * "http://ostermiller.org/utils/">ostermiller.org</a>. * * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities * @since ostermillerutils 1.04.00 */ public class ConcatInputStream extends InputStream { /** * Current index to inputStreamQueue * * @since ostermillerutils 1.04.01 */ private int inputStreamQueueIndex = 0; /** * Queue of inputStreams that have yet to be read from. * * @since ostermillerutils 1.04.01 */ private ArrayList<InputStream> inputStreamQueue = new ArrayList<InputStream>(); /** * A cache of the current inputStream from the inputStreamQueue * to avoid unneeded access to the queue which must * be synchronized. * * @since ostermillerutils 1.04.01 */ private InputStream currentInputStream = null; /** * true iff the client may add more inputStreams. * * @since ostermillerutils 1.04.01 */ private boolean doneAddingInputStreams = false; /** * Causes the addInputStream method to throw IllegalStateException * and read() methods to return -1 (end of stream) * when there is no more available data. * <p> * Calling this method when this class is no longer accepting * more inputStreams has no effect. * * @since ostermillerutils 1.04.01 */ public void lastInputStreamAdded(){ doneAddingInputStreams = true; } /** * Add the given inputStream to the queue of inputStreams from which to * concatenate data. * * @param in InputStream to add to the concatenation. * @throws IllegalStateException if more inputStreams can't be added because lastInputStreamAdded() has been called, close() has been called, or a constructor with inputStream parameters was used. * * @since ostermillerutils 1.04.01 */ public void addInputStream(InputStream in){ synchronized(inputStreamQueue){ if (in == null) throw new NullPointerException(); if (closed) throw new IllegalStateException("ConcatInputStream has been closed"); if (doneAddingInputStreams) throw new IllegalStateException("Cannot add more inputStreams - the last inputStream has already been added."); inputStreamQueue.add(in); } } /** * Add the given inputStream to the queue of inputStreams from which to * concatenate data. * * @param in InputStream to add to the concatenation. * @throws IllegalStateException if more inputStreams can't be added because lastInputStreamAdded() has been called, close() has been called, or a constructor with inputStream parameters was used. * @throws NullPointerException the array of inputStreams, or any of the contents is null. * * @since ostermillerutils 1.04.01 */ public void addInputStreams(InputStream[] in){ for (InputStream element: in) { addInputStream(element); } } /** * Gets the current inputStream, looking at the next * one in the list if the current one is null. * * @since ostermillerutils 1.04.01 */ private InputStream getCurrentInputStream(){ if (currentInputStream == null && inputStreamQueueIndex < inputStreamQueue.size()){ synchronized(inputStreamQueue){ // inputStream queue index is advanced only by the nextInputStream() // method. Don't do it here. currentInputStream = inputStreamQueue.get(inputStreamQueueIndex); } } return currentInputStream; } /** * Indicate that we are done with the current inputStream and we should * advance to the next inputStream. * * @since ostermillerutils 1.04.01 */ private void advanceToNextInputStream(){ currentInputStream = null; inputStreamQueueIndex++; } /** * True iff this the close() method has been called on this stream. * * @since ostermillerutils 1.04.00 */ private boolean closed = false; /** * Create a new input stream that can dynamically accept new sources. * <p> * New sources should be added using the addInputStream() method. * When all sources have been added the lastInputStreamAdded() should * be called so that read methods can return -1 (end of stream). * <p> * Adding new sources may by interleaved with read calls. * * @since ostermillerutils 1.04.01 */ public ConcatInputStream(){ // Empty constructor } /** * Create a new InputStream with one source. * * @param in InputStream to use as a source. * * @throws NullPointerException if in is null * * @since ostermillerutils 1.04.00 */ public ConcatInputStream(InputStream in){ addInputStream(in); lastInputStreamAdded(); } /** * Create a new InputStream with two sources. * * @param in1 first InputStream to use as a source. * @param in2 second InputStream to use as a source. * * @throws NullPointerException if either source is null. * * @since ostermillerutils 1.04.00 */ public ConcatInputStream(InputStream in1, InputStream in2){ addInputStream(in1); addInputStream(in2); lastInputStreamAdded(); } /** * Create a new InputStream with an arbitrary number of sources. * * @param in InputStreams to use as a sources. * * @throws NullPointerException if the input array on any element is null. * * @since ostermillerutils 1.04.00 */ public ConcatInputStream(InputStream[] in){ addInputStreams(in); lastInputStreamAdded(); } /** * Reads the next byte of data from the underlying streams. The value byte is * returned as an int in the range 0 to 255. If no byte is available because * the end of the stream has been reached, the value -1 is returned. This method * blocks until input data is available, the end of the stream is detected, or * an exception is thrown. * <p> * If this class in not done accepting input streams and the end of the last known * stream is reached, this method will block forever unless another thread * adds an input stream or interrupts. * * @return the next byte of data, or -1 if the end of the stream is reached. * * @throws IOException if an I/O error occurs. */ @Override public int read() throws IOException { if (closed) throw new IOException("InputStream closed"); int r = -1; while (r == -1){ InputStream in = getCurrentInputStream(); if (in == null){ if (doneAddingInputStreams) return -1; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { r = in.read(); if (r == -1) advanceToNextInputStream(); } } return r; } /** * Reads some number of bytes from the underlying streams and stores them into * the buffer array b. The number of bytes actually read is returned as an * integer. This method blocks until input data is available, end of file is * detected, or an exception is thrown. * <p> * If the length of b is zero, * then no bytes are read and 0 is returned; otherwise, there is an attempt * to read at least one byte. * <p> * The read(b) method for class InputStream has the same effect as:<br> * read(b, 0, b.length) * <p> * If this class in not done accepting input streams and the end of the last known * stream is reached, this method will block forever unless another thread * adds an input stream or interrupts. * * @param b - Destination buffer * @return The number of bytes read, or -1 if the end of the stream has been reached * * @throws IOException - If an I/O error occurs * @throws NullPointerException - If b is null. * * @since ostermillerutils 1.04.00 */ @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Reads up to length bytes of data from the underlying streams into an array of bytes. * An attempt is made to read as many as length bytes, but a smaller number may be read, * possibly zero. The number of bytes actually read is returned as an integer. * <p> * If length is zero, * then no bytes are read and 0 is returned; otherwise, there is an attempt * to read at least one byte. * <p> * This method blocks until input data is available * <p> * If this class in not done accepting input streams and the end of the last known * stream is reached, this method will block forever unless another thread * adds an input stream or interrupts. * * @param b Destination buffer * @param off Offset at which to start storing bytes * @param len Maximum number of bytes to read * @return The number of bytes read, or -1 if the end of the stream has been reached * * @throws IOException - If an I/O error occurs * @throws NullPointerException - If b is null. * @throws IndexOutOfBoundsException - if length or offset are not possible. */ @Override public int read(byte[] b, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len > b.length) throw new IllegalArgumentException(); if (closed) throw new IOException("InputStream closed"); int r = -1; while (r == -1){ InputStream in = getCurrentInputStream(); if (in == null){ if (doneAddingInputStreams) return -1; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { r = in.read(b, off, len); if (r == -1) advanceToNextInputStream(); } } return r; } /** * Skips over and discards n bytes of data from this input stream. The skip method * may, for a variety of reasons, end up skipping over some smaller number of bytes, * possibly 0. This may result from any of a number of conditions; reaching end of * file before n bytes have been skipped is only one possibility. The actual number * of bytes skipped is returned. If n is negative, no bytes are skipped. * <p> * If this class in not done accepting input streams and the end of the last known * stream is reached, this method will block forever unless another thread * adds an input stream or interrupts. * * @param n he number of characters to skip * @return The number of characters actually skipped * * @throws IOException If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public long skip(long n) throws IOException { if (closed) throw new IOException("InputStream closed"); if (n <= 0) return 0; long s = -1; while (s <= 0){ InputStream in = getCurrentInputStream(); if (in == null){ if (doneAddingInputStreams) return 0; try { Thread.sleep(100); } catch (InterruptedException iox){ throw new IOException("Interrupted"); } } else { s = in.skip(n); // When nothing was skipped it is a bit of a puzzle. // The most common cause is that the end of the underlying // stream was reached. In which case calling skip on it // will always return zero. If somebody were calling skip // until it skipped everything they needed, there would // be an infinite loop if we were to return zero here. // If we get zero, let us try to read one character so // we can see if we are at the end of the stream. If so, // we will move to the next. if (s <= 0) { // read() will advance to the next stream for us, so don't do it again s = ((read()==-1)?-1:1); } } } return s; } /** * Returns the number of bytes that can be read (or skipped over) from this input * stream without blocking by the next caller of a method for this input stream. * The next caller might be the same thread or or another thread. * * @throws IOException If an I/O error occurs * * @since ostermillerutils 1.04.00 */ @Override public int available() throws IOException { if (closed) throw new IOException("InputStream closed"); InputStream in = getCurrentInputStream(); if (in == null) return 0; return in.available(); } /** * Closes this input stream and releases any system resources associated with the stream. * * @since ostermillerutils 1.04.00 */ @Override public void close() throws IOException { if (closed) return; for (Object element: inputStreamQueue) { ((InputStream)element).close(); } closed = true; } /** * Mark not supported * * @since ostermillerutils 1.04.00 */ @Override public void mark(int readlimit){ // Mark not supported -- do nothing } /** * Reset not supported. * * @throws IOException because reset is not supported. * * @since ostermillerutils 1.04.00 */ @Override public void reset() throws IOException { throw new IOException("Reset not supported"); } /** * Does not support mark. * * @return false * * @since ostermillerutils 1.04.00 */ @Override public boolean markSupported(){ return false; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08873.java
2531
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest08873") public class BenchmarkTest08873 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames.hasMoreElements()) { param = headerNames.nextElement(); // just grab first element } String bar = new Test().doSomething(param); try { java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG"); boolean randNumber = numGen.nextBoolean(); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextBoolean() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextBoolean() executed"); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param); return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
tomas-pluskal/mzmine3
src/main/java/io/github/mzmine/parameters/parametertypes/StringParameter.java
4113
/* * Copyright 2006-2020 The MZmine Development Team * * This file is part of MZmine. * * MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package io.github.mzmine.parameters.parametertypes; import java.util.Collection; import org.w3c.dom.Element; import io.github.mzmine.parameters.UserParameter; import javafx.scene.control.TextField; public class StringParameter implements UserParameter<String, TextField> { private String name, description, value; private int inputsize = 20; private boolean valueRequired = true; private final boolean sensitive; public StringParameter(String name, String description) { this(name, description, null); } public StringParameter(String name, String description, boolean isSensitive) { this(name, description, null, true, isSensitive); } public StringParameter(String name, String description, int inputsize) { this.name = name; this.description = description; this.inputsize = inputsize; this.sensitive = false; } public StringParameter(String name, String description, String defaultValue) { this(name, description, defaultValue, true, false); } public StringParameter(String name, String description, String defaultValue, boolean valueRequired) { this(name, description, defaultValue, valueRequired, false); } public StringParameter(String name, String description, String defaultValue, boolean valueRequired, boolean isSensitive) { this.name = name; this.description = description; this.value = defaultValue; this.valueRequired = valueRequired; this.sensitive = isSensitive; } /** * @see io.github.mzmine.data.Parameter#getName() */ @Override public String getName() { return name; } /** * @see io.github.mzmine.data.Parameter#getDescription() */ @Override public String getDescription() { return description; } @Override public TextField createEditingComponent() { TextField stringComponent = new TextField(); stringComponent.setPrefColumnCount(inputsize); // stringComponent.setBorder(BorderFactory.createCompoundBorder(stringComponent.getBorder(), // BorderFactory.createEmptyBorder(0, 4, 0, 0))); return stringComponent; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public StringParameter cloneParameter() { StringParameter copy = new StringParameter(name, description); copy.setValue(this.getValue()); return copy; } @Override public String toString() { return name; } @Override public void setValueFromComponent(TextField component) { value = component.getText(); } @Override public void setValueToComponent(TextField component, String newValue) { component.setText(newValue); } @Override public void loadValueFromXML(Element xmlElement) { value = xmlElement.getTextContent(); } @Override public void saveValueToXML(Element xmlElement) { if (value == null) return; xmlElement.setTextContent(value); } @Override public boolean checkValue(Collection<String> errorMessages) { if (!valueRequired) return true; if ((value == null) || (value.trim().length() == 0)) { errorMessages.add(name + " is not set properly"); return false; } return true; } @Override public boolean isSensitive() { return sensitive; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest16422.java
2687
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest16422") public class BenchmarkTest16422 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headers = request.getHeaders("foo"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } String bar = doSomething(param); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo", bar}; String[] argsEnv = { "foo=bar" }; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns param to bar on true condition int i = 196; if ( (500/42) + i > 200 ) bar = param; else bar = "This should never happen"; return bar; } }
gpl-2.0
admo/aria
arnetworking/ddd/javaExamples/customClientExample.java
4033
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ import com.mobilerobots.Aria.*; import com.mobilerobots.ArNetworking.*; class ResponseCallback extends ArFunctor_NetPacket { public void invoke(ArNetPacket packet) { System.out.println("customClientExample: ResponseCallback: Got a packet from the server with type " + packet.getCommand()); } } public class customClientExample { /* This loads all the ArNetworking classes (they will be in the global * namespace) when this class is loaded: */ static { try { System.loadLibrary("AriaJava"); System.loadLibrary("ArNetworkingJava"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code libraries (AriaJava and ArNetworkingJava .so or .DLL) failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); System.exit(1); } } public static void main(String argv[]) { Aria.init(); ArClientBase client = new ArClientBase(); ResponseCallback testCB = new ResponseCallback(); ArTime startTime = new ArTime(); startTime.setToNow(); System.out.println("customClientExample: trying to connect to a server running on the local host at port 7273..."); if (!client.blockingConnect("localhost", 7273)) { System.err.println("Error: Could not connect to server on localhost:7273, exiting."); System.exit(1); } System.out.println("customClientExample: Connected after " + startTime.mSecSince() + " msec."); client.runAsync(); System.out.println("\ncustomClientExample: Adding data handler callbacks..."); client.lock(); client.addHandler("test", testCB); client.addHandler("test2", testCB); client.addHandler("test3", testCB); client.logDataList(); System.out.println("\ncustomClientExample: Requesting \"test\" once..."); client.requestOnce("test"); System.out.println("\ncustomClientExample: Requesting \"test2\" with a frequency of 10ms..."); client.request("test2", 100); System.out.println("\ncustomClientExample: Requesting \"test3\" with a frequency of -1 (updates may happen at any time the server sends them) and waiting 5 sec..."); client.request("test3", -1); client.unlock(); ArUtil.sleep(5000); System.out.println("\ncustomClientExample: Changing request frequency of \"test2\" to 300ms and waiting 5 sec"); client.lock(); client.request("test2", 300); client.unlock(); ArUtil.sleep(5000); System.out.println("\ncustomClientExample: Cancelling \"test2\" request."); client.lock(); client.requestStop("test2"); client.unlock(); System.out.println("\ncustomClientExample: waiting 10 seconds, then disconnecting..."); ArUtil.sleep(10000); client.lock(); client.disconnect(); client.unlock(); ArUtil.sleep(50); } }
gpl-2.0
BunnyWei/truffle-llvmir
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/extended/LoadMethodNode.java
4666
/* * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.extended; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodeinfo.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; /** * Loads a method from the virtual method table of a given hub. */ @NodeInfo public final class LoadMethodNode extends FixedWithNextNode implements Lowerable, Canonicalizable { public static final NodeClass<LoadMethodNode> TYPE = NodeClass.create(LoadMethodNode.class); @Input ValueNode hub; protected final ResolvedJavaMethod method; protected final ResolvedJavaType receiverType; public ValueNode getHub() { return hub; } public LoadMethodNode(@InjectedNodeParameter Stamp stamp, ResolvedJavaMethod method, ResolvedJavaType receiverType, ValueNode hub) { super(TYPE, stamp); this.receiverType = receiverType; this.hub = hub; this.method = method; assert method.isConcrete() : "Cannot load abstract method from a hub"; assert method.hasReceiver() : "Cannot load a static method from a hub"; assert method.isInVirtualMethodTable(receiverType); } @Override public void lower(LoweringTool tool) { tool.getLowerer().lower(this, tool); } @Override public Node canonical(CanonicalizerTool tool) { if (hub instanceof LoadHubNode) { ValueNode object = ((LoadHubNode) hub).getValue(); ResolvedJavaType type = StampTool.typeOrNull(object); if (StampTool.isExactType(object)) { return resolveExactMethod(tool, type); } Assumptions assumptions = graph().getAssumptions(); if (type != null && assumptions != null) { ResolvedJavaMethod resolvedMethod = type.findUniqueConcreteMethod(method); if (resolvedMethod != null && !type.isInterface() && method.getDeclaringClass().isAssignableFrom(type)) { assumptions.recordConcreteMethod(method, type, resolvedMethod); return ConstantNode.forConstant(stamp(), resolvedMethod.getEncoding(), tool.getMetaAccess()); } } } if (hub.isConstant()) { return resolveExactMethod(tool, tool.getConstantReflection().asJavaType(hub.asConstant())); } return this; } /** * Find the method which would be loaded. * * @param tool * @param type the exact type of object being loaded from * @return the method which would be invoked for {@code type} or null if it doesn't implement * the method */ private Node resolveExactMethod(CanonicalizerTool tool, ResolvedJavaType type) { ResolvedJavaMethod newMethod = type.resolveConcreteMethod(method, type); if (newMethod == null) { /* * This really represent a misuse of LoadMethod since we're loading from a class which * isn't known to implement the original method but for now at least fold it away. */ return ConstantNode.forConstant(JavaConstant.NULL_POINTER, null); } else { return ConstantNode.forConstant(stamp(), newMethod.getEncoding(), tool.getMetaAccess()); } } public ResolvedJavaMethod getMethod() { return method; } public ResolvedJavaType getReceiverType() { return receiverType; } }
gpl-2.0
rex-xxx/mt6572_x201
external/bouncycastle/bcprov/src/main/java/org/bouncycastle/jcajce/provider/symmetric/util/BaseMac.java
10635
package org.bouncycastle.jcajce.provider.symmetric.util; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.MacSpi; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEParameterSpec; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Mac; // BEGIN android-removed // import org.bouncycastle.crypto.digests.MD2Digest; // import org.bouncycastle.crypto.digests.MD4Digest; // import org.bouncycastle.crypto.digests.MD5Digest; // import org.bouncycastle.crypto.digests.RIPEMD128Digest; // import org.bouncycastle.crypto.digests.RIPEMD160Digest; // import org.bouncycastle.crypto.digests.SHA1Digest; // import org.bouncycastle.crypto.digests.SHA224Digest; // import org.bouncycastle.crypto.digests.SHA256Digest; // import org.bouncycastle.crypto.digests.SHA384Digest; // import org.bouncycastle.crypto.digests.SHA512Digest; // import org.bouncycastle.crypto.digests.TigerDigest; // END android-removed // BEGIN android-added import org.bouncycastle.crypto.digests.AndroidDigestFactory; // END android-added import org.bouncycastle.crypto.engines.DESEngine; import org.bouncycastle.crypto.engines.RC2Engine; import org.bouncycastle.crypto.macs.CBCBlockCipherMac; // BEGIN android-removed // import org.bouncycastle.crypto.macs.CFBBlockCipherMac; // import org.bouncycastle.crypto.macs.GOST28147Mac; // END android-removed import org.bouncycastle.crypto.macs.HMac; // BEGIN android-removed // import org.bouncycastle.crypto.macs.ISO9797Alg3Mac; // import org.bouncycastle.crypto.macs.OldHMac; // END android-removed import org.bouncycastle.crypto.paddings.ISO7816d4Padding; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; public class BaseMac extends MacSpi implements PBE { private Mac macEngine; private int pbeType = PKCS12; private int pbeHash = SHA1; private int keySize = 160; protected BaseMac( Mac macEngine) { this.macEngine = macEngine; } protected BaseMac( Mac macEngine, int pbeType, int pbeHash, int keySize) { this.macEngine = macEngine; this.pbeType = pbeType; this.pbeHash = pbeHash; this.keySize = keySize; } protected void engineInit( Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException { CipherParameters param; if (key == null) { throw new InvalidKeyException("key is null"); } if (key instanceof BCPBEKey) { BCPBEKey k = (BCPBEKey)key; if (k.getParam() != null) { param = k.getParam(); } else if (params instanceof PBEParameterSpec) { param = PBE.Util.makePBEMacParameters(k, params); } else { throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); } } else if (params instanceof IvParameterSpec) { param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec)params).getIV()); } else if (params == null) { param = new KeyParameter(key.getEncoded()); } else { throw new InvalidAlgorithmParameterException("unknown parameter type."); } macEngine.init(param); } protected int engineGetMacLength() { return macEngine.getMacSize(); } protected void engineReset() { macEngine.reset(); } protected void engineUpdate( byte input) { macEngine.update(input); } protected void engineUpdate( byte[] input, int offset, int len) { macEngine.update(input, offset, len); } protected byte[] engineDoFinal() { byte[] out = new byte[engineGetMacLength()]; macEngine.doFinal(out, 0); return out; } /** * the classes that extend directly off us. */ /** * DES */ public static class DES extends BaseMac { public DES() { super(new CBCBlockCipherMac(new DESEngine())); } } /** * DES 64 bit MAC */ public static class DES64 extends BaseMac { public DES64() { super(new CBCBlockCipherMac(new DESEngine(), 64)); } } /** * RC2 */ public static class RC2 extends BaseMac { public RC2() { super(new CBCBlockCipherMac(new RC2Engine())); } } // BEGIN android-removed // /** // * GOST28147 // */ // public static class GOST28147 // extends BaseMac // { // public GOST28147() // { // super(new GOST28147Mac()); // } // } // // // // /** // * DES // */ // public static class DESCFB8 // extends BaseMac // { // public DESCFB8() // { // super(new CFBBlockCipherMac(new DESEngine())); // } // } // // /** // * RC2CFB8 // */ // public static class RC2CFB8 // extends BaseMac // { // public RC2CFB8() // { // super(new CFBBlockCipherMac(new RC2Engine())); // } // } // // /** // * DES9797Alg3with7816-4Padding // */ // public static class DES9797Alg3with7816d4 // extends BaseMac // { // public DES9797Alg3with7816d4() // { // super(new ISO9797Alg3Mac(new DESEngine(), new ISO7816d4Padding())); // } // } // // /** // * DES9797Alg3 // */ // public static class DES9797Alg3 // extends BaseMac // { // public DES9797Alg3() // { // super(new ISO9797Alg3Mac(new DESEngine())); // } // } // // /** // * MD2 HMac // */ // public static class MD2 // extends BaseMac // { // public MD2() // { // super(new HMac(new MD2Digest())); // } // } // // /** // * MD4 HMac // */ // public static class MD4 // extends BaseMac // { // public MD4() // { // super(new HMac(new MD4Digest())); // } // } // END android-removed /** * MD5 HMac */ public static class MD5 extends BaseMac { public MD5() { // BEGIN android-changed super(new HMac(AndroidDigestFactory.getMD5())); // END android-changed } } /** * SHA1 HMac */ public static class SHA1 extends BaseMac { public SHA1() { // BEGIN android-changed super(new HMac(AndroidDigestFactory.getSHA1())); // END android-changed } } // BEGIN android-removed // /** // * SHA-224 HMac // */ // public static class SHA224 // extends BaseMac // { // public SHA224() // { // super(new HMac(new SHA224Digest())); // } // } // END android-removed /** * SHA-256 HMac */ public static class SHA256 extends BaseMac { public SHA256() { super(new HMac(AndroidDigestFactory.getSHA256())); } } /** * SHA-384 HMac */ public static class SHA384 extends BaseMac { public SHA384() { super(new HMac(AndroidDigestFactory.getSHA384())); } } // BEGIN android-removed // public static class OldSHA384 // extends BaseMac // { // public OldSHA384() // { // super(new OldHMac(new SHA384Digest())); // } // } // END android-removed /** * SHA-512 HMac */ public static class SHA512 extends BaseMac { public SHA512() { super(new HMac(AndroidDigestFactory.getSHA512())); } } // BEGIN android-removed // /** // * SHA-512 HMac // */ // public static class OldSHA512 // extends BaseMac // { // public OldSHA512() // { // super(new OldHMac(new SHA512Digest())); // } // } // // /** // * RIPEMD128 HMac // */ // public static class RIPEMD128 // extends BaseMac // { // public RIPEMD128() // { // super(new HMac(new RIPEMD128Digest())); // } // } // // /** // * RIPEMD160 HMac // */ // public static class RIPEMD160 // extends BaseMac // { // public RIPEMD160() // { // super(new HMac(new RIPEMD160Digest())); // } // } // // /** // * Tiger HMac // */ // public static class Tiger // extends BaseMac // { // public Tiger() // { // super(new HMac(new TigerDigest())); // } // } // // // // // PKCS12 states that the same algorithm should be used // // for the key generation as is used in the HMAC, so that // // is what we do here. // // // // /** // * PBEWithHmacRIPEMD160 // */ // public static class PBEWithRIPEMD160 // extends BaseMac // { // public PBEWithRIPEMD160() // { // super(new HMac(new RIPEMD160Digest()), PKCS12, RIPEMD160, 160); // } // } // END android-removed /** * PBEWithHmacSHA */ public static class PBEWithSHA extends BaseMac { public PBEWithSHA() { // BEGIN android-changed super(new HMac(AndroidDigestFactory.getSHA1()), PKCS12, SHA1, 160); // END android-changed } } // BEGIN android-removed // /** // * PBEWithHmacTiger // */ // public static class PBEWithTiger // extends BaseMac // { // public PBEWithTiger() // { // super(new HMac(new TigerDigest()), PKCS12, TIGER, 192); // } // } // END android-removed }
gpl-2.0
mzmine/mzmine3
src/test/java/datamodel/IntentionalOvershootTypeTest.java
1731
package datamodel; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.features.ModularFeature; import io.github.mzmine.datamodel.features.ModularFeatureList; import io.github.mzmine.datamodel.features.ModularFeatureListRow; import io.github.mzmine.datamodel.features.types.abstr.StringType; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; /** * Intentionally creates a data type that reads for too long. Used to test if a change to {@link * DataTypeTestUtils} is consistent. * * @author https://github.com/SteffenHeu */ public class IntentionalOvershootTypeTest { @Test void overshootTypeTest() { OvershootType type = new OvershootType(); var value = "hi"; Assertions.assertThrows(AssertionFailedError.class, () -> DataTypeTestUtils.simpleDataTypeSaveLoadTest(type, value)); } public static class OvershootType extends StringType { public OvershootType() { super(); } @Override public @NotNull String getUniqueID() { return "overshoot_type"; } @Override public @NotNull String getHeaderString() { return "overshoot"; } @Override public Object loadFromXML(@NotNull XMLStreamReader reader, @NotNull ModularFeatureList flist, @NotNull ModularFeatureListRow row, @Nullable ModularFeature feature, @Nullable RawDataFile file) throws XMLStreamException { while (reader.hasNext()) { reader.next(); } return null; } } }
gpl-2.0
CMPUT301W16T01/Crimson_Horizons
ParkingHelper/app/src/main/java/cmput301w16t01crimsonhorizons/parkinghelper/NotificationAdapter.java
2892
package cmput301w16t01crimsonhorizons.parkinghelper; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.List; /** * Created by Kevin L on 3/25/2016. */ public class NotificationAdapter extends ArrayAdapter<NotificationObject>{ private int Layout; public NotificationAdapter(Context context, int resource, List<NotificationObject> objects) { super(context, resource, objects); Layout=resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { NotificationHolder mainHolder = null; final NotificationObject notification = getItem(position); if (convertView == null){ LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(Layout,parent,false); final NotificationHolder viewHolder = new NotificationHolder(); viewHolder.Bidder=(TextView)convertView.findViewById(R.id.NotificationBidder); viewHolder.Date = (TextView)convertView.findViewById(R.id.NotificationDate); viewHolder.BidAmt = (TextView)convertView.findViewById(R.id.NotificationBidAmt); viewHolder.Delete = (Button)convertView.findViewById(R.id.DeleteNotificationBtn); viewHolder.Picture = (ImageView)convertView.findViewById(R.id.NotificationPicture); viewHolder.Delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NotificationElasticSearch.DeleteNotification deleteNotification = new NotificationElasticSearch.DeleteNotification(); deleteNotification.execute(notification); Toast.makeText(getContext(), "Deleted!!", Toast.LENGTH_SHORT).show(); } }); viewHolder.Bidder.setText(notification.getBidder()); viewHolder.Date.setText(notification.getDate()); viewHolder.BidAmt.setText(notification.getBidAmt()); //viewHolder.Picture.setImageBitmap(notification.getOnotification.getStallID()); convertView.setTag(viewHolder); } else{ mainHolder = (NotificationHolder)convertView.getTag(); mainHolder.Bidder.setText(notification.getBidder()); mainHolder.BidAmt.setText(notification.getBidAmt()); mainHolder.Date.setText(notification.getDate()); } return convertView; } public class NotificationHolder { TextView Bidder; TextView BidAmt; TextView Date; Button Delete; ImageView Picture; } }
gpl-2.0
angelazarquiel/programacion
UT5Clases/src/ejemplos/SaldoInsuficiente.java
78
package ejemplos; public class SaldoInsuficiente extends Exception { }
gpl-2.0
lexml/madoc
madoc-engine/src/main/java/br/gov/lexml/madoc/server/execution/hosteditor/HostEditorReplacer.java
814
package br.gov.lexml.madoc.server.execution.hosteditor; import br.gov.lexml.madoc.server.schema.Constants; import br.gov.lexml.madoc.server.util.MultipleStringReplacer; public class HostEditorReplacer { private final MultipleStringReplacer replacer; public HostEditorReplacer(){ this(null); } public HostEditorReplacer(HostEditor hostEditor){ if (hostEditor!= null){ replacer = new MultipleStringReplacer(hostEditor.getProperties(), Constants.REPLACEMENT_PREFIX, Constants.REPLACEMENT_SUFFIX, false); } else { replacer = null; } } /** * Replaces all occurrences of hosteditor's properties * @param src * @return */ public String replaceString(String src) { if (replacer == null || src == null || src.equals("")) { return src; } return replacer.replace(src); } }
gpl-2.0
meijmOrg/Repo-test
freelance-hr-res/src/java/com/yh/hr/res/pt/queryhelper/PtReportFileQueryHelper.java
986
package com.yh.hr.res.pt.queryhelper; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import com.yh.hr.res.pt.bo.PtReportFile; import com.yh.platform.core.dao.DaoUtil; import com.yh.platform.core.exception.ServiceException; /** * 文号信息查询工具类 * @author lenghh * * 时间:2016-11-10下午03:09:39 */ public class PtReportFileQueryHelper { /** * 根据报表类型获取文号类型 * @param reportFileType * @throws ServiceException */ public static String getFileNoType(String reportFileType) throws ServiceException { String hql = "from PtReportFile rf where rf.reportFileType = :reportFileType"; Map<String, Object> params = new HashMap<String, Object>(); params.put("reportFileType", reportFileType); List<PtReportFile> boList = DaoUtil.find(hql, params); if(CollectionUtils.isNotEmpty(boList)){ return boList.get(0).getFileNoType(); } return null; } }
gpl-2.0
IFT8/JavaSE
expert/designPattern/proxy/dynamicProxy/cglibProxy/ProxyTest.java
459
package expert.designPattern.proxy.dynamicProxy.cglibProxy; import org.testng.annotations.Test; /** * Created by IFT8 * on 2015/8/17. */ public class ProxyTest { @Test public void test() { DaoProxy daoProxy = new DaoProxy(new Dao(), new Transaction()); //可以不用接口 返回的是子类 Dao dao = (Dao) daoProxy.creatProxy(); dao.add(); dao.del(); dao.update(); dao.read(); } }
gpl-2.0
Piski/VariousSmallProjects
Exercises/Exercises/src/com/designpatterns/decorator/exercise2/Decorator.java
343
package com.designpatterns.decorator.exercise2; public abstract class Decorator implements Icecream { protected Icecream decoratedIcecream; public Decorator(Icecream decoratedIcecream) { this.decoratedIcecream = decoratedIcecream; } @Override public abstract double getCost(); @Override public abstract String getDescription(); }
gpl-2.0
Daniel-Dos/SpringFrameworkTutorial
Spring-Annotation-Based Configuration/QualifierAnnotation/src/com/tutorialspoint/springframework/annotation/qualifier/MainApp.java
527
package com.tutorialspoint.springframework.annotation.qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author daniel * Daniel-Dos * daniel.dias.analistati@gmail.com */ public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Profile profile = (Profile) context.getBean("profile"); profile.printAge(); profile.printName(); } }
gpl-2.0
Nikesh-Masiwal/Materialgram
app/src/main/java/workingsaturdays/com/materialgram/MainActivity.java
5350
package workingsaturdays.com.materialgram; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.ImageButton; import android.widget.ImageView; import butterknife.Bind; import butterknife.ButterKnife; import workingsaturdays.com.materialgram.activity.CommentsActivity; import workingsaturdays.com.materialgram.adapters.FeedAdapter; public class MainActivity extends AppCompatActivity implements FeedAdapter.OnFeedItemClickListner { @Bind(R.id.rvFeed)RecyclerView rvFeed; @Bind(R.id.toolbar)Toolbar toolbar; @Bind(R.id.ivLogo)ImageView ivLogo; @Bind(R.id.btnCreate)ImageButton btnCreate; private FeedAdapter feedAdapter; private MenuItem inboxMenuItem; private boolean pendingIntroAnimation = true; private static final int ANIM_DURATION_TOOLBAR = 300; private static final int ANIM_DURATION_FAB = 400; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setupToolbar(); setupFeed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); inboxMenuItem = menu.findItem(R.id.action_inbox); inboxMenuItem.setActionView(R.layout.menu_item_view); if (pendingIntroAnimation) { pendingIntroAnimation = false; startIntroAnimation(); } return true; } private void setupToolbar() { setSupportActionBar(toolbar); toolbar.setNavigationIcon(R.drawable.ic_menu_white); } private void setupFeed() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this){ /** * <p>Returns the amount of extra space that should be laid out by LayoutManager. * By default, {@link LinearLayoutManager} lays out 1 extra page of * items while smooth scrolling and 0 otherwise. You can override this method to implement your * custom layout pre-cache logic.</p> * <p>Laying out invisible elements will eventually come with performance cost. On the other * hand, in places like smooth scrolling to an unknown location, this extra content helps * LayoutManager to calculate a much smoother scrolling; which improves user experience.</p> * <p>You can also use this if you are trying to pre-layout your upcoming views.</p> * * @param state * @return The extra space that should be laid out (in pixels). */ @Override protected int getExtraLayoutSpace(RecyclerView.State state) { return 700; } }; rvFeed.setLayoutManager(linearLayoutManager); feedAdapter = new FeedAdapter(this); feedAdapter.setOnFeedItemClickListener(this); rvFeed.setAdapter(feedAdapter); } private void startIntroAnimation() { btnCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.btn_fab_size)); int actionbarSize = Utils.dpToPx(56); toolbar.setTranslationY(-actionbarSize); ivLogo.setTranslationY(-actionbarSize); inboxMenuItem.getActionView().setTranslationY(-actionbarSize); toolbar.animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(300); ivLogo.animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(400); inboxMenuItem.getActionView().animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(500) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { startContentAnimation(); } }) .start(); } private void startContentAnimation() { btnCreate.animate() .translationY(0) .setInterpolator(new OvershootInterpolator(1.f)) .setStartDelay(300) .setDuration(ANIM_DURATION_FAB) .start(); feedAdapter.updateItems(); } @Override public void onCommentsClick(View v, int position) { final Intent intent = new Intent(this, CommentsActivity.class); //Get location on screen int[] startingLocation = new int[2]; v.getLocationOnScreen(startingLocation); intent.putExtra(CommentsActivity.ARG_DRAWING_START_LOCATION,startingLocation[1]); startActivity(intent); //Disable enter transition for new Acitvity overridePendingTransition(0, 0); } }
gpl-2.0
Iolaum/MrSmith
AdX/src/main/java/tau/tac/adx/report/demand/AdNetworkDailyNotification.java
3521
package tau.tac.adx.report.demand; import java.text.ParseException; import se.sics.isl.transport.TransportReader; import se.sics.isl.transport.TransportWriter; import se.sics.tasim.props.SimpleContent; import tau.tac.adx.demand.Campaign; import tau.tac.adx.demand.UserClassificationServiceAdNetData; /** * * @author Mariano Schain * */ public class AdNetworkDailyNotification extends SimpleContent { /** * */ public AdNetworkDailyNotification() { super(); } /** * */ private static final long serialVersionUID = -2893212570481112391L; /* user classification service data */ private int effectiveDay; private double serviceLevel; private double price; /* quality score data */ private double qualityScore; /* campaign allocation data */ private int campaignId; private String winner; private long costMillis; public AdNetworkDailyNotification(int effectiveDay, double serviceLevel, double price, double qualityScore, int campaignId, String winner, long costMillis) { this.effectiveDay = effectiveDay; this.serviceLevel = serviceLevel; this.price = price; this.qualityScore = qualityScore; this.campaignId = campaignId; this.winner = winner; this.costMillis = costMillis; } public AdNetworkDailyNotification( UserClassificationServiceAdNetData ucsData, Campaign campaign, double qualityScore, int date) { this.qualityScore = qualityScore; this.effectiveDay = date; if (ucsData != null) { this.serviceLevel = ucsData.getServiceLevel(); this.price = ucsData.getPrice(); } if (campaign != null) { this.campaignId = campaign.getId(); this.winner = campaign.getAdvertiser(); this.costMillis = campaign.getBudgetMillis(); } else { this.campaignId = 0; this.winner = "NONE"; this.costMillis = 0; } } public int getEffectiveDay() { return effectiveDay; } public double getServiceLevel() { return serviceLevel; } public double getPrice() { return price; } public double getQualityScore() { return qualityScore; } public int getCampaignId() { return campaignId; } public String getWinner() { return winner; } public long getCostMillis() { return costMillis; } public void zeroCost() { costMillis = 0; } @Override public void read(TransportReader reader) throws ParseException { if (isLocked()) { throw new IllegalStateException("locked"); } effectiveDay = reader.getAttributeAsInt("effectiveDay"); serviceLevel = reader.getAttributeAsDouble("serviceLevel"); price = reader.getAttributeAsDouble("price"); qualityScore = reader.getAttributeAsDouble("qualityScore"); campaignId = reader.getAttributeAsInt("campaignId"); winner = reader.getAttribute("winner"); costMillis = reader.getAttributeAsLong("costMillis"); super.read(reader); } @Override public void write(TransportWriter writer) { writer.attr("effectiveDay", effectiveDay) .attr("serviceLevel", serviceLevel).attr("price", price) .attr("qualityScore", qualityScore) .attr("campaignId", campaignId).attr("winner", winner) .attr("costMillis", costMillis); super.write(writer); } @Override public String getTransportName() { return getClass().getName(); } @Override public String toString() { return "AdNetworkDailyNotification [effectiveDay=" + effectiveDay + ", serviceLevel=" + serviceLevel + ", price=" + price + ", qualityScore=" + qualityScore + ", campaignId=" + campaignId + ", winner=" + winner + ", costMillis=" + costMillis + "]"; } }
gpl-2.0
angelazarquiel/programacion
UT3ControFlujo/src/condicionales/Ejercicio7b.java
1601
package condicionales; import java.util.Scanner; public class Ejercicio7b { public static void main(String[] args) { int ordenador; String juego_ordenador; // ordenador elige su juego ordenador = (int) (Math.random() * 3 + 1); if (ordenador==1) juego_ordenador="piedra"; else if (ordenador==2) juego_ordenador="papel"; else juego_ordenador="tijera"; // usuario elige su juego Scanner teclado = new Scanner (System.in); System.out.println("-- Juego Piedra/Papel/Tijera --"); System.out.println("¿Que sacas? [piedra, papel o tijera]"); String juego_usuario; juego_usuario=teclado.next(); juego_usuario=juego_usuario.toLowerCase(); System.out.println("Mi elección: " + juego_ordenador); // comprobar quien gana if ( !(juego_usuario.equals("piedra") || juego_usuario.equals("papel") || juego_usuario.equals("tijera")) ) { System.out.println("ERROR: no has escrito un juego correcto"); } else { if (juego_usuario.equals(juego_ordenador)) { System.out.println("¡¡EMPATE!!"); } else if (juego_usuario.equals("piedra") && juego_ordenador.equals("tijera") || juego_usuario.equals("papel") && juego_ordenador.equals("piedra") || juego_usuario.equals("tijera") && juego_ordenador.equals("papel")) { System.out.println("¡¡GANASTE!!"); } else System.out.println("¡¡PERDISTE!!"); } } }
gpl-2.0
naveenr58/write_optimization_column_store_on_mapreduce-
hdfs_tests/exp_select/prepare_files1.java
1213
package exp_select; import static java.lang.System.out; import java.io.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import basic.DataCreator; import basic.DataUpdator; public class prepare_files { public static void main(String[] args) throws IOException { String program_start_date_time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ssZ").format(Calendar.getInstance().getTime()); long start=System.currentTimeMillis(); // PrintWriter result_file= new PrintWriter(new FileWriter("data/result-selection.txt")); int num_lines = 15000000, double per = 0.1, //create update lists String update_file_name="data/update_"+per+".txt"; DataCreator.prepareUpdateList3(per, num_lines, update_file_name); out.println("\t update list created"); //update tbat //DataUpdator.updateTBAT(tbat_file_name, update_file_name); //out.println("\t tbat updated (unclean)"); //update bat //DataUpdator.updateBAT_BinarySearch(bat_file_name, update_file_name); //out.println("\t bat updated"); } long end=System.currentTimeMillis(); double elapsedTime=(end-start)/1000.0; out.println("Elapsed Time:"+elapsedTime+"s"); } }
gpl-2.0
intfloat/CoreNLP
src/edu/stanford/nlp/trees/TreebankLanguagePack.java
13596
package edu.stanford.nlp.trees; import edu.stanford.nlp.process.TokenizerFactory; import java.util.function.Function; import java.util.function.Predicate; import edu.stanford.nlp.international.morph.MorphoFeatureSpecification; import edu.stanford.nlp.ling.HasWord; import java.io.Serializable; /** * This interface specifies language/treebank specific information for a * Treebank, which a parser or other treebank user might need to know. * * Some of this is fixed for a (treebank,language) pair, but some of it * reflects feature extraction decisions, so it can be sensible to have * multiple implementations of this interface for the same * (treebank,language) pair. * * So far this covers punctuation, character encodings, and characters * reserved for label annotations. It should probably be expanded to * cover other stuff (unknown words?). * * Various methods in this class return arrays. You should treat them * as read-only, even though one cannot enforce that in Java. * * Implementations in this class do not call basicCategory() on arguments * before testing them, so if needed, you should explicitly call * basicCategory() yourself before passing arguments to these routines for * testing. * * This class should be able to be an immutable singleton. It contains * data on various things, but no state. At some point we should make it * a real immutable singleton. * * @author Christopher Manning * @version 1.1, Mar 2003 */ public interface TreebankLanguagePack extends Serializable { /** * Use this as the default encoding for Readers and Writers of * Treebank data. */ String DEFAULT_ENCODING = "UTF-8"; /** * Accepts a String that is a punctuation * tag name, and rejects everything else. * * @param str The string to check * @return Whether this is a punctuation tag */ boolean isPunctuationTag(String str); /** * Accepts a String that is a punctuation * word, and rejects everything else. * If one can't tell for sure (as for ' in the Penn Treebank), it * maks the best guess that it can. * * @param str The string to check * @return Whether this is a punctuation word */ boolean isPunctuationWord(String str); /** * Accepts a String that is a sentence end * punctuation tag, and rejects everything else. * * @param str The string to check * @return Whether this is a sentence final punctuation tag */ boolean isSentenceFinalPunctuationTag(String str); /** * Accepts a String that is a punctuation * tag that should be ignored by EVALB-style evaluation, * and rejects everything else. * Traditionally, EVALB has ignored a subset of the total set of * punctuation tags in the English Penn Treebank (quotes and * period, comma, colon, etc., but not brackets) * * @param str The string to check * @return Whether this is a EVALB-ignored punctuation tag */ boolean isEvalBIgnoredPunctuationTag(String str); /** * Return a filter that accepts a String that is a punctuation * tag name, and rejects everything else. * * @return The filter */ Predicate<String> punctuationTagAcceptFilter(); /** * Return a filter that rejects a String that is a punctuation * tag name, and accepts everything else. * * @return The filter */ Predicate<String> punctuationTagRejectFilter(); /** * Returns a filter that accepts a String that is a punctuation * word, and rejects everything else. * If one can't tell for sure (as for ' in the Penn Treebank), it * maks the best guess that it can. * * @return The Filter */ Predicate<String> punctuationWordAcceptFilter(); /** * Returns a filter that accepts a String that is not a punctuation * word, and rejects punctuation. * If one can't tell for sure (as for ' in the Penn Treebank), it * makes the best guess that it can. * * @return The Filter */ Predicate<String> punctuationWordRejectFilter(); /** * Returns a filter that accepts a String that is a sentence end * punctuation tag, and rejects everything else. * * @return The Filter */ Predicate<String> sentenceFinalPunctuationTagAcceptFilter(); /** * Returns a filter that accepts a String that is a punctuation * tag that should be ignored by EVALB-style evaluation, * and rejects everything else. * Traditionally, EVALB has ignored a subset of the total set of * punctuation tags in the English Penn Treebank (quotes and * period, comma, colon, etc., but not brackets) * * @return The Filter */ Predicate<String> evalBIgnoredPunctuationTagAcceptFilter(); /** * Returns a filter that accepts everything except a String that is a * punctuation tag that should be ignored by EVALB-style evaluation. * Traditionally, EVALB has ignored a subset of the total set of * punctuation tags in the English Penn Treebank (quotes and * period, comma, colon, etc., but not brackets) * * @return The Filter */ Predicate<String> evalBIgnoredPunctuationTagRejectFilter(); /** * Returns a String array of punctuation tags for this treebank/language. * * @return The punctuation tags */ String[] punctuationTags(); /** * Returns a String array of punctuation words for this treebank/language. * * @return The punctuation words */ String[] punctuationWords(); /** * Returns a String array of sentence final punctuation tags for this * treebank/language. The first in the list is assumed to be the most * basic one. * * @return The sentence final punctuation tags */ String[] sentenceFinalPunctuationTags(); /** * Returns a String array of sentence final punctuation words for * this treebank/language. * * @return The punctuation words */ String[] sentenceFinalPunctuationWords(); /** * Returns a String array of punctuation tags that EVALB-style evaluation * should ignore for this treebank/language. * Traditionally, EVALB has ignored a subset of the total set of * punctuation tags in the English Penn Treebank (quotes and * period, comma, colon, etc., but not brackets) * * @return Whether this is a EVALB-ignored punctuation tag */ String[] evalBIgnoredPunctuationTags(); /** * Return a GrammaticalStructureFactory suitable for this language/treebank. * * @return A GrammaticalStructureFactory suitable for this language/treebank */ GrammaticalStructureFactory grammaticalStructureFactory(); /** * Return a GrammaticalStructureFactory suitable for this language/treebank. * * @param puncFilter A filter which should reject punctuation words (as Strings) * @return A GrammaticalStructureFactory suitable for this language/treebank */ GrammaticalStructureFactory grammaticalStructureFactory(Predicate<String> puncFilter); /** * Return a GrammaticalStructureFactory suitable for this language/treebank. * * @param puncFilter A filter which should reject punctuation words (as Strings) * @param typedDependencyHF A HeadFinder which finds heads for typed dependencies * @return A GrammaticalStructureFactory suitable for this language/treebank */ GrammaticalStructureFactory grammaticalStructureFactory(Predicate<String> puncFilter, HeadFinder typedDependencyHF); /** * Whether or not we have typed dependencies for this language. If * this method returns false, a call to grammaticalStructureFactory * will cause an exception. */ boolean supportsGrammaticalStructures(); /** * Return the charset encoding of the Treebank. See * documentation for the <code>Charset</code> class. * * @return Name of Charset */ String getEncoding(); /** * Return a tokenizer factory which might be suitable for tokenizing text * that will be used with this Treebank/Language pair. This is for * real text of this language pair, not for reading stuff inside the * treebank files. * * @return A tokenizer */ TokenizerFactory<? extends HasWord> getTokenizerFactory(); /** * Return an array of characters at which a String should be * truncated to give the basic syntactic category of a label. * The idea here is that Penn treebank style labels follow a syntactic * category with various functional and crossreferencing information * introduced by special characters (such as "NP-SBJ=1"). This would * be truncated to "NP" by the array containing '-' and "=". <br> * Note that these are never deleted as the first character as a label * (so they are okay as one character tags, etc.), but only when * subsequent characters. * * @return An array of characters that set off label name suffixes */ char[] labelAnnotationIntroducingCharacters(); /** * Say whether this character is an annotation introducing * character. * * @param ch A char * @return Whether this char introduces functional annotations */ boolean isLabelAnnotationIntroducingCharacter(char ch); /** * Returns the basic syntactic category of a String by truncating * stuff after a (non-word-initial) occurrence of one of the * <code>labelAnnotationIntroducingCharacters()</code>. This * function should work on phrasal category and POS tag labels, * but needn't (and couldn't be expected to) work on arbitrary * Word strings. * * @param category The whole String name of the label * @return The basic category of the String */ String basicCategory(String category); /** * Returns the category for a String with everything following * the gf character (which may be language specific) stripped. * * @param category The String name of the label (may previously have had basic category called on it) * @return The String stripped of grammatical functions */ String stripGF(String category); /** * Returns a {@link Function Function} object that maps Strings to Strings according * to this TreebankLanguagePack's basicCategory method. * * @return the String-&gt;String Function object */ Function<String,String> getBasicCategoryFunction(); /** * Returns the syntactic category and 'function' of a String. * This normally involves truncating numerical coindexation * showing coreference, etc. By 'function', this means * keeping, say, Penn Treebank functional tags or ICE phrasal functions, * perhaps returning them as <code>category-function</code>. * * @param category The whole String name of the label * @return A String giving the category and function */ String categoryAndFunction(String category); /** * Returns a {@link Function Function} object that maps Strings to Strings according * to this TreebankLanguagePack's categoryAndFunction method. * * @return the String-&gt;String Function object */ Function<String,String> getCategoryAndFunctionFunction(); /** * Accepts a String that is a start symbol of the treebank. * * @param str The str to test * @return Whether this is a start symbol */ boolean isStartSymbol(String str); /** * Return a filter that accepts a String that is a start symbol * of the treebank, and rejects everything else. * * @return The filter */ Predicate<String> startSymbolAcceptFilter(); /** * Returns a String array of treebank start symbols. * * @return The start symbols */ String[] startSymbols(); /** * Returns a String which is the first (perhaps unique) start symbol * of the treebank, or null if none is defined. * * @return The start symbol */ String startSymbol(); /** * Returns the extension of treebank files for this treebank. * This should be passed as an argument to Treebank loading classes. * It might be "mrg" or "fid" or whatever. Don't include the period. * * @return the extension on files for this treebank */ String treebankFileExtension(); /** * Sets the grammatical function indicating character to gfCharacter. * * @param gfCharacter Sets the character in label names that sets of * grammatical function marking (from the phrase label). */ void setGfCharacter(char gfCharacter); /** Returns a TreeReaderFactory suitable for general purpose use * with this language/treebank. * * @return A TreeReaderFactory suitable for general purpose use * with this language/treebank. */ TreeReaderFactory treeReaderFactory(); /** Return a TokenizerFactory for Trees of this language/treebank. * * @return A TokenizerFactory for Trees of this language/treebank. */ TokenizerFactory<Tree> treeTokenizerFactory(); /** * The HeadFinder to use for your treebank. * * @return A suitable HeadFinder */ HeadFinder headFinder(); /** * The HeadFinder to use when making typed dependencies. * * @return A suitable HeadFinder */ HeadFinder typedDependencyHeadFinder(); /** * The morphological feature specification for the language. * * @return A language-specific MorphoFeatureSpecification */ MorphoFeatureSpecification morphFeatureSpec(); /** * Used for languages where an original Stanford Dependency * converter and a Universal Dependency converter exists. */ void setGenerateOriginalDependencies(boolean generateOriginalDependencies); /** * Used for languages where an original Stanford Dependency * converter and a Universal Dependency converter exists. */ boolean generateOriginalDependencies(); }
gpl-2.0
sarikamm/codemitts
IdeaProjects/Cormen/src/com/codemitts/chapter8/WaterJugs.java
8053
package com.codemitts.chapter8; import com.codemitts.ArrayUtils; import org.junit.Assert; import org.junit.Test; import java.util.Random; /** * Created by Sarika on 5/1/2015. * * 8-4 Water jugs * Suppose that you are given n red and n blue water jugs, all of different shapes and * sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, * for every red jug, there is a blue jug that holds the same amount of water, and vice * versa. * Your task is to find a grouping of the jugs into pairs of red and blue jugs that hold * the same amount of water. To do so, you may perform the following operation: pick * a pair of jugs in which one is red and one is blue, fill the red jug with water, and * then pour the water into the blue jug. This operation will tell you whether the red * or the blue jug can hold more water, or that they have the same volume. Assume * that such a comparison takes one time unit. Your goal is to find an algorithm that * makes a minimum number of comparisons to determine the grouping. Remember * that you may not directly compare two red jugs or two blue jugs. */ enum Color { Red, Blue } class Jug { private Color color; private int amt; public Jug(Color color, int amt) { this.color = color; this.amt = amt; } public static int compare(Jug j1, Jug j2) throws Exception { if (j1.color == j2.color) { throw new Exception("Cannot compare same color jugs"); } if (j1.amt == j2.amt) { return 0; } else if (j1.amt > j2.amt) { return 1; } else { return -1; } } public static boolean isGoodPair(Jug j1, Jug j2) { return (j1.amt == j2.amt); } public String getString() { return Integer.toString(amt)+"\t"; } } public class WaterJugs { @Test public void testPairUp1() throws Exception { int len = 10; Jug[] blueJugs = new Jug[len]; Jug[] redJugs = new Jug[len]; fillJugs(blueJugs, redJugs, len); randomize(blueJugs, len, 10); randomize(redJugs, len, 10); pairUp(blueJugs, redJugs, len); System.out.print("Blue: "); print(blueJugs); System.out.print("Red: "); print(redJugs); Assert.assertTrue(testPairUp(blueJugs, redJugs, len)); } @Test public void testPairUpFast1() throws Exception { int len = 10; Jug[] blueJugs = new Jug[len]; Jug[] redJugs = new Jug[len]; fillJugs(blueJugs, redJugs, len); randomize(blueJugs, len, 10); randomize(redJugs, len, 10); pairUpFast(blueJugs, redJugs, len); System.out.print("Blue: "); print(blueJugs); System.out.print("Red: "); print(redJugs); Assert.assertTrue(testPairUp(blueJugs, redJugs, len)); } @Test public void testPairUp2() throws Exception { int len = 100000; Jug[] blueJugs = new Jug[len]; Jug[] redJugs = new Jug[len]; fillJugs(blueJugs, redJugs, len); randomize(blueJugs, len, len); randomize(redJugs, len, len); long t1 = System.currentTimeMillis(); pairUp(blueJugs, redJugs, len); long t2 = System.currentTimeMillis(); System.out.println(t2-t1); Assert.assertTrue(testPairUp(blueJugs, redJugs, len)); } @Test public void testPairUpFast2() throws Exception { int len = 100000; Jug[] blueJugs = new Jug[len]; Jug[] redJugs = new Jug[len]; fillJugs(blueJugs, redJugs, len); randomize(blueJugs, len, len); randomize(redJugs, len, len); long t1 = System.currentTimeMillis(); pairUpFast(blueJugs, redJugs, len); long t2 = System.currentTimeMillis(); System.out.println(t2-t1); Assert.assertTrue(testPairUp(blueJugs, redJugs, len)); } private void print(Jug[] jugs) { for (int i = 0; i < jugs.length; i++) { System.out.print(jugs[i].getString()); } } private boolean testPairUp(Jug[] blueJugs, Jug[] redJugs, int len) { for (int i=0; i<len; i++) { if (!Jug.isGoodPair(blueJugs[i], redJugs[i])) { return false; } } return true; } private void randomize(Jug[] jugs, int len, int times) { Random r = new Random(System.currentTimeMillis()); int x,y; Jug temp; for (int i=0; i<times; i++) { x = r.nextInt(len); y = r.nextInt(len); temp = jugs[x]; jugs[x] = jugs[y]; jugs[y] = temp; } } private void fillJugs(Jug[] blueJugs, Jug[] redJugs, int len) { int[] amts = ArrayUtils.getRandom(len); for (int i=0; i<len; i++) { blueJugs[i] = new Jug(Color.Blue, amts[i]); redJugs[i] = new Jug(Color.Red, amts[i]); } } /** * Deterministic algorithm that uses O(n^2) comparisons to group the jugs into pairs * @param blueJugs * @param redJugs * @param len * @throws Exception */ public void pairUp(Jug[] blueJugs, Jug[] redJugs, int len) throws Exception { for (int i = 0; i < len; i++) { // find the right blue jug int j; for (j = i; j < len; j++) { if (Jug.compare(blueJugs[j],redJugs[i]) == 0) { break; } } if (j >= len) { throw new IllegalArgumentException("Cannot find 2 jugs of same amount of water. Inconsistent input."); } // swap if (j != i) { Jug temp = blueJugs[j]; blueJugs[j] = blueJugs[i]; blueJugs[i] = temp; } } } /** * Randomized algorithm whose expected number of comparisons is O(n log n) * @param blueJugs * @param redJugs * @param len * @throws Exception */ public void pairUpFast(Jug[] blueJugs, Jug[] redJugs, int len) throws Exception { pairUpFast(blueJugs, redJugs, 0, len-1); } private void pairUpFast(Jug[] blueJugs, Jug[] redJugs, int start, int end) throws Exception { if (start >= end) { return; } // parse red jugs Jug pivot = blueJugs[end]; int i,mid,cmp,same=-1; for (i=start,mid=start; i<=end; i++) { cmp = Jug.compare(redJugs[i], pivot); if (cmp == 0) { same = mid; } if (cmp <= 0) { // swap mid and i Jug temp = redJugs[i]; redJugs[i] = redJugs[mid]; redJugs[mid] = temp; mid++; } } mid--; if (same < 0) { throw new IllegalArgumentException("Cannot find 2 jugs of same amount of water. Inconsistent input."); } // swap same and mid Jug temp = redJugs[mid]; redJugs[mid] = redJugs[same]; redJugs[same] = temp; // parse blue jugs pivot = redJugs[mid]; same = -1; for (i=start,mid=start; i<=end; i++) { cmp = Jug.compare(blueJugs[i], pivot); if (cmp == 0) { same = mid; } if (cmp <= 0) { // swap mid and i temp = blueJugs[i]; blueJugs[i] = blueJugs[mid]; blueJugs[mid] = temp; mid++; } } mid--; if (same < 0) { throw new IllegalArgumentException("Cannot find 2 jugs of same amount of water. Inconsistent input."); } // swap same and mid temp = blueJugs[mid]; blueJugs[mid] = blueJugs[same]; blueJugs[same] = temp; // call pair up on sub arrays pairUpFast(blueJugs, redJugs, start, mid-1); pairUpFast(blueJugs, redJugs, mid+1, end); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/test/java/nio/channels/FileChannel/TryLock.java
3813
/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /** * @test * @bug 4486154 4495729 * @summary The FileChannel file locking */ import java.io.*; import java.nio.channels.*; import java.nio.*; /** * Testing FileChannel's locking methods. */ public class TryLock { public static void main(String[] args) throws Exception { test1(true, true); test1(false, true); test1(true, false); test1(false, false); test2(true, true); test2(false, true); test2(true, false); test2(false, false); test3(true, true); test3(false, true); test3(true, false); test3(false, false); } public static void test1(boolean shared, boolean trylock) throws Exception { File testFile = File.createTempFile("test1", null); testFile.deleteOnExit(); FileInputStream fis = new FileInputStream(testFile); FileChannel fc = fis.getChannel(); FileLock fl = null; try { if (trylock) fl = fc.tryLock(0, fc.size(), shared); else fl = fc.lock(0, fc.size(), shared); if (!shared) throw new RuntimeException("No exception thrown for test1"); } catch (NonWritableChannelException e) { if (shared) throw new RuntimeException("Exception thrown for wrong case test1"); } finally { if (fl != null) fl.release(); } } public static void test2(boolean shared, boolean trylock) throws Exception { File testFile = File.createTempFile("test2", null); testFile.deleteOnExit(); FileOutputStream fis = new FileOutputStream(testFile); FileChannel fc = fis.getChannel(); FileLock fl = null; try { if (trylock) fl = fc.tryLock(0, fc.size(), shared); else fl = fc.lock(0, fc.size(), shared); if (shared) throw new RuntimeException("No exception thrown for test2"); } catch (NonReadableChannelException e) { if (!shared) throw new RuntimeException("Exception thrown incorrectly for test2"); } finally { if (fl != null) fl.release(); } } public static void test3(boolean shared, boolean trylock) throws Exception { File testFile = File.createTempFile("test3", null); testFile.deleteOnExit(); RandomAccessFile fis = new RandomAccessFile(testFile, "rw"); FileChannel fc = fis.getChannel(); FileLock fl = null; if (trylock) fl = fc.tryLock(0, fc.size(), shared); else fl = fc.lock(0, fc.size(), shared); fl.release(); } }
gpl-2.0
USGS-CIDA/SOS
core/api/src/main/java/org/n52/sos/coding/OperationKey.java
3445
/** * Copyright (C) 2012-2014 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * 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. */ package org.n52.sos.coding; import org.n52.sos.util.Comparables; import com.google.common.base.Objects; /** * TODO JavaDoc * * @author Christian Autermann <c.autermann@52north.org> * * @since 4.0.0 */ public class OperationKey implements Comparable<OperationKey> { private final String service; private final String version; private final String operation; public OperationKey(String service, String version, String operation) { this.service = service; this.version = version; this.operation = operation; } public OperationKey(String service, String version, Enum<?> operation) { this(service, version, operation.name()); } public OperationKey(OperationKey key) { this(key.getService(), key.getVersion(), key.getOperation()); } public String getService() { return service; } public String getVersion() { return version; } public String getOperation() { return operation; } @Override public boolean equals(Object obj) { if (obj != null && getClass() == obj.getClass()) { final OperationKey o = (OperationKey) obj; return Objects.equal(getService(), o.getService()) && Objects.equal(getVersion(), o.getVersion()) && Objects.equal(getOperation(), o.getOperation()); } return false; } @Override public String toString() { return Objects.toStringHelper(getClass()).add("service", getService()).add("version", getVersion()) .add("operation", getOperation()).toString(); } @Override public int hashCode() { return Objects.hashCode(getClass().getName(), getService(), getVersion(), getOperation()); } public int getSimilarity(OperationKey key) { return this.equals(key) ? 0 : -1; } @Override public int compareTo(OperationKey other) { return Comparables.chain(other).compare(getService(), other.getService()) .compare(getVersion(), other.getVersion()).compare(getOperation(), other.getOperation()).result(); } }
gpl-2.0
jorgegalvez/funeralesmodernos
FunerariaEAR/FunerariaWAR/src/java/sv/com/fm/web/ui/recursohumano/PreparacionesEmpleadoMttoCtrl.java
10459
/* * ESTE COMPONENTE SE ENCUENTRA PROTEGIDO POR LAS LEYES DE DERECHOS DE AUTOR. * @author Carlos Godoy * 2016 */ package sv.com.fm.web.ui.recursohumano; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.event.InputEvent; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Comboitem; import org.zkoss.zul.Intbox; import org.zkoss.zul.Label; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Window; import sv.com.fm.business.dto.GenericResponse; import sv.com.fm.business.ejb.GestorPersonalBeanLocal; import sv.com.fm.business.ejb.UsuarioBeanLocal; import sv.com.fm.business.entity.Planilla; import sv.com.fm.business.entity.PlanillaDetalle; import sv.com.fm.business.exception.FmWebException; import sv.com.fm.business.exception.ServiceLocatorException; import sv.com.fm.business.util.Constants; import sv.com.fm.business.util.ServiceLocator; import sv.com.fm.web.ui.recursohumano.rendered.VariosComboItemRendered; import sv.com.fm.web.ui.util.BaseController; import sv.com.fm.web.ui.util.MensajeMultilinea; /** * * @author Carlos Godoy */ public class PreparacionesEmpleadoMttoCtrl extends BaseController { private static final long serialVersionUID = -6102616129515843465L; private static final transient Logger logger = Logger.getLogger(PreparacionesEmpleadoMttoCtrl.class.getCanonicalName()); //Componentes ZUL protected Window preparacionesEmpleadoMttoWindow; protected Label lblNombrePlanillaSelected; protected Combobox cmbEmpleadosPreparaciones; protected Button btnCerrarIngresoCantidadPreparaciones; protected Button btnRefrescarIngresoCantidadPreparaciones; protected Button btnGuardarIngresoCantidadPreparaciones; protected Intbox intCantidadPrepNormales; protected Intbox intCantidadPrepEmbalsamado; protected Intbox intCantidadPrepEnjabado; //Services private ServiceLocator serviceLocator; private GestorPersonalBeanLocal personalBean; private UsuarioBeanLocal usuarioBean; //Variables de Negocio private Planilla planillaSelected; private List<PlanillaDetalle> listaPlanillaDetalles; private PlanillaDetalle planillaDetalleSelected; public PreparacionesEmpleadoMttoCtrl() { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl]INIT"); try { serviceLocator = ServiceLocator.getInstance(); personalBean = serviceLocator.getService(Constants.JNDI_PERSONAL_FM_BEAN); usuarioBean = serviceLocator.getService(Constants.JNDI_USUARIOS_BEAN); } catch (ServiceLocatorException ex) { logger.log(Level.SEVERE, ex.getLocalizedMessage()); ex.printStackTrace(); } } public void onCreate$preparacionesEmpleadoMttoWindow(Event event) throws Exception { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][onCreate$preparacionesEmpleadoMttoWindow]"); try { doOnCreateCommon(this.preparacionesEmpleadoMttoWindow, event); MensajeMultilinea.doSetTemplate(); planillaSelected = null; if (this.args.containsKey("planillaSelected")) { planillaSelected = (Planilla) this.args.get("planillaSelected"); lblNombrePlanillaSelected.setValue(planillaSelected.getDescripcionPlanilla()); } llenarDatosCampos(); revisarEstadoComponentes(); preparacionesEmpleadoMttoWindow.doModal(); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage()); e.printStackTrace(); } } public void onChanging$cmbEmpleadosPreparaciones(ForwardEvent event) { logger.log(Level.INFO, "[GestionIngresosDescuentosCtrl][onChanging$cmbEmpleadosPreparaciones]"); try { listaPlanillaDetalles = null; InputEvent input = (InputEvent) event.getOrigin(); if (planillaSelected != null && StringUtils.isNotBlank(input.getValue())) { listaPlanillaDetalles = personalBean.obtenerPlanillasDetallesPorCriterio(planillaSelected.getCodigoPlanilla(), input.getValue(), Boolean.TRUE); } renderizarDatosPlanillaDetalle(); } catch (Exception e) { e.printStackTrace(); } } private void renderizarDatosPlanillaDetalle() { logger.log(Level.INFO, "[GestionIngresosDescuentosCtrl][renderizarDatosPlanillaDetalle]"); try { planillaDetalleSelected = null; if (listaPlanillaDetalles == null) { listaPlanillaDetalles = new ArrayList<PlanillaDetalle>(); } cmbEmpleadosPreparaciones.setModel(new ListModelList(listaPlanillaDetalles)); cmbEmpleadosPreparaciones.setItemRenderer(new VariosComboItemRendered()); llenarDatosCampos(); revisarEstadoComponentes(); } catch (Exception e) { e.printStackTrace(); } } public void onSelect$cmbEmpleadosPreparaciones(Event event) { logger.log(Level.INFO, "[GestionIngresosDescuentosCtrl][onChanging$cmbEmpleadosPreparaciones]"); Comboitem itm; try { planillaDetalleSelected = null; itm = cmbEmpleadosPreparaciones.getSelectedItem(); if (itm != null) { planillaDetalleSelected = (PlanillaDetalle) itm.getAttribute("data"); } llenarDatosCampos(); revisarEstadoComponentes(); } catch (Exception e) { e.printStackTrace(); } } private void llenarDatosCampos() { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][llenarDatosCampos]"); try { intCantidadPrepNormales.setValue(planillaDetalleSelected!=null?planillaDetalleSelected.getCantPreparacionNormal():null); intCantidadPrepEmbalsamado.setValue(planillaDetalleSelected!=null?planillaDetalleSelected.getCantPreparacionEmbalsam():null); intCantidadPrepEnjabado.setValue(planillaDetalleSelected!=null?planillaDetalleSelected.getCantPreparacionEnjabado():null); if(planillaDetalleSelected==null){ cmbEmpleadosPreparaciones.setValue(null); } } catch (Exception e) { e.printStackTrace(); } } private void revisarEstadoComponentes() { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][revisarEstadoComponentes]"); try { intCantidadPrepNormales.setReadonly(planillaDetalleSelected == null); intCantidadPrepEmbalsamado.setReadonly(planillaDetalleSelected == null); intCantidadPrepEnjabado.setReadonly(planillaDetalleSelected == null); btnRefrescarIngresoCantidadPreparaciones.setDisabled(planillaDetalleSelected == null); btnGuardarIngresoCantidadPreparaciones.setDisabled(planillaDetalleSelected == null); } catch (Exception e) { e.printStackTrace(); } } public void onClick$btnCerrarIngresoCantidadPreparaciones(Event event) { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][onClick$btnCerrarIngresoCantidadPreparaciones]"); try { this.preparacionesEmpleadoMttoWindow.onClose(); } catch (Exception e) { e.printStackTrace(); } } public void onClick$btnRefrescarIngresoCantidadPreparaciones(Event event) { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][onClick$btnRefrescarIngresoCantidadPreparaciones]"); try { listaPlanillaDetalles = null; renderizarDatosPlanillaDetalle(); } catch (Exception e) { e.printStackTrace(); } } public void onClick$btnGuardarIngresoCantidadPreparaciones(Event event) { logger.log(Level.INFO, "[PreparacionesEmpleadoMttoCtrl][onClick$btnGuardarIngresoCantidadPreparaciones]"); GenericResponse resp; try { if (planillaDetalleSelected == null) { throw new FmWebException(Constants.CODE_OPERATION_EXCEPTION, "Debe de seleccionar un empleado!!"); } if (intCantidadPrepNormales.getValue() == null) { throw new FmWebException(Constants.CODE_OPERATION_EXCEPTION, "Ingrese la cantidad de preparaciones normales!!"); } if (intCantidadPrepEmbalsamado.getValue() == null) { throw new FmWebException(Constants.CODE_OPERATION_EXCEPTION, "Ingrese la cantidad de preparaciones embalsamadas!!"); } if (intCantidadPrepEnjabado.getValue() == null) { throw new FmWebException(Constants.CODE_OPERATION_EXCEPTION, "Ingrese la cantidad de preparaciones enjabadas!!"); } planillaDetalleSelected.setCantPreparacionNormal(intCantidadPrepNormales.getValue()); planillaDetalleSelected.setCantPreparacionEmbalsam(intCantidadPrepEmbalsamado.getValue()); planillaDetalleSelected.setCantPreparacionEnjabado(intCantidadPrepEnjabado.getValue()); planillaDetalleSelected.setEstadoRegistro(Boolean.TRUE); planillaDetalleSelected.setFechaEvento(new Date()); planillaDetalleSelected.setCodigoEmpleadoUsuario(getUserLogin().getUsuario()); resp = usuarioBean.saveOrModifyEntity(planillaDetalleSelected, planillaDetalleSelected.getCodigoDetallePlanilla() == null);//Boolean.TRUE if (resp.getCodigoRespuesta().intValue() == Constants.CODE_OPERATION_OK.intValue()) { // if (resp.getObjeto() != null) { // planillaDetalleSelected = (PlanillaDetalle) resp.getObjeto(); // } MensajeMultilinea.show("Registro almacenado exitosamente!!", Constants.MENSAJE_TIPO_INFO); listaPlanillaDetalles = null; renderizarDatosPlanillaDetalle(); } else { MensajeMultilinea.show(resp.getMensajeRespuesta(), Constants.MENSAJE_TIPO_ERROR); } } catch (FmWebException fwe) { MensajeMultilinea.show(fwe.getMensaje(), Constants.MENSAJE_TIPO_ALERTA); } catch (Exception e) { e.printStackTrace(); } } }
gpl-2.0
lexaxa/Auction
src/main/java/com/govauction/entity/BaseEntity.java
257
package com.govauction.entity; /** * Author: Georgy Gobozov * Date: 21.04.13 */ public class BaseEntity { private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
gpl-2.0
vfmunhoz/MateriaRest
src/br/com/blogdofornias/rest/ListarProdutosREST.java
1357
package br.com.blogdofornias.rest; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import br.com.blogdofornias.bo.ProdutoBO; import br.com.blogdofornias.vo.Produto; @LocalBean @Stateless @Path(value="/ListarProdutos") public class ListarProdutosREST { @EJB private ProdutoBO produtoBO; public ListarProdutosREST() { } @GET @Path(value="/listarTodosProdutos") @Produces(MediaType.APPLICATION_JSON) public List<Produto> listarTodosProdutos() { return this.produtoBO.listarTodosProdutos(); } @GET @Path(value="/buscarProdutoPorID") @Produces(MediaType.APPLICATION_JSON) public Produto buscarProdutoPorID(@QueryParam("cod_prod") Integer codigoProduto) throws RestException { if(codigoProduto == null) { throw new RestException(10, "Parâmetro obrigatório nulo. [cod_prod]"); } return this.produtoBO.buscarProdutoPorID(codigoProduto); } @POST @Path(value="/buscarProdutoPorIDPost") @Produces(MediaType.APPLICATION_JSON) public Produto buscarProdutoPorIDPost(@FormParam("cod_prod") Integer codigoProduto) { return this.produtoBO.buscarProdutoPorID(codigoProduto); } }
gpl-2.0
meijmOrg/Repo-test
freelance-hr-worktop/src/java/com/yh/hr/worktop/facade/impl/TaskRecheckDisAgreeFlowFacade.java
1068
package com.yh.hr.worktop.facade.impl; import org.apache.commons.lang.StringUtils; import com.yh.hr.component.task.service.TaskNextService; import com.yh.hr.res.bt.dto.LinkDTO; import com.yh.hr.worktop.factory.TaskRecheckFactory; import com.yh.hr.worktop.util.TaskWorkTopConstants; import com.yh.platform.core.exception.ServiceException; /** * *@description 默认(审核、复核...)不同意业务工作台Facade实现 *@author liuhw *@created 2016-08-31 *@version 1.0 * */ public class TaskRecheckDisAgreeFlowFacade { /** * 不同意 * @param LinkDTO * @throws ServiceException */ public void submitRecheckDisAgree(LinkDTO linkDTO) throws ServiceException { linkDTO.setDefFlowExpressName(TaskWorkTopConstants.FLOW_EXPRESSION_KEY_CHECK); if(StringUtils.isEmpty(linkDTO.getDefFlowExpress())) { linkDTO.setDefFlowExpress(TaskWorkTopConstants.FLOW_EXPRESSION_VALUE_CHECK_N); } TaskNextService TaskNextService = TaskRecheckFactory.getBizNextWorktopService(linkDTO); TaskNextService.next(); } }
gpl-2.0
AdamHansrod/Graphr
DBAGraph/src/com/port/dbagraph/model/SQLResult.java
452
package com.port.dbagraph.model; public class SQLResult { private int moodleUsersCount; private int eventCount; public int getMoodleUsersCount() { return moodleUsersCount; } public void setMoodleUsersCount(int moodleUsersCount) { this.moodleUsersCount = moodleUsersCount; } public int getEventCount() { return eventCount; } public void setEventCount(int eventCount) { this.eventCount = eventCount; } }
gpl-2.0
tsdotca/dmclient
android/app/src/main/java/ca/theshrine/dmclient/activity/WelcomeActivity.java
875
package ca.theshrine.dmclient.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import ca.theshrine.dmclient.R; public class WelcomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); } @Override protected void onResume() { super.onResume(); // TODO: check list of recents to see what sessions we have TextView thing = (TextView)this.findViewById(R.id.recentSessionsTextLabel); thing.setText("No recent sessions."); } public void onFindNearbyGames(View view) { Intent intent = new Intent(this, LoadingActivity.class); this.startActivity(intent); } }
gpl-2.0
FreeCol/freecol
src/net/sf/freecol/common/networking/ScoutIndianSettlementMessage.java
4316
/** * Copyright (C) 2002-2022 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import javax.xml.stream.XMLStreamException; import net.sf.freecol.common.io.FreeColXMLReader; import net.sf.freecol.common.model.Ability; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Direction; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.MoveType; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.model.ServerPlayer; import net.sf.freecol.server.model.ServerUnit; /** * The message sent when scouting a native settlement. */ public class ScoutIndianSettlementMessage extends AttributeMessage { public static final String TAG = "scoutIndianSettlement"; private static final String DIRECTION_TAG = "direction"; private static final String UNIT_TAG = "unit"; /** * Create a new {@code ScoutIndianSettlementMessage} with the * supplied unit and direction. * * @param unit The {@code Unit} that is learning. * @param direction The {@code Direction} the unit is looking. */ public ScoutIndianSettlementMessage(Unit unit, Direction direction) { super(TAG, UNIT_TAG, unit.getId(), DIRECTION_TAG, String.valueOf(direction)); } /** * Create a new {@code ScoutIndianSettlementMessage} from a stream. * * @param game The {@code Game} this message belongs to. * @param xr The {@code FreeColXMLReader} to read from. * @exception XMLStreamException if the stream is corrupt. */ public ScoutIndianSettlementMessage(Game game, FreeColXMLReader xr) throws XMLStreamException { super(TAG, xr, UNIT_TAG, DIRECTION_TAG); } /** * {@inheritDoc} */ @Override public boolean currentPlayerMessage() { return true; } /** * {@inheritDoc} */ @Override public MessagePriority getPriority() { return Message.MessagePriority.NORMAL; } /** * {@inheritDoc} */ @Override public ChangeSet serverHandler(FreeColServer freeColServer, ServerPlayer serverPlayer) { final String unitId = getStringAttribute(UNIT_TAG); final String directionString = getStringAttribute(DIRECTION_TAG); ServerUnit unit; try { unit = serverPlayer.getOurFreeColGameObject(unitId, ServerUnit.class); } catch (Exception e) { return serverPlayer.clientError(e.getMessage()); } if (!unit.hasAbility(Ability.SPEAK_WITH_CHIEF)) { return serverPlayer.clientError("Unit lacks ability" + " to speak to chief: " + unitId); } Tile tile; try { tile = unit.getNeighbourTile(directionString); } catch (Exception e) { return serverPlayer.clientError(e.getMessage()); } IndianSettlement is = tile.getIndianSettlement(); if (is == null) { return serverPlayer.clientError("There is no native settlement at: " + tile.getId()); } MoveType type = unit.getMoveType(is.getTile()); if (type != MoveType.ENTER_INDIAN_SETTLEMENT_WITH_SCOUT) { return serverPlayer.clientError("Unable to enter " + is.getName() + ": " + type.whyIllegal()); } // Valid request, do the scouting. return igc(freeColServer) .scoutIndianSettlement(serverPlayer, unit, is); } }
gpl-2.0
SomeRandomPerson9/3DT
src/com/harry9137/api/scenes/Objects/logic/TextObject.java
1929
package com.harry9137.api.scenes.Objects.logic; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.UnicodeFont; public class TextObject extends GenericObject { private UnicodeFont font; String string; String objName; int x; int y; public TextObject(String string){ this.string = string; } public TextObject(UnicodeFont updatedFont, String string){ this.string = string; font = updatedFont; } public TextObject(String string, int updatedX, int updatedY){ this.string = string; x = updatedX; y = updatedY; } public TextObject(UnicodeFont updatedFont, String string, int updatedX, int updatedY){ this.string = string; x = updatedX; y = updatedY; font = updatedFont; } public TextObject(UnicodeFont updatedFont){ font = updatedFont; } public TextObject(UnicodeFont updatedFont, int updatedX, int updatedY){ font = updatedFont; x = updatedX; y = updatedY; } public TextObject(){ }; public void render(){ font.drawString(this.x, this.y, string); } public void render(int x, int y){ font.drawString(x, y, string); } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public String getString() { return string; } public void setString(String string) { this.string = string; } public UnicodeFont getFont() { return font; } public void setFont(UnicodeFont font) { this.font = font; } public String getObjName() { return objName; } public GenericObject setObjName(String objName) { this.objName = objName; return this; } }
gpl-2.0
cnicola/android-ormlite-sample
app/src/main/java/com/cnicola/sample/ormlite/Constants.java
117
package com.cnicola.sample.ormlite; public class Constants { public static final String EMPTY_STRING = ""; }
gpl-2.0
streamsupport/streamsupport
src/literal/java/java8/util/Maps2.java
20740
/* * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java8.util; import java.util.Map; import java.util.Map.Entry; /** * A place for the new Java 9 <a href="http://openjdk.java.net/jeps/269">JEP * 269</a> {@code "Unmodifiable Map Static Factory Methods"} in the {@link Map} * interface. * * <h2><a id="unmodifiable">Unmodifiable Maps</a></h2> * <p>The {@link Maps2#of() Maps2.of}, * {@link Maps2#ofEntries(Map.Entry...) Maps2.ofEntries}, and * {@link Maps2#copyOf Maps2.copyOf} * static factory methods provide a convenient way to create unmodifiable maps. * The {@code Map} * instances created by these methods have the following characteristics: * * <ul> * <li>They are <a href="./package-summary.html#unmodifiable"><i>unmodifiable</i></a>. Keys and values * cannot be added, removed, or updated. Calling any mutator method on the Map * will always cause {@code UnsupportedOperationException} to be thrown. * However, if the contained keys or values are themselves mutable, this may cause * the Map to behave inconsistently or its contents to appear to change. * <li>They disallow {@code null} keys and values. Attempts to create them with * {@code null} keys or values result in {@code NullPointerException}. * <li>They are serializable if all keys and values are serializable. * <li>They reject duplicate keys at creation time. Duplicate keys passed to a * static factory method result in {@code IllegalArgumentException}. * <li>The iteration order of mappings is unspecified and is subject to change. * <li>They are <a * href="package-summary.html#Value-based-Classes">value-based</a>. Callers * should make no assumptions about the identity of the returned instances. * Factories are free to create new instances or reuse existing ones. Therefore, * identity-sensitive operations on these instances (reference equality ( * {@code ==}), identity hash code, and synchronization) are unreliable and * should be avoided. * </ul> */ public final class Maps2 { /** * Returns an unmodifiable map containing zero mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @return an empty {@code Map} * * @since 9 */ public static <K, V> Map<K, V> of() { return Unmodifiable.Map0.instance(); } /** * Returns an unmodifiable map containing a single mapping. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the mapping's key * @param v1 the mapping's value * @return a {@code Map} containing the specified mapping * @throws NullPointerException if the key or the value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1) { return new Unmodifiable.Map1<K, V>(k1, v1); } /** * Returns an unmodifiable map containing two mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if the keys are duplicates * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2); } /** * Returns an unmodifiable map containing three mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3); } /** * Returns an unmodifiable map containing four mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4); } /** * Returns an unmodifiable map containing five mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); } /** * Returns an unmodifiable map containing six mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6); } /** * Returns an unmodifiable map containing seven mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7); } /** * Returns an unmodifiable map containing eight mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8); } /** * Returns an unmodifiable map containing nine mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @param k9 the ninth mapping's key * @param v9 the ninth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9); } /** * Returns an unmodifiable map containing ten mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @param k9 the ninth mapping's key * @param v9 the ninth mapping's value * @param k10 the tenth mapping's key * @param v10 the tenth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { return new Unmodifiable.MapN<K, V>(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10); } /** * Returns an unmodifiable map containing keys and values extracted from the given entries. * The entries themselves are not stored in the map. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * <p><b>API Note:</b><br> * It is convenient to create the map entries using the {@link Maps2#entry Maps2.entry()} method. * For example, * * <pre> * {@code * import static java.util.Maps.entry; * * Map<Integer,String> map = Maps2.ofEntries( * entry(1, "a"), * entry(2, "b"), * entry(3, "c"), * ... * entry(26, "z")); * }</pre> * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param entries {@code Map.Entry}s containing the keys and values from which the map is populated * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any entry, key, or value is {@code null}, or if * the {@code entries} array is {@code null} * * @see Maps2#entry Maps2.entry() * @since 9 */ public static <K, V> Map<K, V> ofEntries(Map.Entry<? extends K, ? extends V>... entries) { if (entries.length == 0) { // implicit null check of entries array return Unmodifiable.Map0.instance(); } else if (entries.length == 1) { // implicit null check of the array slot return new Unmodifiable.Map1<K, V>(entries[0].getKey(), entries[0].getValue()); } else { Object[] kva = new Object[entries.length << 1]; int a = 0; for (Map.Entry<? extends K, ? extends V> entry : entries) { // implicit null checks of each array slot kva[a++] = entry.getKey(); kva[a++] = entry.getValue(); } return new Unmodifiable.MapN<K, V>(kva); } } /** * Returns an unmodifiable {@link Entry} containing the given key and value. * These entries are suitable for populating {@code Map} instances using the * {@link Maps2#ofEntries Maps2.ofEntries()} method. * The {@code Entry} instances created by this method have the following characteristics: * * <ul> * <li>They disallow {@code null} keys and values. Attempts to create them using a {@code null} * key or value result in {@code NullPointerException}. * <li>They are unmodifiable. Calls to {@link Map.Entry#setValue Entry.setValue()} * on a returned {@code Entry} result in {@code UnsupportedOperationException}. * <li>They are not serializable. * <li>They are <a href="package-summary.html#Value-based-Classes">value-based</a>. * Callers should make no assumptions about the identity of the returned instances. * This method is free to create new instances or reuse existing ones. Therefore, * identity-sensitive operations on these instances (reference equality ({@code ==}), * identity hash code, and synchronization) are unreliable and should be avoided. * </ul> * * <p><b>API Note:</b><br> * For a serializable {@code Entry}, see {@link java.util.AbstractMap.SimpleEntry} or * {@link java.util.AbstractMap.SimpleImmutableEntry}. * * @param <K> the key's type * @param <V> the value's type * @param k the key * @param v the value * @return an {@code Entry} containing the specified key and value * @throws NullPointerException if the key or value is {@code null} * * @see Maps2#ofEntries Maps2.ofEntries() * @since 9 */ public static <K, V> Map.Entry<K, V> entry(K k, V v) { // KVHolder checks for nulls return new KVHolder<K, V>(k, v); } /** * Returns an <a href="#unmodifiable">unmodifiable Map</a> containing the entries * of the given Map. The given Map must not be null, and it must not contain any * null keys or values. If the given Map is subsequently modified, the returned * Map will not reflect such modifications. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param map the map from which entries are drawn, must be non-null * @return the new {@code Map} * @throws NullPointerException if map is null, or if it contains any null keys or values * @since 10 */ @SuppressWarnings({"unchecked"}) public static <K, V> Map<K, V> copyOf(Map<? extends K, ? extends V> map) { if (map instanceof Unmodifiable.AbstractImmutableMap) { return (Map<K, V>) map; } else { return (Map<K, V>) Maps2.ofEntries(map.entrySet().toArray(new Map.Entry[0])); } } private Maps2() { } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/frameworks/opt/ngin3d/java/com/mediatek/ngin3d/animation/PropertyAnimation.java
14888
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.ngin3d.animation; import android.util.Log; import com.mediatek.ngin3d.Actor; import com.mediatek.ngin3d.Color; import com.mediatek.ngin3d.Point; import com.mediatek.ngin3d.Property; import com.mediatek.ngin3d.Rotation; import com.mediatek.ngin3d.Scale; import com.mediatek.ngin3d.Stage; import com.mediatek.ngin3d.utils.Ngin3dException; /** * Used to animate a property of specified target from one value to another. */ public class PropertyAnimation extends BasicAnimation { private static final String TAG = "PropertyAnimation"; protected Actor mTarget; protected Property mProperty; // cached property key protected String mPropertyName; // cached property name protected Object[] mValues; private Interpolator mInterpolator; public PropertyAnimation() { // Do nothing } /** * Base class for all internal value interpolator. */ private abstract class Interpolator implements Alpha.Listener { public void onStarted() { PropertyAnimation.this.onStarted(); } public void onPaused() { PropertyAnimation.this.onPaused(); } public void onCompleted(int direction) { PropertyAnimation.this.onCompleted(direction); } } /** * Construct animation that modifies target property from specified start to end value. * * @param target Actor to modify * @param propertyName property name * @param values the first one should be start value and the second one is end value. */ public PropertyAnimation(Actor target, String propertyName, Object... values) { if (target == null) { throw new IllegalArgumentException("Target cannot be null"); } Property prop = target.getProperty(propertyName); if (prop == null) { throw new IllegalArgumentException("Cannot find property " + propertyName); } initialize(target, prop, values); } public PropertyAnimation(String propertyName, Object... values) { if (propertyName == null) { throw new IllegalArgumentException("Specify property name cannot be null"); } mPropertyName = propertyName; mValues = values; } public PropertyAnimation(Actor target, Property property, Object... values) { initialize(target, property, values); } public PropertyAnimation(Property property, Object... values) { if (property == null) { throw new IllegalArgumentException("Specify property cannot be null"); } mProperty = property; mValues = values; } private void initialize(Actor target, Property property, Object... values) { if (target == null) { throw new IllegalArgumentException("Target cannot be null"); } if (property == null) { throw new IllegalArgumentException("Specify property cannot be null"); } if (values.length < 2) { throw new IllegalArgumentException("Should specify at least two values"); } mProperty = property; mTarget = target; mValues = values; if (mValues[0] instanceof Float) { mInterpolator = new Interpolator() { float mStart = (Float) mValues[0]; float mEnd = (Float) mValues[1]; public void onAlphaUpdate(float progress) { if (progress <= 1) { float value = mStart + progress * (mEnd - mStart); mTarget.setValue(mProperty, value); } } }; } else if (mValues[0] instanceof Integer) { mInterpolator = new Interpolator() { int mStart = (Integer) mValues[0]; int mEnd = (Integer) mValues[1]; public void onAlphaUpdate(float progress) { if (progress <= 1) { int value = mStart + (int) (progress * (mEnd - mStart)); mTarget.setValue(mProperty, value); } } }; } else if (mValues[0] instanceof Point) { if (((Point) mValues[0]).isNormalized != ((Point)mValues[1]).isNormalized) { throw new IllegalArgumentException("Cannot animate between normalized and unnormalized position"); } mInterpolator = new Interpolator() { Point mStart = (Point) mValues[0]; Point mEnd = (Point) mValues[1]; Point mValue = new Point(mEnd); public void onAlphaUpdate(float progress) { if (progress <= 1) { mValue.set(mStart.x + progress * (mEnd.x - mStart.x), mStart.y + progress * (mEnd.y - mStart.y), mStart.z + progress * (mEnd.z - mStart.z)); mTarget.setValue(mProperty, mValue); } } }; } else if (mValues[0] instanceof Scale) { mInterpolator = new Interpolator() { Scale mStart = (Scale) mValues[0]; Scale mEnd = (Scale) mValues[1]; Scale mValue = new Scale(); public void onAlphaUpdate(float progress) { if (progress <= 1) { mValue.set(mStart.x + progress * (mEnd.x - mStart.x), mStart.y + progress * (mEnd.y - mStart.y), mStart.z + progress * (mEnd.z - mStart.z)); mTarget.setValue(mProperty, mValue); } } }; } else if (mValues[0] instanceof Color) { mInterpolator = new Interpolator() { Color mStart = (Color) mValues[0]; Color mEnd = (Color) mValues[1]; Color mValue = new Color(); public void onAlphaUpdate(float progress) { if (progress <= 1) { mValue.red = mStart.red + (int)(progress * (mEnd.red - mStart.red)); mValue.green = mStart.green + (int)(progress * (mEnd.green - mStart.green)); mValue.blue = mStart.blue + (int)(progress * (mEnd.blue - mStart.blue)); mValue.alpha = mStart.alpha + (int)(progress * (mEnd.alpha - mStart.alpha)); mTarget.setValue(mProperty, mValue); } } }; } else if (mValues[0] instanceof Rotation) { mInterpolator = new Interpolator() { Rotation mStart = (Rotation) mValues[0]; Rotation mEnd = (Rotation) mValues[1]; Rotation mValue = new Rotation(); public void onAlphaUpdate(float progress) { if (progress <= 1) { if (mEnd.getMode() == Rotation.MODE_XYZ_EULER) { float[] euler1 = mStart.getEulerAngles(); float[] euler2 = mEnd.getEulerAngles(); float x = euler1[0] + progress * (euler2[0] - euler1[0]); float y = euler1[1] + progress * (euler2[1] - euler1[1]); float z = euler1[2] + progress * (euler2[2] - euler1[2]); mValue.set(x, y, z); } else if (mEnd.getMode() == Rotation.MODE_AXIS_ANGLE) { float angle1 = mStart.getAxisAngle(); Point v1 = mStart.getAxis(); float angle2 = mEnd.getAxisAngle(); Point v2 = mEnd.getAxis(); mValue.set( v1.getX() + progress * (v2.getX() - v1.getX()), v1.getY() + progress * (v2.getY() - v1.getY()), v1.getZ() + progress * (v2.getZ() - v1.getZ()), angle1 + progress * (angle2 - angle1)); } mTarget.setValue(mProperty, mValue); if (mStart.getMode() != mEnd.getMode()) { Log.w(TAG, "Warning: mixed angle interpolation"); } } } }; } else if (mValues[0] instanceof Stage.Camera) { mInterpolator = new Interpolator() { Stage.Camera mStart = (Stage.Camera) mValues[0]; Stage.Camera mEnd = (Stage.Camera) mValues[1]; Stage.Camera mValue = new Stage.Camera(mStart.position, mStart.lookAt); public void onAlphaUpdate(float progress) { if (progress <= 1) { mValue.position.set( mStart.position.x + progress * (mEnd.position.x - mStart.position.x), mStart.position.y + progress * (mEnd.position.y - mStart.position.y), mStart.position.z + progress * (mEnd.position.z - mStart.position.z)); mValue.lookAt.set( mStart.lookAt.x + progress * (mEnd.lookAt.x - mStart.lookAt.x), mStart.lookAt.y + progress * (mEnd.lookAt.y - mStart.lookAt.y), mStart.lookAt.z + progress * (mEnd.lookAt.z - mStart.lookAt.z)); mTarget.setValue(mProperty, mValue); } } }; } else { throw new Ngin3dException("Property is not animatable"); } mAlpha.addListener(mInterpolator); } protected void onStarted() { mTarget.onAnimationStarted(mProperty.getName(), this); if ((mOptions & START_TARGET_WITH_INITIAL_VALUE) != 0) { if (getDirection() == FORWARD) { mTarget.setValue(mProperty, mValues[0]); } else { mTarget.setValue(mProperty, mValues[1]); } } } protected void onPaused() { mTarget.onAnimationStopped(mProperty.getName()); } protected void onCompleted(int direction) { if ((mOptions & Animation.BACK_TO_START_POINT_ON_COMPLETED) == 0) { if (direction == Timeline.FORWARD) { mTarget.setValue(mProperty, mValues[1]); } else { mTarget.setValue(mProperty, mValues[0]); } } else { if (direction == Timeline.FORWARD) { mTarget.setValue(mProperty, mValues[0]); } else { mTarget.setValue(mProperty, mValues[1]); } } } public String getPropertyName() { return mProperty.getName(); } public Object getStartValue() { return mValues[0]; } public Object getEndValue() { return mValues[1]; } @Override public Animation setTarget(Actor target) { if (target == null) { throw new IllegalArgumentException("Target cannot be null"); } if (mProperty == null && mPropertyName == null) { // It's impossible to go this line throw new IllegalArgumentException("Property and property name can not both null"); } else { // Need to remove old mInterpolator before changing target mAlpha.removeListener(mInterpolator); if (mPropertyName == null) { if (target.getProperty(mProperty.getName()) == null) { throw new IllegalArgumentException("The target has no property " + mProperty); } initialize(target, mProperty, mValues); } else { Property prop = target.getProperty(mPropertyName); if (prop == null) { throw new IllegalArgumentException("Cannot find property " + mPropertyName); } initialize(target, prop, mValues); } } return this; } @Override public Actor getTarget() { return mTarget; } /** * Clone the PropertyAnimation, value in each member of cloned animation is same of original one, except target. * Mew instance of PropertyAnimation has no target in default. * @return the cloned PropertyAnimation */ @Override public PropertyAnimation clone() { PropertyAnimation animation = (PropertyAnimation) super.clone(); animation.mTarget = null; return animation; } }
gpl-2.0
smarr/graal
graal/com.oracle.graal.word/src/com/oracle/graal/word/phases/WordTypeRewriterPhase.java
20461
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.word.phases; import static com.oracle.graal.api.meta.LocationIdentity.*; import java.lang.reflect.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.compiler.common.*; import com.oracle.graal.compiler.common.calc.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.HeapAccess.BarrierType; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.type.*; import com.oracle.graal.nodes.util.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.graph.*; import com.oracle.graal.word.*; import com.oracle.graal.word.Word.Opcode; import com.oracle.graal.word.Word.Operation; import com.oracle.graal.word.nodes.*; /** * Transforms all uses of the {@link Word} class into unsigned operations on {@code int} or * {@code long} values, depending on the word kind of the underlying platform. */ public class WordTypeRewriterPhase extends Phase { protected final MetaAccessProvider metaAccess; protected final SnippetReflectionProvider snippetReflection; protected final ConstantReflectionProvider constantReflection; protected final ResolvedJavaType wordBaseType; protected final ResolvedJavaType wordImplType; protected final ResolvedJavaType objectAccessType; protected final ResolvedJavaType barrieredAccessType; protected final Kind wordKind; public WordTypeRewriterPhase(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection, ConstantReflectionProvider constantReflection, Kind wordKind) { this.metaAccess = metaAccess; this.snippetReflection = snippetReflection; this.constantReflection = constantReflection; this.wordKind = wordKind; this.wordBaseType = metaAccess.lookupJavaType(WordBase.class); this.wordImplType = metaAccess.lookupJavaType(Word.class); this.objectAccessType = metaAccess.lookupJavaType(ObjectAccess.class); this.barrieredAccessType = metaAccess.lookupJavaType(BarrieredAccess.class); } @Override protected void run(StructuredGraph graph) { InferStamps.inferStamps(graph); for (Node n : graph.getNodes()) { if (n instanceof ValueNode) { changeToWord(graph, (ValueNode) n); } } for (Node node : graph.getNodes()) { rewriteNode(graph, node); } } /** * Change the stamp for word nodes from the object stamp ({@link WordBase} or anything extending * or implementing that interface) to the primitive word stamp. */ protected void changeToWord(StructuredGraph graph, ValueNode node) { if (isWord(node)) { if (node.isConstant()) { ConstantNode oldConstant = (ConstantNode) node; assert oldConstant.asJavaConstant().getKind() == Kind.Object; WordBase value = snippetReflection.asObject(WordBase.class, oldConstant.asJavaConstant()); ConstantNode newConstant = ConstantNode.forIntegerKind(wordKind, value.rawValue(), node.graph()); graph.replaceFloating(oldConstant, newConstant); } else { node.setStamp(StampFactory.forKind(wordKind)); } } } /** * Clean up nodes that are no longer necessary or valid after the stamp change, and perform * intrinsification of all methods called on word types. */ protected void rewriteNode(StructuredGraph graph, Node node) { if (node instanceof CheckCastNode) { rewriteCheckCast(graph, (CheckCastNode) node); } else if (node instanceof LoadFieldNode) { rewriteLoadField(graph, (LoadFieldNode) node); } else if (node instanceof AccessIndexedNode) { rewriteAccessIndexed(graph, (AccessIndexedNode) node); } else if (node instanceof MethodCallTargetNode) { rewriteInvoke(graph, (MethodCallTargetNode) node); } } /** * Remove casts between word types (which by now no longer have kind Object). */ protected void rewriteCheckCast(StructuredGraph graph, CheckCastNode node) { if (node.getKind() == wordKind) { node.replaceAtUsages(node.object()); graph.removeFixed(node); } } /** * Fold constant field reads, e.g. enum constants. */ protected void rewriteLoadField(StructuredGraph graph, LoadFieldNode node) { ConstantNode constant = node.asConstant(metaAccess, constantReflection, node.object()); if (constant != null) { node.replaceAtUsages(graph.unique(constant)); graph.removeFixed(node); } } /** * Change loads and stores of word-arrays. Since the element kind is managed by the node on its * own and not in the stamp, {@link #changeToWord} does not perform all necessary changes. */ protected void rewriteAccessIndexed(StructuredGraph graph, AccessIndexedNode node) { ResolvedJavaType arrayType = StampTool.typeOrNull(node.array()); /* * There are cases where the array does not have a known type yet, i.e., the type is null. * In that case we assume it is not a word type. */ if (arrayType != null && isWord(arrayType.getComponentType()) && node.elementKind() != wordKind) { /* * The elementKind of the node is a final field, and other information such as the stamp * depends on elementKind. Therefore, just create a new node and replace the old one. */ if (node instanceof LoadIndexedNode) { graph.replaceFixedWithFixed(node, graph.add(LoadIndexedNode.create(node.array(), node.index(), wordKind))); } else if (node instanceof StoreIndexedNode) { graph.replaceFixedWithFixed(node, graph.add(StoreIndexedNode.create(node.array(), node.index(), wordKind, ((StoreIndexedNode) node).value()))); } else { throw GraalInternalError.shouldNotReachHere(); } } } /** * Intrinsification of methods defined on the {@link Word} class that are annotated with * {@link Operation}. */ protected void rewriteInvoke(StructuredGraph graph, MethodCallTargetNode callTargetNode) { ResolvedJavaMethod targetMethod = callTargetNode.targetMethod(); final boolean isWordBase = wordBaseType.isAssignableFrom(targetMethod.getDeclaringClass()); final boolean isObjectAccess = objectAccessType.equals(targetMethod.getDeclaringClass()); final boolean isBarrieredAccess = barrieredAccessType.equals(targetMethod.getDeclaringClass()); if (!isWordBase && !isObjectAccess && !isBarrieredAccess) { /* * Not a method defined on WordBase or a subclass / subinterface, and not on * ObjectAccess and not on BarrieredAccess, so nothing to rewrite. */ return; } if (!callTargetNode.isStatic()) { assert callTargetNode.receiver().getKind() == wordKind : "changeToWord() missed the receiver " + callTargetNode.receiver(); assert wordImplType.isLinked(); targetMethod = wordImplType.resolveConcreteMethod(targetMethod, callTargetNode.invoke().getContextType()); } rewriteWordOperation(graph, callTargetNode, targetMethod); } protected void rewriteWordOperation(StructuredGraph graph, MethodCallTargetNode callTargetNode, ResolvedJavaMethod targetMethod) throws GraalInternalError { Invoke invoke = callTargetNode.invoke(); Operation operation = targetMethod.getAnnotation(Word.Operation.class); assert operation != null : targetMethod; NodeInputList<ValueNode> arguments = callTargetNode.arguments(); switch (operation.opcode()) { case NODE_CLASS: assert arguments.size() == 2; ValueNode left = arguments.get(0); ValueNode right = operation.rightOperandIsInt() ? toUnsigned(graph, arguments.get(1), Kind.Int) : fromSigned(graph, arguments.get(1)); ValueNode replacement = graph.addOrUnique(createBinaryNodeInstance(operation.node(), left, right)); if (replacement instanceof FixedWithNextNode) { graph.addBeforeFixed(invoke.asNode(), (FixedWithNextNode) replacement); } replace(invoke, replacement); break; case COMPARISON: assert arguments.size() == 2; replace(invoke, comparisonOp(graph, operation.condition(), arguments.get(0), fromSigned(graph, arguments.get(1)))); break; case NOT: assert arguments.size() == 1; replace(invoke, graph.unique(XorNode.create(arguments.get(0), ConstantNode.forIntegerKind(wordKind, -1, graph)))); break; case READ_POINTER: case READ_OBJECT: case READ_BARRIERED: { assert arguments.size() == 2 || arguments.size() == 3; Kind readKind = asKind(callTargetNode.returnType()); LocationNode location; if (arguments.size() == 2) { location = makeLocation(graph, arguments.get(1), readKind, ANY_LOCATION); } else { location = makeLocation(graph, arguments.get(1), readKind, arguments.get(2)); } replace(invoke, readOp(graph, arguments.get(0), invoke, location, operation.opcode())); break; } case READ_HEAP: { assert arguments.size() == 3; Kind readKind = asKind(callTargetNode.returnType()); LocationNode location = makeLocation(graph, arguments.get(1), readKind, ANY_LOCATION); BarrierType barrierType = snippetReflection.asObject(BarrierType.class, arguments.get(2).asJavaConstant()); replace(invoke, readOp(graph, arguments.get(0), invoke, location, barrierType, true)); break; } case WRITE_POINTER: case WRITE_OBJECT: case WRITE_BARRIERED: case INITIALIZE: { assert arguments.size() == 3 || arguments.size() == 4; Kind writeKind = asKind(targetMethod.getSignature().getParameterType(targetMethod.isStatic() ? 2 : 1, targetMethod.getDeclaringClass())); LocationNode location; if (arguments.size() == 3) { location = makeLocation(graph, arguments.get(1), writeKind, LocationIdentity.ANY_LOCATION); } else { location = makeLocation(graph, arguments.get(1), writeKind, arguments.get(3)); } replace(invoke, writeOp(graph, arguments.get(0), arguments.get(2), invoke, location, operation.opcode())); break; } case ZERO: assert arguments.size() == 0; replace(invoke, ConstantNode.forIntegerKind(wordKind, 0L, graph)); break; case FROM_UNSIGNED: assert arguments.size() == 1; replace(invoke, fromUnsigned(graph, arguments.get(0))); break; case FROM_SIGNED: assert arguments.size() == 1; replace(invoke, fromSigned(graph, arguments.get(0))); break; case TO_RAW_VALUE: assert arguments.size() == 1; replace(invoke, toUnsigned(graph, arguments.get(0), Kind.Long)); break; case FROM_OBJECT: assert arguments.size() == 1; WordCastNode objectToWord = graph.add(WordCastNode.objectToWord(arguments.get(0), wordKind)); graph.addBeforeFixed(invoke.asNode(), objectToWord); replace(invoke, objectToWord); break; case FROM_ARRAY: assert arguments.size() == 2; replace(invoke, graph.unique(ComputeAddressNode.create(arguments.get(0), arguments.get(1), StampFactory.forKind(wordKind)))); break; case TO_OBJECT: assert arguments.size() == 1; WordCastNode wordToObject = graph.add(WordCastNode.wordToObject(arguments.get(0), wordKind)); graph.addBeforeFixed(invoke.asNode(), wordToObject); replace(invoke, wordToObject); break; default: throw new GraalInternalError("Unknown opcode: %s", operation.opcode()); } } protected ValueNode fromUnsigned(StructuredGraph graph, ValueNode value) { return convert(graph, value, wordKind, true); } private ValueNode fromSigned(StructuredGraph graph, ValueNode value) { return convert(graph, value, wordKind, false); } protected ValueNode toUnsigned(StructuredGraph graph, ValueNode value, Kind toKind) { return convert(graph, value, toKind, true); } private static ValueNode convert(StructuredGraph graph, ValueNode value, Kind toKind, boolean unsigned) { if (value.getKind() == toKind) { return value; } if (toKind == Kind.Int) { assert value.getKind() == Kind.Long; return graph.unique(NarrowNode.create(value, 32)); } else { assert toKind == Kind.Long; assert value.getKind().getStackKind() == Kind.Int; if (unsigned) { return graph.unique(ZeroExtendNode.create(value, 64)); } else { return graph.unique(SignExtendNode.create(value, 64)); } } } /** * Create an instance of a binary node which is used to lower Word operations. This method is * called for all Word operations which are annotated with @Operation(node = ...) and * encapsulates the reflective allocation of the node. */ private static ValueNode createBinaryNodeInstance(Class<? extends ValueNode> nodeClass, ValueNode left, ValueNode right) { try { Method factory = nodeClass.getDeclaredMethod("create", ValueNode.class, ValueNode.class); return (ValueNode) factory.invoke(null, left, right); } catch (Throwable ex) { throw new GraalInternalError(ex).addContext(nodeClass.getName()); } } private ValueNode comparisonOp(StructuredGraph graph, Condition condition, ValueNode left, ValueNode right) { assert left.getKind() == wordKind && right.getKind() == wordKind; // mirroring gets the condition into canonical form boolean mirror = condition.canonicalMirror(); ValueNode a = mirror ? right : left; ValueNode b = mirror ? left : right; CompareNode comparison; if (condition == Condition.EQ || condition == Condition.NE) { comparison = IntegerEqualsNode.create(a, b); } else if (condition.isUnsigned()) { comparison = IntegerBelowNode.create(a, b); } else { comparison = IntegerLessThanNode.create(a, b); } ConstantNode trueValue = ConstantNode.forInt(1, graph); ConstantNode falseValue = ConstantNode.forInt(0, graph); if (condition.canonicalNegate()) { ConstantNode temp = trueValue; trueValue = falseValue; falseValue = temp; } ConditionalNode materialize = graph.unique(ConditionalNode.create(graph.unique(comparison), trueValue, falseValue)); return materialize; } protected LocationNode makeLocation(StructuredGraph graph, ValueNode offset, Kind readKind, ValueNode locationIdentity) { if (locationIdentity.isConstant()) { return makeLocation(graph, offset, readKind, snippetReflection.asObject(LocationIdentity.class, locationIdentity.asJavaConstant())); } return SnippetLocationNode.create(snippetReflection, locationIdentity, ConstantNode.forConstant(snippetReflection.forObject(readKind), metaAccess, graph), ConstantNode.forLong(0, graph), fromSigned(graph, offset), ConstantNode.forInt(1, graph), graph); } protected LocationNode makeLocation(StructuredGraph graph, ValueNode offset, Kind readKind, LocationIdentity locationIdentity) { return IndexedLocationNode.create(locationIdentity, readKind, 0, fromSigned(graph, offset), graph, 1); } protected ValueNode readOp(StructuredGraph graph, ValueNode base, Invoke invoke, LocationNode location, Opcode op) { assert op == Opcode.READ_POINTER || op == Opcode.READ_OBJECT || op == Opcode.READ_BARRIERED; final BarrierType barrier = (op == Opcode.READ_BARRIERED ? BarrierType.PRECISE : BarrierType.NONE); final boolean compressible = (op == Opcode.READ_OBJECT || op == Opcode.READ_BARRIERED); return readOp(graph, base, invoke, location, barrier, compressible); } protected ValueNode readOp(StructuredGraph graph, ValueNode base, Invoke invoke, LocationNode location, BarrierType barrierType, boolean compressible) { JavaReadNode read = graph.add(JavaReadNode.create(base, location, barrierType, compressible)); graph.addBeforeFixed(invoke.asNode(), read); /* * The read must not float outside its block otherwise it may float above an explicit zero * check on its base address. */ read.setGuard(BeginNode.prevBegin(invoke.asNode())); return read; } protected ValueNode writeOp(StructuredGraph graph, ValueNode base, ValueNode value, Invoke invoke, LocationNode location, Opcode op) { assert op == Opcode.WRITE_POINTER || op == Opcode.WRITE_OBJECT || op == Opcode.WRITE_BARRIERED || op == Opcode.INITIALIZE; final BarrierType barrier = (op == Opcode.WRITE_BARRIERED ? BarrierType.PRECISE : BarrierType.NONE); final boolean compressible = (op == Opcode.WRITE_OBJECT || op == Opcode.WRITE_BARRIERED); final boolean initialize = (op == Opcode.INITIALIZE); JavaWriteNode write = graph.add(JavaWriteNode.create(base, value, location, barrier, compressible, initialize)); write.setStateAfter(invoke.stateAfter()); graph.addBeforeFixed(invoke.asNode(), write); return write; } protected void replace(Invoke invoke, ValueNode value) { FixedNode next = invoke.next(); invoke.setNext(null); invoke.asNode().replaceAtPredecessor(next); invoke.asNode().replaceAtUsages(value); GraphUtil.killCFG(invoke.asNode()); } protected boolean isWord(ValueNode node) { return isWord(StampTool.typeOrNull(node)); } protected boolean isWord(ResolvedJavaType type) { return type != null && wordBaseType.isAssignableFrom(type); } protected Kind asKind(JavaType type) { if (type instanceof ResolvedJavaType && isWord((ResolvedJavaType) type)) { return wordKind; } else { return type.getKind(); } } }
gpl-2.0
ZDChuang/Info_Release_System
src/com/zdc/action/NewsAction.java
1726
package com.zdc.action; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.zdc.dto.NewsInfo; import com.zdc.model.News; import com.zdc.model.User; import com.zdc.service.Release; @Component("newsSubmit") @Scope("prototype") public class NewsAction extends ActionSupport implements ModelDriven<Object> { private static final long serialVersionUID = 8151960239812789250L; private Release ri; private NewsInfo info = new NewsInfo(); private News news = new News(); private User user; @Override public Object getModel() { return info; } @Override public String execute() throws Exception { info.setDate(getCurrentDate()); news.setType(info.getType()); news.setHead(info.getHead()); news.setContent(info.getContent()); news.setDate(info.getDate()); news.setIssueUser(info.getIssueUser()); if (news.getHead() != null && news.getHead().length() > 0 && news.getContent() != null && news.getContent().length() > 0 && news.getIssueUser() != null && ri.isSuccess(news)) { ri.saveNews(news); return "success"; } return "fail"; } private String getCurrentDate() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } public Release getRi() { return ri; } @Resource(name = "release") public void setRi(Release ri) { this.ri = ri; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
gpl-2.0
tommythorn/yari
shared/cacao-related/phoneme_feature/cldc/src/javaapi/cldc1.1/java/io/InputStream.java
15242
/* * * * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This 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 version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. */ package java.io; /** * This abstract class is the superclass of all classes representing * an input stream of bytes. * * <p> Applications that need to define a subclass of <code>InputStream</code> * must always provide a method that returns the next byte of input. * * @version 12/17/01 (CLDC 1.1) * @see java.io.ByteArrayInputStream * @see java.io.DataInputStream * @see java.io.InputStream#read() * @see java.io.OutputStream * @since JDK1.0, CLDC 1.0 */ public abstract class InputStream { /** * Reads the next byte of data from the input stream. The value byte is * returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the stream * has been reached, the value <code>-1</code> is returned. This method * blocks until input data is available, the end of the stream is detected, * or an exception is thrown. * * <p> A subclass must provide an implementation of this method. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception IOException if an I/O error occurs. */ public abstract int read() throws IOException; /** * Reads some number of bytes from the input stream and stores them into * the buffer array <code>b</code>. The number of bytes actually read is * returned as an integer. This method blocks until input data is * available, end of file is detected, or an exception is thrown. * * <p> If <code>b</code> is <code>null</code>, a * <code>NullPointerException</code> is thrown. If the length of * <code>b</code> is zero, then no bytes are read and <code>0</code> is * returned; otherwise, there is an attempt to read at least one byte. If * no byte is available because the stream is at end of file, the value * <code>-1</code> is returned; otherwise, at least one byte is read and * stored into <code>b</code>. * * <p> The first byte read is stored into element <code>b[0]</code>, the * next one into <code>b[1]</code>, and so on. The number of bytes read is, * at most, equal to the length of <code>b</code>. Let <i>k</i> be the * number of bytes actually read; these bytes will be stored in elements * <code>b[0]</code> through <code>b[</code><i>k</i><code>-1]</code>, * leaving elements <code>b[</code><i>k</i><code>]</code> through * <code>b[b.length-1]</code> unaffected. * * <p> If the first byte cannot be read for any reason other than end of * file, then an <code>IOException</code> is thrown. In particular, an * <code>IOException</code> is thrown if the input stream has been closed. * * <p> The <code>read(b)</code> method for class <code>InputStream</code> * has the same effect as: <pre><code> read(b, 0, b.length) </code></pre> * * @param b the buffer into which the data is read. * @return the total number of bytes read into the buffer, or * <code>-1</code> is there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte b[]) throws IOException { return read(b, 0, b.length); } /** * Reads up to <code>len</code> bytes of data from the input stream into * an array of bytes. An attempt is made to read as many as * <code>len</code> bytes, but a smaller number may be read, possibly * zero. The number of bytes actually read is returned as an integer. * * <p> This method blocks until input data is available, end of file is * detected, or an exception is thrown. * * <p> If <code>b</code> is <code>null</code>, a * <code>NullPointerException</code> is thrown. * * <p> If <code>off</code> is negative, or <code>len</code> is negative, or * <code>off+len</code> is greater than the length of the array * <code>b</code>, then an <code>IndexOutOfBoundsException</code> is * thrown. * * <p> If <code>len</code> is zero, then no bytes are read and * <code>0</code> is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of * file, the value <code>-1</code> is returned; otherwise, at least one * byte is read and stored into <code>b</code>. * * <p> The first byte read is stored into element <code>b[off]</code>, the * next one into <code>b[off+1]</code>, and so on. The number of bytes read * is, at most, equal to <code>len</code>. Let <i>k</i> be the number of * bytes actually read; these bytes will be stored in elements * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>, * leaving elements <code>b[off+</code><i>k</i><code>]</code> through * <code>b[off+len-1]</code> unaffected. * * <p> In every case, elements <code>b[0]</code> through * <code>b[off]</code> and elements <code>b[off+len]</code> through * <code>b[b.length-1]</code> are unaffected. * * <p> If the first byte cannot be read for any reason other than end of * file, then an <code>IOException</code> is thrown. In particular, an * <code>IOException</code> is thrown if the input stream has been closed. * * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method * for class <code>InputStream</code> simply calls the method * <code>read()</code> repeatedly. If the first such call results in an * <code>IOException</code>, that exception is returned from the call to * the <code>read(b,</code> <code>off,</code> <code>len)</code> method. If * any subsequent call to <code>read()</code> results in a * <code>IOException</code>, the exception is caught and treated as if it * were end of file; the bytes read up to that point are stored into * <code>b</code> and the number of bytes read before the exception * occurred is returned. Subclasses are encouraged to provide a more * efficient implementation of this method. * * @param b the buffer into which the data is read. * @param off the start offset in array <code>b</code> * at which the data is written. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. * @see java.io.InputStream#read() */ public int read(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } int c = read(); if (c == -1) { return -1; } b[off] = (byte)c; int i = 1; try { for (; i < len ; i++) { c = read(); if (c == -1) { break; } if (b != null) { b[off + i] = (byte)c; } } } catch (IOException ee) { } return i; } /** * Skips over and discards <code>n</code> bytes of data from this input * stream. The <code>skip</code> method may, for a variety of reasons, end * up skipping over some smaller number of bytes, possibly <code>0</code>. * This may result from any of a number of conditions; reaching end of file * before <code>n</code> bytes have been skipped is only one possibility. * The actual number of bytes skipped is returned. If <code>n</code> is * negative, no bytes are skipped. * * <p> The <code>skip</code> method of <code>InputStream</code> creates a * byte array and then repeatedly reads into it until <code>n</code> bytes * have been read or the end of the stream has been reached. Subclasses are * encouraged to provide a more efficient implementation of this method. * * @param n the number of bytes to be skipped. * @return the actual number of bytes skipped. * @exception IOException if an I/O error occurs. */ public long skip(long n) throws IOException { long m = n; while (m > 0) { if (read() < 0) { break; } --m; } return n-m; } /** * Returns the number of bytes that can be read (or skipped over) from * this input stream without blocking by the next caller of a method for * this input stream. The next caller might be the same thread or * another thread. * * <p> The <code>available</code> method for class <code>InputStream</code> * always returns <code>0</code>. * * <p> This method should be overridden by subclasses. * * @return the number of bytes that can be read from this input stream * without blocking. * @exception IOException if an I/O error occurs. */ public int available() throws IOException { return 0; } /** * Closes this input stream and releases any system resources associated * with the stream. * * <p> The <code>close</code> method of <code>InputStream</code> does * nothing. * * @exception IOException if an I/O error occurs. */ public void close() throws IOException {} /** * Marks the current position in this input stream. A subsequent call to * the <code>reset</code> method repositions this stream at the last marked * position so that subsequent reads re-read the same bytes. * * <p> The <code>readlimit</code> arguments tells this input stream to * allow that many bytes to be read before the mark position gets * invalidated. * * <p> The general contract of <code>mark</code> is that, if the method * <code>markSupported</code> returns <code>true</code>, the stream somehow * remembers all the bytes read after the call to <code>mark</code> and * stands ready to supply those same bytes again if and whenever the method * <code>reset</code> is called. However, the stream is not required to * remember any data at all if more than <code>readlimit</code> bytes are * read from the stream before <code>reset</code> is called. * * <p> The <code>mark</code> method of <code>InputStream</code> does * nothing. * * @param readlimit the maximum limit of bytes that can be read before * the mark position becomes invalid. * @see java.io.InputStream#reset() */ public synchronized void mark(int readlimit) {} /** * Repositions this stream to the position at the time the * <code>mark</code> method was last called on this input stream. * * <p> The general contract of <code>reset</code> is: * * <p><ul> * * <li> If the method <code>markSupported</code> returns * <code>true</code>, then: * * <ul><li> If the method <code>mark</code> has not been called since * the stream was created, or the number of bytes read from the stream * since <code>mark</code> was last called is larger than the argument * to <code>mark</code> at that last call, then an * <code>IOException</code> might be thrown. * * <li> If such an <code>IOException</code> is not thrown, then the * stream is reset to a state such that all the bytes read since the * most recent call to <code>mark</code> (or since the start of the * file, if <code>mark</code> has not been called) will be resupplied * to subsequent callers of the <code>read</code> method, followed by * any bytes that otherwise would have been the next input data as of * the time of the call to <code>reset</code>. </ul> * * <li> If the method <code>markSupported</code> returns * <code>false</code>, then: * * <ul><li> The call to <code>reset</code> may throw an * <code>IOException</code>. * * <li> If an <code>IOException</code> is not thrown, then the stream * is reset to a fixed state that depends on the particular type of the * input stream and how it was created. The bytes that will be supplied * to subsequent callers of the <code>read</code> method depend on the * particular type of the input stream. </ul></ul> * * <p> The method <code>reset</code> for class <code>InputStream</code> * does nothing and always throws an <code>IOException</code>. * * @exception IOException if this stream has not been marked or if the * mark has been invalidated. * @see java.io.InputStream#mark(int) * @see java.io.IOException */ public synchronized void reset() throws IOException { throw new IOException( /* #ifdef VERBOSE_EXCEPTIONS */ /// skipped "mark/reset not supported" /* #endif */ ); } /** * Tests if this input stream supports the <code>mark</code> and * <code>reset</code> methods. The <code>markSupported</code> method of * <code>InputStream</code> returns <code>false</code>. * * @return <code>true</code> if this true type supports the mark and reset * method; <code>false</code> otherwise. * @see java.io.InputStream#mark(int) * @see java.io.InputStream#reset() */ public boolean markSupported() { return false; } }
gpl-2.0
christianchristensen/resin
modules/resin/src/com/caucho/jsf/taglib/HtmlCommandButtonTag.java
3268
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.jsf.taglib; import java.io.*; import javax.el.*; import javax.faces.component.*; import javax.faces.component.html.*; import javax.faces.context.*; import javax.faces.event.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * The h:commandButton tag */ public class HtmlCommandButtonTag extends HtmlStyleBaseTag { private MethodExpression _action; private ActionListener _actionListener; private ValueExpression _label; private ValueExpression _immediate; public String getComponentType() { return HtmlCommandButton.COMPONENT_TYPE; } public String getRendererType() { return "javax.faces.Button"; } public void setAction(MethodExpression expr) { _action = expr; } public MethodExpression getAction() { return _action; } public ValueExpression getLabel() { return _label; } public void setLabel(ValueExpression label) { _label = label; } public ValueExpression getImmediate() { return _immediate; } public void setImmediate(ValueExpression immediate) { _immediate = immediate; } public void setActionListener(MethodExpression expr) { _actionListener = new MethodExpressionActionListener(expr); } /** * Sets the overridden properties of the tag */ @Override protected void setProperties(UIComponent component) { super.setProperties(component); UICommand command = (UICommand) component; if (_action != null) command.setActionExpression(_action); if (_label != null) command.setValueExpression("label", _label); if (_immediate != null) command.setValueExpression("immediate", _immediate); if (_actionListener != null) { ActionListener actionListener = null; for (ActionListener listener : command.getActionListeners()) { if (listener.equals(_actionListener)) { actionListener = listener; break; } } if (actionListener == null) command.addActionListener(_actionListener); } } @Override public void release() { _action = null; _actionListener = null; _label = null; _immediate = null; super.release(); } }
gpl-2.0
snoozesoftware/snoozecommon
src/main/java/org/inria/myriads/snoozecommon/communication/virtualcluster/monitoring/NetworkDemand.java
2309
/** * Copyright (C) 2010-2013 Eugen Feller, INRIA <eugen.feller@inria.fr> * * This file is part of Snooze, a scalable, autonomic, and * energy-aware virtual machine (VM) management framework. * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. */ package org.inria.myriads.snoozecommon.communication.virtualcluster.monitoring; import java.io.Serializable; /** * Network demand. * * @author Eugen Feller */ public final class NetworkDemand implements Serializable { /** Default serial. */ private static final long serialVersionUID = 1L; /** Rx byes. */ private double rxBytes_; /** Tx byes. */ private double txBytes_; /** Empty constructor. */ public NetworkDemand() { rxBytes_ = 0; txBytes_ = 0; } /** * Constructor. * * @param rxBytes The number of rxbytes * @param txBytes The number of txBytes */ public NetworkDemand(double rxBytes, double txBytes) { rxBytes_ = rxBytes; txBytes_ = txBytes; } /** * Sets the Rx bytes. * * @param rxBytes The Rx bytes */ public void setRxBytes(double rxBytes) { rxBytes_ = rxBytes; } /** * Sets the Tx bytes. * * @param txBytes The Tx bytes */ public void setTxBytes(double txBytes) { txBytes_ = txBytes; } /** * Returns the Rx bytes. * * @return The Rx byres */ public double getRxBytes() { return rxBytes_; } /** * Returns the Tx bytes. * * @return The Tx byres */ public double getTxBytes() { return txBytes_; } }
gpl-2.0
pablanco/taskManager
Android/FlexibleClient/src/com/artech/base/metadata/expressions/Expression.java
4540
package com.artech.base.metadata.expressions; import java.math.BigDecimal; import java.util.Date; import java.util.UUID; import com.artech.base.metadata.DataItem; import com.artech.base.metadata.theme.ThemeClassDefinition; import com.artech.base.model.Entity; import com.artech.base.model.EntityList; import com.artech.base.utils.Strings; import com.genexus.GXutil; public abstract class Expression { public abstract Value eval(IExpressionContext context); public enum Type { UNKNOWN, STRING, INTEGER, DECIMAL, BOOLEAN, DATE, DATETIME, TIME, GUID, CONTROL, ENTITY, ENTITY_COLLECTION; public boolean isNumeric() { return (this == DECIMAL || this == INTEGER); } public boolean isDateTime() { return (this == DATE || this == DATETIME || this == TIME); } public boolean isSimple() { return (this == STRING || this == INTEGER || this == DECIMAL || this == BOOLEAN || this == DATE || this == DATETIME || this == TIME || this == GUID); } } public static class Value { private final Object mValue; private final Type mType; private DataItem mDefinition; private String mPicture; public Value(Type type, Object value) { mType = type; mValue = value; } public static Value newValue(Object value) { if (value instanceof String) return newString((String)value); else if (value instanceof Integer) return newInteger((Integer)value); else if (value instanceof BigDecimal) return newDecimal((BigDecimal)value); else if (value instanceof Boolean) return newBoolean((Boolean)value); else if (value instanceof ThemeClassDefinition) return newString(((ThemeClassDefinition)value).getName()); // Because theme classes can be compared by equality on their names. else throw new IllegalArgumentException(String.format("Could not guess value type for '%s'.", value)); } public static Value newString(String value) { if (value == null) value = Strings.EMPTY; return new Value(Type.STRING, value); } public static Value newInteger(long value) { return new Value(Type.INTEGER, new BigDecimal(value)); } public static Value newDecimal(BigDecimal value) { return new Value(Type.DECIMAL, value); } public static Value newBoolean(boolean value) { return new Value(Type.BOOLEAN, value); } public static Value newEntity(Entity value) { return new Value(Type.ENTITY, value); } public static Value newEntityCollection(EntityList value) { return new Value(Type.ENTITY_COLLECTION, value); } public static Value newGuid(UUID value) { return new Value(Type.GUID, value); } @Override public String toString() { return String.format("[%s: %s]", mType, mValue); } public DataItem getDefinition() { return mDefinition; } public String getPicture() { if (!Strings.hasValue(mPicture)) mPicture = ExpressionFormatHelper.getDefaultPicture(this); return mPicture; } public void setDefinition(DataItem definition) { mDefinition = definition; mPicture = definition.getInputPicture(); } public void setPicture(String picture) { mPicture = picture; } public String coerceToString() { return mValue.toString(); } public BigDecimal coerceToNumber() { BigDecimal value = (BigDecimal)mValue; if (mType == Type.INTEGER) return new BigDecimal(value.longValue()); else return value; } public int coerceToInt() { return ((BigDecimal)mValue).intValue(); } public Boolean coerceToBoolean() { return (Boolean)mValue; } public Date coerceToDate() { Date value = (Date)mValue; if (mType == Type.DATE) return GXutil.resetTime(value); else if (mType == Type.TIME) return GXutil.resetDate(value); else return value; } public UUID coerceToGuid() { return (UUID)mValue; } public Entity coerceToEntity() { if (mValue instanceof EntityList && ((EntityList)mValue).size() != 0) return ((EntityList)mValue).get(0); return (Entity)mValue; } public EntityList coerceToEntityCollection() { return (EntityList)mValue; } public Type getType() { return mType; } public Object getValue() { return mValue; } public final static Value UNKNOWN = new Value(Type.UNKNOWN, null); } }
gpl-2.0
MosaicOwl/the-erder
The_Erder_Dedicated_New/src/ru/alastar/game/systems/gui/NetGUISystem.java
3579
package ru.alastar.game.systems.gui; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryonet.Connection; import ru.alastar.game.Entity; import ru.alastar.game.systems.gui.hadlers.TileButtonGUIHandler; import ru.alastar.main.Main; import ru.alastar.main.net.ConnectedClient; import ru.alastar.main.net.Server; import ru.alastar.main.net.requests.DropdownMenuRequest; import ru.alastar.main.net.responses.CloseGUIResponse; import ru.alastar.world.ServerTile; public class NetGUISystem { public static void sendGUIElement(NetGUIInfo info, ConnectedClient c) { Server.SendTo(c.connection, info); } public static NetGUIInfo CreateGUIInfo(String name, Vector2 position, Vector2 scale, String parentName, String elementClasspath, String variable, String text) { NetGUIInfo r = new NetGUIInfo(); r.name = name; r.position = position; r.parentName = parentName; r.scale = scale; r.text = text; r.variable = variable; r.elementClasspath = elementClasspath; return r; } // Main method, sending net gui public static void OpenGUI(NetGUIInfo info, ConnectedClient c) { c.controlledEntity.AddGUI(info); sendGUIElement(info, c); } public static void handleAnswer(NetGUIAnswer r, Connection connection) { ConnectedClient c = Server.getClient(connection); c.controlledEntity.invokeGUIHandler(r, c); } public static void handleDropRequest(DropdownMenuRequest r, Connection connection) { try { ConnectedClient c = Server.getClient(connection); if (r.type == 0) { if (c.controlledEntity.haveGUI("dropdown")) { c.controlledEntity.closeGUI("dropdown"); } String t = "nothing"; ServerTile tile = c.controlledEntity.world.GetTile((int) r.x, (int) r.y, (int) c.controlledEntity.z); if (tile != null) { t = tile.type.name(); NetGUISystem.OpenGUI(NetGUISystem.CreateGUIInfo("dropdown", new Vector2(r.x, r.y + tile.position.z), new Vector2(50, 50), "", "com.alastar.game.gui.GUIDropdown", "", "Tile(X:" + r.x + ",Y:" + r.y + ")"), c); NetGUISystem.OpenGUI(NetGUISystem.CreateGUIInfo( "tile_dropdown_info", new Vector2(r.x, r.y), new Vector2(50, 50), "dropdown", "com.alastar.game.gui.GUILabel", "", "Just " + t), c); c.controlledEntity.AddGUIHandler("dropdown", new TileButtonGUIHandler()); Main.Log("[DEBUG]", "Tile touch on " + r.x + " " + r.y); } } else if (r.type == 1) { Entity e = Server.getEntity(r.id); if (e != null) { e.ProcessDropdown(c); } } } catch (Exception e) { Server.handleError(e); } } public static void closeGUI(String string, Entity entity) { CloseGUIResponse r = new CloseGUIResponse(); r.name = string; Server.SendTo(Server.getClient(entity).connection, r); } }
gpl-2.0
cyberpython/java-gnome
src/bindings/org/gnome/gdk/InputSource.java
2485
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2007-2010 Operational Dynamics Consulting, Pty Ltd * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.gdk; import org.freedesktop.bindings.Constant; /* * FIXME this is a placeholder stub for what will become the public API for * this type. Replace this comment with appropriate javadoc including author * and since tags. Note that the class may need to be made abstract, implement * interfaces, or even have its parent changed. No API stability guarantees * are made about this class until it has been reviewed by a hacker and this * comment has been replaced. */ public final class InputSource extends Constant { private InputSource(int ordinal, String nickname) { super(ordinal, nickname); } }
gpl-2.0
AlvaroVega/TIDNamingJ
idl/.java/es/tid/corba/TIDNamingAdmin/AgentPackage/CannotProceed.java
603
// // CannotProceed.java (exception) // // File generated: Wed Jun 23 11:46:46 CEST 2010 // by TIDorb idl2java 1.3.11 // package es.tid.corba.TIDNamingAdmin.AgentPackage; final public class CannotProceed extends org.omg.CORBA.UserException { public java.lang.String why; public CannotProceed() { super(CannotProceedHelper.id()); } public CannotProceed(java.lang.String _why) { super(CannotProceedHelper.id()); this.why = _why; } public CannotProceed(String reason, java.lang.String _why) { super(CannotProceedHelper.id()+" "+reason); this.why = _why; } }
gpl-2.0
pezia/poker-croupier
player/java/src/main/java/com/devillsroom/poker/client/BetLimits.java
15153
/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.devillsroom.poker.client; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BetLimits implements org.apache.thrift.TBase<BetLimits, BetLimits._Fields>, java.io.Serializable, Cloneable, Comparable<BetLimits> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("BetLimits"); private static final org.apache.thrift.protocol.TField TO_CALL_FIELD_DESC = new org.apache.thrift.protocol.TField("to_call", org.apache.thrift.protocol.TType.I64, (short)1); private static final org.apache.thrift.protocol.TField MINIMUM_RAISE_FIELD_DESC = new org.apache.thrift.protocol.TField("minimum_raise", org.apache.thrift.protocol.TType.I64, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new BetLimitsStandardSchemeFactory()); schemes.put(TupleScheme.class, new BetLimitsTupleSchemeFactory()); } public long to_call; // required public long minimum_raise; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { TO_CALL((short)1, "to_call"), MINIMUM_RAISE((short)2, "minimum_raise"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // TO_CALL return TO_CALL; case 2: // MINIMUM_RAISE return MINIMUM_RAISE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __TO_CALL_ISSET_ID = 0; private static final int __MINIMUM_RAISE_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.TO_CALL, new org.apache.thrift.meta_data.FieldMetaData("to_call", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.MINIMUM_RAISE, new org.apache.thrift.meta_data.FieldMetaData("minimum_raise", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(BetLimits.class, metaDataMap); } public BetLimits() { } public BetLimits( long to_call, long minimum_raise) { this(); this.to_call = to_call; setTo_callIsSet(true); this.minimum_raise = minimum_raise; setMinimum_raiseIsSet(true); } /** * Performs a deep copy on <i>other</i>. */ public BetLimits(BetLimits other) { __isset_bitfield = other.__isset_bitfield; this.to_call = other.to_call; this.minimum_raise = other.minimum_raise; } public BetLimits deepCopy() { return new BetLimits(this); } @Override public void clear() { setTo_callIsSet(false); this.to_call = 0; setMinimum_raiseIsSet(false); this.minimum_raise = 0; } public long getTo_call() { return this.to_call; } public BetLimits setTo_call(long to_call) { this.to_call = to_call; setTo_callIsSet(true); return this; } public void unsetTo_call() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TO_CALL_ISSET_ID); } /** Returns true if field to_call is set (has been assigned a value) and false otherwise */ public boolean isSetTo_call() { return EncodingUtils.testBit(__isset_bitfield, __TO_CALL_ISSET_ID); } public void setTo_callIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TO_CALL_ISSET_ID, value); } public long getMinimum_raise() { return this.minimum_raise; } public BetLimits setMinimum_raise(long minimum_raise) { this.minimum_raise = minimum_raise; setMinimum_raiseIsSet(true); return this; } public void unsetMinimum_raise() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MINIMUM_RAISE_ISSET_ID); } /** Returns true if field minimum_raise is set (has been assigned a value) and false otherwise */ public boolean isSetMinimum_raise() { return EncodingUtils.testBit(__isset_bitfield, __MINIMUM_RAISE_ISSET_ID); } public void setMinimum_raiseIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MINIMUM_RAISE_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case TO_CALL: if (value == null) { unsetTo_call(); } else { setTo_call((Long)value); } break; case MINIMUM_RAISE: if (value == null) { unsetMinimum_raise(); } else { setMinimum_raise((Long)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case TO_CALL: return Long.valueOf(getTo_call()); case MINIMUM_RAISE: return Long.valueOf(getMinimum_raise()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case TO_CALL: return isSetTo_call(); case MINIMUM_RAISE: return isSetMinimum_raise(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof BetLimits) return this.equals((BetLimits)that); return false; } public boolean equals(BetLimits that) { if (that == null) return false; boolean this_present_to_call = true; boolean that_present_to_call = true; if (this_present_to_call || that_present_to_call) { if (!(this_present_to_call && that_present_to_call)) return false; if (this.to_call != that.to_call) return false; } boolean this_present_minimum_raise = true; boolean that_present_minimum_raise = true; if (this_present_minimum_raise || that_present_minimum_raise) { if (!(this_present_minimum_raise && that_present_minimum_raise)) return false; if (this.minimum_raise != that.minimum_raise) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(BetLimits other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetTo_call()).compareTo(other.isSetTo_call()); if (lastComparison != 0) { return lastComparison; } if (isSetTo_call()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.to_call, other.to_call); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMinimum_raise()).compareTo(other.isSetMinimum_raise()); if (lastComparison != 0) { return lastComparison; } if (isSetMinimum_raise()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.minimum_raise, other.minimum_raise); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("BetLimits("); boolean first = true; sb.append("to_call:"); sb.append(this.to_call); first = false; if (!first) sb.append(", "); sb.append("minimum_raise:"); sb.append(this.minimum_raise); first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class BetLimitsStandardSchemeFactory implements SchemeFactory { public BetLimitsStandardScheme getScheme() { return new BetLimitsStandardScheme(); } } private static class BetLimitsStandardScheme extends StandardScheme<BetLimits> { public void read(org.apache.thrift.protocol.TProtocol iprot, BetLimits struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // TO_CALL if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.to_call = iprot.readI64(); struct.setTo_callIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // MINIMUM_RAISE if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.minimum_raise = iprot.readI64(); struct.setMinimum_raiseIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, BetLimits struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(TO_CALL_FIELD_DESC); oprot.writeI64(struct.to_call); oprot.writeFieldEnd(); oprot.writeFieldBegin(MINIMUM_RAISE_FIELD_DESC); oprot.writeI64(struct.minimum_raise); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class BetLimitsTupleSchemeFactory implements SchemeFactory { public BetLimitsTupleScheme getScheme() { return new BetLimitsTupleScheme(); } } private static class BetLimitsTupleScheme extends TupleScheme<BetLimits> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, BetLimits struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetTo_call()) { optionals.set(0); } if (struct.isSetMinimum_raise()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetTo_call()) { oprot.writeI64(struct.to_call); } if (struct.isSetMinimum_raise()) { oprot.writeI64(struct.minimum_raise); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, BetLimits struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.to_call = iprot.readI64(); struct.setTo_callIsSet(true); } if (incoming.get(1)) { struct.minimum_raise = iprot.readI64(); struct.setMinimum_raiseIsSet(true); } } } }
gpl-2.0
TheRemixPvP/HexKits
src/me/theremixpvp/hexkits/cmds/HKCommand.java
6285
package me.theremixpvp.hexkits.cmds; import java.util.ArrayList; import java.util.List; import me.theremixpvp.hexkits.HexKits; import me.theremixpvp.hexkits.utils.KitConfigHandler; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class HKCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "Only players can use this command!"); return true; } Player p = (Player) sender; if(args.length == 0) { p.sendMessage(ChatColor.GOLD + "" + ChatColor.STRIKETHROUGH + " " + ChatColor.RESET + ChatColor.GOLD + "HexKits v" + HexKits.get().pdf.getVersion() + ChatColor.GOLD + "" + ChatColor.STRIKETHROUGH + " "); p.sendMessage(ChatColor.GOLD + "Plugin Created by: " + ChatColor.BOLD + HexKits.get().pdf.getAuthors().toString().replace("[", "").replace("]", "")); p.sendMessage(ChatColor.GOLD + "" + ChatColor.STRIKETHROUGH + " "); return true; } else if(args.length == 2) { if(args[0].equalsIgnoreCase("create")) { if(!p.hasPermission("hexkits.create")) { p.sendMessage(ChatColor.RED + "You do not have permission to create kits!"); return true; } String name = args[1]; if(KitConfigHandler.getInstance().kitExists(name)) { p.sendMessage(ChatColor.RED + "Kit already exists!"); return true; } FileConfiguration cfg = KitConfigHandler.getInstance().getConfig(); List<String> kits = cfg.getStringList("kitlist"); kits.add(name); cfg.set("kitlist", kits); ConfigurationSection ms = cfg.createSection("kits." + name); ConfigurationSection is = ms.createSection("items"); List<String> items = new ArrayList<String>(); for(ItemStack item : p.getInventory().getContents()) { if(item != null) { String finals = item.getType().name() + " " + item.getAmount(); if(item.getEnchantments().size() != 0) { for(Enchantment ench : item.getEnchantments().keySet()) { String ename = " " + ench.getName(); String lvl = " " + item.getEnchantmentLevel(ench); finals = finals + ename + lvl; } } items.add(finals); } } is.set("items", items); ConfigurationSection as = ms.createSection("armor"); if(p.getInventory().getHelmet() != null) { String helmet = p.getInventory().getHelmet().getType().name() + " " + p.getInventory().getHelmet().getAmount(); if(p.getInventory().getHelmet().getEnchantments().size() != 0) { for(Enchantment ench : p.getInventory().getHelmet().getEnchantments().keySet()) helmet = helmet + " " + ench.getName() + " " + p.getInventory().getHelmet().getEnchantmentLevel(ench); } as.set("helmet", helmet); } else as.set("helmet", null); if(p.getInventory().getChestplate() != null) { String chestplate = p.getInventory().getChestplate().getType().name() + " " + p.getInventory().getChestplate().getAmount(); if(p.getInventory().getChestplate().getEnchantments().size() != 0) { for(Enchantment ench : p.getInventory().getChestplate().getEnchantments().keySet()) chestplate = chestplate + " " + ench.getName() + " " + p.getInventory().getChestplate().getEnchantmentLevel(ench); } as.set("chestplate", chestplate); } else as.set("chestplate", null); if(p.getInventory().getLeggings() != null) { String leggings = p.getInventory().getLeggings().getType().name() + " " + p.getInventory().getLeggings().getAmount(); if(p.getInventory().getLeggings().getEnchantments().size() != 0) { for(Enchantment ench : p.getInventory().getLeggings().getEnchantments().keySet()) leggings = leggings + " " + ench.getName() + " " + p.getInventory().getLeggings().getEnchantmentLevel(ench); } as.set("leggings", leggings); } else as.set("leggings", null); if(p.getInventory().getBoots() != null) { String boots = p.getInventory().getBoots().getType().name() + " " + p.getInventory().getBoots().getAmount(); if(p.getInventory().getBoots().getEnchantments().size() != 0) { for(Enchantment ench : p.getInventory().getBoots().getEnchantments().keySet()) boots = boots + " " + ench.getName() + " " + p.getInventory().getBoots().getEnchantmentLevel(ench); } as.set("boots", boots); } else as.set("boots", null); List<String> pots = new ArrayList<String>(); for(PotionEffect pe : p.getActivePotionEffects()) { PotionEffectType type = pe.getType(); int time = pe.getDuration(); int power = pe.getAmplifier(); String finalp = type.getName() + " " + time + " " + power; pots.add(finalp); } ms.set("potions", pots); KitConfigHandler.getInstance().saveConfig(); p.sendMessage(ChatColor.AQUA + "Kit created!"); return true; } else if(args[0].equalsIgnoreCase("delete")) { if(!p.hasPermission("hexkits.delete")) { p.sendMessage(ChatColor.RED + "You do not have permission to delete kits!"); return true; } String name = args[1]; if(!KitConfigHandler.getInstance().kitExists(name)) { p.sendMessage(ChatColor.RED + "Kit doesn't exist!"); return true; } String fname = KitConfigHandler.getInstance().getKitName(name); FileConfiguration conf = KitConfigHandler.getInstance().getConfig(); List<String> kits = conf.getStringList("kitlist"); kits.remove(fname); conf.set("kitlist", kits); conf.set("kits." + fname, null); KitConfigHandler.getInstance().saveConfig(); p.sendMessage(ChatColor.AQUA + fname + " kit deleted!"); return true; } } unrecognizedCommand(p); return true; } private void unrecognizedCommand(Player p) { p.sendMessage(ChatColor.RED + "Unrecognized SimpleKits command!"); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest17369.java
2407
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest17369") public class BenchmarkTest17369 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { java.util.Map<String,String[]> map = request.getParameterMap(); String param = ""; if (!map.isEmpty()) { param = map.get("foo")[0]; } String bar = doSomething(param); try { java.io.FileInputStream fis = new java.io.FileInputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar); } catch (Exception e) { // OK to swallow any exception // TODO: Fix this. System.out.println("File exception caught and swallowed: " + e.getMessage()); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(1); // get the last 'safe' value return bar; } }
gpl-2.0
hmsiccbl/screensaver
core/src/main/java/edu/harvard/med/screensaver/model/screenresults/AnnotationType.java
11199
// $HeadURL$ // $Id$ // // Copyright © 2006, 2010, 2011, 2012 by the President and Fellows of Harvard College. // // Screensaver is an open-source project developed by the ICCB-L and NSRB labs // at Harvard Medical School. This software is distributed under the terms of // the GNU General Public License. package edu.harvard.med.screensaver.model.screenresults; import java.util.HashMap; import java.util.Map; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapKey; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import com.google.common.base.Function; import org.apache.log4j.Logger; import org.hibernate.annotations.OptimisticLock; import edu.harvard.med.screensaver.db.ScreenDAO; import edu.harvard.med.screensaver.model.AbstractEntity; import edu.harvard.med.screensaver.model.AbstractEntityVisitor; import edu.harvard.med.screensaver.model.annotations.ToMany; import edu.harvard.med.screensaver.model.libraries.Reagent; import edu.harvard.med.screensaver.model.meta.Cardinality; import edu.harvard.med.screensaver.model.meta.RelationshipPath; import edu.harvard.med.screensaver.model.screens.Screen; import edu.harvard.med.screensaver.model.screens.Study; /** * Annotation type on a reagent. * * @author <a mailto="andrew_tolopko@hms.harvard.edu">Andrew Tolopko</a> * @author <a mailto="john_sullivan@hms.harvard.edu">John Sullivan</a> */ @Entity @Table(uniqueConstraints={ @UniqueConstraint(columnNames={ "studyId", "name" }) }) @org.hibernate.annotations.Proxy @edu.harvard.med.screensaver.model.annotations.ContainedEntity(containingEntityClass=Screen.class) public class AnnotationType extends AbstractEntity<Integer> implements MetaDataType, Comparable<AnnotationType> { // private static data private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(AnnotationType.class); public static final RelationshipPath<AnnotationType> study = RelationshipPath.from(AnnotationType.class).to("study", Cardinality.TO_ONE); public static final RelationshipPath<AnnotationType> annotationValues = RelationshipPath.from(AnnotationType.class).to("annotationValues"); public static final Function<AnnotationType,String> ToName = new Function<AnnotationType,String>() { public String apply(AnnotationType entity) { return entity.getName(); } }; // private instance data private Integer _version; private Screen _study; private String _name; private String _description; private Integer _ordinal; private boolean _isNumeric; private Map<Reagent,AnnotationValue> _values = new HashMap<Reagent,AnnotationValue>(); // constructors /** * Construct an initialized <code>AnnotationType</code>. Intended only for use by {@link * Screen}. * @param study the study * @param name the name of the annotation type * @param description the description for the annotation type * @param ordinal the ordinal position of this <code>AnnotationType</code> within its * parent {@link Screen}. * @param isNumeric true iff this annotation type contains numeric result values */ public AnnotationType(Screen study, String name, String description, Integer ordinal, boolean isNumeric) { _study = study; _name = name; _description = description; _ordinal = ordinal; _isNumeric = isNumeric; //TODO: may have to lazily make this connection, re: large studies, [#2268] -sde4 _study.getAnnotationTypes().add(this); } // public instance methods @Override public Object acceptVisitor(AbstractEntityVisitor visitor) { return visitor.visit(this); } /** * Defines natural ordering of <code>AnnotationType</code> objects, based * upon their ordinal field value. Note that natural ordering is only defined * between <code>AnnotationType</code> objects that share the same parent * {@link Screen}. */ public int compareTo(AnnotationType that) { return getOrdinal().compareTo(that.getOrdinal()); } /** * Get the id for the annotation. * @return the id for the annotation type */ @Id @org.hibernate.annotations.GenericGenerator( name="annotation_type_id_seq", strategy="sequence", parameters = { @org.hibernate.annotations.Parameter(name="sequence", value="annotation_type_id_seq") } ) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="annotation_type_id_seq") public Integer getAnnotationTypeId() { return getEntityId(); } /** * Get the study. * @return the study */ @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="studyId", nullable=false, updatable=false) @org.hibernate.annotations.ForeignKey(name="fk_annotation_type_to_screen") @org.hibernate.annotations.LazyToOne(value=org.hibernate.annotations.LazyToOneOption.PROXY) public Screen getStudy() { return _study; } /** * Get the set of annotation values for this annotation type * @return the set of annotation values for this annotation type */ @OneToMany(fetch=FetchType.LAZY, cascade={ CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE }, mappedBy="annotationType") @ToMany(hasNonconventionalMutation=true /* model unit tests don't handle Maps yet, tested in AnnotationTypeTest#testAnnotationValues */) @MapKey(name="reagent") @OptimisticLock(excluded=true) @org.hibernate.annotations.Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE}) // removing, as this inconveniently forces us to access all reagents before looking for them in the map collection @org.hibernate.annotations.LazyCollection(LazyCollectionOption.EXTRA) public Map<Reagent,AnnotationValue> getAnnotationValues() { return _values; } public AnnotationValue createAnnotationValue( Reagent reagent, String value) { return createAnnotationValue(reagent, value, true); } /** * Create and return an annotation value for the annotation type. * * @param reagent the reagent * @param value the value * @param populateStudyReagentLink if set to false, the annotation value will be created without populating * the {@link Study#getReagents()} and the {@link Reagent#getStudies() } links. * if this is done, then {@ ScreenDAO#populateStudyReagentLinkTable(int) } must be called after creating the study. * @return the new annotation value */ public AnnotationValue createAnnotationValue( Reagent reagent, String value, boolean populateStudyReagentLink ) { if (_values.containsKey(reagent)) { AnnotationValue extantAnnotValue = _values.get(reagent); if (extantAnnotValue.getValue().equals(value)) { log.warn("duplicate annotation for " + reagent + " (ignoring duplicate)"); } else { log.error("conflicting annotations exist for " + reagent + " (fix this!)"); } return null; } AnnotationValue annotationValue = new AnnotationValue( this, reagent, value, _isNumeric && value != null ? new Double(value) : null); // lazily make this connection, re: large studies, [#2268] -sde4 if(populateStudyReagentLink) reagent.getAnnotationValues().put(this, annotationValue); // lazily make this connection, re: large studies, [#2268] -sde4 if(populateStudyReagentLink) getStudy().addReagent(reagent); _values.put(reagent, annotationValue); return annotationValue; } /** * Get the name of the annotation type. * @return the name of the annotation type */ @org.hibernate.annotations.Type(type="text") public String getName() { return _name; } /** * Set the name of the annotation type. * @param name the new name of the annotation type */ public void setName(String name) { _name = name; } /** * Get the description * @return the description */ @org.hibernate.annotations.Type(type="text") public String getDescription() { return _description; } /** * Set the description * @param description the new description */ public void setDescription(String description) { _description = description; } /** * Get the 0-based ordinal position of this <code>AnnotationType</code> within its * parent {@link Screen}. * @return the 0-based ordinal position */ @Column(nullable=false, updatable=false) public Integer getOrdinal() { return _ordinal; } /** * Return true iff this annotation type contains numeric result values. * @return true iff this annotation type contains numeric result values */ @Column(nullable=false, updatable=false, name="isNumeric") public boolean isNumeric() { return _isNumeric; } // protected constructor /** * Construct an uninitialized <code>AnnotationType</code>. * @motivation for hibernate and proxy/concrete subclass constructors */ protected AnnotationType() {} // private instance methods /** * Set the id for the annotation type. * @param annotationTypeId the new id for the annotation type * @motivation for hibernate */ private void setAnnotationTypeId(Integer annotationTypeId) { setEntityId(annotationTypeId); } /** * Get the version for the annotation type. * @return the version for the annotation type * @motivation for hibernate */ @Column(nullable=false) @Version private Integer getVersion() { return _version; } /** * Set the version for the annotation type. * @param version the new version for the annotation type * @motivation for hibernate */ private void setVersion(Integer version) { _version = version; } /** * Set the study. * @param study the new study * @motivation for hibernate */ private void setStudy(Screen study) { _study = study; } /** * Set the annotation values. * @param values the new set of annotation values */ private void setAnnotationValues(Map<Reagent,AnnotationValue> values) { _values = values; } /** * Set the ordinal position of this <code>AnnotationType</code> within its * parent {@link Screen}. * @param ordinal the ordinal position of this <code>AnnotationType</code> * within its parent {@link ScreenResult} * @motivation for Hibernate */ private void setOrdinal(Integer ordinal) { _ordinal = ordinal; } /** * Set the numericalness of this annotation type. * @param isNumeric the new numericalness of this annotation type */ private void setNumeric(boolean isNumeric) { _isNumeric = isNumeric; } public void clearAnnotationValues() { _values.clear(); } }
gpl-2.0
ohpauleez/soymacchiato
src/jdk/src/share/classes/java/lang/StringCoding.java
15819
/* * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; import java.io.UnsupportedEncodingException; import java.lang.ref.SoftReference; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CharacterCodingException; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import sun.misc.MessageUtils; import sun.nio.cs.HistoricallyNamedCharset; import sun.nio.cs.ArrayDecoder; import sun.nio.cs.ArrayEncoder; /** * Utility class for string encoding and decoding. */ class StringCoding { private StringCoding() { } /** The cached coders for each thread */ private final static ThreadLocal<SoftReference<StringDecoder>> decoder = new ThreadLocal<>(); private final static ThreadLocal<SoftReference<StringEncoder>> encoder = new ThreadLocal<>(); private static boolean warnUnsupportedCharset = true; private static <T> T deref(ThreadLocal<SoftReference<T>> tl) { SoftReference<T> sr = tl.get(); if (sr == null) return null; return sr.get(); } private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) { tl.set(new SoftReference<T>(ob)); } // Trim the given byte array to the given length // private static byte[] safeTrim(byte[] ba, int len, Charset cs, boolean isTrusted) { if (len == ba.length && (isTrusted || System.getSecurityManager() == null)) return ba; else return Arrays.copyOf(ba, len); } // Trim the given char array to the given length // private static char[] safeTrim(char[] ca, int len, Charset cs, boolean isTrusted) { if (len == ca.length && (isTrusted || System.getSecurityManager() == null)) return ca; else return Arrays.copyOf(ca, len); } private static int scale(int len, float expansionFactor) { // We need to perform double, not float, arithmetic; otherwise // we lose low order bits when len is larger than 2**24. return (int)(len * (double)expansionFactor); } private static Charset lookupCharset(String csn) { if (Charset.isSupported(csn)) { try { return Charset.forName(csn); } catch (UnsupportedCharsetException x) { throw new Error(x); } } return null; } private static void warnUnsupportedCharset(String csn) { if (warnUnsupportedCharset) { // Use sun.misc.MessageUtils rather than the Logging API or // System.err since this method may be called during VM // initialization before either is available. MessageUtils.err("WARNING: Default charset " + csn + " not supported, using ISO-8859-1 instead"); warnUnsupportedCharset = false; } } // -- Decoding -- private static class StringDecoder { private final String requestedCharsetName; private final Charset cs; private final CharsetDecoder cd; private final boolean isTrusted; private StringDecoder(Charset cs, String rcn) { this.requestedCharsetName = rcn; this.cs = cs; this.cd = cs.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); this.isTrusted = (cs.getClass().getClassLoader0() == null); } String charsetName() { if (cs instanceof HistoricallyNamedCharset) return ((HistoricallyNamedCharset)cs).historicalName(); return cs.name(); } final String requestedCharsetName() { return requestedCharsetName; } char[] decode(byte[] ba, int off, int len) { int en = scale(len, cd.maxCharsPerByte()); char[] ca = new char[en]; if (len == 0) return ca; if (cd instanceof ArrayDecoder) { int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca); return safeTrim(ca, clen, cs, isTrusted); } else { cd.reset(); ByteBuffer bb = ByteBuffer.wrap(ba, off, len); CharBuffer cb = CharBuffer.wrap(ca); try { CoderResult cr = cd.decode(bb, cb, true); if (!cr.isUnderflow()) cr.throwException(); cr = cd.flush(cb); if (!cr.isUnderflow()) cr.throwException(); } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen throw new Error(x); } return safeTrim(ca, cb.position(), cs, isTrusted); } } } static char[] decode(String charsetName, byte[] ba, int off, int len) throws UnsupportedEncodingException { StringDecoder sd = deref(decoder); String csn = (charsetName == null) ? "ISO-8859-1" : charsetName; if ((sd == null) || !(csn.equals(sd.requestedCharsetName()) || csn.equals(sd.charsetName()))) { sd = null; try { Charset cs = lookupCharset(csn); if (cs != null) sd = new StringDecoder(cs, csn); } catch (IllegalCharsetNameException x) {} if (sd == null) throw new UnsupportedEncodingException(csn); set(decoder, sd); } return sd.decode(ba, off, len); } static char[] decode(Charset cs, byte[] ba, int off, int len) { // (1)We never cache the "external" cs, the only benefit of creating // an additional StringDe/Encoder object to wrap it is to share the // de/encode() method. These SD/E objects are short-lifed, the young-gen // gc should be able to take care of them well. But the best approash // is still not to generate them if not really necessary. // (2)The defensive copy of the input byte/char[] has a big performance // impact, as well as the outgoing result byte/char[]. Need to do the // optimization check of (sm==null && classLoader0==null) for both. // (3)getClass().getClassLoader0() is expensive // (4)There might be a timing gap in isTrusted setting. getClassLoader0() // is only chcked (and then isTrusted gets set) when (SM==null). It is // possible that the SM==null for now but then SM is NOT null later // when safeTrim() is invoked...the "safe" way to do is to redundant // check (... && (isTrusted || SM == null || getClassLoader0())) in trim // but it then can be argued that the SM is null when the opertaion // is started... CharsetDecoder cd = cs.newDecoder(); int en = scale(len, cd.maxCharsPerByte()); char[] ca = new char[en]; if (len == 0) return ca; boolean isTrusted = false; if (System.getSecurityManager() != null) { if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) { ba = Arrays.copyOfRange(ba, off, off + len); off = 0; } } if (cd instanceof ArrayDecoder) { int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca); return safeTrim(ca, clen, cs, isTrusted); } else { cd.onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .reset(); ByteBuffer bb = ByteBuffer.wrap(ba, off, len); CharBuffer cb = CharBuffer.wrap(ca); try { CoderResult cr = cd.decode(bb, cb, true); if (!cr.isUnderflow()) cr.throwException(); cr = cd.flush(cb); if (!cr.isUnderflow()) cr.throwException(); } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen throw new Error(x); } return safeTrim(ca, cb.position(), cs, isTrusted); } } static char[] decode(byte[] ba, int off, int len) { String csn = Charset.defaultCharset().name(); try { return decode(csn, ba, off, len); } catch (UnsupportedEncodingException x) { warnUnsupportedCharset(csn); } try { return decode("ISO-8859-1", ba, off, len); } catch (UnsupportedEncodingException x) { // If this code is hit during VM initialization, MessageUtils is // the only way we will be able to get any kind of error message. MessageUtils.err("ISO-8859-1 charset not available: " + x.toString()); // If we can not find ISO-8859-1 (a required encoding) then things // are seriously wrong with the installation. System.exit(1); return null; } } // -- Encoding -- private static class StringEncoder { private Charset cs; private CharsetEncoder ce; private final String requestedCharsetName; private final boolean isTrusted; private StringEncoder(Charset cs, String rcn) { this.requestedCharsetName = rcn; this.cs = cs; this.ce = cs.newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); this.isTrusted = (cs.getClass().getClassLoader0() == null); } String charsetName() { if (cs instanceof HistoricallyNamedCharset) return ((HistoricallyNamedCharset)cs).historicalName(); return cs.name(); } final String requestedCharsetName() { return requestedCharsetName; } byte[] encode(char[] ca, int off, int len) { int en = scale(len, ce.maxBytesPerChar()); byte[] ba = new byte[en]; if (len == 0) return ba; if (ce instanceof ArrayEncoder) { int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba); return safeTrim(ba, blen, cs, isTrusted); } else { ce.reset(); ByteBuffer bb = ByteBuffer.wrap(ba); CharBuffer cb = CharBuffer.wrap(ca, off, len); try { CoderResult cr = ce.encode(cb, bb, true); if (!cr.isUnderflow()) cr.throwException(); cr = ce.flush(bb); if (!cr.isUnderflow()) cr.throwException(); } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen throw new Error(x); } return safeTrim(ba, bb.position(), cs, isTrusted); } } } static byte[] encode(String charsetName, char[] ca, int off, int len) throws UnsupportedEncodingException { StringEncoder se = deref(encoder); String csn = (charsetName == null) ? "ISO-8859-1" : charsetName; if ((se == null) || !(csn.equals(se.requestedCharsetName()) || csn.equals(se.charsetName()))) { se = null; try { Charset cs = lookupCharset(csn); if (cs != null) se = new StringEncoder(cs, csn); } catch (IllegalCharsetNameException x) {} if (se == null) throw new UnsupportedEncodingException (csn); set(encoder, se); } return se.encode(ca, off, len); } static byte[] encode(Charset cs, char[] ca, int off, int len) { CharsetEncoder ce = cs.newEncoder(); int en = scale(len, ce.maxBytesPerChar()); byte[] ba = new byte[en]; if (len == 0) return ba; boolean isTrusted = false; if (System.getSecurityManager() != null) { if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) { ca = Arrays.copyOfRange(ca, off, off + len); off = 0; } } if (ce instanceof ArrayEncoder) { int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba); return safeTrim(ba, blen, cs, isTrusted); } else { ce.onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .reset(); ByteBuffer bb = ByteBuffer.wrap(ba); CharBuffer cb = CharBuffer.wrap(ca, off, len); try { CoderResult cr = ce.encode(cb, bb, true); if (!cr.isUnderflow()) cr.throwException(); cr = ce.flush(bb); if (!cr.isUnderflow()) cr.throwException(); } catch (CharacterCodingException x) { throw new Error(x); } return safeTrim(ba, bb.position(), cs, isTrusted); } } static byte[] encode(char[] ca, int off, int len) { String csn = Charset.defaultCharset().name(); try { return encode(csn, ca, off, len); } catch (UnsupportedEncodingException x) { warnUnsupportedCharset(csn); } try { return encode("ISO-8859-1", ca, off, len); } catch (UnsupportedEncodingException x) { // If this code is hit during VM initialization, MessageUtils is // the only way we will be able to get any kind of error message. MessageUtils.err("ISO-8859-1 charset not available: " + x.toString()); // If we can not find ISO-8859-1 (a required encoding) then things // are seriously wrong with the installation. System.exit(1); return null; } } }
gpl-2.0
sengsational/cwhelper
CwHelperC/src/com/cwepg/build/BuildExeFromClassFiles.java
8315
/* * Created on Apr 30, 2021 * */ package com.cwepg.build; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Writer; import java.util.Date; import org.cwepg.hr.CaptureManager; public class BuildExeFromClassFiles { /** * * This class * 1) pulls the version from the source control system * 2) writes the version into the CwHelper_lib folder as "version.txt" * 3) updates the "version.txt" file inside of "cw_icons.jar" resource file * 4) packages the class files as an EXE file using Jar2Exe, creating CwHelper.exe * 5) zips the EXE file into CwHelper(version).zip (so it can be managed on a Google drive, that doesn't allow EXE files) * * Typically, the zip file would be uploaded. * Manually, Eclipse IDE "Make runnable jar" can also be run and that result uploaded. Manual addition of version in the file name is required. * */ public static void main(String[] args) throws Exception { String version = "5,0,0,"; String versionFileName = "version.txt"; String wDir = "C:\\my\\dev\\eclipsewrk\\CwHelper\\"; String wDirLib = wDir + "CwHelper_lib\\"; String revision = getRevision(); writeVersionToLibDirectory(version, revision, wDirLib + versionFileName); writeVersionToJarFile(version, revision, wDirLib + versionFileName, wDirLib + "cw_icons.jar"); String[] parms = { "C:\\Program Files (x86)\\Jar2Exe Wizard\\j2ewiz.exe", "/jar ", wDir + "classes", "/o", wDir + "CwHelper.exe", "/m", "org.cwepg.hr.ServiceLauncher", "/type","windows", "/minjre","1.6", "/platform","windows", "/checksum", "/embed", wDirLib + "commons-lang-2.6.jar", // "/embed", wDirLib + "commons-logging-1.1.3.jar", // "/embed", wDirLib + "cw_icons.jar", // "/embed", wDirLib + "hsqldb.jar", // "/embed", wDirLib + "jackcess-2.1.11.jar", // "/embed", wDirLib + "jna-5.7.0.jar", // "/embed", wDirLib + "jna-platform-5.7.0.jar", // "/embed", wDirLib + "mailapi.jar", // "/embed", wDirLib + "smtp.jar", // "/embed", wDirLib + "ucanaccess-4.0.4.jar", // "/embed", wDirLib + "httpclient-4.0.1.jar", // "/embed", wDirLib + "httpcore-4.0.1.jar", // "/icon", "#" + wDir + "Cw_EPG.exe, 0#", "/pv", "5,0,0,0", "/fv", "5,0,0," + revision, "/ve", "ProductVersion=5.0.0.0", "/ve", "ProductName=CW_EPG", "/ve", "#LegalCopyright=Copyright (c) 2008 - 2021#", "/ve", "#SpecialBuild=5, 0, 0, " + revision + "#", "/ve", "#FileDescription=Capture Manager#", "/ve", "FileVersion=5.0.0.*", "/ve", "OriginalFilename=CwHelper.exe", "/ve", "#Comments=Background Job for CW_EPG#", "/ve", "#CompanyName=CW_EPG Team# /ve #InternalName=5, 0, 0, 0#", "/ve", "#LegalTrademarks=CW_EPG Team#", "/splash", wDir + "CW_Logo.jpg", "/closeonwindow:false", "/splashtitle", "#Please wait ...#" }; //for (int i = 0; i < parms.length; i++) { // parms[i] = parms[i].replaceAll("#", "\""); // System.out.println("[" + parms[i] + "]"); //} if (buildClassesToExe(parms)) { ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\Android\\Android Studio\\jre\\bin\\jar.exe", "-cMfv", "CwHelper_5-0-0-" + revision + ".zip", "CwHelper.exe"); builder.directory(new File(wDir)); //ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\Java\\jdk1.8.0_66\\bin\\jar.exe", "-verbose"); builder.redirectErrorStream(true); Process process = builder.start(); InputStream is = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { System.out.println("output: [" + line + "]"); //if (line.contains("successfully")) processResult = true; } //Rename what we presume is the previously manually created "Runnable Jar" File runnableJarFile = new File(wDir + "CwHelper.jar"); if (runnableJarFile.renameTo(new File(wDir + "CwHelper_5-0-0-" + revision + ".jar"))) { System.out.println("CwHelper.jar renamed to CwHelper_5-0-0-" + revision + ".jar"); } else { System.out.println("Failed to rename CwHelper.jar"); } } else { System.out.println("Exe not created, so no attempt to zip being made."); } } private static void writeVersionToJarFile(String version, String revision, String versionFileName, String jarFileName) throws Exception { File[] contents = {new File(versionFileName)}; File jarFile = new File(jarFileName); try { JarUpdater.updateZipFile(jarFile, contents); } catch (IOException e) { e.printStackTrace(); } } private static void writeVersionToLibDirectory(String version, String revision, String versionFileName) { try { System.out.println(new Date() + " Saving to " + versionFileName); Writer writer = new FileWriter(versionFileName); writer.write(version + revision); writer.close(); } catch (Exception e) { System.err.println(new Date() + " ERROR: Could not save version file. " + e.getMessage()); e.printStackTrace(); } } private static boolean buildClassesToExe(String[] parms) throws Exception { boolean processResult = false; ProcessBuilder builder = new ProcessBuilder(parms); builder.redirectErrorStream(true); Process process = builder.start(); InputStream is = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { System.out.println("output: [" + line + "]"); if (line.contains("successfully")) processResult = true; } return processResult; } private static String getRevision() throws Exception { //https://stackoverflow.com/a/14915348/897007 ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\TortoiseSVN\\bin\\svn", "info", "svn://192.168.3.65/CwHelperB/src"); builder.redirectErrorStream(true); Process process = builder.start(); InputStream is = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String[] revision = {"Revision:","0"}; String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("Revision:")) { revision = line.split(":"); System.out.println("revision [" + revision[1].trim() + "]"); break; } } return revision[1].trim(); } }
gpl-2.0
camelCasee/OnlineShop
src/main/java/ru/ncedu/onlineshop/vaadin/componentlayouts/content/productlayouts/EditProductLayout.java
7437
package ru.ncedu.onlineshop.vaadin.componentlayouts.content.productlayouts; import com.vaadin.ui.Button; import com.vaadin.ui.Notification; import ru.ncedu.onlineshop.entity.product.Parameter; import ru.ncedu.onlineshop.entity.product.Product; import ru.ncedu.onlineshop.vaadin.componentlayouts.common.DoubleButtonsDialog; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.manufacturer.EditableManufacturerLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.name.EditableNameLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.price.EditablePriceLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.simpleparameter.SimpleParameterLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.simpleparameter.CreateSimpleParameterLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.simpleparameter.EditableSimpleParameterLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.size.EditableSizeLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.parameters.storage.EditableStorageLayout; import ru.ncedu.onlineshop.vaadin.componentlayouts.content.productgrouplyaouts.ProductListLayout; /** * Created by nikita on 06.02.15. */ public class EditProductLayout extends ProductLayout { protected CreateSimpleParameterLayout createParameterLayout; protected DoubleButtonsDialog doubleButtonsDialog; private ProductListLayout parent; public EditProductLayout(Product product, ProductListLayout productListLayout) { super(product); parent = productListLayout; fillLayoutWithComponents(); } private void fillLayoutWithComponents() { addNameLayout(); addPriceLayout(); addSizeLayout(); addManufacturerLayout(); addStorageLayout(); addNameLayoutClickListener(); addLayoutWithCreatingTheParameter(); addListOfProductParameterLayouts(); addLayoutWithDialogButtons(); } @Override protected void addNameLayout() { nameLayout = new EditableNameLayout(product.getName()); addComponent(nameLayout); } @Override protected void addPriceLayout() { priceLayout = new EditablePriceLayout(product.getPrice()); addComponent(priceLayout); } @Override protected void addSizeLayout() { sizeLayout = new EditableSizeLayout(product.getSize().getStringValue()); addComponent(sizeLayout); } @Override protected void addListOfProductParameterLayouts() { //parameterLayoutsList.add(new EditableParameterLayout("Manufacturer", product.getManufacturer().getStringValue())); for (Parameter parameter : product.getParameterList()) { final EditableSimpleParameterLayout parameterLayout = new EditableSimpleParameterLayout(parameter, this); parametersLayoutsList.add(parameterLayout); addComponent(parameterLayout); addDeleteParameterClickListener(parameterLayout); } } @Override protected void addManufacturerLayout() { manufacturerLayout = new EditableManufacturerLayout(product.getManufacturer()); addComponent(manufacturerLayout); } @Override protected void addStorageLayout() { storageLayout = new EditableStorageLayout(product.getProductStorage()); addComponent(storageLayout); } @Override protected void addNameLayoutClickListener() { // no need to add click listener parametersListIsVisible = true; // all parameters are always visible } private void addDeleteParameterClickListener(final EditableSimpleParameterLayout parameterLayout) { parameterLayout.getDeleteButton().addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { product.getParameterList().remove(parameterLayout.getParameter()); parametersLayoutsList.remove(parameterLayout); if (parametersListIsVisible) { EditProductLayout.this.removeComponent(parameterLayout); } } }); } private void addLayoutWithCreatingTheParameter() { createParameterLayout = new CreateSimpleParameterLayout(product, serviceAPI); addComponent(createParameterLayout); addClickListenerForAddButton(); } private void addClickListenerForAddButton() { createParameterLayout.getAddButton().addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { createNewParameterAndAddNewLayout(); } }); } private void createNewParameterAndAddNewLayout() { Parameter parameter = createParameterLayout.getNewParameter(); if (parameter == null) { Notification.show("Can't create the parameter!"); return; } product.getParameterList().add(parameter); EditableSimpleParameterLayout parameterLayout = new EditableSimpleParameterLayout(parameter, this); parametersLayoutsList.add(parameterLayout); int index = getComponentIndex(doubleButtonsDialog) - 1; addComponent(parameterLayout, index); addDeleteParameterClickListener(parameterLayout); } private void addLayoutWithDialogButtons() { doubleButtonsDialog = new DoubleButtonsDialog("Confirm", "Cancel"); addComponent(doubleButtonsDialog); addConfirmationListener(); addCancelingListener(); } protected void addConfirmationListener() { doubleButtonsDialog.getConfirmButton().addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { saveChanges(); } }); } protected void saveChanges() { updateProductFields(); product = serviceAPI.updateProduct(product); replaceEditProductLayoutWithEditableProductLayout(); } protected void updateProductFields() { product.setName(nameLayout.getName()); // TODO: Set size product.setPrice(priceLayout.getPrice()); product.getProductStorage().setQuantity(storageLayout.getProductQuantity()); product.getManufacturer().setName(manufacturerLayout.getManufacturerName()); product.getManufacturer().setCountry(manufacturerLayout.getManufacturerCountry()); for (SimpleParameterLayout parameterLayout: parametersLayoutsList) { parameterLayout.updateParameter(); } //product = serviceAPI.updateProduct(product); } protected void addCancelingListener() { doubleButtonsDialog.getCancelButton().addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { product = serviceAPI.getProduct(product.getId()); replaceEditProductLayoutWithEditableProductLayout(); } }); } protected void replaceEditProductLayoutWithEditableProductLayout() { Integer index = parent.getComponentIndex(this); parent.addComponent(new EditableProductLayout(product, parent), index); parent.removeComponent(this); } }
gpl-2.0
Arquisoft/Trivial4b
game/src/main/java/es/uniovi/asw/trivial/db/impl/local/persistencia/model/Pregunta.java
2301
package es.uniovi.asw.trivial.db.impl.local.persistencia.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @SuppressWarnings("serial") @Entity @Table(name="TPREGUNTAS") public class Pregunta implements Serializable{ @Id @GeneratedValue private Long id; private String pregunta; private String categoria; @OneToMany(mappedBy = "pregunta") private List<Respuesta> respuestas = new ArrayList<Respuesta>(); public void addRespuesta(Respuesta respuesta){ respuesta._setPregunta(this); respuestas.add(respuesta); } public List<Respuesta> getRespuestas() { return respuestas; } public void setRespuestas(List<Respuesta> respuestas) { this.respuestas = respuestas; } public Pregunta(Long id, String pregunta, String categoria) { super(); this.id = id; this.pregunta = pregunta; this.categoria = categoria; } public Pregunta(String pregunta, String categoria) { this.pregunta = pregunta; this.categoria = categoria; } public Pregunta() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPregunta() { return pregunta; } public void setPregunta(String pregunta) { this.pregunta = pregunta; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pregunta other = (Pregunta) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } public Respuesta getRespuestaCorrecta() { Iterator<Respuesta> it = respuestas.iterator() ; while(it.hasNext()){ Respuesta r= it.next(); if(r.isCorrecta()){ return r; } } return null; } }
gpl-2.0
moeckel/silo
third-party/common-base/src/java/com/pb/common/matrix/ZipMatrixReader.java
6946
/* * Copyright 2005 PB Consult Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pb.common.matrix; import java.io.*; import java.util.StringTokenizer; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.log4j.Logger; /** * Implementes a MatrixReader to read matrices from a compressed matrix file. * * @author Tim Heier * @version 1.0, 1/11/2003 */ public class ZipMatrixReader extends MatrixReader { private ZipFile zfile = null; //Store header values - used by readData() private int version; private int nRows; private int nCols; private String name = ""; private String description = ""; private int[] externalRowNumbers; private int[] externalColumnNumbers; protected static Logger logger = Logger.getLogger("com.pb.common.matrix"); /** * Prevent outside classes from instantiating the default constructor. */ private ZipMatrixReader() {} /** * @param file represents the physical matrix file */ public ZipMatrixReader(File file) throws MatrixException { this.file = file; openZipFile(); } public Matrix readMatrix() throws MatrixException { return readMatrix(""); } public Matrix readMatrix(String index) throws MatrixException { readHeader(); return readData(); } private void openZipFile() throws MatrixException { try { zfile = new ZipFile( file ); } catch (Exception e) { throw new MatrixException(e, MatrixException.FILE_NOT_FOUND + ", "+ file); } } /** Reads and returns an entire matrix * (not implemented for this matrix type.) * */ public Matrix[] readMatrices() throws MatrixException { Matrix[] m = null; return m; } /** * Read matrix information from zip file. * */ private void readHeader() { ZipEntry entry = null; InputStream input = null; byte[] buf = new byte[256]; int len; try { entry = zfile.getEntry("_version"); input = zfile.getInputStream(entry); String versionString = ""; while((len = input.read(buf)) > -1) { versionString += new String(buf,0,len); } version = Integer.parseInt(versionString); entry = zfile.getEntry("_rows"); input = zfile.getInputStream(entry); String rowString = ""; while((len = input.read(buf)) > -1) { rowString += new String(buf, 0, len); } nRows += Integer.parseInt(rowString); entry = zfile.getEntry("_columns"); input = zfile.getInputStream(entry); String colString = ""; while((len = input.read(buf)) > -1) { colString += new String(buf, 0, len); } nCols += Integer.parseInt(colString); entry = zfile.getEntry("_name"); input = zfile.getInputStream(entry); while((len = input.read(buf)) > -1) { name += new String(buf, 0, len); } entry = zfile.getEntry("_description"); input = zfile.getInputStream(entry); while((len = input.read(buf)) > -1) { description += new String(buf, 0, len); } //--Read externalNumbers from file if (version == 2) { externalRowNumbers = readArrayEntry("_external row numbers"); externalColumnNumbers = readArrayEntry("_external column numbers"); } else { externalRowNumbers = readArrayEntry("_external numbers"); externalColumnNumbers = externalRowNumbers.clone(); } } catch (Exception e) { e.printStackTrace(); } } private int[] readArrayEntry(String entryName) throws IOException { ZipEntry entry = zfile.getEntry(entryName); InputStream input = zfile.getInputStream(entry); byte[] buf = new byte[8192]; int[] intArray; int len; //Read string in chunks String str = ""; while((len = input.read(buf)) > -1) { str += new String(buf, 0, len); } //Split array using comma String[] values = str.split(","); intArray = new int[values.length + 1]; //Convert string values to int for (int i=0; i < values.length; i++) { intArray[i+1] = Integer.parseInt( values[i] ); } return intArray; } /** * Returns a matrix. * */ private Matrix readData() { int len; float[][] values = new float[nRows][nCols]; byte[] byteArray = new byte[(nCols+1)*ZipMatrixWriter.WORDSIZE]; try { for (int row=0; row < nRows; row++) { String rowName = "row_" + (row+1); ZipEntry entry = zfile.getEntry(rowName); if (entry == null){ throw new RuntimeException("could not read row = " + rowName); } InputStream input = zfile.getInputStream(entry); //Read the contents of the zip file for (int s=0 ; ;) { len = input.read(byteArray, s, byteArray.length-s); if (len <= 0) break; s += len; } input.close(); //Create a data input stream to read from byte array. DataInputStream din = new DataInputStream(new ByteArrayInputStream(byteArray)); //Read float values from byte array for(int col=0; col < nCols; col++) { values[row][col] = din.readFloat(); } } } catch (Exception e) { throw new MatrixException(e, MatrixException.ERROR_READING_FILE); } Matrix m = new Matrix(name, description, values); m.setExternalNumbers(externalRowNumbers, externalColumnNumbers); return m; } }
gpl-2.0
mevqz/nblocks
src/com/gammery/nblocks/view/NextPiecesPanel.java
4728
/* * NBlocks, Copyright (C) 2011 Matías E. Vazquez (matiasevqz@gmail.com) * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //TODO //arreglar el cleanPanel (porq borra el fondo tambien) //arreglar el PieceFactory, porq algo esta mal en los metodos //de esa clase // agregar un metodo setHighScore package com.gammery.nblocks.view; import javax.swing.*; import java.awt.*; import com.gammery.nblocks.model.*; //import java.util.*; public class NextPiecesPanel extends JPanel { private PieceFrame[] fNextPieces; private int framesUsed; private int frameWidth; private int frameHeight; private Color backgroundColor; private BlockType blockType; public static final int MAX_PANELS = 5; public NextPiecesPanel() { this(Color.BLACK, MAX_PANELS, 144, 144); } //TODO Podria recibir un Color[] para usar distintos colores para cada frame public NextPiecesPanel(Color bgColor, int frames, int fWidth, int fHeight) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); frameWidth = fWidth; frameHeight = fHeight; backgroundColor = bgColor; framesUsed = (frames < 1) ? 1 : frames; fNextPieces = new PieceFrame[frames]; //PanelPiece[] fNextPieces[0] = new PieceFrame(BlockType.GRADIENT_BLOCK, Color.RED, backgroundColor, frameWidth, frameHeight); add(fNextPieces[0]); for (int i = 1; i < fNextPieces.length; i++) { //add(Box.createRigidArea(new Dimension(0, 8))); fNextPieces[i] = new PieceFrame(frameWidth, frameHeight); add(fNextPieces[i]); } framesUsed = frames; } public void setBlockType(BlockType bType) { blockType = bType; for (int i = 0; i < fNextPieces.length; i++) { // tiene que ser a todos por mas que no se esten usando en este momento fNextPieces[i].setBlockType(blockType); // para que cuando se habiliten otros tengan todos el mismo bType } } /* public void setFrameColors(Color frameColor, Color bgColor) { // this.frameColor = frameColor; // this.bgColor = bgColor; for (int i = 0; i < framesUsed; i++) { fNextPieces[i].setFrameColors(frameColor, bgColor); } } */ public int getFramesUsed() { return framesUsed; } public void setFramesUsed(int newFramesUsed) { if (newFramesUsed > fNextPieces.length) newFramesUsed = fNextPieces.length; else if (newFramesUsed < 0) newFramesUsed = 0; if (newFramesUsed < framesUsed) { for (int i = 0; (newFramesUsed + i) < framesUsed; i++) fNextPieces[newFramesUsed + i].drawPiece(null); } framesUsed = newFramesUsed; // repaint(); // XXX ES NECESARIO????? } //FIXME Esto tiene que verificar el length del array o a framesUsed??????????????????? // es mejor usar foreach aca y Collection, o sea este metdo //public void displayNextPiece(Collection<Piece> nextPieces) // nextPieces -> pieces public void displayNextPiece(java.util.List<Piece> pieces) { // int i = 0; // for (Piece piece : nextPieces) { // if (i >= fNextPieces.length) // break; // fNextPieces[i++].drawPiece(piece, blockType); // } for (int i = 0; i < framesUsed; i++) { fNextPieces[i].drawPiece(pieces.get(i)); } } /* * Alternativa usando iterator public void displayNextPiece(Iterator<Piece> it) { int i = 0; while (i++ < fNextPiece.length && it.hasNext()) { fNextPiece[i++].drawPiece(it.next()); } } */ public void cleanFrames() { for (int i = 0; i < fNextPieces.length; i++) { fNextPieces[i].clean(); } } // Testing method public static void main(String args[]) { NextPiecesPanel gp = new NextPiecesPanel(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); f.setLayout(new FlowLayout()); f.add(gp); f.setSize(800, 800); PieceFactory pFactory = PieceFactory.getInstance(); try { for (int i = 0; i < 16; i++) { int framesUsed = gp.getFramesUsed(); gp.displayNextPiece(pFactory.next(framesUsed)); Thread.sleep(800); pFactory.next(); gp.cleanFrames(); Thread.sleep(800); } } catch (Exception e) { } } }
gpl-2.0
tharindum/opennms_dashboard
opennms-dao/src/main/java/org/opennms/netmgt/dao/db/columnchanges/AutoIntegerReplacement.java
2308
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ /** * <p>AutoIntegerReplacement class.</p> * * @author ranger * @version $Id: $ */ package org.opennms.netmgt.dao.db.columnchanges; import java.sql.ResultSet; import java.util.Map; import org.opennms.netmgt.dao.db.ColumnChange; import org.opennms.netmgt.dao.db.ColumnChangeReplacement; public class AutoIntegerReplacement implements ColumnChangeReplacement { private int m_value; /** * <p>Constructor for AutoIntegerReplacement.</p> * * @param initialValue a int. */ public AutoIntegerReplacement(int initialValue) { m_value = initialValue; } /** * <p>getInt</p> * * @return a int. */ public int getInt() { return m_value++; } /** {@inheritDoc} */ public Integer getColumnReplacement(ResultSet rs, Map<String, ColumnChange> columnChanges) { return getInt(); } /** * <p>addColumnIfColumnIsNew</p> * * @return a boolean. */ public boolean addColumnIfColumnIsNew() { return true; } /** * <p>close</p> */ public void close() { } }
gpl-2.0
taopmindray/server
data/src/main/java/com/youthclub/model/support/RestfulEnum.java
524
package com.youthclub.model.support; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonProperty; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; /** * @author Frank <frank@baileyroberts.com.au> */ @JsonAutoDetect(creatorVisibility = NONE, fieldVisibility = NONE, getterVisibility = NONE, isGetterVisibility = NONE, setterVisibility = NONE) public interface RestfulEnum { @JsonProperty String getLabel(); }
gpl-2.0
graalvm/fastr
com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/base/AsCall.java
4370
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 3 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 3 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.nodes.builtin.base; import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE; import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.r.nodes.RASTUtils; import com.oracle.truffle.r.runtime.data.nodes.attributes.SpecialAttributesFunctions.GetNamesAttributeNode; import com.oracle.truffle.r.nodes.builtin.RBuiltinNode; import com.oracle.truffle.r.runtime.ArgumentsSignature; import com.oracle.truffle.r.runtime.RError; import com.oracle.truffle.r.runtime.RError.Message; import com.oracle.truffle.r.runtime.builtins.RBuiltin; import com.oracle.truffle.r.runtime.data.RPairList; import com.oracle.truffle.r.runtime.data.RStringVector; import com.oracle.truffle.r.runtime.data.model.RAbstractContainer; import com.oracle.truffle.r.runtime.data.model.RAbstractListBaseVector; import com.oracle.truffle.r.runtime.gnur.SEXPTYPE; import com.oracle.truffle.r.runtime.nodes.RSyntaxNode; @RBuiltin(name = "as.call", kind = PRIMITIVE, parameterNames = {"x"}, behavior = PURE) public abstract class AsCall extends RBuiltinNode.Arg1 { private final ConditionProfile nullNamesProfile = ConditionProfile.createBinaryProfile(); @Child private GetNamesAttributeNode getNamesNode = GetNamesAttributeNode.create(); static { Casts.noCasts(AsCall.class); } @Specialization @TruffleBoundary protected RPairList asCallFunction(RAbstractListBaseVector x) { if (x.getLength() == 0) { throw error(Message.INVALID_LEN_0_ARG); } // separate the first element (call target) from the rest (arguments) RSyntaxNode target = RASTUtils.createNodeForValue(x.getDataAt(0)).asRSyntaxNode(); ArgumentsSignature signature = createSignature(x); Object[] arguments = new Object[signature.getLength()]; for (int i = 0; i < arguments.length; i++) { arguments[i] = x.getDataAt(i + 1); } return Call.makeCall(getRLanguage(), target, arguments, signature); } private ArgumentsSignature createSignature(RAbstractContainer x) { int length = x.getLength() - 1; RStringVector ns = getNamesNode.getNames(x); if (nullNamesProfile.profile(ns == null)) { return ArgumentsSignature.empty(length); } else { String[] names = new String[length]; // extract names, converting "" to null for (int i = 0; i < length; i++) { String name = ns.getDataAt(i + 1); if (name != null && !name.isEmpty()) { names[i] = name; } } return ArgumentsSignature.get(names); } } @Specialization protected Object asCall(RPairList l) { if (l.isLanguage()) { return l; } else { return RPairList.asPairList(l, SEXPTYPE.LANGSXP); } } @Fallback protected Object asCallFunction(@SuppressWarnings("unused") Object x) { throw error(RError.Message.GENERIC, "invalid argument list"); } }
gpl-2.0
campanhacompleta/zap
TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java
18521
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.Spanned; import android.text.style.DynamicDrawableSpan; import android.text.style.ImageSpan; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; public class Emoji { private static HashMap<CharSequence, DrawableInfo> rects = new HashMap<>(); private static int drawImgSize; private static int bigImgSize; private static boolean inited = false; private static Paint placeholderPaint; private static final int splitCount = 4; private static Bitmap emojiBmp[][] = new Bitmap[5][splitCount]; private static boolean loadingEmoji[][] = new boolean[5][splitCount]; private static final int[][] cols = { {11, 11, 11, 11}, {6, 6, 6, 6}, {9, 9, 9, 9}, {9, 9, 9, 9}, {8, 8, 8, 7} }; static { int emojiFullSize; if (AndroidUtilities.density <= 1.0f) { emojiFullSize = 32; } else if (AndroidUtilities.density <= 1.5f) { emojiFullSize = 48; } else if (AndroidUtilities.density <= 2.0f) { emojiFullSize = 64; } else { emojiFullSize = 64; } drawImgSize = AndroidUtilities.dp(20); bigImgSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32); for (int j = 0; j < EmojiData.data.length; j++) { int count2 = (int) Math.ceil(EmojiData.data[j].length / (float) splitCount); int position; for (int i = 0; i < EmojiData.data[j].length; i++) { int page = i / count2; position = i - page * count2; Rect rect = new Rect((position % cols[j][page]) * emojiFullSize, (position / cols[j][page]) * emojiFullSize, (position % cols[j][page] + 1) * emojiFullSize, (position / cols[j][page] + 1) * emojiFullSize); rects.put(EmojiData.data[j][i], new DrawableInfo(rect, (byte) j, (byte) page)); } } placeholderPaint = new Paint(); placeholderPaint.setColor(0x00000000); } private static void loadEmoji(final int page, final int page2) { try { float scale; int imageResize = 1; if (AndroidUtilities.density <= 1.0f) { scale = 2.0f; imageResize = 2; } else if (AndroidUtilities.density <= 1.5f) { scale = 3.0f; imageResize = 2; } else if (AndroidUtilities.density <= 2.0f) { scale = 2.0f; } else { scale = 2.0f; } String imageName; File imageFile; try { for (int a = 4; a < 6; a++) { imageName = String.format(Locale.US, "v%d_emoji%.01fx_%d.jpg", a, scale, page); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (imageFile.exists()) { imageFile.delete(); } imageName = String.format(Locale.US, "v%d_emoji%.01fx_a_%d.jpg", a, scale, page); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (imageFile.exists()) { imageFile.delete(); } } } catch (Exception e) { FileLog.e("tmessages", e); } imageName = String.format(Locale.US, "v7_emoji%.01fx_%d_%d.jpg", scale, page, page2); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (!imageFile.exists()) { InputStream is = ApplicationLoader.applicationContext.getAssets().open("emoji/" + imageName); AndroidUtilities.copyFile(is, imageFile); is.close(); } BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFile.getAbsolutePath(), opts); int width = opts.outWidth / imageResize; int height = opts.outHeight / imageResize; int stride = width * 4; final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Utilities.loadBitmap(imageFile.getAbsolutePath(), bitmap, imageResize, width, height, stride); imageName = String.format(Locale.US, "v7_emoji%.01fx_a_%d_%d.jpg", scale, page, page2); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (!imageFile.exists()) { InputStream is = ApplicationLoader.applicationContext.getAssets().open("emoji/" + imageName); AndroidUtilities.copyFile(is, imageFile); is.close(); } Utilities.loadBitmap(imageFile.getAbsolutePath(), bitmap, imageResize, width, height, stride); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { emojiBmp[page][page2] = bitmap; NotificationCenter.getInstance().postNotificationName(NotificationCenter.emojiDidLoaded); } }); } catch (Throwable x) { FileLog.e("tmessages", "Error loading emoji", x); } } public static void invalidateAll(View view) { if (view instanceof ViewGroup) { ViewGroup g = (ViewGroup) view; for (int i = 0; i < g.getChildCount(); i++) { invalidateAll(g.getChildAt(i)); } } else if (view instanceof TextView) { view.invalidate(); } } public static String fixEmoji(String emoji) { char ch; int lenght = emoji.length(); for (int a = 0; a < lenght; a++) { ch = emoji.charAt(a); if (ch >= 0xD83C && ch <= 0xD83E) { if (ch == 0xD83C && a < lenght - 1) { ch = emoji.charAt(a + 1); if (ch == 0xDE2F || ch == 0xDC04 || ch == 0xDE1A || ch == 0xDD7F) { emoji = emoji.substring(0, a + 2) + "\uFE0F" + emoji.substring(a + 2); lenght++; a += 2; } else { a++; } } else { a++; } } else if (ch == 0x20E3) { return emoji; } else if (ch >= 0x203C && ch <= 0x3299) { if (EmojiData.emojiToFE0FMap.containsKey(ch)) { emoji = emoji.substring(0, a + 1) + "\uFE0F" + emoji.substring(a + 1); lenght++; a++; } } } return emoji; } public static EmojiDrawable getEmojiDrawable(CharSequence code) { DrawableInfo info = rects.get(code); if (info == null) { FileLog.e("tmessages", "No drawable for emoji " + code); return null; } EmojiDrawable ed = new EmojiDrawable(info); ed.setBounds(0, 0, drawImgSize, drawImgSize); return ed; } public static Drawable getEmojiBigDrawable(String code) { EmojiDrawable ed = getEmojiDrawable(code); if (ed == null) { return null; } ed.setBounds(0, 0, bigImgSize, bigImgSize); ed.fullSize = true; return ed; } public static class EmojiDrawable extends Drawable { private DrawableInfo info; private boolean fullSize = false; private static Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); private static Rect rect = new Rect(); public EmojiDrawable(DrawableInfo i) { info = i; } public DrawableInfo getDrawableInfo() { return info; } public Rect getDrawRect() { Rect original = getBounds(); int cX = original.centerX(), cY = original.centerY(); rect.left = cX - (fullSize ? bigImgSize : drawImgSize) / 2; rect.right = cX + (fullSize ? bigImgSize : drawImgSize) / 2; rect.top = cY - (fullSize ? bigImgSize : drawImgSize) / 2; rect.bottom = cY + (fullSize ? bigImgSize : drawImgSize) / 2; return rect; } @Override public void draw(Canvas canvas) { if (emojiBmp[info.page][info.page2] == null) { if (loadingEmoji[info.page][info.page2]) { return; } loadingEmoji[info.page][info.page2] = true; Utilities.globalQueue.postRunnable(new Runnable() { @Override public void run() { loadEmoji(info.page, info.page2); loadingEmoji[info.page][info.page2] = false; } }); canvas.drawRect(getBounds(), placeholderPaint); return; } Rect b; if (fullSize) { b = getDrawRect(); } else { b = getBounds(); } //if (!canvas.quickReject(b.left, b.top, b.right, b.bottom, Canvas.EdgeType.AA)) { canvas.drawBitmap(emojiBmp[info.page][info.page2], info.rect, b, paint); //} } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } } private static class DrawableInfo { public Rect rect; public byte page; public byte page2; public DrawableInfo(Rect r, byte p, byte p2) { rect = r; page = p; page2 = p2; } } private static boolean inArray(char c, char[] a) { for (char cc : a) { if (cc == c) { return true; } } return false; } public static CharSequence replaceEmoji(CharSequence cs, Paint.FontMetricsInt fontMetrics, int size, boolean createNew) { if (cs == null || cs.length() == 0) { return cs; } /*if (ApplicationLoader.ENABLE_TAGS){ String s = cs.toString(); Pattern pattern = Pattern.compile("([*])"); //case insensitive, use [g] for only lower Matcher matcher = pattern.matcher(s); int count = 0; while (matcher.find()) count++; boolean b = false; if(count >= 2){ s = s.replaceAll("\\*(.+?)\\*", "<b>$1</b>"); b = true; } //pattern = Pattern.compile("([_])"); //case insensitive, use [g] for only lower //matcher = pattern.matcher(s); //count = 0; //while (matcher.find()) count++; //if(count >= 2) { // s = s.replaceAll("\\_(.+?)\\_", "<i>$1</i>"); // b = true; //} if(b)cs = Html.fromHtml(s); /*String s = cs.toString(); boolean b = false; if(s.contains("*")){ s = s.replaceAll("\\*(.+?)\\*", "<b>$1</b>"); b = true; } //if(s.contains("_")) { // s = s.replaceAll("\\_(.+?)\\_", "<i>$1</i>"); // b = true; //} if(b)cs = AndroidUtilities.replaceBoldItalicTags(s); }*/ //SpannableStringLight.isFieldsAvailable(); //SpannableStringLight s = new SpannableStringLight(cs.toString()); Spannable s; if (!createNew && cs instanceof Spannable) { s = (Spannable) cs; } else { s = Spannable.Factory.getInstance().newSpannable(cs.toString()); } // If showAndroidEmoji is enabled don't replace anything if (android.os.Build.VERSION.SDK_INT >= 19 && ApplicationLoader.SHOW_ANDROID_EMOJI) { return s; } long buf = 0; int emojiCount = 0; char c; int startIndex = -1; int startLength = 0; int previousGoodIndex = 0; StringBuilder emojiCode = new StringBuilder(16); boolean nextIsSkinTone; EmojiDrawable drawable; EmojiSpan span; int length = cs.length(); boolean doneEmoji = false; //s.setSpansCount(emojiCount); try { for (int i = 0; i < length; i++) { c = cs.charAt(i); if (c >= 0xD83C && c <= 0xD83E || (buf != 0 && (buf & 0xFFFFFFFF00000000L) == 0 && (buf & 0xFFFF) == 0xD83C && (c >= 0xDDE6 && c <= 0xDDFF))) { if (startIndex == -1) { startIndex = i; } emojiCode.append(c); startLength++; buf <<= 16; buf |= c; } else if (buf > 0 && (c & 0xF000) == 0xD000) { emojiCode.append(c); startLength++; buf = 0; doneEmoji = true; } else if (c == 0x20E3) { if (i > 0) { char c2 = cs.charAt(previousGoodIndex); if ((c2 >= '0' && c2 <= '9') || c2 == '#' || c2 == '*') { startIndex = previousGoodIndex; startLength = i - previousGoodIndex + 1; emojiCode.append(c2); emojiCode.append(c); doneEmoji = true; } } } else if ((c == 0x00A9 || c == 0x00AE || c >= 0x203C && c <= 0x3299) && EmojiData.dataCharsMap.containsKey(c)) { if (startIndex == -1) { startIndex = i; } startLength++; emojiCode.append(c); doneEmoji = true; } else if (startIndex != -1) { emojiCode.setLength(0); startIndex = -1; startLength = 0; doneEmoji = false; } previousGoodIndex = i; for (int a = 0; a < 3; a++) { if (i + 1 < length) { c = cs.charAt(i + 1); if (a == 1) { if (c == 0x200D) { emojiCode.append(c); i++; startLength++; doneEmoji = false; } } else { if (c >= 0xFE00 && c <= 0xFE0F) { i++; startLength++; } } } } if (doneEmoji) { if (i + 2 < length) { if (cs.charAt(i + 1) == 0xD83C && cs.charAt(i + 2) >= 0xDFFB && cs.charAt(i + 2) <= 0xDFFF) { emojiCode.append(cs.subSequence(i + 1, i + 3)); startLength += 2; i += 2; } } drawable = Emoji.getEmojiDrawable(emojiCode.subSequence(0, emojiCode.length())); if (drawable != null) { span = new EmojiSpan(drawable, DynamicDrawableSpan.ALIGN_BOTTOM, size, fontMetrics); s.setSpan(span, startIndex, startIndex + startLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); emojiCount++; } startLength = 0; startIndex = -1; emojiCode.setLength(0); doneEmoji = false; } if (emojiCount >= 50) { //654 new break; } } } catch (Exception e) { FileLog.e("tmessages", e); return cs; } return s; } public static class EmojiSpan extends ImageSpan { private Paint.FontMetricsInt fontMetrics = null; private int size = AndroidUtilities.dp(20); public EmojiSpan(EmojiDrawable d, int verticalAlignment, int s, Paint.FontMetricsInt original) { super(d, verticalAlignment); fontMetrics = original; if (original != null) { size = Math.abs(fontMetrics.descent) + Math.abs(fontMetrics.ascent); if (size == 0) { size = AndroidUtilities.dp(20); } } } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { if (fm == null) { fm = new Paint.FontMetricsInt(); } if (fontMetrics == null) { int sz = super.getSize(paint, text, start, end, fm); int offset = AndroidUtilities.dp(8); int w = AndroidUtilities.dp(10); fm.top = -w - offset; fm.bottom = w - offset; fm.ascent = -w - offset; fm.leading = 0; fm.descent = w - offset; return sz; } else { if (fm != null) { fm.ascent = fontMetrics.ascent; fm.descent = fontMetrics.descent; fm.top = fontMetrics.top; fm.bottom = fontMetrics.bottom; } if (getDrawable() != null) { getDrawable().setBounds(0, 0, size, size); } return size; } } } }
gpl-2.0
CS447/TowerGame
src/towergame/circuits/OneTimeOnSingleCircuit.java
380
package towergame.circuits; public class OneTimeOnSingleCircuit extends Circuit{ private boolean solved; public OneTimeOnSingleCircuit(int id) { super(id, 1); } @Override public void doLogic() { if (inputList[0] == true){ this.power = true; this.solved = true; } else { this.power = false; } if (solved == false){ inputList[0] = false; } } }
gpl-2.0
solvery/lang-features
java/package_a/p1/p2/p3/package_b.java
177
package package_a.p1.p2.p3; public class package_b { public void m1() { System.out.println("hello package b."); } public static void main(String[] args) { } }
gpl-2.0
rpereira-dev/MineMods_1_7_10
MineTeam/src/main/java/com/rpereira/mineteam/client/gui/GuiInvitation.java
2029
package com.rpereira.mineteam.client.gui; import com.rpereira.mineteam.common.packets.Packets; import com.rpereira.mineteam.common.packets.client.PacketTeamInvitation; import com.rpereira.mineteam.common.packets.server.PacketTeamAcceptInvitation; import com.rpereira.mineteam.common.packets.server.PacketTeamRefuseInvitation; import com.rpereira.mineutils.ChatColor; import cpw.mods.fml.common.network.simpleimpl.IMessage; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; public class GuiInvitation extends GuiScreen { private PacketTeamInvitation message; public GuiInvitation(PacketTeamInvitation message) { this.message = message; } @SuppressWarnings("unchecked") @Override public void initGui() { this.buttonList.add( new GuiButton(42, this.width / 4, this.height - 80, this.width / 2, 20, ChatColor.RESET + "Accept")); this.buttonList.add( new GuiButton(43, this.width / 4, this.height - 40, this.width / 2, 20, ChatColor.RESET + "Decline")); } /** * Draws the screen and all the components in it. */ @Override public void drawScreen(int x, int y, float useless) { this.drawCenteredString(this.fontRendererObj, ChatColor.UNDERLINE + this.message.inviter + " has invited you in his team: " + this.message.teamName, this.width / 2, 14, Integer.MAX_VALUE); super.drawScreen(x, y, useless); } @Override public boolean doesGuiPauseGame() { return false; } @Override protected void actionPerformed(GuiButton b) { if (b.id == 42) { // accept IMessage packet = new PacketTeamAcceptInvitation(this.message.token); Packets.network.sendToServer(packet); this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); } else if (b.id == 43) { // refuses IMessage packet = new PacketTeamRefuseInvitation(this.message.token); Packets.network.sendToServer(packet); this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); } } }
gpl-3.0
Nateowami/Solve4x
src/com/github/nateowami/solve4x/algorithm/DivideBothSides.java
4124
/* Solve4x - An algebra solver that shows its work Copyright (C) 2015 Nathaniel Paulus 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.nateowami.solve4x.algorithm; import com.github.nateowami.solve4x.solver.*; import com.github.nateowami.solve4x.solver.Number; /** * Divides both sides of an equation by the same value, which hopefully isn't 0. Yeah, we hope. * Works in the following situations:<br> * A term with a numeric value on one side, and a number on the other:<br> * 2x=5<br> * 1/2=(2x)4(x-3)<br> * What about situations with numbers on both sides, for example, 2x=4(y-2)? In this case, if they * are both Numbers, both sides are divided by the smaller one. * @author Nateowami */ public class DivideBothSides extends Algorithm { public DivideBothSides() { super(Equation.class); // Declare that this algorithm operates on equations } @Override public Step execute(Algebra algebra) { Equation eq = (Equation) algebra; boolean fromRight = isNumeric(eq.left()); //set "from" and "to" to the sides of the equations we'll be moving from and to Term from = (Term) (fromRight ? eq.right() : eq.left()); AlgebraicParticle to = (AlgebraicParticle) (fromRight ? eq.left() : eq.right()); //the number we need to divide by (Watch for signs. In -2x we divide by -2) int indexOfNumeric = indexOfNumeric(from); AlgebraicParticle numeric = from.get(indexOfNumeric); AlgebraicParticle divisor = numeric.cloneWithNewSign(indexOfNumeric == 0 ? from.sign() == numeric.sign() : numeric.sign()); //now calculate the resulting fraction Fraction frac = new Fraction(true, to, divisor, 1); //the sign of the term we divide from could change if we divided by the first element boolean fromSign = indexOfNumeric == 0 ? true : from.sign(); //and calculate the side we're moving from AlgebraicParticle resultingFromSide = unwrap(from.cloneAndRemove(indexOfNumeric).cloneWithNewSign(fromSign)); //calculate the final equation Equation out = fromRight ? new Equation(frac, resultingFromSide) : new Equation(resultingFromSide, frac); //create a step and explain Step step = new Step(out); step.explain("Divide both sides of the equation by ").explain(divisor) .explain(". This leaves ").explain(resultingFromSide).explain(" on one side, and ") .explain(frac).explain(" on the other."); return step; } @Override public int smarts(Algebra algebra) { Equation eq = (Equation) algebra; //if one side is a term with a numeric part and the other is numeric if(indexOfNumeric(eq.left()) != -1 && isNumeric(eq.right()) || isNumeric(eq.left()) && indexOfNumeric(eq.right()) != -1) { return 7; } else return 0; } /** * Finds a numeric item in a (Number, MixedNumber, or constant Fraction) and * returns its index. * @param a A term to search. * @return The index of the first numeric element in a. If none exist -1 is returned. */ private int indexOfNumeric(Algebra a) { if(a instanceof Term) { Term t = (Term) a; for(int i = 0; i < t.length(); i++) { if(isNumeric(t.get(i))) return i; } } return -1; } /** * Tells whether a is numeric, that is that it is a Number, MixedNumber, or constant Fraction. * @param a The AlgebraicParticle to check. * @return True if a is numeric, otherwise false; */ private boolean isNumeric(AlgebraicParticle a) { return a instanceof Number || a instanceof Fraction && ((Fraction)a).constant() || a instanceof MixedNumber; } }
gpl-3.0
SafirSDK/safir-sdk-core
examples/vehicleapp/src/java/com/saabgroup/safir/samples/vehicleappjava/MainLoop.java
3736
/****************************************************************************** * * Copyright Saab AB, 2011-2013 (http://safirsdkcore.com) * ******************************************************************************* * * This file is part of Safir SDK Core. * * Safir SDK Core is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Safir SDK Core 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 Safir SDK Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ package com.saabgroup.safir.samples.vehicleappjava; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import com.saabgroup.safir.Logging; public class MainLoop implements IMainLoop { private volatile boolean running = false; private volatile boolean disposed = false; // Track whether Dispose has been called. private BlockingQueue<IMainLoop.Callback> methods = new LinkedBlockingQueue<IMainLoop.Callback>(); /* * (non-Javadoc) * @see com.saabgroup.safir.application.MainLoop#start() */ public void start() { start(null); } /* * (non-Javadoc) * @see com.saabgroup.safir.application.MainLoop#start(com.saabgroup.safir.application.MainLoop.Callback) */ public void start(IMainLoop.Callback initMethod) { // run init method if(initMethod != null) { initMethod.onInvoke(); } // Start the main loop and continue until it's stopped running = true; while(running) { try { IMainLoop.Callback method = methods.take(); method.onInvoke(); } catch (InterruptedException e) { com.saabgroup.safir.Logging.sendSystemLog (com.saabgroup.safir.Logging.Severity.ERROR, "Error in MainLoop when taking method from the queue"); } catch (Exception e) { com.saabgroup.safir.Logging.sendSystemLog (com.saabgroup.safir.Logging.Severity.CRITICAL, "Unhandled exception in MainLoop when invoking method. " + e.getMessage()); } } } /* * (non-Javadoc) * @see com.saabgroup.safir.application.MainLoop#isStarted() */ public boolean isStarted() { return running; } /* * (non-Javadoc) * @see com.saabgroup.safir.application.MainLoop#stop() */ public void stop() { running = false; } /* * (non-Javadoc) * @see com.saabgroup.safir.application.IMainLoop#invokeLater(com.saabgroup.safir.application.IMainLoop.Callback) */ @Override public void invokeLater(IMainLoop.Callback callback) { try { methods.put(callback); } catch (InterruptedException e) {} } /* * (non-Javadoc) * @see com.saabgroup.safir.application.MainLoop#dispose() */ public void dispose() { if (!disposed) { methods.clear(); disposed = true; } } /* * (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { dispose(); super.finalize(); } }
gpl-3.0
MyCoRe-Org/mycore
mycore-indexing/src/main/java/org/mycore/frontend/indexbrowser/MCRGoogleSitemapServlet.java
4048
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe 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. * * MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.indexbrowser; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRFileContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; /** * This class builds a google sitemap containing links to all documents. The * web.xml file should contain a mapping to /sitemap.xml See * http://www.google.com/webmasters/sitemaps/docs/en/protocol.html * * @author Frank Lützenkirchen * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) * @version $Revision$ $Date$ */ public final class MCRGoogleSitemapServlet extends MCRServlet { private static final long serialVersionUID = 1L; /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRGoogleSitemapServlet.class.getName()); /** * This method implement the doGetPost method of MCRServlet. It build a XML * file for the Google search engine. * * @param job * a MCRServletJob instance */ public void doGetPost(MCRServletJob job) throws Exception { File baseDir = MCRFrontendUtil .getWebAppBaseDir(getServletContext()) .orElseGet(() -> new File(MCRConfiguration2.getStringOrThrow("MCR.WebApplication.basedir"))); MCRGoogleSitemapCommon common = new MCRGoogleSitemapCommon(MCRFrontendUtil.getBaseURL(job.getRequest()), baseDir); int number = common.checkSitemapFile(); LOGGER.debug("Build Google number of URL files {}.", Integer.toString(number)); Document jdom = null; // check if sitemap_google.xml exist String fnsm = common.getFileName(1, true); LOGGER.debug("Build Google check file {}", fnsm); File fi = new File(fnsm); if (fi.isFile()) { jdom = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(fi)); if (jdom == null) { if (number == 1) { jdom = common.buildSingleSitemap(); } else { jdom = common.buildSitemapIndex(number); } } //send XML output getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(jdom)); return; } // remove old files common.removeSitemapFiles(); // build new return and URL files if (number == 1) { jdom = common.buildSingleSitemap(); } else { for (int i = 0; i < number; i++) { String fn = common.getFileName(i + 2, true); File xml = new File(fn); jdom = common.buildPartSitemap(i); LOGGER.info("Write Google sitemap file {}.", fn); new MCRJDOMContent(jdom).sendTo(xml); } jdom = common.buildSitemapIndex(number); } // send XML output getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(jdom)); } }
gpl-3.0
LogisimIt/Logisim
Logisim-Fork/src/main/java/com/cburch/logisim/std/memory/MemContentsSub.java
4569
/* Copyright (c) 2010, Carl Burch. License information is located in the * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */ package com.cburch.logisim.std.memory; import java.util.Arrays; class MemContentsSub { private static class ByteContents extends ContentsInterface { private byte[] data; public ByteContents(int size) { data = new byte[size]; } @Override void clear() { Arrays.fill(data, (byte) 0); } @Override public ByteContents clone() { ByteContents ret = (ByteContents) super.clone(); ret.data = new byte[this.data.length]; System.arraycopy(this.data, 0, ret.data, 0, this.data.length); return ret; } @Override int get(int addr) { return addr >= 0 && addr < data.length ? data[addr] : 0; } // // methods for accessing data within memory // @Override int getLength() { return data.length; } @Override void load(int start, int[] values, int mask) { int n = Math.min(values.length, data.length - start); for (int i = 0; i < n; i++) { data[start + i] = (byte) (values[i] & mask); } } @Override void set(int addr, int value) { if (addr >= 0 && addr < data.length) { byte oldValue = data[addr]; if (value != oldValue) { data[addr] = (byte) value; } } } } static abstract class ContentsInterface implements Cloneable { abstract void clear(); @Override public ContentsInterface clone() { try { return (ContentsInterface) super.clone(); } catch (CloneNotSupportedException e) { return this; } } abstract int get(int addr); int[] get(int start, int len) { int[] ret = new int[len]; for (int i = 0; i < ret.length; i++) ret[i] = get(start + i); return ret; } abstract int getLength(); boolean isClear() { for (int i = 0, n = getLength(); i < n; i++) { if (get(i) != 0) return false; } return true; } abstract void load(int start, int[] values, int mask); boolean matches(int[] values, int start, int mask) { for (int i = 0; i < values.length; i++) { if (get(start + i) != (values[i] & mask)) return false; } return true; } abstract void set(int addr, int value); } private static class IntContents extends ContentsInterface { private int[] data; public IntContents(int size) { data = new int[size]; } @Override void clear() { Arrays.fill(data, 0); } @Override public IntContents clone() { IntContents ret = (IntContents) super.clone(); ret.data = new int[this.data.length]; System.arraycopy(this.data, 0, ret.data, 0, this.data.length); return ret; } @Override int get(int addr) { return addr >= 0 && addr < data.length ? data[addr] : 0; } // // methods for accessing data within memory // @Override int getLength() { return data.length; } @Override void load(int start, int[] values, int mask) { int n = Math.min(values.length, data.length - start); for (int i = 0; i < n; i++) { data[i] = values[i] & mask; } } @Override void set(int addr, int value) { if (addr >= 0 && addr < data.length) { int oldValue = data[addr]; if (value != oldValue) { data[addr] = value; } } } } private static class ShortContents extends ContentsInterface { private short[] data; public ShortContents(int size) { data = new short[size]; } @Override void clear() { Arrays.fill(data, (short) 0); } @Override public ShortContents clone() { ShortContents ret = (ShortContents) super.clone(); ret.data = new short[this.data.length]; System.arraycopy(this.data, 0, ret.data, 0, this.data.length); return ret; } @Override int get(int addr) { return addr >= 0 && addr < data.length ? data[addr] : 0; } // // methods for accessing data within memory // @Override int getLength() { return data.length; } @Override void load(int start, int[] values, int mask) { int n = Math.min(values.length, data.length - start); for (int i = 0; i < n; i++) { data[start + i] = (short) (values[i] & mask); } } @Override void set(int addr, int value) { if (addr >= 0 && addr < data.length) { short oldValue = data[addr]; if (value != oldValue) { data[addr] = (short) value; } } } } static ContentsInterface createContents(int size, int bits) { if (bits <= 8) return new ByteContents(size); else if (bits <= 16) return new ShortContents(size); else return new IntContents(size); } private MemContentsSub() { } }
gpl-3.0
OpenGeoportal/ogpHarvester
harvester-api/src/main/java/org/opengeoportal/harvester/api/client/geonetwork/XmlRequest.java
11582
package org.opengeoportal.harvester.api.client.geonetwork; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.protocol.Protocol; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.opengeoportal.harvester.api.client.geonetwork.exception.BadSoapResponseEx; import org.opengeoportal.harvester.api.client.geonetwork.exception.BadXmlResponseEx; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Utility class used in {@link GeoNetworkClient} to send requests to the * GeoNetwork server. * * Code from GeoNetwork opensource project. * */ public class XmlRequest { private static final Namespace NAMESPACE_ENV = Namespace.getNamespace( "env", "http://www.w3.org/2003/05/soap-envelope"); public enum Method { GET, POST } public XmlRequest() { this(null, 80); } public XmlRequest(String host) { this(host, 80); } public XmlRequest(String host, int port) { this(host, port, "http"); } public XmlRequest(String host, int port, String protocol) { this.host = host; this.port = port; this.protocol = protocol; setMethod(Method.GET); state.addCookie(cookie); client.setState(state); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setHostConfiguration(config); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); // This will exclude the NTLM authentication scheme client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } /** * Build a {@link XmlRequest} based on the URL passed. * @param url the URL to be requested. */ public XmlRequest(URL url) { this(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url .getPort(), url.getProtocol()); address = url.getPath(); query = url.getQuery(); } public String getHost() { return host; } public int getPort() { return port; } public String getAddress() { return address; } public Method getMethod() { return method; } public String getSentData() { return sentData; } public String getReceivedData() { return receivedData; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setAddress(String address) { this.address = address; } // --------------------------------------------------------------------------- public void setUrl(URL url) { host = url.getHost(); port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort(); protocol = url.getProtocol(); address = url.getPath(); query = url.getQuery(); } public void setMethod(Method m) { method = m; } public void setUseSOAP(boolean yesno) { useSOAP = yesno; } public void setUseProxy(boolean yesno) { useProxy = yesno; } public void setProxyHost(String host) { proxyHost = host; } public void setProxyPort(int port) { proxyPort = port; } public void setProxyCredentials(String username, String password) { if (username == null || username.trim().length() == 0) return; Credentials cred = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); client.getState().setProxyCredentials(scope, cred); proxyAuthent = true; } public void clearParams() { alSimpleParams.clear(); postParams = null; } public void addParam(String name, Object value) { if (value != null) alSimpleParams.add(new NameValuePair(name, value.toString())); method = Method.GET; } public void setRequest(Element request) { postParams = (Element) request.detach(); method = Method.POST; } /** * Sends an xml request and obtains an xml response */ public Element execute(Element request) throws IOException, BadXmlResponseEx, BadSoapResponseEx { setRequest(request); return execute(); } /** * Sends a request and obtains an xml response. The request can be a GET or * a POST depending on the method used to set parameters. Calls to the * 'addParam' method set a GET request while the setRequest method sets a * POST/xml request. */ public Element execute() throws IOException, BadXmlResponseEx, BadSoapResponseEx { HttpMethodBase httpMethod = setupHttpMethod(); Element response = doExecute(httpMethod); if (useSOAP) response = soapUnembed(response); return response; } /** * Sends the content of a file using a POST request and gets the response in * xml format. */ public Element send(String name, File inFile) throws IOException, BadXmlResponseEx, BadSoapResponseEx { Part[] parts = new Part[alSimpleParams.size() + 1]; int partsIndex = 0; parts[partsIndex] = new FilePart(name, inFile); for (NameValuePair nv : alSimpleParams) parts[++partsIndex] = new StringPart(nv.getName(), nv.getValue()); PostMethod post = new PostMethod(); post.setRequestEntity(new MultipartRequestEntity(parts, post .getParams())); post.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml"); post.setPath(address); post.setDoAuthentication(useAuthent()); // --- execute request Element response = doExecute(post); if (useSOAP) response = soapUnembed(response); return response; } public void setCredentials(String username, String password) { Credentials cred = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); client.getState().setCredentials(scope, cred); client.getParams().setAuthenticationPreemptive(true); serverAuthent = true; } private Element doExecute(HttpMethodBase httpMethod) throws IOException, BadXmlResponseEx { config.setHost(host, port, Protocol.getProtocol(protocol)); if (useProxy) config.setProxy(proxyHost, proxyPort); byte[] data = null; try { client.executeMethod(httpMethod); data = httpMethod.getResponseBody(); // HttpClient is unable to automatically handle redirects of entity // enclosing methods such as POST and PUT. // Get the location header and run the request against it. String redirectLocation; Header locationHeader = httpMethod.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); httpMethod.setPath(redirectLocation); client.executeMethod(httpMethod); data = httpMethod.getResponseBody(); } return Xml.loadStream(new ByteArrayInputStream(data)); } catch (JDOMException e) { throw new BadXmlResponseEx(new String(data, "UTF8")); } finally { httpMethod.releaseConnection(); sentData = getSentData(httpMethod); receivedData = getReceivedData(httpMethod, data); } } private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException { HttpMethodBase httpMethod; if (method == Method.GET) { httpMethod = new GetMethod(); if (query != null && !query.equals("")) httpMethod.setQueryString(query); else if (alSimpleParams.size() != 0) httpMethod.setQueryString(alSimpleParams .toArray(new NameValuePair[alSimpleParams.size()])); httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml"); httpMethod.setFollowRedirects(true); } else { PostMethod post = new PostMethod(); if (!useSOAP) { postData = (postParams == null) ? "" : Xml .getString(new Document(postParams)); post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8")); } else { postData = Xml.getString(new Document(soapEmbed(postParams))); post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8")); } httpMethod = post; } httpMethod.setPath(address); httpMethod.setDoAuthentication(useAuthent()); return httpMethod; } private String getSentData(HttpMethodBase httpMethod) { String sentData = httpMethod.getName() + " " + httpMethod.getPath(); if (httpMethod.getQueryString() != null) sentData += "?" + httpMethod.getQueryString(); sentData += "\r\n"; for (Header h : httpMethod.getRequestHeaders()) sentData += h; sentData += "\r\n"; if (httpMethod instanceof PostMethod) sentData += postData; return sentData; } private String getReceivedData(HttpMethodBase httpMethod, byte[] response) { String receivedData = ""; try { // --- if there is a connection error (the server is unreachable) // this // --- call causes a NullPointerEx receivedData = httpMethod.getStatusText() + "\r\r"; for (Header h : httpMethod.getResponseHeaders()) receivedData += h; receivedData += "\r\n"; if (response != null) receivedData += new String(response, "UTF8"); } catch (Exception e) { receivedData = ""; } return receivedData; } private Element soapEmbed(Element elem) { Element envl = new Element("Envelope", NAMESPACE_ENV); Element body = new Element("Body", NAMESPACE_ENV); envl.addContent(body); body.addContent(elem); return envl; } @SuppressWarnings("unchecked") private Element soapUnembed(Element envelope) throws BadSoapResponseEx { Namespace ns = envelope.getNamespace(); Element body = envelope.getChild("Body", ns); if (body == null) throw new BadSoapResponseEx(Xml.getString(envelope)); List<Element> list = body.getChildren(); if (list.size() == 0) throw new BadSoapResponseEx(Xml.getString(envelope)); return list.get(0); } private boolean useAuthent() { return proxyAuthent || serverAuthent; } private String host; private int port; private String protocol; private String address; private boolean serverAuthent; private String query; private Method method; private boolean useSOAP; private Element postParams; private boolean useProxy; private String proxyHost; private int proxyPort; private boolean proxyAuthent; private HttpClient client = new HttpClient(); private HttpState state = new HttpState(); private Cookie cookie = new Cookie(); private HostConfiguration config = new HostConfiguration(); private ArrayList<NameValuePair> alSimpleParams = new ArrayList<NameValuePair>(); // --- transient vars private String sentData; private String receivedData; private String postData; }
gpl-3.0
applifireAlgo/HR
hrproject/src/main/java/demo/app/server/bean/ProjectBean.java
2817
package demo.app.server.bean; import java.util.ArrayList; import java.util.Date; import javax.persistence.Column; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * */ public class ProjectBean { private int projectId; private String projectName; private String projectDesc; private String domainName; private int databaseId; private String schemaName; private String userId; private String password; private ArrayList<Integer> components; private String email; public ProjectBean() { super(); } @Override public String toString() { return "ProjectBean [projectId=" + projectId + ", projectName=" + projectName + ", projectDesc=" + projectDesc + ", domainName=" + domainName + ", databaseId=" + databaseId + ", schemaName=" + schemaName + ", userId=" + userId + ", password=" + password + ", components=" + components + ", email=" + email + "]"; } public ProjectBean(int projectId, String projectName, String projectDesc, String domainName, int databaseId, String schemaName, String userId, String password, ArrayList<Integer> components, String email) { super(); this.projectId = projectId; this.projectName = projectName; this.projectDesc = projectDesc; this.domainName = domainName; this.databaseId = databaseId; this.schemaName = schemaName; this.userId = userId; this.password = password; this.components = components; this.email = email; } public int getDatabaseId() { return databaseId; } public void setDatabaseId(int databaseId) { this.databaseId = databaseId; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getProjectDesc() { return projectDesc; } public void setProjectDesc(String projectDesc) { this.projectDesc = projectDesc; } public String getDomainName() { return domainName; } public void setDomainName(String domainName) { this.domainName = domainName; } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ArrayList<Integer> getComponents() { return components; } public void setComponents(ArrayList<Integer> components) { this.components = components; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } }
gpl-3.0
malsadig/rsbotscripts
src/org/sol/core/ui/Paint.java
6290
package org.sol.core.ui; import org.powerbot.script.rt6.Constants; import org.sol.core.script.Contextable; import org.sol.core.script.Methods; import org.sol.util.Timer; import java.awt.*; import java.util.HashMap; import java.util.List; import java.util.Map; public class Paint extends Contextable { public final Timer RUN_TIME = new Timer(0); private final MouseTrail trail = new MouseTrail(); private static final String[] SKILL_NAMES = {"attack", "defence", "strength", "constitution", "range", "prayer", "magic", "cooking", "woodcutting", "fletching", "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction", "summoning", "dungeoneering"}; private static final Color[] COLORS = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.ORANGE}; public final Skill[] SKILL_LIST = new Skill[SKILL_NAMES.length]; static final BasicStroke STROKE_2 = new BasicStroke(2); public final Map<String, Movable> movables; private final String title; private final Color color; private int startY = 45; public Paint(final Methods methods, final String title) { super(methods); this.title = title; final int rand = (int) (Math.random() * (COLORS.length)); this.color = COLORS[rand]; for (int i = 0; i < SKILL_NAMES.length; i++) { SKILL_LIST[i] = new Skill(i); } this.movables = new HashMap<String, Movable>(); } public class Skill { private final int startXp; private final int startLvl; private final int index; private final String name; public int expPerHour; public Skill(final int index) { this.index = index; this.name = SKILL_NAMES[index].substring(0, 1).toUpperCase() + SKILL_NAMES[index].substring(1); this.startLvl = methods.context.skills.realLevel(index);//todo this.startXp = methods.context.skills.experience(index); } public final boolean isValid() { int experience = methods.context.skills.experience(index); return (experience - startXp) != 0; } public double getRatio() { final double currExp = methods.context.skills.experience(index); final int currLvl = methods.context.skills.realLevel(index); if (currLvl > 98) { return 100; } double currLvlExp = Constants.SKILLS_XP[currLvl], nextLvlExp = Constants.SKILLS_XP[currLvl + 1]; return ((currExp - currLvlExp) / (nextLvlExp - currLvlExp)); } public int getPercent() { return (int) (getRatio() * 100); } public String getPaintLineInfo() { final int currExp = methods.context.skills.experience(index); final int expGained = currExp - startXp; final int currLevel = methods.context.skills.realLevel(index); final int levelsGained = currLevel - startLvl; expPerHour = (int) (3600000.0 / (double) (RUN_TIME.getElapsed()) * expGained); long ttl = 0; if (currLevel != 99) { long nextLvlExp = Constants.SKILLS_XP[currLevel + 1]; ttl = (RUN_TIME.getElapsed() * (nextLvlExp - currExp)) / expGained; } return name + ": Exp Gained: " + expGained + " (" + expPerHour + " /hr) | " + getPercent() + "% to lvl " + (currLevel + 1) + " (+" + levelsGained + ") | TTL: " + format(ttl); } } public void draw(final Graphics2D graphics, final List<String> skillsTrained) { String text = title + " | Run Time: " + format(RUN_TIME.getElapsed()) + " | " + methods.status; if (movables.containsKey(title)) { movables.get(title).texts.set(0, text); } else { Movable m = new MovableRectangle(methods, 7, startY, color); m.texts.add(text); movables.put(title, m); startY += 40; } for (Skill skill : SKILL_LIST) { if (skillsTrained.isEmpty() || skillsTrained.contains(skill.name)) { int realLevel = methods.context.skills.realLevel(skill.index); if (skill.isValid() && realLevel < 99) { if (!movables.containsKey(skill.name)) { Movable m = new SkillRectangle(methods, startY, color, skill.getPaintLineInfo(), skill.index); movables.put(skill.name, m); startY += 40; } else { movables.get(skill.name).texts.set(0, skill.getPaintLineInfo()); } } } } if (!methods.loot.isEmpty()) { if (movables.containsKey("Loot")) { ((LootRectangle) movables.get("Loot")).update(false); } else { LootRectangle loot = new LootRectangle(methods, 7, startY, color); loot.update(true); movables.put("Loot", loot); } } for (final Movable movable : movables.values()) { movable.draw(graphics, methods); } Point location = methods.context.input.getLocation(); trail.add(location); graphics.setColor(color); trail.draw(graphics); } public static String format(final long time) { final StringBuilder t = new StringBuilder(); final long total_secs = time / 1000; final long total_minutes = total_secs / 60; final long total_hrs = total_minutes / 60; final int secs = (int) total_secs % 60; final int minutes = (int) total_minutes % 60; final int hrs = (int) total_hrs % 60; if (hrs < 10) { t.append("0"); } t.append(hrs); t.append(":"); if (minutes < 10) { t.append("0"); } t.append(minutes); t.append(":"); if (secs < 10) { t.append("0"); } t.append(secs); return t.toString(); } }
gpl-3.0
aguillem/festival-manager
festival-manager-core/src/main/java/com/aguillem/festival/manager/core/dto/IdLabelLinkedCriteriaDto.java
1121
package com.aguillem.festival.manager.core.dto; import org.scub.foundation.framework.core.interfaces.dto.IdLabelCriteriaDto; /** * Criteria for IdLabelDto linked to an other object. * @author Anthony Guillemette (anthony.guillemette@gmail.com) */ public class IdLabelLinkedCriteriaDto extends IdLabelCriteriaDto { private static final long serialVersionUID = 5530445469962780225L; private Long linkId; public IdLabelLinkedCriteriaDto() { super(); } public IdLabelLinkedCriteriaDto(String filter) { super(filter); } public IdLabelLinkedCriteriaDto(String filter, Long linkId) { super(filter); this.linkId = linkId; } /** * Get linkId. * @return the linkId */ public Long getLinkId() { return linkId; } /** * Set linkId. * @param linkId the linkId to set */ public void setLinkId(Long linkId) { this.linkId = linkId; } @Override public String toString() { return "IdLabelLinkedCriteriaDto [linkId=" + linkId + ", toString()=" + super.toString() + "]"; } }
gpl-3.0
sne11ius/stunden
src/main/java/nu/wasis/stunden/model/Day.java
3616
package nu.wasis.stunden.model; import java.util.Collection; import java.util.List; import org.joda.time.DateTime; import org.joda.time.Duration; /** * A day full of work. */ public class Day implements Comparable<Day> { private final DateTime date; private final List<Entry> entries; /** * Create a new {@link Day} object. * @param date The date of this day. The exact time (hours, minutes etc.) of * the used {@link DateTime} object are supposed to be ignored. Must * not be <code>null</code>. * @param entries A {@link List} of {@link Entry} objects that occured on * this day. Must not be <code>null</code>. */ public Day(final DateTime date, final List<Entry> entries) { if (null == date) { throw new IllegalArgumentException("Param `date' must not be null."); } if (null == entries) { throw new IllegalArgumentException("Param `entries' must not be null."); } this.date = new DateTime(date); this.entries = entries; } public DateTime getDate() { return new DateTime(date); } public List<Entry> getEntries() { return entries; } /** * Check if the {@link Day} is tagged with a tag. * @param tag The tag to check. * @return <code>true</code> if any of the {@link Entry}s of this day is * tagged with the provided tag. Else <code>false</code>. */ public boolean isTagged(final String tag) { for (final Entry entry : entries) { if (entry.isTagged(tag)) { return true; } } return false; } /** * Check if the {@link Day} is tagged with any of the provided tags. * @param tags A collection of tags to be checked. * @return <code>true</code> if any of the {@link Entry}s of this day is * tagged with any of the provided tags. Else <code>false</code>. */ public boolean isTagged(final Collection<String> tags) { for (final String tag : tags) { if (isTagged(tag)) { return true; } } return false; } /** * Get the total (billable) work duration for this {@link Day}. * * @return The sum of the (billable) work durations of all {@link Entry}s of * this day. {@link Entry}s are skipped if their * <code>isBreak</code> method returns <code>true</code>. */ public Duration getWorkDuration() { Duration duration = new Duration(0); for (final Entry entry : entries) { if (!entry.isBreak()) { duration = duration.plus(entry.getDuration()); } } return duration; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date == null) ? 0 : date.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Day other = (Day) obj; if (date == null) { if (other.date != null) { return false; } } else if (!date.equals(other.date)) { return false; } return true; } @Override public int compareTo(final Day other) { return getDate().compareTo(other.getDate()); } @Override public String toString() { return "Day [date=" + date + ", entries=" + entries + "]"; } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/rec/view/util/RecConstants.java
7860
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.rec.view.util; public interface RecConstants { // ---> TipoObra public static final String ACTION_BUSCAR_TIPOOBRA = "buscarTipoObra"; public static final String ACTION_ADMINISTRAR_TIPOOBRA = "administrarTipoObra"; public static final String FWD_TIPOOBRA_SEARCHPAGE = "tipoObraSearchPage"; public static final String FWD_TIPOOBRA_VIEW_ADAPTER = "tipoObraViewAdapter"; public static final String FWD_TIPOOBRA_EDIT_ADAPTER = "tipoObraEditAdapter"; // <--- TipoObra // ---> FormaPago public static final String ACTION_BUSCAR_FORMAPAGO = "buscarFormaPago"; public static final String ACTION_ADMINISTRAR_FORMAPAGO = "administrarFormaPago"; public static final String FWD_FORMAPAGO_SEARCHPAGE = "formaPagoSearchPage"; public static final String FWD_FORMAPAGO_VIEW_ADAPTER = "formaPagoViewAdapter"; public static final String FWD_FORMAPAGO_EDIT_ADAPTER = "formaPagoEditAdapter"; // <--- FormaPago // ---> Contrato public static final String ACTION_BUSCAR_CONTRATO = "buscarContrato"; public static final String ACTION_ADMINISTRAR_CONTRATO = "administrarContrato"; public static final String FWD_CONTRATO_SEARCHPAGE = "contratoSearchPage"; public static final String FWD_CONTRATO_VIEW_ADAPTER = "contratoViewAdapter"; public static final String FWD_CONTRATO_EDIT_ADAPTER = "contratoEditAdapter"; // <--- Contrato // ---> PlanillaCuadra (Encabezado) public static final String ACTION_BUSCAR_PLANILLACUADRA = "buscarPlanillaCuadra"; public static final String FWD_PLANILLACUADRA_SEARCHPAGE = "planillaCuadraSearchPage"; public static final String ACTION_ADMINISTRAR_PLANILLACUADRA = "administrarPlanillaCuadra"; public static final String FWD_PLANILLACUADRA_VIEW_ADAPTER = "planillaCuadraViewAdapter"; public static final String FWD_PLANILLACUADRA_ENC_EDIT_ADAPTER = "planillaCuadraEncEditAdapter"; public static final String ACTION_BUSCAR_CALLE = "buscarCalle"; public static final String FWD_PLANILLACUADRA_ADAPTER = "planillaCuadraAdapter"; public static final String ACTION_ADMINISTRAR_ENC_PLANILLACUADRA = "administrarEncPlanillaCuadra"; public static final String PATH_ADMINISTRAR_PLANILLACUADRA = "/rec/AdministrarPlanillaCuadra"; // utilizado para redirigir en el agregar PlanillaCuadra public static final String ACT_CAMBIAR_ESTADO = "cambiarEstado"; public static final String ACT_INFORMAR_CATASTRALES = "informarCatastrales"; public static final String ACT_MODIFICAR_NUMERO_CUADRA = "modificarNumeroCuadra"; public static final String MTD_PARAM_CALLE = "paramCalle"; // <--- PlanillaCuadra (Encabezado) // ---> PlaCuaDet (Detalle) public static final String ACTION_BUSCAR_PLACUADET = "buscarPlaCuaDet"; public static final String FWD_PLACUADET_SEARCHPAGE = "plaCuaDetSearchPage"; public static final String ACTION_ADMINISTRAR_PLACUADET = "administrarPlaCuaDet"; public static final String FWD_PLACUADET_ADAPTER = "plaCuaDetAdapter"; public static final String FWD_PLACUADET_VIEW_ADAPTER = "plaCuaDetViewAdapter"; public static final String FWD_PLACUADET_EDIT_ADAPTER = "plaCuaDetEditAdapter"; // <--- PlaCuaDet // Mantenedor de Obra // ---> Obra (Encabezado) public static final String ACTION_BUSCAR_OBRA = "buscarObra"; public static final String FWD_OBRA_SEARCHPAGE = "obraSearchPage"; public static final String ACTION_ADMINISTRAR_OBRA = "administrarObra"; public static final String FWD_OBRA_VIEW_ADAPTER = "obraViewAdapter"; public static final String FWD_OBRA_ENC_EDIT_ADAPTER = "obraEncEditAdapter"; public static final String FWD_OBRA_ADAPTER = "obraAdapter"; public static final String ACTION_ADMINISTRAR_ENC_OBRA = "administrarEncObra"; public static final String PATH_ADMINISTRAR_OBRA = "/rec/AdministrarObra"; // utilizado para redirigir en el agregar Obra // <--- Obra // ---> ObraFormaPago (Detalle) public static final String ACTION_ADMINISTRAR_OBRAFORMAPAGO = "administrarObraFormaPago"; public static final String FWD_OBRAFORMAPAGO_ADAPTER = "obraFormaPagoAdapter"; public static final String FWD_OBRAFORMAPAGO_VIEW_ADAPTER = "obraFormaPagoViewAdapter"; public static final String FWD_OBRAFORMAPAGO_EDIT_ADAPTER = "obraFormaPagoEditAdapter"; // <--- ObraFormaPago // ---> ObraPlanillaCuadra (Detalle) public static final String ACTION_ADMINISTRAR_OBRAPLANILLACUADRA = "administrarObraPlanillaCuadra"; public static final String FWD_OBRAPLANILLACUADRA_VIEW_ADAPTER = "obraPlanillaCuadraViewAdapter"; public static final String FWD_OBRAPLANILLACUADRA_SELECT_SEARCHPAGE = "planillaCuadraSearchPage"; // <--- ObraPlanillaCuadra // ---> ObrRepVen (Detalle) public static final String ACTION_ADMINISTRAR_OBRREPVEN = "administrarObrRepVen"; public static final String FWD_OBRREPVEN_EDIT_ADAPTER = "obrRepVenEditAdapter"; // <--- ObrRepVen (Detalle) // ---> Asignar repartidores a planillas public static final String ACTION_BUSCARPLANILLAS_FORASIGNARREPARTIDOR = "buscarPlanillasForAsignarRepartidor"; public static final String FWD_PLANILLACUADRA_FORASIGNARREPARTIDOR = "planillaCuadraForAsignarRepartidor"; public static final String ACT_OBRA_ASIGNAR_REPARTIDOR = "asignarRepartidor"; public static final String MTD_PARAM_CALLE_FORASIGNARREPARTIDOR = "paramCalleForAsignarRepartidor"; // <--- Asignar repartidores a planillas // Fin Mantenedor de Obra // ---> UsoCdM public static final String ACTION_BUSCARUSOCDM = "buscarUsoCdM"; public static final String ACTION_ADMINISTRAR_USOCDM = "administrarUsoCdM"; public static final String FWD_USOCDM_SEARCHPAGE = "usoCdMSearchPage"; public static final String FWD_USOCDM_VIEW_ADAPTER = "usoCdMViewAdapter"; public static final String FWD_USOCDM_EDIT_ADAPTER = "usoCdMEditAdapter"; // <--- UsoCdM // ---> AnulacionObra public static final String ACTION_ADMINISTRAR_ANULACIONOBRA = "administrarAnulacionObra"; public static final String ACTION_ADMINISTRAR_PROCESO_ANULACIONOBRA = "administrarProcesoAnulacionObra"; public static final String FWD_ANULACIONOBRA_SEARCHPAGE = "anulacionObraSearchPage"; public static final String FWD_ANULACIONOBRA_EDIT_ADAPTER = "anulacionObraEditAdapter"; public static final String FWD_ANULACIONOBRA_VIEW_ADAPTER = "anulacionObraViewAdapter"; public static final String ACT_ADM_PROCESO_ANULACION_OBRA = "administrarProceso"; public static final String FWD_PROCESO_ANULACION_OBRA_ADAPTER = "procesoAnulacionObraAdapter"; // <--- AnulacionObra // ---> Novedad RS public static final String FWD_NOVEDADRS_SEARCHPAGE = "novedadRSSearchPage"; public static final String ACTION_BUSCAR_NOVEDADRS = "buscarNovedadRS"; public static final String ACTION_ADMINISTRAR_NOVEDADRS = "administrarNovedadRS"; public static final String FWD_NOVEDADRS_VIEW_ADAPTER = "novedadRSViewAdapter"; public static final String FWD_NOVEDADRS_EDIT_ADAPTER = "novedadRSEditAdapter"; public static final String ACT_APLICAR_NOVEDADRS = "aplicar"; public static final String ACT_APLICAR_MASIVO_NOVEDADRS = "aplicarMasivo"; public static final String FWD_CATRSDREI_EDIT_ADAPTER = "catRSDreiEditAdapter"; public static final String FWD_CATRSDREI_SEARCHPAGE = "catRSDreiSearchPage"; public static final String ACTION_ADMINISTRAR_CATRSDREI = "administrarCatRSDrei"; public static final String FWD_CATRSDREI_VIEW_ADAPTER = "catRSDreiViewAdapter"; }
gpl-3.0
stacs-srg/utilities
src/main/java/uk/ac/standrews/cs/utilities/crypto/Utils.java
1083
/* * Copyright 2021 Systems Research Group, University of St Andrews: * <https://github.com/stacs-srg> * * This file is part of the module utilities. * * utilities 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. * * utilities 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 utilities. If not, see * <http://www.gnu.org/licenses/>. */ package uk.ac.standrews.cs.utilities.crypto; import java.nio.file.Path; import java.nio.file.Paths; /** * @author Simone I. Conte "sic2@st-andrews.ac.uk" */ class Utils { static Path extension(Path path, String extension) { return Paths.get(path.toString() + extension); } }
gpl-3.0
PhaniGaddipati/Stacks-Flashcards
src/main/java/com/google/android/apps/dashclock/ui/SwipeDismissGridViewTouchListener.java
14664
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.dashclock.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.graphics.Rect; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.GridView; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SwipeDismissGridViewTouchListener implements View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values private int mSlop; private int mMinFlingVelocity; private int mMaxFlingVelocity; private long mAnimationTime; // Fixed properties private GridView mGridView; private DismissCallbacks mCallbacks; private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero // Transient properties private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>(); private int mDismissAnimationRefCount = 0; private float mDownX; private boolean mSwiping; private VelocityTracker mVelocityTracker; private int mDownPosition; private View mDownView; private boolean mPaused; /** * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client * about a successful dismissal of one or more list item positions. */ public interface DismissCallbacks { /** * Called to determine whether the given position can be dismissed. */ boolean canDismiss(int position); /** * Called when the user has indicated they she would like to dismiss one or more list item * positions. * * @param gridView The originating {@link ListView}. * @param reverseSortedPositions An array of positions to dismiss, sorted in descending * order for convenience. */ void onDismiss(GridView gridView, int[] reverseSortedPositions); } /** * Constructs a new swipe-to-dismiss touch listener for the given list view. * * @param listView The list view whose items should be dismissable. * @param callbacks The callback to trigger when the user has indicated that she would like to * dismiss one or more list items. */ public SwipeDismissGridViewTouchListener(GridView listView, DismissCallbacks callbacks) { ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); mSlop = vc.getScaledTouchSlop(); mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16; mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); mAnimationTime = listView.getContext().getResources().getInteger( android.R.integer.config_shortAnimTime); mGridView = listView; mCallbacks = callbacks; } /** * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. * * @param enabled Whether or not to watch for gestures. */ public void setEnabled(boolean enabled) { mPaused = !enabled; } /** * Returns an {@link android.widget.AbsListView.OnScrollListener} to be added to the {@link * ListView} using {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}. * If a scroll listener is already assigned, the caller should still pass scroll changes through * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is * paused during list view scrolling.</p> * * @see SwipeDismissListViewTouchListener */ public AbsListView.OnScrollListener makeScrollListener() { return new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); } @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) { } }; } /** * Manually cause the item at the given position to be dismissed (trigger the dismiss * animation). */ public void dismiss(int position) { dismiss(getViewForPosition(position), position, true); } @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mGridView.getWidth() / mGridView.getNumColumns(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mGridView.getChildCount(); int[] listViewCoords = new int[2]; mGridView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = mGridView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownPosition = mGridView.getPositionForView(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss dismiss(mDownView, mDownPosition, dismissRight); } else { // cancel mDownView.animate() .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_CANCEL: { if (mVelocityTracker == null) { break; } if (mDownView != null) { // cancel mDownView.animate() .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { mSwiping = true; mGridView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mGridView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX); mDownView.setAlpha(Math.max(0.15f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; } private void dismiss(final View view, final int position, boolean dismissRight) { ++mDismissAnimationRefCount; if (view == null) { // No view, shortcut to calling onDismiss to let it deal with adapter // updates and all that. mCallbacks.onDismiss(mGridView, new int[]{position}); return; } view.animate() .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(view, position); } }); } private View getViewForPosition(int position) { int index = position - (mGridView.getFirstVisiblePosition()); return (index >= 0 && index < mGridView.getChildCount()) ? mGridView.getChildAt(index) : null; } class PendingDismissData implements Comparable<PendingDismissData> { public int position; public View view; public PendingDismissData(int position, View view) { this.position = position; this.view = view; } @Override public int compareTo(PendingDismissData other) { // Sort by descending position return other.position - position; } } private void performDismiss(final View dismissView, final int dismissPosition) { // Animate the dismissed list item to zero-height and fire the dismiss callback when // all dismissed list item animations have completed. This triggers layout on each animation // frame; in the future we may want to do something smarter and more performant. final ViewGroup.LayoutParams lp = dismissView.getLayoutParams(); final int originalHeight = dismissView.getHeight(); ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { --mDismissAnimationRefCount; if (mDismissAnimationRefCount == 0) { // No active animations, process all pending dismisses. // Sort by descending position Collections.sort(mPendingDismisses); int[] dismissPositions = new int[mPendingDismisses.size()]; for (int i = mPendingDismisses.size() - 1; i >= 0; i--) { dismissPositions[i] = mPendingDismisses.get(i).position; } mCallbacks.onDismiss(mGridView, dismissPositions); ViewGroup.LayoutParams lp; for (PendingDismissData pendingDismiss : mPendingDismisses) { // Reset view presentation pendingDismiss.view.setAlpha(1f); pendingDismiss.view.setTranslationX(0); lp = pendingDismiss.view.getLayoutParams(); lp.height = originalHeight; pendingDismiss.view.setLayoutParams(lp); } mPendingDismisses.clear(); } } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { lp.height = (Integer) valueAnimator.getAnimatedValue(); dismissView.setLayoutParams(lp); } }); mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView)); animator.start(); } }
gpl-3.0
jasonleaster/TheWayToJava
SimpleWebApp/src/main/java/org/jasonleaster/bookstore/util/AttributesKey.java
993
package org.jasonleaster.bookstore.util; public class AttributesKey { private AttributesKey(){} public final static String SESSION_ATTRIBUTES_USER = "user"; public final static String SESSION_ATTRIBUTES_ADMIN = "admin"; public final static String SESSION_ATTRIBUTES_USER_QUERY_FORM = "userQueryForm"; public final static String SESSION_ATTRIBUTES_BOOK_QUERY_FORM = "bookQueryForm"; public final static String SESSION_ATTRIBUTES_RECORD_QUERY_FORM = "recordQueryForm"; public final static String MODEL_ATTRIBUTES_USER = "book"; public final static String MODEL_ATTRIBUTES_BOOK = "book"; public final static String MODEL_ATTRIBUTES_BOOKS = "books"; public final static String MODEL_ATTRIBUTES_RECORDS = "records"; public final static String MODEL_ATTRIBUTES_RECORDS_FORM = "recordsForm"; public final static String MODEL_ATTRIBUTES_ERR_MSG = "errMsg"; public final static String MODEL_ATTRIBUTES_PAGEINFO= "pageInfo"; }
gpl-3.0
DarioGT/OMS-PluginXML
org.modelsphere.jack/src/org/modelsphere/jack/baseDb/assistant/JHtmlBallonHelp.java
31986
/************************************************************************* Copyright (C) 2009 Grandite This file is part of Open ModelSphere. Open ModelSphere 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can redistribute and/or modify this particular file even under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can reach Grandite at: 20-1220 Lebourgneuf Blvd. Quebec, QC Canada G2K 2G4 or open-modelsphere@grandite.com **********************************************************************/ package org.modelsphere.jack.baseDb.assistant; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyVetoException; import java.net.URL; import java.util.*; import javax.swing.*; import javax.swing.border.SoftBevelBorder; import javax.swing.event.*; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeSelectionModel; import org.modelsphere.jack.debug.Debug; import org.modelsphere.jack.international.LocaleMgr; public abstract class JHtmlBallonHelp extends JInternalFrame implements MouseListener, ListSelectionListener { private static final String kShowHelpExplorer = LocaleMgr.screen.getString("ShowHelpExplorer"); private static final String kHideHelpExplorer = LocaleMgr.screen.getString("HideHelpExplorer"); protected Vector indexList; protected Vector indexPages; protected Vector categoryList; protected Vector bookList; protected Vector htmlPagesTocList; protected Vector vec; protected Vector searchVector; protected Vector titles; protected JButton backButton = null; protected JButton exitButton = null; protected JButton refreshButton = null; protected JButton forwardButton = null; protected JButton printButton = null; protected JButton showHideButton = null; // protected JButton findButton = null; protected JEditorPane baloonHelpPane; protected JScrollPane baloonHelpView; protected JScrollPane listScrollPane; protected JScrollPane findListScrollPane; protected JList list; protected JList findList; protected JTabbedPane tabbedPane = new JTabbedPane(); protected JTextField indexField; protected JPanel indexPane; protected JPanel findPane; // protected JTextField findTextField; protected JTextField searchTextField; protected String keyWord = ""; protected String findTextFieldEntry = ""; protected URL helpURL; protected URL startURL; protected URL link; protected URL[] historyUrl = new URL[10]; protected URL currentURL; protected int i = 0; protected int numberOfEntries = 0; protected int[] pos = new int[400]; protected int select = 0; protected int x = 0; protected int j = 0; protected String helpRootDirectory; public JHtmlBallonHelp(String helpRootDirectory) { super(LocaleMgr.screen.getString("help"), true, true, true, true); // resizable, // closable, // maximizable, // iconifiable this.helpRootDirectory = helpRootDirectory; getIndexPages(); getIndexEntries(); // //////Table Of Contents // Create the nodes. DefaultMutableTreeNode top = new DefaultMutableTreeNode(getRootNodeName()); createNodes(top); // Create a tree that allows one selection at a time. JTree tree = new JTree(top); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer .setClosedIcon(new ImageIcon(LocaleMgr.class.getResource("resources/booknode.gif"))); renderer.setOpenIcon(new ImageIcon(LocaleMgr.class.getResource("resources/opennode.gif"))); renderer.setLeafIcon(new ImageIcon(LocaleMgr.class.getResource("resources/leafnode.gif"))); tree.setCellRenderer(renderer); // Listen for when the selection changes. tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) (e.getPath() .getLastPathComponent()); Object nodeInfo = node.getUserObject(); if (node.isLeaf()) { BookInfo book = (BookInfo) nodeInfo; displayURL(book.bookURL, true); } else { displayURL(helpURL, false); } } }); // Create the scroll pane and add the tree to it. JScrollPane treeView = new JScrollPane(tree); // //end of TOC // ///INDEX PANE START // /Index TextField indexField = new JTextField(20); indexField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { synchIndexFieldList(); } }); // List list = new JList(indexList); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(this); listScrollPane = new JScrollPane(list); listScrollPane.setMinimumSize(new Dimension(100, 50)); // Index Panel indexPane = new JPanel(new BorderLayout()); indexPane.add(indexField, BorderLayout.NORTH); indexPane.add(listScrollPane, BorderLayout.CENTER); // /////INDEX PANE STOP // Find Pane // ///Find TextField // findTextField = new JTextField(); // findTextField.setMaximumSize (new Dimension(100, 20)); // findTextField.setAlignmentY (-45); // findTextField.setToolTipText("Find in Document"); // NOT LOCALIZABLE // /Search TextField searchTextField = new JTextField(); searchTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { JSearch search = new JSearch(searchTextField.getText(), JHtmlBallonHelp.this.helpRootDirectory); searchVector = search.getSearchResultVector(); titles = search.getTitle(); findList.setListData(titles); Debug.trace(titles); } }); // find result list findList = new JList(); findList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); findList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList) e.getSource(); if (theList.isSelectionEmpty()) { helpURL = getHtmlFile("welcome.html"); // NOT LOCALIZABLE - // link } else { int index = theList.getSelectedIndex(); helpURL = ((URL) searchVector.elementAt(index)); displayURL(helpURL, true); } } }); findListScrollPane = new JScrollPane(findList); findListScrollPane.setMinimumSize(new Dimension(100, 50)); // find panel findPane = new JPanel(new BorderLayout()); findPane.add(findListScrollPane, BorderLayout.CENTER); findPane.add(searchTextField, BorderLayout.NORTH); // Find Pane // /CONSTRUCTING HELP FRAME // THE Toolbar JToolBar toolBar = new JToolBar(); addButtons(toolBar); // toolBar.add (findTextField); toolBar.setFloatable(false); // THE Tab Pane tabbedPane.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8)); tabbedPane.addTab(LocaleMgr.screen.getString("TOC"), treeView); tabbedPane.addTab(LocaleMgr.screen.getString("Index"), indexPane); tabbedPane.addTab(LocaleMgr.screen.getString("Find"), findPane); tabbedPane.setSelectedIndex(0); // THE HTML Viewer baloonHelpPane = new JEditorPane(); baloonHelpPane.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8)); baloonHelpPane.setEditable(false); baloonHelpPane.addHyperlinkListener(new HyperlinkListener() { public final void hyperlinkUpdate(HyperlinkEvent e) { HyperlinkEvent.EventType type = e.getEventType(); if (type == HyperlinkEvent.EventType.ENTERED) baloonHelpPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); else if (type == HyperlinkEvent.EventType.EXITED) baloonHelpPane.setCursor(Cursor.getDefaultCursor()); else if (type == HyperlinkEvent.EventType.ACTIVATED) { link = e.getURL(); displayURL(link, true); } } }); baloonHelpView = new JScrollPane(baloonHelpPane); baloonHelpView.setPreferredSize(new Dimension(400, 500)); initBaloonHelp(); Container contentPane = getContentPane(); contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(tabbedPane, BorderLayout.WEST); contentPane.add(baloonHelpView, BorderLayout.CENTER); pack(); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } /** * To close the window, you must call this method (do not call dispose). */ public final void close() { try { setClosed(true); } catch (PropertyVetoException e) { } // should not happen } // /CONSTRUCTING HELP FRAME END private URL getHtmlFile(String fileName) { URL helpURL; String pattern; if (fileName.endsWith(".html")) // NOT LOCALIZABLE pattern = "File:{0}/{1}"; // NOT LOCALIZABLE else pattern = "File:{0}/{1}.html"; // NOT LOCALIZABLE String file = java.text.MessageFormat.format(pattern, new Object[] { helpRootDirectory, fileName }); try { helpURL = new URL(file); } catch (java.net.MalformedURLException e) { org.modelsphere.jack.debug.Debug.trace("getHtmlFile bad URL:" + file); // NOT LOCALIZABLE helpURL = null; } return helpURL; } // public URL getResource(String resName){ // return classForGetResource.getResource(resName); // } // /INDEX PROPERTIES public void synchIndexFieldList() { int j = 0; j = numberOfEntries / 2; String s = indexField.getText(); for (int h = 0; h < j; h++) { String indexEntry = ((String) indexList.elementAt(h)); String indexURL = ((String) indexPages.elementAt(h)); if (indexEntry.equals(s)) { list.setSelectedIndex(h); helpURL = getHtmlFile(indexURL); displayURL(helpURL, false); break; } } } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList) e.getSource(); if (theList.isSelectionEmpty()) { helpURL = getHtmlFile("welcome"); // NOT LOCALIZABLE } else { int index = theList.getSelectedIndex(); String page = ((String) indexPages.elementAt(index)); helpURL = getHtmlFile(page); displayURL(helpURL, true); } } protected Vector parseList(String indexList) { Vector v = new Vector(10); StringTokenizer tokenizer = new StringTokenizer(indexList, ","); // NOT // LOCALIZABLE while (tokenizer.hasMoreTokens()) { String index = tokenizer.nextToken(); v.addElement(index); numberOfEntries++; } return v; } public void getIndexEntries() { // getting the list for the index ResourceBundle indexResource; try { indexResource = ResourceBundle.getBundle(getHelpPackageName() + "index"); // NOT LOCALIZABLE String indexEntry = indexResource.getString("index"); // NOT // LOCALIZABLE indexList = parseList(indexEntry); } catch (MissingResourceException e) { Debug.trace("Unable to parse properties file."); return; } } public void getIndexPages() { // getting the corresponding html page for the selected index ResourceBundle indexPagesResource; try { indexPagesResource = ResourceBundle.getBundle(getHelpPackageName() + "html"); // NOT LOCALIZABLE String indexPage = indexPagesResource.getString("html"); // NOT // LOCALIZABLE indexPages = parseList(indexPage); } catch (MissingResourceException e) { Debug.trace("Unable to parse properties file."); return; } } // ///INDEX PROPERTIES END protected final void addButtons(JToolBar toolBar) { // Exit button exitButton = new JButton(new ImageIcon(LocaleMgr.class .getResource("resources/exitover.gif"))); exitButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/exitover.gif"))); exitButton.setRolloverEnabled(true); exitButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/exitover.gif"))); exitButton.setToolTipText(LocaleMgr.screen.getString("ExitHelp")); exitButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); exitButton.setBorderPainted(false); exitButton.setFocusPainted(false); exitButton.addMouseListener(this); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); toolBar.add(exitButton); // Back button backButton = new JButton(new ImageIcon(LocaleMgr.class .getResource("resources/backover.gif"))); backButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/backover.gif"))); backButton.setRolloverEnabled(true); backButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/backover.gif"))); backButton.setToolTipText(LocaleMgr.screen.getString("Back")); backButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); backButton.setBorderPainted(false); backButton.setFocusPainted(false); backButton.setEnabled(false); backButton.addMouseListener(this); backButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { goBack(); } }); toolBar.add(backButton); // forward button forwardButton = new JButton(new ImageIcon(LocaleMgr.class .getResource("resources/forwardover.gif"))); forwardButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/forwardover.gif"))); forwardButton.setRolloverEnabled(true); forwardButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/forwardover.gif"))); forwardButton.setToolTipText(LocaleMgr.screen.getString("Forward")); forwardButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); forwardButton.setBorderPainted(false); forwardButton.setFocusPainted(false); forwardButton.setEnabled(false); forwardButton.addMouseListener(this); forwardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { goNext(); } }); toolBar.add(forwardButton); // refresh button refreshButton = new JButton(new ImageIcon(LocaleMgr.class .getResource("resources/refresh.gif"))); refreshButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/refresh.gif"))); refreshButton.setRolloverEnabled(true); refreshButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/refresh.gif"))); refreshButton.setToolTipText(LocaleMgr.screen.getString("ReloadCurrentDoc")); refreshButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); refreshButton.setBorderPainted(false); refreshButton.setFocusPainted(false); refreshButton.addMouseListener(this); refreshButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { reload(); } }); toolBar.add(refreshButton); // Print button printButton = new JButton(new ImageIcon(LocaleMgr.class.getResource("resources/print.gif"))); printButton .setPressedIcon(new ImageIcon(LocaleMgr.class.getResource("resources/print.gif"))); printButton.setRolloverEnabled(true); printButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/print.gif"))); printButton.setToolTipText(LocaleMgr.screen.getString("PrintCurrentDocument")); printButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); printButton.setBorderPainted(false); printButton.setFocusPainted(false); printButton.addMouseListener(this); printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { print(); } }); toolBar.add(printButton); // Show button showHideButton = new JButton(new ImageIcon(LocaleMgr.class .getResource("resources/hide.gif"))); showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/hide.gif"))); showHideButton.setRolloverEnabled(true); showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/hide.gif"))); showHideButton.setToolTipText(kHideHelpExplorer); showHideButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); showHideButton.setBorderPainted(false); showHideButton.setFocusPainted(false); showHideButton.addMouseListener(this); showHideButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { if (tabbedPane.isVisible()) { showHideToc(true); } else { showHideToc(false); } } }); toolBar.add(showHideButton); /* * toolBar.addSeparator(new Dimension(65,0)); * * //Find button findButton = new JButton(new * ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE * findButton.setPressedIcon(new * ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE * findButton.setRolloverEnabled(true); findButton.setRolloverIcon(new * ImageIcon(Application.class.getResource("resources/find.gif"))); // NOT LOCALIZABLE * findButton.setToolTipText("Show Next Occurence"); // NOT LOCALIZABLE * findButton.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); * findButton.setBorderPainted(false); findButton.setFocusPainted(false); * findButton.addMouseListener(this); findButton.addActionListener(new * java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { * selectOccurence(); } }); toolBar.add(findButton); */ } // ////////////////////////////////////////////// // MouseListener Support // public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { JButton button = ((JButton) e.getSource()); if (!button.isEnabled()) { button.setBorderPainted(false); } } } public void mousePressed(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { JButton button = ((JButton) e.getSource()); if (button.isEnabled()) { button.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED)); } } } public void mouseReleased(MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { JButton button = ((JButton) e.getSource()); button.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); } } public void mouseEntered(MouseEvent e) { JButton button = ((JButton) e.getSource()); if (button.isEnabled()) { button.setBorderPainted(true); } } public void mouseExited(MouseEvent e) { JButton button = ((JButton) e.getSource()); button.setBorderPainted(false); } // ////////////////////////////////////////////// // MouseListener Support END // // ////Navigation Methods // contructing url array for Back and Forward buttons protected final void addStack(URL u) { i++; historyUrl[i] = u; backButton.setEnabled(true); if (i == 9) { for (int j = 0; j <= 8; j++) { historyUrl[j] = historyUrl[j + 1]; } i--; } } // reload protected final void reload() { helpURL = getHtmlFile("empty"); // NOT LOCALIZABLE URL reloadURL = currentURL; displayURL(helpURL, false); displayURL(reloadURL, false); } // print protected final void print() { PrintJob job = Toolkit.getDefaultToolkit().getPrintJob( (Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), LocaleMgr.misc.getString("Help"), null); if (job != null) { Graphics pg = job.getGraphics(); pg.setFont(new Font("arial", Font.PLAIN, 10)); // NOT LOCALIZABLE baloonHelpPane.print(pg); pg.dispose(); job.end(); } } // forward public final void goNext() { try { i++; displayURL(historyUrl[i], false); backButton.setEnabled(true); if (historyUrl[i + 1] == null) { forwardButton.setEnabled(false); } if (i == 8) { forwardButton.setEnabled(false); } } catch (ArrayIndexOutOfBoundsException o) { i = i - 1; } } // back public final void goBack() { try { i--; displayURL(historyUrl[i], false); forwardButton.setEnabled(true); if (i == 0) { backButton.setEnabled(false); } else { } } catch (ArrayIndexOutOfBoundsException o) { i = i + 1; } } // Showing or Hiding the TabPane (for the show/hide button) public final void showHideToc(boolean visible) { if (visible == true) { tabbedPane.setVisible(false); showHideButton .setIcon(new ImageIcon(LocaleMgr.class.getResource("resources/show.gif"))); showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/show.gif"))); showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/show.gif"))); showHideButton.setToolTipText(kShowHelpExplorer); } if (visible == false) { tabbedPane.setVisible(true); showHideButton .setIcon(new ImageIcon(LocaleMgr.class.getResource("resources/hide.gif"))); showHideButton.setPressedIcon(new ImageIcon(LocaleMgr.class .getResource("resources/hide.gif"))); showHideButton.setRolloverIcon(new ImageIcon(LocaleMgr.class .getResource("resources/hide.gif"))); showHideButton.setToolTipText(kHideHelpExplorer); } } // ////Navigation Methods END // //TOC PROPERTIES protected Vector parseToc(String tocList) { Vector v = new Vector(10); StringTokenizer tokenizer = new StringTokenizer(tocList, ","); // NOT // LOCALIZABLE while (tokenizer.hasMoreTokens()) { String index = tokenizer.nextToken(); v.addElement(index); } return v; } // populating the TOC via properties files private void createNodes(DefaultMutableTreeNode top) { DefaultMutableTreeNode category = null; DefaultMutableTreeNode book = null; ResourceBundle TocCategoryResource; ResourceBundle TocBookResource; ResourceBundle TocHtmlPagesResource; // properties for the nodes TocCategoryResource = ResourceBundle.getBundle(getHelpPackageName() + "category"); // NOT LOCALIZABLE // properties for the entries for each nodes TocBookResource = ResourceBundle.getBundle(getHelpPackageName() + "book"); // NOT LOCALIZABLE // properties for the html pages corresponding to each node entries TocHtmlPagesResource = ResourceBundle.getBundle(getHelpPackageName() + "htmlPagesToc"); // NOT LOCALIZABLE for (int c = 0; c < 30; c++) try { String bookNode = ("book" + c); // NOT LOCALIZABLE String bookCategory = ("category" + c); // NOT LOCALIZABLE String bookHtmlPage = ("html" + c); // NOT LOCALIZABLE String tocCategory = TocCategoryResource.getString(bookCategory); String tocBook = TocBookResource.getString(bookNode); String tocHtmlPage = TocHtmlPagesResource.getString(bookHtmlPage); categoryList = parseToc(tocCategory); // adding nodes category = new DefaultMutableTreeNode(tocCategory); top.add(category); // adding entries for each nodes bookList = parseToc(tocBook); htmlPagesTocList = parseToc(tocHtmlPage); for (int b = 0; b < bookList.size(); b++) { String bookEntry = ((String) bookList.elementAt(b)); String bookHtml = ((String) htmlPagesTocList.elementAt(b)); book = new DefaultMutableTreeNode( new BookInfo(bookEntry, getHtmlFile(bookHtml))); category.add(book); } if (bookCategory == null) break; } catch (MissingResourceException e) { break; } } // Find methods // Parsing the EditorPane protected Vector parseText(String input) { Vector v = new Vector(10); StringTokenizer tokenizer = new StringTokenizer(input, " "); // NOT // LOCALIZABLE while (tokenizer.hasMoreTokens()) { String index = tokenizer.nextToken(); v.addElement(index); } return v; } // Returns the position of the first letter of // the word specified in the FindTextField. public final void getPosition(String entry) { try { Document doc = baloonHelpPane.getDocument(); String docString = doc.getText(0, doc.getLength()); vec = parseText(docString); for (int v = 0; v < vec.size(); v++) { String pageEntry = ((String) vec.elementAt(v)); if (pageEntry.equalsIgnoreCase(entry)) { pos[j] = docString.indexOf(pageEntry, select + entry.length()); j++; select = pos[j - 1]; } } j = 0; } catch (BadLocationException b) { } } /* * //Select the occurence from the word //specified in the FindTextField protected final void * selectOccurence(){ findTextFieldEntry = findTextField.getText (); if * (keyWord.equals(findTextFieldEntry)){ baloonHelpPane.select (pos[x], pos[x] + * findTextFieldEntry.length()); x++; } else{ keyWord = findTextFieldEntry; for (int a=0; * a<pos.length; a++) pos[a]=0; getPosition(keyWord); baloonHelpPane.select (pos[0], pos[0] + * findTextFieldEntry.length()); x=1; } if (pos[x]==0){ x=0; } } */ private void initBaloonHelp() { try { helpURL = getHtmlFile("welcome"); // NOT LOCALIZABLE baloonHelpPane.setPage(helpURL); historyUrl[i] = helpURL; currentURL = helpURL; } catch (Exception e) { } } public final void display(Object helpObjectKey) { displayURL(getHtmlFile(getURLForObjectKey(helpObjectKey)), true); } private void displayURL(URL nUrl, boolean stack) { try { baloonHelpPane.setPage(nUrl); currentURL = nUrl; if (stack) addStack(nUrl); } catch (Exception e) { JOptionPane.showMessageDialog(this, LocaleMgr.message.getString("helpnotfound")); } } // ////////////////////////////////////// // Abstract Methods // public abstract String getHelpPackageName(); public abstract String getRootNodeName(); public abstract String getURLForObjectKey(Object helpObjectKey); // // End of Abstract Method // ////////////////////////////////////// }
gpl-3.0
GoFact-AAL/PayFact
src/main/java/com/payfact/modelo/persistencia/entidades/Tipocobranza.java
3180
/* * 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 com.payfact.modelo.persistencia.entidades; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author camm */ @Entity @Table(catalog = "", schema = "PAYFACT") @NamedQueries({ @NamedQuery(name = "Tipocobranza.findAll", query = "SELECT t FROM Tipocobranza t"), @NamedQuery(name = "Tipocobranza.findByIdtipocobranza", query = "SELECT t FROM Tipocobranza t WHERE t.idtipocobranza = :idtipocobranza"), @NamedQuery(name = "Tipocobranza.findByNombretipo", query = "SELECT t FROM Tipocobranza t WHERE t.nombretipo = :nombretipo"), @NamedQuery(name = "Tipocobranza.findByResultado", query = "SELECT t FROM Tipocobranza t WHERE t.resultado = :resultado")}) public class Tipocobranza implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(nullable = false) private Integer idtipocobranza; @Column(length = 20) private String nombretipo; @Column(length = 100) private String resultado; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idtipocobranza") private List<Cobranza> cobranzaList; public Tipocobranza() { } public Tipocobranza(Integer idtipocobranza) { this.idtipocobranza = idtipocobranza; } public Integer getIdtipocobranza() { return idtipocobranza; } public void setIdtipocobranza(Integer idtipocobranza) { this.idtipocobranza = idtipocobranza; } public String getNombretipo() { return nombretipo; } public void setNombretipo(String nombretipo) { this.nombretipo = nombretipo; } public String getResultado() { return resultado; } public void setResultado(String resultado) { this.resultado = resultado; } public List<Cobranza> getCobranzaList() { return cobranzaList; } public void setCobranzaList(List<Cobranza> cobranzaList) { this.cobranzaList = cobranzaList; } @Override public int hashCode() { int hash = 0; hash += (idtipocobranza != null ? idtipocobranza.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Tipocobranza)) { return false; } Tipocobranza other = (Tipocobranza) object; if ((this.idtipocobranza == null && other.idtipocobranza != null) || (this.idtipocobranza != null && !this.idtipocobranza.equals(other.idtipocobranza))) { return false; } return true; } @Override public String toString() { return "com.payfact.modelo.persistencia.entidades.Tipocobranza[ idtipocobranza=" + idtipocobranza + " ]"; } }
gpl-3.0
rychu777/neo-starters
request-parameters/src/test/java/com/neoteric/starter/request/sort/SortOperatorTest.java
1058
package com.neoteric.starter.request.sort; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SortOperatorTest { @Test public void shouldCreateSortOperatorForProperName() { SortOperator sortOperator = SortOperator.fromString("$order"); assertThat(SortOperator.ORDER).isEqualTo(sortOperator); } @Test public void shouldCreateSortOperatorForProperNameIgnoreCase() { SortOperator sortOperator = SortOperator.fromString("$oRDEr"); assertThat(SortOperator.ORDER).isEqualTo(sortOperator); } @Test(expected = IllegalArgumentException.class) public void shouldFailToCreateSortOperatorOnIncorrectName() { SortOperator sortOperator = SortOperator.fromString("$wrongName"); } @Test public void shouldReturnTrueForOrderOperator() { assertThat(SortOperator.contains("$order")).isTrue(); } @Test public void shouldReturnFalseForUnknownOperator() { assertThat(SortOperator.contains("$foo")).isFalse(); } }
gpl-3.0
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/actor/status/SiegeFlagStatus.java
1539
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either 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.l2jglobal.gameserver.model.actor.status; import com.l2jglobal.gameserver.model.actor.L2Character; import com.l2jglobal.gameserver.model.actor.instance.L2SiegeFlagInstance; public class SiegeFlagStatus extends NpcStatus { public SiegeFlagStatus(L2SiegeFlagInstance activeChar) { super(activeChar); } @Override public void reduceHp(double value, L2Character attacker) { reduceHp(value, attacker, true, false, false); } @Override public void reduceHp(double value, L2Character attacker, boolean awake, boolean isDOT, boolean isHpConsumption) { if (getActiveChar().isAdvancedHeadquarter()) { value /= 2.; } super.reduceHp(value, attacker, awake, isDOT, isHpConsumption); } @Override public L2SiegeFlagInstance getActiveChar() { return (L2SiegeFlagInstance) super.getActiveChar(); } }
gpl-3.0
Isylwin/JCCa
Opdracht1/src/drawing/persistency/SerializationMediator.java
2349
/* * 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 drawing.persistency; import drawing.domain.Drawing; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Oscar */ public class SerializationMediator implements PersistencyMediator { private Properties props; @Override public Drawing load(String nameDrawing) { System.out.println("Loading: " + nameDrawing + "..."); Drawing drawing = null; String path = props.getProperty("Path") + nameDrawing + props.getProperty("FileType"); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) { drawing = (Drawing) ois.readObject(); } catch (IOException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); } if (drawing != null) { System.out.println("Loaded: " + nameDrawing); } return drawing; } @Override public boolean save(Drawing drawing) { System.out.println("Saving " + drawing.getName() + "..."); String path = props.getProperty("Path") + drawing.getName() + props.getProperty("FileType"); File file = new File(path); try { file.createNewFile(); } catch (IOException ex) { System.out.println("Couldn't find file: " + file.getAbsolutePath()); } boolean greatSuccess = false; try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { oos.writeObject(drawing); greatSuccess = true; } catch (IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(System.err); } System.out.println("Saving succesful"); return greatSuccess; } @Override public boolean init(Properties props) { this.props = props; return true; } }
gpl-3.0
sambenz/URingPaxos
clients/SMR/src/java/ch/usi/da/smr/thrift/gen/ControlType.java
1036
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package ch.usi.da.smr.thrift.gen; @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)", date = "2021-04-23") public enum ControlType implements org.apache.thrift.TEnum { SUBSCRIBE(0), UNSUBSCRIBE(1), PREPARE(2); private final int value; private ControlType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ @org.apache.thrift.annotation.Nullable public static ControlType findByValue(int value) { switch (value) { case 0: return SUBSCRIBE; case 1: return UNSUBSCRIBE; case 2: return PREPARE; default: return null; } } }
gpl-3.0
tkohegyi/adoration
adoration-application/modules/adoration-database/src/main/java/org/rockhill/adoration/database/business/helper/BusinessBase.java
966
package org.rockhill.adoration.database.business.helper; import java.util.List; /** * The Base class of Business classes those are handling database tables. * Not a must use, but helps to provide common solution for parent classes. */ public class BusinessBase { protected static final String EXPECTED_PARAMETER = "expectedParameter"; protected static final boolean CREATE = false; protected static final boolean UPDATE = true; /** * Return with the first item of the list, if the list exists and has at least one item - otherwise returns with null. * @param result is the list, usually result of a database query * @return with the first item of the list, if the list exists and has at least one item - otherwise returns with null */ protected Object returnWithFirstItem(final List<?> result) { if (result != null && !result.isEmpty()) { return result.get(0); } return null; } }
gpl-3.0
farble1670/gdstockcheck
GoogleDeviceStockChecker/app/src/nexus6/java/org/jtb/gdstockcheck/Device.java
952
package org.jtb.gdstockcheck; enum Device { NEXUS_6_BLUE_32GB("https://play.google.com/store/devices/details/Nexus_6_32GB_Midnight_Blue?id=nexus_6_blue_32gb", R.drawable.nexus_6_blue, "Nexus 6, Blue, 32GB"), NEXUS_6_BLUE_64GB("https://play.google.com/store/devices/details/Nexus_6_64GB_Midnight_Blue?id=nexus_6_blue_64gb", R.drawable.nexus_6_blue, "Nexus 6, Blue, 64GB" ), NEXUS_6_WHITE_32GB("https://play.google.com/store/devices/details/Nexus_6_32GB_Cloud_White?id=nexus_6_white_32gb", R.drawable.nexus_6_white, "Nexus 6, White, 32GB"), NEXUS_6_WHITE_64GB("https://play.google.com/store/devices/details/Nexus_6_64GB_Cloud_White?id=nexus_6_white_64gb", R.drawable.nexus_6_white, "Nexus 6, White, 64GB"), ; public final String pageUrl; public final int imageId; public final String name; private Device(String pageUrl, int imageId, String name) { this.pageUrl = pageUrl; this.imageId = imageId; this.name = name; } }
gpl-3.0
P3pp3rF1y/BigMachines
src/main/java/com/p3pp3rf1y/bigmachines/utility/DirectionHelper.java
885
package com.p3pp3rf1y.bigmachines.utility; import net.minecraftforge.common.util.ForgeDirection; public class DirectionHelper { //TODO: figure out why there's a need for duplicate first two lines public static final ForgeDirection neighborsBySide[][] = new ForgeDirection[][] { {ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST}, {ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST}, {ForgeDirection.UP, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.WEST}, {ForgeDirection.UP, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.EAST}, {ForgeDirection.UP, ForgeDirection.DOWN, ForgeDirection.NORTH, ForgeDirection.SOUTH}, {ForgeDirection.UP, ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.NORTH} }; }
gpl-3.0
NewCell/Call-Text-v1
src/org/pjsip/pjsua/pjsua_create_media_transport_flag.java
1764
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.pjsip.pjsua; public enum pjsua_create_media_transport_flag { PJSUA_MED_TP_CLOSE_MEMBER(pjsuaJNI.PJSUA_MED_TP_CLOSE_MEMBER_get()); public final int swigValue() { return swigValue; } public static pjsua_create_media_transport_flag swigToEnum(int swigValue) { pjsua_create_media_transport_flag[] swigValues = pjsua_create_media_transport_flag.class.getEnumConstants(); if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (pjsua_create_media_transport_flag swigEnum : swigValues) if (swigEnum.swigValue == swigValue) return swigEnum; throw new IllegalArgumentException("No enum " + pjsua_create_media_transport_flag.class + " with value " + swigValue); } @SuppressWarnings("unused") private pjsua_create_media_transport_flag() { this.swigValue = SwigNext.next++; } @SuppressWarnings("unused") private pjsua_create_media_transport_flag(int swigValue) { this.swigValue = swigValue; SwigNext.next = swigValue+1; } @SuppressWarnings("unused") private pjsua_create_media_transport_flag(pjsua_create_media_transport_flag swigEnum) { this.swigValue = swigEnum.swigValue; SwigNext.next = this.swigValue+1; } private final int swigValue; private static class SwigNext { private static int next = 0; } }
gpl-3.0
princeeriktheblue/console
ELib/lib/exceptions/MathInputException.java
238
package lib.exceptions; public class MathInputException extends LibException { private static final long serialVersionUID = 1L; public MathInputException() {} public MathInputException(String x) { super(x); } }
gpl-3.0
xVir/tasks
src/main/java/com/todoroo/astrid/activity/TaskEditActivity.java
2124
/** * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import com.todoroo.andlib.utility.AndroidUtilities; import org.tasks.R; import org.tasks.preferences.ActivityPreferences; import javax.inject.Inject; public class TaskEditActivity extends AstridActivity { @Inject ActivityPreferences preferences; /** * @see android.app.Activity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); preferences.applyTheme(); setContentView(R.layout.task_edit_wrapper_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } } /* (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onResume() */ @Override protected void onResume() { super.onResume(); Fragment frag = getSupportFragmentManager() .findFragmentByTag(TaskListFragment.TAG_TASKLIST_FRAGMENT); if (frag == null) { fragmentLayout = LAYOUT_SINGLE; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { TaskEditFragment frag = (TaskEditFragment) getSupportFragmentManager() .findFragmentByTag(TaskEditFragment.TAG_TASKEDIT_FRAGMENT); if (frag != null && frag.isInLayout()) { return frag.onKeyDown(keyCode); } return super.onKeyDown(keyCode, event); } @Override public void finish() { super.finish(); AndroidUtilities.callOverridePendingTransition(this, R.anim.slide_right_in, R.anim.slide_right_out); } }
gpl-3.0
jfreax/Omni-Notes
omniNotes/src/main/java/it/feio/android/omninotes/ShortcutActivity.java
1592
/* * Copyright (C) 2015 Federico Iosue (federico.iosue@gmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.feio.android.omninotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import it.feio.android.omninotes.utils.Constants; public class ShortcutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent shortcutIntent = new Intent(this, MainActivity.class); shortcutIntent.setAction(Constants.ACTION_SHORTCUT_WIDGET); Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable .shortcut_icon); Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.add_note)); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); setResult(RESULT_OK, intent); finish(); } }
gpl-3.0
waikato-datamining/adams-base
adams-meta/src/main/java/adams/flow/sink/FlowDisplay.java
8225
/* * 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/>. */ /* * FlowDisplay.java * Copyright (C) 2017 University of Waikato, Hamilton, NZ */ package adams.flow.sink; import adams.core.Utils; import adams.flow.core.Actor; import adams.flow.core.Token; import adams.gui.core.BasePanel; import adams.gui.core.BaseScrollPane; import adams.gui.core.ExtensionFileFilter; import adams.gui.flow.tree.Tree; import javax.swing.JComponent; import java.awt.BorderLayout; /** <!-- globalinfo-start --> * Displays an actor or flow. * <br><br> <!-- globalinfo-end --> * <!-- flow-summary-start --> * Input&#47;output:<br> * - accepts:<br> * &nbsp;&nbsp;&nbsp;adams.flow.core.Actor<br> * <br><br> <!-- flow-summary-end --> * <!-- options-start --> * <pre>-logging-level &lt;OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST&gt; (property: loggingLevel) * &nbsp;&nbsp;&nbsp;The logging level for outputting errors and debugging output. * &nbsp;&nbsp;&nbsp;default: WARNING * </pre> * * <pre>-name &lt;java.lang.String&gt; (property: name) * &nbsp;&nbsp;&nbsp;The name of the actor. * &nbsp;&nbsp;&nbsp;default: FlowDisplay * </pre> * * <pre>-annotation &lt;adams.core.base.BaseAnnotation&gt; (property: annotations) * &nbsp;&nbsp;&nbsp;The annotations to attach to this actor. * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-skip &lt;boolean&gt; (property: skip) * &nbsp;&nbsp;&nbsp;If set to true, transformation is skipped and the input token is just forwarded * &nbsp;&nbsp;&nbsp;as it is. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-stop-flow-on-error &lt;boolean&gt; (property: stopFlowOnError) * &nbsp;&nbsp;&nbsp;If set to true, the flow execution at this level gets stopped in case this * &nbsp;&nbsp;&nbsp;actor encounters an error; the error gets propagated; useful for critical * &nbsp;&nbsp;&nbsp;actors. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-silent &lt;boolean&gt; (property: silent) * &nbsp;&nbsp;&nbsp;If enabled, then no errors are output in the console; Note: the enclosing * &nbsp;&nbsp;&nbsp;actor handler must have this enabled as well. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-short-title &lt;boolean&gt; (property: shortTitle) * &nbsp;&nbsp;&nbsp;If enabled uses just the name for the title instead of the actor's full * &nbsp;&nbsp;&nbsp;name. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-display-in-editor &lt;boolean&gt; (property: displayInEditor) * &nbsp;&nbsp;&nbsp;If enabled displays the panel in a tab in the flow editor rather than in * &nbsp;&nbsp;&nbsp;a separate frame. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-width &lt;int&gt; (property: width) * &nbsp;&nbsp;&nbsp;The width of the dialog. * &nbsp;&nbsp;&nbsp;default: 800 * &nbsp;&nbsp;&nbsp;minimum: -1 * </pre> * * <pre>-height &lt;int&gt; (property: height) * &nbsp;&nbsp;&nbsp;The height of the dialog. * &nbsp;&nbsp;&nbsp;default: 600 * &nbsp;&nbsp;&nbsp;minimum: -1 * </pre> * * <pre>-x &lt;int&gt; (property: x) * &nbsp;&nbsp;&nbsp;The X position of the dialog (&gt;=0: absolute, -1: left, -2: center, -3: right * &nbsp;&nbsp;&nbsp;). * &nbsp;&nbsp;&nbsp;default: -1 * &nbsp;&nbsp;&nbsp;minimum: -3 * </pre> * * <pre>-y &lt;int&gt; (property: y) * &nbsp;&nbsp;&nbsp;The Y position of the dialog (&gt;=0: absolute, -1: top, -2: center, -3: bottom * &nbsp;&nbsp;&nbsp;). * &nbsp;&nbsp;&nbsp;default: -1 * &nbsp;&nbsp;&nbsp;minimum: -3 * </pre> * * <pre>-writer &lt;adams.gui.print.JComponentWriter&gt; (property: writer) * &nbsp;&nbsp;&nbsp;The writer to use for generating the graphics output. * &nbsp;&nbsp;&nbsp;default: adams.gui.print.NullWriter * </pre> * <!-- options-end --> * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class FlowDisplay extends AbstractGraphicalDisplay implements DisplayPanelProvider, TextSupplier { private static final long serialVersionUID = -4848073007226064084L; /** the tree used for displaying the actor. */ protected Tree m_Tree; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Displays an actor or flow."; } /** * Returns the class that the consumer accepts. * * @return the Class of objects that can be processed */ @Override public Class[] accepts() { return new Class[]{Actor.class}; } /** * Displays the token (the panel and dialog have already been created at * this stage). * * @param token the token to display */ @Override protected void display(Token token) { m_Tree.setActor((Actor) token.getPayload()); } /** * Clears the content of the panel. */ @Override public void clearPanel() { m_Tree.setActor(null); } /** * Creates the panel to display in the dialog. * * @return the panel */ @Override protected BasePanel newPanel() { BasePanel result; m_Tree = new Tree(null); result = new BasePanel(new BorderLayout()); result.add(new BaseScrollPane(m_Tree), BorderLayout.CENTER); return result; } /** * Returns the text for the menu item. * * @return the menu item text, null for default */ @Override public String getCustomSupplyTextMenuItemCaption() { return "Save flow as..."; } /** * Returns a custom file filter for the file chooser. * * @return the file filter, null if to use default one */ @Override public ExtensionFileFilter getCustomTextFileFilter() { return new ExtensionFileFilter("Flow file", "flow"); } /** * Supplies the text. May get called even if actor hasn't been executed yet. * * @return the text, null if none available */ @Override public String supplyText() { return Utils.flatten(m_Tree.getCommandLines(), "\n"); } /** * Creates a new display panel for the token. * * @param token the token to display in a new panel, can be null * @return the generated panel */ @Override public DisplayPanel createDisplayPanel(Token token) { return new AbstractTextAndComponentDisplayPanel(getClass().getSimpleName()) { private static final long serialVersionUID = -2507397847572050956L; protected Tree m_Tree; @Override protected void initGUI() { super.initGUI(); setLayout(new BorderLayout()); m_Tree = new Tree(null); add(new BaseScrollPane(m_Tree), BorderLayout.CENTER); } @Override public JComponent supplyComponent() { return m_Tree; } @Override public ExtensionFileFilter getCustomTextFileFilter() { return new ExtensionFileFilter("Flow file", "flow"); } @Override public String supplyText() { return Utils.flatten(m_Tree.getCommandLines(), "\n"); } @Override public void display(Token token) { m_Tree.setActor((Actor) token.getPayload()); } @Override public void clearPanel() { m_Tree.setActor(null); } @Override public void cleanUp() { m_Tree.cleanUp(); } }; } /** * Returns whether the created display panel requires a scroll pane or not. * * @return true if the display panel requires a scroll pane */ @Override public boolean displayPanelRequiresScrollPane() { return false; } /** * Cleans up after the execution has finished. Also removes graphical * components. */ @Override public void cleanUp() { if (m_Tree != null) { m_Tree.cleanUp(); m_Tree = null; } super.cleanUp(); } }
gpl-3.0
ivoanjo/phd-jaspexmls
jaspex-mls/benchmarks/javagrande_2.0/section3/JGFRayTracerBenchSizeA.java
1690
/************************************************************************** * * * Java Grande Forum Benchmark Suite - Version 2.0 * * * * produced by * * * * Java Grande Benchmarking Project * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: epcc-javagrande@epcc.ed.ac.uk * * * * * * This version copyright (c) The University of Edinburgh, 1999. * * All rights reserved. * * * **************************************************************************/ import raytracer.*; import jgfutil.*; public class JGFRayTracerBenchSizeA{ public static void main(String argv[]){ JGFInstrumentor.printHeader(3,0); JGFRayTracerBench rtb = new JGFRayTracerBench(); rtb.JGFrun(0); } }
gpl-3.0
CrawlScript/WebCollector
src/main/java/cn/edu/hfut/dmic/webcollector/model/CrawlDatum.java
8405
/* * Copyright (C) 2015 hu * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package cn.edu.hfut.dmic.webcollector.model; import cn.edu.hfut.dmic.webcollector.util.CrawlDatumFormater; import cn.edu.hfut.dmic.webcollector.util.GsonUtils; import cn.edu.hfut.dmic.webcollector.util.RegexRule; import com.google.gson.*; import java.io.Serializable; import java.util.regex.Pattern; /** * 爬取任务的数据结构 * * @author hu */ public class CrawlDatum implements Serializable, MetaGetter, MetaSetter<CrawlDatum> { public final static int STATUS_DB_UNEXECUTED = 0; public final static int STATUS_DB_FAILED = 1; public final static int STATUS_DB_SUCCESS = 5; // 未获取到http code时为-1 public final static int CODE_NOT_SET = -1; private String url = null; private long executeTime = System.currentTimeMillis(); private int code = CODE_NOT_SET; // 如果有重定向,location会保存重定向的地址 private String location = null; private int status = STATUS_DB_UNEXECUTED; private int executeCount = 0; /** * 在WebCollector 2.5之后,不再根据URL去重,而是根据key去重 * 可以通过getKey()方法获得CrawlDatum的key,如果key为null,getKey()方法会返回URL * 因此如果不设置key,爬虫会将URL当做key作为去重标准 */ private String key = null; /** * 在WebCollector 2.5之后,可以为每个CrawlDatum添加附加信息metaData * 附加信息并不是为了持久化数据,而是为了能够更好地定制爬取任务 * 在visit方法中,可以通过page.getMetaData()方法来访问CrawlDatum中的metaData */ private JsonObject metaData = new JsonObject(); public CrawlDatum() { } public CrawlDatum(String url) { this.url = url; } public CrawlDatum(String url,String type) { this.url = url; type(type); } public boolean matchType(String type){ if(type==null){ return type()==null; }else{ return type.equals(type()); } } /** * 判断当前Page的URL是否和输入正则匹配 * * @param urlRegex * @return */ public boolean matchUrl(String urlRegex) { return Pattern.matches(urlRegex, url()); } /** * 判断当前Page的URL是否和输入正则规则匹配 * @param urlRegexRule * @return */ public boolean matchUrlRegexRule(RegexRule urlRegexRule) { return urlRegexRule.satisfy(url()); } public CrawlDatum(String url, String[] metas) throws Exception { this(url); if (metas.length % 2 != 0) { throw new Exception("length of metas must be even"); } else { for (int i = 0; i < metas.length; i += 2) { meta(metas[i * 2], metas[i * 2 + 1]); } } } public int incrExecuteCount(int count) { executeCount+=count; return executeCount; } public static final String META_KEY_TYPE="s_t"; public String type(){ return meta(META_KEY_TYPE); } public CrawlDatum type(String type){ return meta(META_KEY_TYPE, type); } public int code() { return code; } public CrawlDatum code(int code) { this.code = code; return this; } public String location() { return location; } public CrawlDatum location(String location) { this.location = location; return this; } public String url() { return url; } public CrawlDatum url(String url) { this.url = url; return this; } public long getExecuteTime() { return executeTime; } public void setExecuteTime(long executeTime) { this.executeTime = executeTime; } public int getExecuteCount() { return executeCount; } public void setExecuteCount(int executeCount) { this.executeCount = executeCount; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public JsonObject meta() { return metaData; } @Override public String meta(String key){ JsonElement value = metaData.get(key); return (value==null || (value instanceof JsonNull))?null:value.getAsString(); } @Override public int metaAsInt(String key){ return metaData.get(key).getAsInt(); } @Override public boolean metaAsBoolean(String key) { return metaData.get(key).getAsBoolean(); } @Override public double metaAsDouble(String key) { return metaData.get(key).getAsDouble(); } @Override public long metaAsLong(String key) { return metaData.get(key).getAsLong(); } @Override public JsonObject copyMeta() { return meta().deepCopy(); } public String briefInfo(){ StringBuilder sb = new StringBuilder(); if(code != CODE_NOT_SET) { sb.append("[").append(code); if (location != null) { sb.append(" -> ").append(location); } sb.append("] "); } sb.append("Key: ").append(key()) .append(" (URL: ").append(url()).append(")"); return sb.toString(); } public String key() { if (key == null) { return url; } else { return key; } } public CrawlDatum key(String key) { this.key = key; return this; } @Override public String toString() { return CrawlDatumFormater.datumToString(this); } @Override public CrawlDatum meta(JsonObject metaData) { this.metaData = metaData; return this; } @Override public CrawlDatum meta(String key, String value) { metaData.addProperty(key, value); return this; } @Override public CrawlDatum meta(String key, int value) { metaData.addProperty(key, value); return this; } @Override public CrawlDatum meta(String key, boolean value) { metaData.addProperty(key, value); return this; } @Override public CrawlDatum meta(String key, double value) { metaData.addProperty(key, value); return this; } @Override public CrawlDatum meta(String key, long value) { metaData.addProperty(key, value); return this; } public String asJsonArray() { JsonArray jsonArray = new JsonArray(); jsonArray.add(url()); jsonArray.add(getStatus()); jsonArray.add(getExecuteTime()); jsonArray.add(getExecuteCount()); jsonArray.add(code()); jsonArray.add(location()); if (meta().size() > 0) { jsonArray.add(meta()); } return jsonArray.toString(); } public static CrawlDatum fromJsonArray(String crawlDatumKey, JsonArray jsonArray) { // JsonArray jsonArray = GsonUtils.parse(jsonStr).getAsJsonArray(); CrawlDatum crawlDatum = new CrawlDatum(); crawlDatum.key(crawlDatumKey); crawlDatum.url(jsonArray.get(0).getAsString()); crawlDatum.setStatus(jsonArray.get(1).getAsInt()); crawlDatum.setExecuteTime(jsonArray.get(2).getAsLong()); crawlDatum.setExecuteCount(jsonArray.get(3).getAsInt()); if (jsonArray.size() == 7) { JsonObject metaJsonObject = jsonArray.get(6).getAsJsonObject(); crawlDatum.meta(metaJsonObject); } return crawlDatum; } }
gpl-3.0
RandalfMx/RandalfProtocol
RandalfCatSan/src/main/java/it/mibac/san/eac_san/DescriptiveEntries.java
2328
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.30 at 03:35:08 PM CEST // package it.mibac.san.eac_san; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; 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 ref="{http://san.mibac.it/eac-san/}descriptiveEntry" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "descriptiveEntry" }) @XmlRootElement(name = "descriptiveEntries") public class DescriptiveEntries { @XmlElement(required = true) protected List<DescriptiveEntry> descriptiveEntry; /** * Gets the value of the descriptiveEntry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the descriptiveEntry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDescriptiveEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DescriptiveEntry } * * */ public List<DescriptiveEntry> getDescriptiveEntry() { if (descriptiveEntry == null) { descriptiveEntry = new ArrayList<DescriptiveEntry>(); } return this.descriptiveEntry; } }
gpl-3.0
organicsmarthome/OSHv4
source/osh_driver_appliance/src/osh/mgmt/localcontroller/ipp/GenericApplianceSolution.java
2241
package osh.mgmt.localcontroller.ipp; import java.util.Arrays; import java.util.UUID; import osh.datatypes.ea.interfaces.ISolution; /** * * @author Ingo Mauser * */ public class GenericApplianceSolution implements ISolution { public UUID acpUUID; public long[] startingTimes; public int profileId; /** * CONSTRUCTOR * @param startTime * @param isPredicted */ public GenericApplianceSolution( UUID acpUUID, long[] startingTimes, int profileId) { super(); this.acpUUID = acpUUID; this.startingTimes = startingTimes; this.profileId = profileId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((acpUUID == null) ? 0 : acpUUID.hashCode()); result = prime * result + profileId; result = prime * result + Arrays.hashCode(startingTimes); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GenericApplianceSolution other = (GenericApplianceSolution) obj; if (acpUUID == null) { if (other.acpUUID != null) return false; } else if (!acpUUID.equals(other.acpUUID)) return false; if (profileId != other.profileId) return false; if (!Arrays.equals(startingTimes, other.startingTimes)) return false; return true; } @Override public GenericApplianceSolution clone() throws CloneNotSupportedException { long[] startingTimes = new long[this.startingTimes.length]; for (int i = 0; i < this.startingTimes.length; i++) { startingTimes[i] = this.startingTimes[i]; } GenericApplianceSolution clonedSolution = new GenericApplianceSolution( this.acpUUID, startingTimes, this.profileId); return clonedSolution; } @Override public String toString() { String pausesString = "["; if (startingTimes != null) { for (int i = 0; i < startingTimes.length; i++) { if (i > 0) { pausesString = pausesString + ","; } pausesString = pausesString + startingTimes[i]; } } pausesString = pausesString + "]"; return "referenceTime=" + acpUUID + " | profileId=" + profileId + " | pauses=" + pausesString; } }
gpl-3.0