repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/giph/mp4/GiphyMp4VideoPlayer.java | 3611 | package org.thoughtcrime.securesms.giph.mp4;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.DefaultLifecycleObserver;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.CornerMask;
import org.thoughtcrime.securesms.util.Projection;
/**
* Video Player class specifically created for the GiphyMp4Fragment.
*/
public final class GiphyMp4VideoPlayer extends FrameLayout implements DefaultLifecycleObserver {
@SuppressWarnings("unused")
private static final String TAG = Log.tag(GiphyMp4VideoPlayer.class);
private final PlayerView exoView;
private SimpleExoPlayer exoPlayer;
private CornerMask cornerMask;
private MediaItem mediaItem;
public GiphyMp4VideoPlayer(Context context) {
this(context, null);
}
public GiphyMp4VideoPlayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GiphyMp4VideoPlayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflate(context, R.layout.gif_player, this);
this.exoView = findViewById(R.id.video_view);
}
@Override
protected void onDetachedFromWindow() {
Log.d(TAG, "onDetachedFromWindow");
super.onDetachedFromWindow();
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (cornerMask != null) {
cornerMask.mask(canvas);
}
}
@Nullable SimpleExoPlayer getExoPlayer() {
return exoPlayer;
}
void setExoPlayer(@Nullable SimpleExoPlayer exoPlayer) {
exoView.setPlayer(exoPlayer);
this.exoPlayer = exoPlayer;
}
int getPlaybackState() {
if (exoPlayer != null) {
return exoPlayer.getPlaybackState();
} else {
return -1;
}
}
void setVideoItem(@NonNull MediaItem mediaItem) {
this.mediaItem = mediaItem;
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
}
void setCorners(@Nullable Projection.Corners corners) {
if (corners == null) {
this.cornerMask = null;
} else {
this.cornerMask = new CornerMask(this);
this.cornerMask.setRadii(corners.getTopLeft(), corners.getTopRight(), corners.getBottomRight(), corners.getBottomLeft());
}
invalidate();
}
void play() {
if (exoPlayer != null) {
exoPlayer.setPlayWhenReady(true);
}
}
void pause() {
if (exoPlayer != null) {
exoPlayer.pause();
}
}
void stop() {
if (exoPlayer != null) {
exoPlayer.stop();
exoPlayer.clearMediaItems();
mediaItem = null;
}
}
long getDuration() {
if (exoPlayer != null) {
return exoPlayer.getDuration();
} else {
return C.LENGTH_UNSET;
}
}
void setResizeMode(@AspectRatioFrameLayout.ResizeMode int resizeMode) {
exoView.setResizeMode(resizeMode);
}
@Nullable Bitmap getBitmap() {
final View view = exoView.getVideoSurfaceView();
if (view instanceof TextureView) {
return ((TextureView) view).getBitmap();
}
return null;
}
}
| gpl-3.0 |
iterate-ch/cyberduck | binding/src/main/java/ch/cyberduck/binding/application/NSValidatedUserInterfaceItem.java | 1346 | package ch.cyberduck.binding.application;
/*
* Copyright (c) 2002-2009 David Kocher. All rights reserved.
*
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* dkocher@cyberduck.ch
*/
import org.rococoa.Selector;
/// <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:69</i>
public interface NSValidatedUserInterfaceItem {
/**
* Original signature : <code>action()</code><br>
* <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:70</i>
*/
Selector action();
/**
* Original signature : <code>NSInteger tag()</code><br>
* <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:71</i>
*/
int tag();
}
| gpl-3.0 |
mcomas/codapack | src/main/java/coda/plot2/window/TernaryPlot2dDialogDataSet.java | 6629 | /**
* Copyright 2011-2016 Marc Comas - Santiago Thió
*
* This file is part of CoDaPack.
*
* CoDaPack 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.
*
* CoDaPack 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 CoDaPack. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package coda.plot2.window;
import coda.ext.jama.Matrix;
import coda.gui.menu.CoDaPackDialog;
import coda.gui.utils.AddDataManually;
import coda.plot2.ColorPanel;
import coda.plot2.ShapePanel;
import coda.plot2.datafig.CoDaShape;
import coda.plot2.datafig.FilledCircle;
import coda.plot2.objects.Ternary2dDataObject;
import coda.plot2.objects.Ternary2dObject;
import coda.plot2.TernaryPlot2dDisplay;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
/**
*
* @author marc
*/
public class TernaryPlot2dDialogDataSet extends CoDaPackDialog{
double JTextBox [] = null;
double data[][] = null;
SamplePanel sample = new SamplePanel();
ColorPanel selectedColor;
ShapePanel selectedShape;
CoDaShape shape = new FilledCircle();
TernaryPlot2dWindow window;
public TernaryPlot2dDialogDataSet(TernaryPlot2dWindow window){
super(window, "Add Data Set");
shape.setSize(3f);
shape.setColor(Color.gray);
this.window = window;
setSize(560,430);
setLocationRelativeTo(window);
JButton manually = new JButton("Add data manually");
manually.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
manuallyButton();
}
});
JButton fromTable = new JButton("Add data from table");
fromTable.setEnabled(false);
fromTable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fromTableButton();
}
});
JPanel importing = new JPanel();
importing.add(manually);
importing.add(fromTable);
JPanel propertyPanel = new JPanel();
propertyPanel.setSize(new Dimension(350,150));
propertyPanel.setPreferredSize(new Dimension(350,150));
selectedColor = new ColorPanel();
selectedColor.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
selectedColor.addMouseListener(selectedColor);
selectedColor.setBackground(shape.getColor());
selectedColor.setPreferredSize(new Dimension(50,20));
selectedShape = new ShapePanel();
selectedShape.addItemListener(selectedShape);
propertyPanel.add(new JLabel("Color:"));
propertyPanel.add(selectedColor);
propertyPanel.add(new JLabel("Shape:"));
propertyPanel.add(selectedShape);
/*
* JPanel samplePanel = new JPanel();
sample.setSize(new Dimension(70,70));
sample.setPreferredSize(new Dimension(70,70));
samplePanel.add(sample);
* */
JPanel mainArea = new JPanel();
mainArea.add(importing);
mainArea.add(propertyPanel);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(mainArea, BorderLayout.CENTER);
JPanel south = new JPanel();
JButton accept = new JButton("Accept");
accept.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
acceptButton();
}
});
south.add(accept);
getContentPane().add(south, BorderLayout.SOUTH);
sample.repaint();
}
private void acceptButton(){
TernaryPlot2dDisplay display = window.getDisplay();
Ternary2dDataObject dataObject = new Ternary2dDataObject(display, new Matrix(data).transpose().getArray(), shape);
dataObject.setShape(selectedShape.getShape());
dataObject.setColor(selectedColor.getBackground());
display.addCoDaObject(dataObject);
display.repaint();
setVisible(false);
}
private void manuallyButton(){
String labels[] = {"X","Y","Z"};
AddDataManually dialog = new AddDataManually(this, data, labels);
dialog.setModal(true);
dialog.setVisible(true);
data = dialog.data;
}
private void fromTableButton(){ }
// private class ColorPanel extends JPanel implements MouseListener{
// Color color = new Color(70, 70, 200);
// public void mouseClicked(MouseEvent me) {
// Color initialBackground = selectedColor.getBackground();
// Color colorSelected = JColorChooser.showDialog(this,
// "Choose a color", initialBackground);
// if (colorSelected != null) {
// color = colorSelected;
// selectedColor.setBackground(colorSelected);
// }
// shape.setColor(color);
// sample.repaint();
// }
// public void mousePressed(MouseEvent me) { }
//
// public void mouseReleased(MouseEvent me) { }
//
// public void mouseEntered(MouseEvent me) { }
//
// public void mouseExited(MouseEvent me) { }
//
// }
class SamplePanel extends JComponent{
public SamplePanel(){
this.setBackground(Color.white);
}
@Override
public final void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
selectedShape.getShape().plot(g2, new Point2D.Double(sample.getWidth()/2, sample.getHeight()/2));
}
}
}
| gpl-3.0 |
athrane/bassebombecraft | src/main/java/bassebombecraft/operator/projectile/ShootLightningProjectile2.java | 1070 | package bassebombecraft.operator.projectile;
import static bassebombecraft.event.projectile.RegisteredEntityTypes.LIGHTNING_PROJECTILE;
import bassebombecraft.entity.projectile.GenericCompositeProjectileEntity;
import bassebombecraft.entity.projectile.LightningProjectileEntity;
import bassebombecraft.operator.Operator2;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.math.vector.Vector3d;
/**
* Implementation of the {@linkplain Operator2} interface which shoots composite
* lightning projectile(s) from the invoker position.
*
* Sub class of the {@linkplain GenericShootProjectile2} generic projectile
* shooter operator.
*/
public class ShootLightningProjectile2 extends GenericShootProjectile2 {
@Override
Entity createProjectile(LivingEntity invoker, Vector3d orientation) {
GenericCompositeProjectileEntity projectile = new LightningProjectileEntity(LIGHTNING_PROJECTILE, invoker);
projectile.shootUsingProjectileConfig(orientation);
return projectile;
}
}
| gpl-3.0 |
kpu/MEMT | MEMT/Alignment/MMBRMatcherMEMT.java | 7217 | /*
* Carnegie Mellon University
* Copyright (c) 2004, 2009
* All Rights Reserved.
*
* Any use of this software must follow the terms
* outlined in the included LICENSE file.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import edu.cmu.meteor.aligner.Aligner;
import edu.cmu.meteor.aligner.Alignment;
import edu.cmu.meteor.aligner.Match;
import edu.cmu.meteor.scorer.MeteorConfiguration;
import edu.cmu.meteor.scorer.MeteorScorer;
import edu.cmu.meteor.scorer.MeteorStats;
import edu.cmu.meteor.util.Constants;
public class MMBRMatcherMEMT {
public static void main(String[] args) throws Exception {
// Usage
if (args.length < 1) {
System.out.println("METEOR Aligner and MMBR for MEMT version "
+ Constants.VERSION);
System.out.println("Usage: java -cp meteor.jar MatcherMEMT "
+ "<file1> <file2> ... <filen> [options]");
System.out.println();
System.out.println("Options:");
System.out.println("-l language\t\t\tOne of: en cz de es fr");
System.out
.println("-m \"module1 module2 ...\"\tSpecify modules (overrides default)");
System.out
.println("\t\t\t\t One of: exact stem synonym paraphrase");
System.out.println("-x maxComputations\t\tKeep speed reasonable");
System.out.println("-d synonymDirectory\t\t(if not default)");
System.out.println("-a paraphraseFile\t\t(if not default)");
System.out.println();
System.out
.println("Default settings are stored in the matcher.properties file bundled in the JAR");
return;
}
// Defaults
String propFile = "matcher.properties";
Properties props = new Properties();
try {
props.load(ClassLoader.getSystemResource(propFile).openStream());
} catch (Exception ex) {
System.err.println("Error: Could not load properties file:");
ex.printStackTrace();
System.exit(1);
}
ArrayList<BufferedReader> files = new ArrayList<BufferedReader>();
int curArg;
for (curArg = 0; curArg < args.length; ++curArg) {
if (args[0].charAt(0) == '-') {
break;
}
files.add(new BufferedReader(new FileReader(args[curArg])));
}
// Options
while (curArg < args.length) {
if (args[curArg].equals("-l")) {
props.setProperty("language", args[curArg + 1]);
curArg += 2;
} else if (args[curArg].equals("-x")) {
props.setProperty("maxcomp", args[curArg + 1]);
curArg += 2;
} else if (args[curArg].equals("-d")) {
props.setProperty("synDir", args[curArg + 1]);
curArg += 2;
} else if (args[curArg].equals("-a")) {
props.setProperty("paraDir", args[curArg + 1]);
curArg += 2;
} else if (args[curArg].equals("-m")) {
props.setProperty("modules", args[curArg + 1]);
curArg += 2;
} else {
System.err.println("Bad argument " + args[curArg]);
System.exit(1);
}
}
// Language
String language = props.getProperty("language");
if (language.equals("default"))
language = "english";
language = Constants.normLanguageName(language);
// Synonym Location
String synDir = props.getProperty("synDir");
URL synURL;
if (synDir.equals("default"))
synURL = Constants.DEFAULT_SYN_DIR_URL;
else
synURL = (new File(synDir)).toURI().toURL();
// Paraphrase Location
String paraDir = props.getProperty("paraDir");
URL paraURL;
if (paraDir.equals("default"))
paraURL = Constants.DEFAULT_PARA_DIR_URL;
else
paraURL = (new File(paraDir)).toURI().toURL();
// Max Computations
String mx = props.getProperty("maxcomp");
int maxComp = 0;
if (mx.equals("default"))
maxComp = Constants.DEFAULT_MAXCOMP;
else
maxComp = Integer.parseInt(mx);
// Modules
String modNames = props.getProperty("modules");
if (modNames.equals("default"))
modNames = "exact stem synonym paraphrase";
ArrayList<Integer> modules = new ArrayList<Integer>();
ArrayList<Double> moduleWeights = new ArrayList<Double>();
StringTokenizer mods = new StringTokenizer(modNames);
while (mods.hasMoreTokens()) {
int module = Constants.getModuleID(mods.nextToken());
modules.add(module);
moduleWeights.add(1.0);
}
// Construct aligner
Aligner aligner = new Aligner(language, modules, moduleWeights,
maxComp, synURL, paraURL);
// Construct Scorer only (no Aligner modules)
MeteorConfiguration noAligner = new MeteorConfiguration();
noAligner.setTask("hter");
noAligner.setModules(new ArrayList<Integer>());
MeteorScorer scorer = new MeteorScorer(noAligner);
while (true) {
ArrayList<String> lines = new ArrayList<String>(files.size());
for (BufferedReader f : files) {
lines.add(f.readLine());
}
for (String l : lines) {
if ((lines.get(0) == null) != (l == null)) {
System.err.println("Files are not equal length");
System.exit(1);
}
}
if (lines.get(0) == null)
break;
handleLines(aligner, moduleWeights, scorer, lines);
}
}
static void handleLines(Aligner aligner, ArrayList<Double> moduleWeights,
MeteorScorer scorer, ArrayList<String> lines) {
System.out.println(lines.size());
for (String l : lines) {
System.out.println(l);
}
for (int i = 0; i < lines.size(); ++i) {
for (int j = i + 1; j < lines.size(); ++j) {
// Align
Alignment alignment = aligner.align(lines.get(i), lines.get(j));
// Direction 1 precision, recall, chunks, score
MeteorStats stats = scorer.getMeteorStats(alignment);
System.out.println(stats.precision + "\t" + stats.recall + "\t"
+ stats.chunks + "\t" + stats.score);
// Direction 2 precision, recall, chunks, score
swap(stats);
scorer.computeMetrics(stats);
System.out.println(stats.precision + "\t" + stats.recall + "\t"
+ stats.chunks + "\t" + stats.score);
// Matches
printAlignment(moduleWeights, alignment);
System.out.println();
}
}
}
static void swap(MeteorStats stats) {
stats.testWeightedMatches = 0;
stats.referenceWeightedMatches = 0;
int testLength = stats.testLength;
stats.testLength = stats.referenceLength;
stats.referenceLength = testLength;
int testTotalMatches = stats.testTotalMatches;
stats.testTotalMatches = stats.referenceTotalMatches;
stats.referenceTotalMatches = testTotalMatches;
ArrayList<Integer> testTotalStageMatches = stats.testTotalStageMatches;
stats.testTotalStageMatches = stats.referenceTotalStageMatches;
stats.referenceTotalStageMatches = testTotalStageMatches;
ArrayList<Double> testWeightedStageMatches = stats.testWeightedStageMatches;
stats.testWeightedStageMatches = stats.referenceWeightedStageMatches;
stats.referenceWeightedStageMatches = testWeightedStageMatches;
}
static void printAlignment(ArrayList<Double> moduleWeights,
Alignment alignment) {
for (int i = 0; i < alignment.matches.size(); ++i) {
Match m = alignment.matches.get(i);
if (m.matchStringStart != -1) {
// First string word
System.out.print(m.matchStringStart + "\t");
// Second string word
System.out.print(m.start + "\t");
// Module stage
System.out.print(m.stage + "\t");
// Score
System.out.println(m.prob * moduleWeights.get(m.stage));
}
}
}
}
| gpl-3.0 |
eldersantos/community | server/src/main/java/org/neo4j/server/rest/domain/TraversalDescriptionBuilder.java | 7331 | /**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.rest.domain;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Traverser.Order;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
/*
* Maybe refactor to have a constructor with default stuff and make
* methods non-static
*/
public class TraversalDescriptionBuilder
{
public static TraversalDescription from( Map<String, Object> description )
{
try
{
TraversalDescription result = Traversal.description();
result = describeOrder( result, description );
result = describeUniqueness( result, description );
result = describeRelationships( result, description );
result = describePruneEvaluator( result, description );
result = describeReturnFilter( result, description );
return result;
}
catch ( NoClassDefFoundError e )
{
// This one can happen if you run on Java 5, but haven't included the
// backported javax.script jar file(s) on the classpath.
throw new EvaluationException( e );
}
}
@SuppressWarnings("unchecked")
private static TraversalDescription describeReturnFilter(
TraversalDescription result, Map<String, Object> description )
{
Object returnDescription = description.get( "return filter" );
if ( returnDescription != null )
{
result = result.filter( EvaluatorFactory.returnFilter( (Map) returnDescription ) );
}
else
{
// Default return evaluator
result = result.filter( Traversal.returnAllButStartNode() );
}
return result;
}
@SuppressWarnings("unchecked")
private static TraversalDescription describePruneEvaluator(
TraversalDescription result, Map<String, Object> description )
{
Object pruneDescription = description.get( "prune evaluator" );
if ( pruneDescription != null )
{
result = result.prune( EvaluatorFactory.pruneEvaluator( (Map) pruneDescription ) );
}
Object maxDepth = description.get( "max depth" );
maxDepth = maxDepth != null || pruneDescription != null ? maxDepth : 1;
if ( maxDepth != null )
{
result = result.prune( Traversal.pruneAfterDepth(
((Number) maxDepth).intValue() ) );
}
return result;
}
@SuppressWarnings("unchecked")
private static TraversalDescription describeRelationships(
TraversalDescription result, Map<String, Object> description )
{
Object relationshipsDescription = description.get( "relationships" );
if ( relationshipsDescription != null )
{
Collection<Object> pairDescriptions;
if ( relationshipsDescription instanceof Collection )
{
pairDescriptions = (Collection<Object>) relationshipsDescription;
}
else
{
pairDescriptions = Arrays.asList( relationshipsDescription );
}
for ( Object pairDescription : pairDescriptions )
{
Map map = (Map) pairDescription;
String name = (String) map.get( "type" );
RelationshipType type = DynamicRelationshipType.withName( name );
String directionName = (String) map.get( "direction" );
result = directionName == null ? result.relationships( type ) :
result.relationships( type, stringToEnum( directionName,
RelationshipDirection.class, true ).internal );
}
}
return result;
}
private static TraversalDescription describeUniqueness(
TraversalDescription result, Map<String, Object> description )
{
Object uniquenessDescription = description.get( "uniqueness" );
if ( uniquenessDescription != null )
{
String name = null;
Object value = null;
if ( uniquenessDescription instanceof Map )
{
Map map = (Map) uniquenessDescription;
name = (String) map.get( "name" );
value = map.get( "value" );
}
else
{
name = (String) uniquenessDescription;
}
org.neo4j.kernel.Uniqueness uniqueness = stringToEnum( enumifyName( name ), org.neo4j.kernel.Uniqueness.class, true );
result = value == null ? result.uniqueness( uniqueness ) :
result.uniqueness( uniqueness, value );
}
return result;
}
private static TraversalDescription describeOrder(
TraversalDescription result, Map<String, Object> description )
{
String orderDescription = (String) description.get( "order" );
if ( orderDescription != null )
{
Order order = stringToEnum( enumifyName( orderDescription ), Order.class, true );
// TODO Fix
switch ( order )
{
case BREADTH_FIRST:
result = result.breadthFirst();
break;
case DEPTH_FIRST:
result = result.depthFirst();
break;
}
}
return result;
}
private static <T extends Enum<T>> T stringToEnum( String name, Class<T> enumClass,
boolean fuzzyMatch )
{
if ( name == null )
{
return null;
}
// name = enumifyName( name );
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name().equals( name ) )
{
return candidate;
}
}
if ( fuzzyMatch )
{
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name().startsWith( name ) )
{
return candidate;
}
}
}
throw new RuntimeException( "Unregognized " + enumClass.getSimpleName() + " '" +
name + "'" );
}
private static String enumifyName( String name )
{
return name.replaceAll( " ", "_" ).toUpperCase();
}
}
| gpl-3.0 |
petroniocandido/GerenciadorEventos | Projetos/GerenciamentoEventosDomainModel/src/br/edu/ifnmg/GerenciamentoEventos/DomainModel/EventoInscricaoCategoria.java | 6702 | /*
* This file is part of SGEA - Sistema de Gestão de Eventos Acadêmicos - TADS IFNMG Campus Januária.
*
* SGEA 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.
*
* SGEA 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 SGEA. If not, see <http://www.gnu.org/licenses/>.
*/
package br.edu.ifnmg.GerenciamentoEventos.DomainModel;
import br.edu.ifnmg.DomainModel.Pessoa;
import br.edu.ifnmg.DomainModel.Entidade;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
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.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.MapKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
/**
*
* @author petronio
*/
@Entity
@Table(name = "eventosinscricoescategorias")
public class EventoInscricaoCategoria implements Entidade, Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Evento evento;
@Column(length = 500, nullable = false, unique = true)
private String nome;
@Lob
private String descricao;
@Column(precision = 10, scale = 2)
private BigDecimal valorInscricao;
@ElementCollection
@CollectionTable(name = "eventosinscricoescategorias_inscricoesPorAtividade",
joinColumns = @JoinColumn(name = "evento"))
@MapKeyJoinColumn(name = "atividadeTipo", referencedColumnName = "id")
@Column(name = "quantidadeInscricoes")
private Map<AtividadeTipo, Integer> inscricoesPorAtividade;
public EventoInscricaoCategoria() {
inscricoesPorAtividade = new HashMap<>();
valorInscricao = new BigDecimal("0.00");
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Evento getEvento() {
return evento;
}
public void setEvento(Evento evento) {
this.evento = evento;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public BigDecimal getValorInscricao() {
return valorInscricao;
}
public void setValorInscricao(BigDecimal valorInscricao) {
this.valorInscricao = valorInscricao;
}
public int getLimiteInscricoes(AtividadeTipo a){
if(inscricoesPorAtividade.containsKey(a)){
return inscricoesPorAtividade.get(a).intValue();
} else {
return 0;
}
}
public void addLimite(AtividadeTipo a, int l){
if(inscricoesPorAtividade.containsKey(a)){
inscricoesPorAtividade.remove(a);
}
inscricoesPorAtividade.put(a, l);
}
public void removeLimite(AtividadeTipo a){
inscricoesPorAtividade.remove(a);
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Map<AtividadeTipo, Integer> getInscricoesPorAtividade() {
return inscricoesPorAtividade;
}
public void setInscricoesPorAtividade(Map<AtividadeTipo, Integer> inscricoesPorAtividade) {
this.inscricoesPorAtividade = inscricoesPorAtividade;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + Objects.hashCode(this.id);
hash = 47 * hash + Objects.hashCode(this.evento);
hash = 47 * hash + Objects.hashCode(this.nome);
hash = 47 * hash + Objects.hashCode(this.valorInscricao);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EventoInscricaoCategoria other = (EventoInscricaoCategoria) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.evento, other.evento)) {
return false;
}
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.valorInscricao, other.valorInscricao)) {
return false;
}
return true;
}
@Override
public String toString() {
return nome;
}
@ManyToOne(fetch = FetchType.LAZY)
private Pessoa criador;
@Temporal(TemporalType.TIMESTAMP)
private Date dataCriacao;
@ManyToOne(fetch = FetchType.LAZY)
private Pessoa ultimoAlterador;
@Temporal(TemporalType.TIMESTAMP)
private Date dataUltimaAlteracao;
@Version
private Long versao;
@Override
public Pessoa getCriador() {
return criador;
}
@Override
public void setCriador(Pessoa criador) {
this.criador = criador;
}
@Override
public Date getDataCriacao() {
return dataCriacao;
}
@Override
public void setDataCriacao(Date dataCriacao) {
this.dataCriacao = dataCriacao;
}
@Override
public Pessoa getUltimoAlterador() {
return ultimoAlterador;
}
@Override
public void setUltimoAlterador(Pessoa ultimoAlterador) {
this.ultimoAlterador = ultimoAlterador;
}
@Override
public Date getDataUltimaAlteracao() {
return dataUltimaAlteracao;
}
@Override
public void setDataUltimaAlteracao(Date dataUltimaAlteracao) {
this.dataUltimaAlteracao = dataUltimaAlteracao;
}
@Override
public Long getVersao() {
return versao;
}
public void setVersao(Long versao) {
this.versao = versao;
}
}
| gpl-3.0 |
jitlogic/zorka | zorka-core/src/test/java/com/jitlogic/zorka/core/test/tracer/STraceHandlerUnitTest.java | 14714 | /*
* Copyright 2012-2020 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
* <p/>
* This 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.
* <p/>
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.core.test.tracer;
import com.jitlogic.zorka.common.tracedata.SymbolRegistry;
import com.jitlogic.zorka.common.util.ObjectInspector;
import com.jitlogic.zorka.common.util.ZorkaUtil;
import com.jitlogic.zorka.core.spy.ltracer.TraceHandler;
import com.jitlogic.zorka.core.spy.stracer.STraceBufChunk;
import com.jitlogic.zorka.core.spy.stracer.STraceBufManager;
import com.jitlogic.zorka.core.test.spy.support.cbor.TestTraceBufOutput;
import com.jitlogic.zorka.core.test.spy.support.cbor.TestSTraceHandler;
import com.jitlogic.zorka.core.test.support.ZorkaFixture;
import com.jitlogic.zorka.core.util.ZorkaUnsafe;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static com.jitlogic.zorka.core.test.spy.support.cbor.STTrcTestUtils.chunksCount;
import static com.jitlogic.zorka.core.test.spy.support.cbor.STTrcTestUtils.decodeTrace;
import static com.jitlogic.zorka.core.test.spy.support.cbor.STTrcTestUtils.mkString;
import static org.junit.Assert.*;
public class STraceHandlerUnitTest extends ZorkaFixture {
private SymbolRegistry symbols = new SymbolRegistry();
private STraceBufManager bm = new STraceBufManager(128, 4);
private TestTraceBufOutput o = new TestTraceBufOutput();
private TestSTraceHandler r;
@Before
public void setUp() {
TraceHandler.setMinMethodTime(4 * 65536);
r = new TestSTraceHandler(bm,symbols,o);
}
@After
public void tearDown() {
tracer.setTracerMinMethodTime(250000);
tracer.setTracerMinTraceTime(50);
}
private static Object l(Object...args) {
return Arrays.asList(args);
}
private static Map m(Object...args) {
return ZorkaUtil.map(args);
}
@Test
public void testStrayShortTraceFragment(){
r.traceEnter(10, 1<<16);
r.traceReturn(3<<16);
assertNull(o.getChunks());
assertEquals(1, bm.getNGets());
assertEquals(0, bm.getNputs());
}
@Test
public void testStrayLongTraceFragment(){
r.traceEnter(10, 1<<16);
r.traceReturn(9<<16);
assertNull(o.getChunks());
assertEquals(1, bm.getNGets());
assertEquals(0, bm.getNputs());
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceSingleCallWithSingleMethod() throws Exception {
r.setMinimumTraceTime(0);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceReturn(9<<16);
assertEquals(1, chunksCount(o.getChunks()));
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 1L,
"begin", m("_", "B", "clock", 11)), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceSingleCallWithTwoMethods() throws Exception {
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceReturn(8<<16);
r.traceReturn(9<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 2L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 8L, "calls", 1L))
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceSingleCallWithSkippedMethod() throws Exception {
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceReturn(6<<16);
r.traceReturn(9<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 2L,
"begin", m("_", "B", "clock", 11)
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceSampleMethodCallsWithSomeAttributes() throws Exception {
r.setMinimumTraceTime(0);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.newAttr(-1, 99, "OJAAA!");
r.traceReturn(9<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 1L,
"begin", m("_", "B", "clock", 11),
"attrs", m(99, "OJAAA!")),
decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceSampleMethodCallWithAttrsBelowTraceBegin() throws Exception {
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.newAttr(-1, 99, "OJAAA!");
r.traceReturn(8<<16);
r.traceReturn(9<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 2L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 8L,
"calls", 1L, "attrs", m(99, "OJAAA!")))
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testIfAttrsForceMethodNotToBeExcludedInTraceTransitiveness() throws Exception {
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceEnter(14, 4<<16);
r.newAttr(-1, 99, "OJAAA!");
r.traceReturn(9<<16);
r.traceReturn(10<<16);
r.traceReturn(11<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 11L, "calls", 3L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 10L, "calls", 2L,
"children", l(m("_", "T", "method", 14L, "tstart", 4L, "tstop", 9L, "calls", 1L,
"attrs", m(99, "OJAAA!")))))
), decodeTrace(o.getChunks()));
}
private Map errorToMap(Throwable e) {
List<Object> stack = new ArrayList<Object>();
for (int i = 0; i < e.getStackTrace().length; i++) {
StackTraceElement se = e.getStackTrace()[i];
stack.add(l(
symbols.symbolId(se.getClassName()),
symbols.symbolId(se.getMethodName()),
symbols.symbolId(se.getFileName()),
se.getLineNumber() > 0 ? se.getLineNumber() : 0));
}
return m(
"_", "E",
"id", System.identityHashCode(e),
"class", symbols.symbolId(e.getClass().getName()),
"message", e.getMessage(), "stack", stack);
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceException() throws Exception {
Exception e = new RuntimeException("test");
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceError(e, 8<<16);
assertEquals(
m("_", "T", "method", 10L, "tstart", 1L, "tstop", 8L, "calls", 1L,
"begin", m("_", "B", "clock", 11),
"error", errorToMap(e)),
decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceExceptionInRecursiveMethodWithTransitiveness() throws Exception {
Exception e = new RuntimeException("test");
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceEnter(14, 4<<16);
r.traceError(e, 9<<16);
r.traceReturn(10<<16);
r.traceReturn(11<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 11L, "calls", 3L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 10L, "calls", 2L,
"children", l(m("_", "T", "method", 14L, "tstart", 4L, "tstop", 9L, "calls", 1L,
"error", errorToMap(e)))))),
decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceExceptionInRecursiveMethodWithTransitivenessWithAttr() throws Exception {
Exception e = new RuntimeException("test");
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceEnter(14, 4<<16);
r.newAttr(-1, 99, "OJAAA!");
r.traceError(e, 9<<16);
r.traceReturn(10<<16);
r.traceReturn(11<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 11L, "calls", 3L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 10L, "calls", 2L,
"children", l(m("_", "T", "method", 14L, "tstart", 4L, "tstop", 9L, "calls", 1L,
"error", errorToMap(e), "attrs", m(99, "OJAAA!")))))
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceExceptionCompression() throws Exception {
Exception e = new RuntimeException("test");
int id = System.identityHashCode(e);
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceEnter(14, 4<<16);
r.traceError(e, 9<<16);
r.traceError(e, 10<<16);
r.traceReturn(11<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 11L, "calls", 3L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 10L, "calls", 2L,
"error", m("_", "E", "id", id),
"children", l(m("_", "T", "method", 14L, "tstart", 4L, "tstop", 9L, "calls", 1L,
"error", errorToMap(e)))))
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testTraceExceptionCompressCause() throws Exception {
Exception e1 = new RuntimeException("test1");
Exception e2 = new RuntimeException("test2", e1);
int i1 = System.identityHashCode(e1);
int i2 = System.identityHashCode(e2);
Map em1 = errorToMap(e1);
Map em2 = errorToMap(e2);
// TODO em2.put("cause", m("_", "E", "id", i1));
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
r.traceEnter(14, 4<<16);
r.traceError(e1, 9<<16);
r.traceError(e2, 10<<16);
r.traceReturn(11<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 11L, "calls", 3L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "tstart", 3L, "tstop", 10L, "calls", 2L,
"error", em2,
"children", l(m("_", "T", "method", 14L, "tstart", 4L, "tstop", 9L, "calls", 1L,
"error",em1))))
), decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testDisableEnableTracer() throws Exception {
r.setMinimumTraceTime(5);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.disable();
r.traceEnter(12, 3<<16);
r.traceReturn(8<<16);
r.enable();
r.traceReturn(9<<16);
assertEquals(1, chunksCount(o.getChunks()));
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 1L,
"begin", m("_", "B", "clock", 11)),
decodeTrace(o.getChunks()));
}
@Ignore("TBD fix streaming tracer later") @Test
public void testSimpleTraceBufOverflowAndReturnWithMethodHalfDrop() throws Exception {
r.setMinimumTraceTime(5);
String s = mkString(104);
r.traceEnter(10, 1<<16);
r.traceBegin(1, 11, 0);
r.traceEnter(12, 3<<16);
assertEquals(1, chunksCount((STraceBufChunk)ObjectInspector.getField(r, "chunk")));
r.newAttr(-1, 1, s);
assertEquals(2, chunksCount((STraceBufChunk)ObjectInspector.getField(r, "chunk")));
r.traceReturn(6<<16);
r.traceReturn(9<<16);
assertEquals(m(
"_", "T", "method", 10L, "tstart", 1L, "tstop", 9L, "calls", 2L,
"begin", m("_", "B", "clock", 11),
"children", l(m("_", "T", "method", 12L, "calls", 1L, "tstart", 3L, "tstop", 6L, "attrs", m(1, s)))
), decodeTrace(o.getChunks()));
}
// TODO test embedded trace with and without automatic flush
// TODO test forced trace submission;
// TODO test forced trace flush;
// TODO test test for embedded trace;
// TODO test for forced flush of embedded trace;
// TODO test for automatic flush of embedded trace;
// TODO test for dropping partially sent trace;
// TODO test for proper buffer queuing;
// TODO test for automatic flush of queued buffers;
// TODO test assigning attributes to specific traces;
// TODO test for automatic flush after selected timeout - triggered from instrumentation;
// TODO test for automatic flush after selected timeout - triggered from external thread;
public void slowLongWriter(byte[] b, long v) {
for (int pos = 0; pos < b.length; pos += 8) {
b[pos] = (byte)((v>>56)&0xff);
b[pos+1] = (byte)((v>>48)&0xff);
b[pos+2] = (byte)((v>>40)&0xff);
b[pos+3] = (byte)((v>>32)&0xff);
b[pos+4] = (byte)((v>>24)&0xff);
b[pos+5] = (byte)((v>>16)&0xff);
b[pos+6] = (byte)((v>>8)&0xff);
b[pos+7] = (byte)(v&0xff);
}
}
}
| gpl-3.0 |
chusobadenas/ACMEButchers | app/src/test/java/com/acmebutchers/app/presentation/map/MapPresenterTest.java | 1582 | package com.acmebutchers.app.presentation.map;
import com.acmebutchers.app.domain.interactor.DefaultSubscriber;
import com.acmebutchers.app.domain.interactor.map.GetButcherShops;
import com.acmebutchers.app.domain.interactor.map.GetCurrentLocation;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
public class MapPresenterTest {
private MapPresenter mapPresenter;
@Mock
private GetButcherShops getButcherShops;
@Mock
private GetCurrentLocation getCurrentLocation;
@Mock
private MapMvpView mapMvpView;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mapPresenter = new MapPresenter(getButcherShops, getCurrentLocation);
mapPresenter.attachView(mapMvpView);
}
@Test
public void testAttachViewSuccess() {
assertNotNull(mapPresenter.getMvpView());
}
@Test
public void testDetachViewSuccess() {
mapPresenter.detachView();
assertNull(mapPresenter.getMvpView());
verify(getButcherShops).unsubscribe();
verify(getCurrentLocation).unsubscribe();
}
@Test
public void testLoadButcherShopsSuccess() {
mapPresenter.loadButcherShops();
verify(getButcherShops).execute(any(DefaultSubscriber.class));
}
@Test
public void testCenterMapSuccess() {
mapPresenter.centerMap();
verify(getCurrentLocation).execute(any(DefaultSubscriber.class));
}
}
| gpl-3.0 |
Sedridor/AMIDST-CC | src/amidst/gui/License.java | 2107 | package amidst.gui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import amidst.logging.Log;
import amidst.resources.ResourceLoader;
public class License
{
private InputStream fileStream;
private String name;
private String contents;
private boolean loaded = false;
public License(String name, String path)
{
this.name = name;
try
{
fileStream = ResourceLoader.getResourceStream(path);
}
catch (NullPointerException e)
{
Log.w("Error finding license for: " + name + " at path: " + path);
e.printStackTrace();
}
}
public String getName()
{
return name;
}
public void load()
{
if (loaded)
{
return;
}
BufferedReader fileReader = new BufferedReader(new InputStreamReader(fileStream));
BufferedReader bufferedReader = new BufferedReader(fileReader);
try
{
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null)
{
stringBuilder.append(line);
stringBuilder.append('\n');
line = bufferedReader.readLine();
}
contents = stringBuilder.toString();
loaded = true;
}
catch (IOException e)
{
Log.w("Unable to read file: " + name + ".");
e.printStackTrace();
}
finally
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
Log.w("Unable to close BufferedReader for: " + name + ".");
e.printStackTrace();
}
}
}
public String getContents()
{
return contents;
}
public boolean isLoaded()
{
return loaded;
}
@Override
public String toString()
{
return name;
}
}
| gpl-3.0 |
slashchenxiaojun/wall.e | src/main/java/org/hacker/core/config/_JFinalDemoGenerator.java | 2129 | package org.hacker.core.config;
import javax.sql.DataSource;
import org.hacker.core.Dict;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.druid.DruidPlugin;
/**
* 在数据库表有任何变动时,运行一下 main 方法,极速响应变化进行代码重构
*/
public class _JFinalDemoGenerator {
public static DataSource getDataSource() {
WebConfig config = new WebConfig();
config.loadPropertyFile("play.properties");
DruidPlugin dp = new DruidPlugin(
config.getProperty(Dict.CONFIG_JDBC_URL),
config.getProperty(Dict.CONFIG_JDBC_USERNAME),
config.getProperty(Dict.CONFIG_JDBC_PASSWORD).trim(),
null, "stat,wall");
dp.start();
return dp.getDataSource();
}
public static void main(String[] args) {
// base model 所使用的包名
String baseModelPackageName = "org.hacker.mvc.model.base";
// base model 文件保存路径
String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/org/hacker/mvc/model/base";
// model 所使用的包名 (MappingKit 默认使用的包名)
String modelPackageName = "org.hacker.mvc.model";
// model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
String modelOutputDir = baseModelOutputDir + "/..";
// 创建生成器
Generator gernerator = new Generator(getDataSource(),
new CustomBaseModelGenerator(baseModelPackageName, baseModelOutputDir),
new CustomModelGenerator(modelPackageName, baseModelPackageName, modelOutputDir));
// 添加不需要生成的表名
gernerator.addExcludedTable(new String[]{""});
// 设置是否在 Model 中生成 dao 对象
gernerator.setGenerateDaoInModel(true);
// 设置是否生成字典文件
gernerator.setGenerateDataDictionary(false);
// 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user",移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
gernerator.setRemovedTableNamePrefixes(new String[]{"w_"});
// 生成
gernerator.generate();
}
}
| gpl-3.0 |
ferquies/2dam | AD/Tema 2/h2/src/tools/org/h2/jaqu/Define.java | 2168 | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.jaqu;
import org.h2.jaqu.Table.IndexType;
/**
* This class provides utility methods to define primary keys, indexes, and set
* the name of the table.
*/
public class Define {
private static TableDefinition<?> currentTableDefinition;
private static Table currentTable;
public static void primaryKey(Object... columns) {
checkInDefine();
currentTableDefinition.setPrimaryKey(columns);
}
public static void index(Object... columns) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.STANDARD, columns);
}
public static void uniqueIndex(Object... columns) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.UNIQUE, columns);
}
public static void hashIndex(Object column) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.HASH, new Object [] { column });
}
public static void uniqueHashIndex(Object column) {
checkInDefine();
currentTableDefinition.addIndex(IndexType.UNIQUE_HASH, new Object [] { column });
}
public static void maxLength(Object column, int length) {
checkInDefine();
currentTableDefinition.setMaxLength(column, length);
}
public static void tableName(String tableName) {
currentTableDefinition.setTableName(tableName);
}
static synchronized <T> void define(TableDefinition<T> tableDefinition,
Table table) {
currentTableDefinition = tableDefinition;
currentTable = table;
tableDefinition.mapObject(table);
table.define();
currentTable = null;
}
private static void checkInDefine() {
if (currentTable == null) {
throw new RuntimeException("This method may only be called " +
"from within the define() method, and the define() method " +
"is called by the framework.");
}
}
}
| gpl-3.0 |
IndiPlex/MultiWorlds | src/de/indiplex/multiworlds/generators/PicWoolPopulator.java | 1231 | package de.indiplex.multiworlds.generators;
import java.util.Random;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.generator.BlockPopulator;
/**
*
* @author temp
*/
public class PicWoolPopulator extends BlockPopulator {
private PicGenerator pg;
public PicWoolPopulator(PicGenerator pg) {
this.pg = pg;
}
@Override
public void populate(World world, Random random, Chunk source) {
int y = 20;
Integer[][] data = pg.datas.get(world.getName());
if (data==null) return;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int absX = source.getX()*16+x;
int absZ = source.getZ()*16+z;
if (absX<pg.width&&absZ<pg.height && absX>=0 && absZ>=0) {
Block block = source.getBlock(x, y, z);
try {
block.setData( data[absX][absZ].byteValue());
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error: "+absX+" "+absZ);
}
}
}
}
}
}
| gpl-3.0 |
kucro3/Jam | Jam/src/org/kucro3/tool/asm/ASM.java | 2273 | package org.kucro3.tool.asm;
import java.util.*;
import org.kucro3.clazz.util.ClassDef;
import org.kucro3.jam.opcodes.CodeBlock;
import org.kucro3.jam.opcodes.OpcodeMap;
import org.objectweb.asm.*;
public class ASM implements Opcodes {
public static void asm(String... lines) throws InstantiationException, IllegalAccessException
{
CompiledCodeBlock ccb = compile(lines);
if(ccb != null)
ccb.run();
}
public static void asm(Object cacheHandle, String... lines) throws InstantiationException, IllegalAccessException
{
CompiledCodeBlock ccb;
if((ccb = cache.get(cacheHandle)) == null)
cache.put(cacheHandle, ccb = compile(lines));
if(ccb != null)
ccb.run();
}
private static final CompiledCodeBlock compile(String... lines) throws InstantiationException, IllegalAccessException
{
if(lines.length == 0)
return null;
String name = CLASS_NAME_HEADER + (count++);
ClassWriter cv = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cv.visit(V1_7, ACC_PUBLIC + ACC_FINAL, name,
null, "org/kucro3/tool/asm/ASM$CompiledCodeBlock", null);
constructor(cv);
CodeBlock cb = new CodeBlock(cv, ACC_PUBLIC + ACC_FINAL, "run", "()V");
cb.code();
for(int i = 0; i < lines.length; i++)
cb.next(lines[i]);
cb.maxs();
cb.end();
cv.visitEnd();
byte[] byts = cv.toByteArray();
Class<?> clz = ClassDef.defClass(name, byts, 0, byts.length);
return (CompiledCodeBlock)clz.newInstance();
}
private static void constructor(ClassWriter cw)
{
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "org/kucro3/tool/asm/ASM$CompiledCodeBlock"
, "<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
private static final Map<Object, CompiledCodeBlock> cache = new HashMap<>();
private static volatile int count;
private static final String CLASS_NAME_HEADER = "COMPILED_CODE_BLOCK_";
public static abstract class CompiledCodeBlock
{
public abstract void run();
}
static {
OpcodeMap.init(ASM.class.getClassLoader()
.getResourceAsStream("org/kucro3/jam/opcodes/res/opcodes.ini"));
}
}
| gpl-3.0 |
CannibalVox/HexxitGear | src/main/java/sct/hexxitgear/net/HexxitGearNetwork.java | 4110 | package sct.hexxitgear.net;
import com.google.common.collect.Maps;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.FMLEmbeddedChannel;
import cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec;
import cpw.mods.fml.common.network.FMLOutboundHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import sct.hexxitgear.net.packets.*;
import java.util.EnumMap;
@ChannelHandler.Sharable
public class HexxitGearNetwork extends FMLIndexedMessageToMessageCodec<HexxitGearPacketBase> {
private static final HexxitGearNetwork INSTANCE = new HexxitGearNetwork();
private static final EnumMap<Side, FMLEmbeddedChannel> channels = Maps.newEnumMap(Side.class);
public static void init() {
if (!channels.isEmpty())
return;
INSTANCE.addDiscriminator(0, CapeChangePacket.class);
INSTANCE.addDiscriminator(1, CapeJoinPacket.class);
INSTANCE.addDiscriminator(2, ArmorAbilityPacket.class);
INSTANCE.addDiscriminator(3, PolarityPacket.class);
channels.putAll(NetworkRegistry.INSTANCE.newChannel("HexxitGear", INSTANCE));
}
public void encodeInto(ChannelHandlerContext ctx, HexxitGearPacketBase msg, ByteBuf target) throws Exception {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
msg.write(out);
target.writeBytes(out.toByteArray());
}
@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, HexxitGearPacketBase msg) {
ByteArrayDataInput in = ByteStreams.newDataInput(source.array());
in.skipBytes(1);
msg.read(in);
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
handleClient(msg);
else
handleServer(ctx, msg);
}
@SideOnly(Side.CLIENT)
private void handleClient(HexxitGearPacketBase msg) {
msg.handleClient(Minecraft.getMinecraft().theWorld, Minecraft.getMinecraft().thePlayer);
}
private void handleServer(ChannelHandlerContext ctx, HexxitGearPacketBase msg) {
EntityPlayerMP player = ((NetHandlerPlayServer) ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()).playerEntity;
msg.handleServer(player.worldObj, player);
}
public static void sendToServer(HexxitGearPacketBase packet) {
channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
channels.get(Side.CLIENT).writeAndFlush(packet);
}
public static void sendToPlayer(HexxitGearPacketBase packet, EntityPlayer player) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
channels.get(Side.SERVER).writeAndFlush(packet);
}
public static void sendToAllPlayers(HexxitGearPacketBase packet) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
channels.get(Side.SERVER).writeAndFlush(packet);
}
public static void sendToNearbyPlayers(HexxitGearPacketBase packet, int dim, double x, double y, double z, double range) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(new NetworkRegistry.TargetPoint(dim, x, y, z, range));
channels.get(Side.SERVER).writeAndFlush(packet);
}
} | gpl-3.0 |
tobiasschulz/voipcall | src/call/Server.java | 5571 | package call;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class Server extends AbstractId implements Runnable {
public Server() {}
private boolean listening = false;
private int[] openPorts = new int[] {};
@Override
public void run() {
listening = true;
while (listening) {
ServerSocket serverSocket1 = openServerSocket(Config.DEFAULT_PORT);
int normalport = serverSocket1.getLocalPort();
ServerSocket serverSocket2 = openServerSocket(Config.DEFAULT_PORT
+ Config.DEFAULT_PORT_OFFSET_CALL);
int callport = serverSocket2.getLocalPort();
ServerSocket serverSocket3 = openServerSocket(Config.DEFAULT_PORT
+ Config.DEFAULT_PORT_OFFSET_CHAT);
int chatport = serverSocket3.getLocalPort();
openPorts = new int[] { normalport, callport, chatport };
Config.CURRENT_PORT = normalport;
new Thread(new UpnpClient(new int[] { normalport, callport, chatport }), "UpnpClient").start();
Thread listen1 = new Thread(new Listener(this, serverSocket1), "Server.Listener");
Thread listen2 = new Thread(new Listener(this, serverSocket2), "Server.Listener");
listen1.start();
listen2.start();
Util.joinThreads(listen1, listen2);
}
}
private ServerSocket openServerSocket(int port) {
ServerSocket serverSocket = null;
while (serverSocket == null) {
try {
serverSocket = new ServerSocket(port);
break;
} catch (IOException e) {
System.err.println("Could not listen on port: " + port + ".");
serverSocket = null;
Util.sleep(1000);
port += 10;
}
}
System.out.println("Server listening on port: " + port);
return serverSocket;
}
public boolean isListening() {
return listening;
}
public void close() {
listening = false;
}
@Override
public String toString() {
return "0.0.0.0:[" + StringUtils.join(Arrays.asList(openPorts), ",") + "]";
}
@Override
public String getId() {
return toString();
}
private static class Listener implements Runnable {
private final Server server;
private final ServerSocket serversocket;
public Listener(Server server, ServerSocket serversocket) {
this.server = server;
this.serversocket = serversocket;
}
@Override
public void run() {
while (server.isListening()) {
try {
final Socket socket = serversocket.accept();
new Thread(new Acceptor(socket), "Server.Acceptor").start();
} catch (IOException e) {
System.out.println("Error in call accept loop (class Server.Listener)!");
e.printStackTrace();
}
}
}
}
private static class Acceptor implements Runnable {
final Socket socket;
public Acceptor(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
handle();
} catch (SocketException e) {} catch (IOException e) {
System.out.println("Error in call accept loop (class Acceptor)!");
e.printStackTrace();
}
}
private void handle() throws IOException {
socket.setReuseAddress(true);
socket.setTcpNoDelay(true);
SocketUtil.writeHeaders(socket.getOutputStream(), SocketUtil.RequestType.ServerCall);
final InputStream instream = socket.getInputStream();
final List<String> headers = SocketUtil.readHeaders(instream);
final String remoteuser = SocketUtil.getHeaderValue(headers, "user");
final String remotehost = socket.getInetAddress().getCanonicalHostName();
Contact contact;
// loopback connection?
if (Config.UID_S.equals(SocketUtil.getHeaderValue(headers, "UID"))) {
contact = new Contact(remotehost, socket.getPort(), remoteuser, Contact.Reachability.LOOPBACK);
}
// normal connection
else {
contact = ContactList.findContact(remotehost, 0, remoteuser);
if (contact == null) {
contact = new Contact(remotehost, socket.getPort(), remoteuser,
Contact.Reachability.UNREACHABLE);
// System.out.println("No contact found for: " +
// contact);
}
}
// handle request
final String request = SocketUtil.getHeaderValue(headers, "request");
if (request.toLowerCase().equals("status")) {
// status connection
socket.close();
} else if (request.toLowerCase().equals("ping")) {
// ping connection
PingClient client = new PingClient(contact, socket, headers);
new Thread(client, "Server -> PingClient").start();
} else if (request.toLowerCase().equals("call")) {
// call connection
socket.setSoTimeout(Config.SOCKET_READ_TIMEOUT);
if (!contact.isReachable()) {
ContactList.addContact(contact);
}
CallClient client = new CallClient(contact, socket, headers);
client.startCall();
Util.msg(contact).println("Incoming call.", Color.green);
Util.log(contact, "Connected to call (Server).");
} else if (request.toLowerCase().equals("chat")) {
// chat connection
socket.setSoTimeout(Config.SOCKET_READ_TIMEOUT);
if (!contact.isReachable()) {
ContactList.addContact(contact);
}
ChatClient client = new ChatClient(contact, socket, headers);
client.saveTo(new ChatCapture(contact));
new Thread(client, "Server -> ChatClient").start();
Util.log(contact, "Connected tp chat (Server).");
} else {
// unknown connection
Util.log(socket.toString(), "Fuck! Unknown connection type!");
for (String header : headers) {
Util.log(socket.toString(), "header: " + header);
}
}
}
}
}
| gpl-3.0 |
misaki-nyanya/MyPieces | TASystem/src/clientUI/LoginUI.java | 8138 | package clientUI;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class LoginUI {
private JFrame loginFrame = new JFrame("Class Manager System");
private JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
private JPanel adminPanel= new JPanel();
private JPanel stuPanel= new JPanel();
private JPanel teaPanel= new JPanel();
private JLabel adminName = new JLabel("Admin");
private JLabel stuNoLabel = new JLabel("Student Number:");
private JLabel teaNoLabel = new JLabel("Teacher Number:");
private JLabel stuPassLabel = new JLabel("Student Password:");
private JLabel teaPassLabel = new JLabel("Teacher Number:");
private JLabel adminPassLabel = new JLabel("Adminster Password:");
private JLabel adminLabel = new JLabel("Adminster:\r\n");
private JTextField stuNo = new JTextField();
private JTextField teaNo = new JTextField();
private JPasswordField adminPassword = new JPasswordField();
private JPasswordField stuPassword = new JPasswordField();
private JPasswordField teaPassword = new JPasswordField();
private JButton stuLogin = new JButton("Login");
private JButton adminLogin = new JButton("Login");
private JButton teaLogin = new JButton("Login");
private String accountNo = "";
private String accountPass = "";
private boolean LoginFrameVisibility = true;
private boolean accountReady = false;
public void init(){
stuLogin.addMouseListener(new LoginStu());
teaLogin.addMouseListener(new LoginTea());
adminLogin.addMouseListener(new LoginAdmin());
tabbedPane.addTab("Administer Login", null, null);
tabbedPane.addTab("Student Login", null, null);
tabbedPane.addTab("Teacher Login", null, null);
loginFrame.add(tabbedPane,BorderLayout.CENTER);
tabbedPane.addChangeListener(
new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
tabbedPane.getSelectedComponent();
}
}
);
adminPanel.setLayout(new BoxLayout(adminPanel,BoxLayout.Y_AXIS));
adminPanel.add(adminLabel);
adminPanel.add(adminName);
adminPanel.add(Box.createVerticalStrut(50));
adminPanel.add(adminPassLabel);
adminPanel.add(Box.createVerticalStrut(50));
adminPanel.add(adminPassword);
adminPanel.add(adminLogin);
stuPanel.setLayout(new BoxLayout(stuPanel,BoxLayout.Y_AXIS));
stuPanel.add(stuNoLabel);
stuPanel.add(Box.createVerticalStrut(50));
stuPanel.add(stuNo);
stuPanel.add(stuPassLabel);
stuPanel.add(Box.createVerticalStrut(50));
stuPanel.add(stuPassword);
stuPanel.add(stuLogin);
teaPanel.setLayout(new BoxLayout(teaPanel,BoxLayout.Y_AXIS));
teaPanel.add(teaNoLabel);
teaPanel.add(Box.createVerticalStrut(50));
teaPanel.add(teaNo);
teaPanel.add(teaPassLabel);
teaPanel.add(Box.createVerticalStrut(50));
teaPanel.add(teaPassword);
teaPanel.add(teaLogin);
tabbedPane.setComponentAt(0, adminPanel);
tabbedPane.setComponentAt(1, stuPanel);
tabbedPane.setComponentAt(2, teaPanel);
loginFrame.setPreferredSize(new Dimension(500,300));
loginFrame.pack();
loginFrame.addWindowListener(new WindowListener(){
@Override
public void windowActivated(WindowEvent arg0) {
}
@Override
public void windowClosed(WindowEvent arg0) {
}
@Override
public void windowClosing(WindowEvent arg0) {
Client.close();
}
@Override
public void windowDeactivated(WindowEvent arg0) {
}
@Override
public void windowDeiconified(WindowEvent arg0) {
}
@Override
public void windowIconified(WindowEvent arg0) {
}
@Override
public void windowOpened(WindowEvent e) {
}
});
// loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.setVisible(true);
}
public String getAccountNo(){
if(!this.accountNo.equals("")){
return accountNo;
}else{
System.out.println("empty account number!");
return null;
}
}
public String getAccountPass(){
if(!this.accountPass.equals("")){
return accountPass;
}else{
System.out.println("empty account Password!");
return null;
}
}
public void setLoginFrameVisibility(boolean visible){
this.LoginFrameVisibility = visible;
this.loginFrame.setVisible(visible);
}
public boolean getVisibility(){
return this.LoginFrameVisibility;
}
public boolean getAccountStatus(){
return accountReady;
}
class LoginAdmin implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
// get account
char[] temp = adminPassword.getPassword();
StringBuilder password = new StringBuilder();
password.append(temp);
accountNo = "Admin";
accountPass = password.toString();
//judge login
boolean login = false;
try {
login = Client.checkAdminLogin(accountPass);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Cannot connect to server!", "Initialization Failed", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
if(login){
setLoginFrameVisibility(false);
}else{
JOptionPane.showMessageDialog(null, "Wrong Password or Wrong Account Name!", "Login Failed", JOptionPane.ERROR_MESSAGE);
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
class LoginStu implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
//get account
accountNo = stuNo.getText();
char[] temp = stuPassword.getPassword();
StringBuilder password = new StringBuilder();
password.append(temp);
accountPass = password.toString();
accountReady = true;
//judge login
boolean login = false;
try {
login = Client.checkStuLogin(accountNo,accountPass);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Cannot connect to server!", "Initialization Failed", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
if(login){
setLoginFrameVisibility(false);
}else{
JOptionPane.showMessageDialog(null, "Wrong Password or Wrong Account Name!", "Login Failed", JOptionPane.ERROR_MESSAGE);
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
class LoginTea implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
// get account
accountNo = teaNo.getText();
char[] temp = teaPassword.getPassword();
StringBuilder password = new StringBuilder();
password.append(temp);
accountPass = password.toString();
accountReady = true;
//judge login
boolean login = false;
try {
login = Client.checkTeaLogin(accountNo,accountPass);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Cannot connect to server!", "Initialization Failed", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
if(login){
setLoginFrameVisibility(false);
}else{
JOptionPane.showMessageDialog(null, "Wrong Password or Wrong Account Name!", "Login Failed", JOptionPane.ERROR_MESSAGE);
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new LoginUI().init();
}
}
| gpl-3.0 |
Solarnum/Hydrogen-Hank | project/src/com/hh/framework/gamestate/states/ControlsState.java | 1881 | package com.hh.framework.gamestate.states;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import com.hh.Game;
import com.hh.framework.RenderHelper;
import com.hh.framework.gamestate.GameState;
import com.hh.input.KeyInput;
import com.hh.objects.TextBox;
/**
* COSC3550 Spring 2014
*
* Created : Apr. 4, 2014
* Last Updated : Apr. 4, 2014
* Purpose: An unused state for modifying controls
*
* @author Mark Schlottke
*/
public class ControlsState extends GameState
{
private RenderHelper renderHelp = new RenderHelper();
private float boxHeight = 0;
private float boxWidth = 0;
private TextBox nameEntry;
private Font font = new Font("Arial", Font.BOLD, 100);
public ControlsState()
{
nameEntry = new TextBox("", 10, Game.width / 2, Game.height / 2, 300, 50);
KeyInput.textEntry = nameEntry;
}
public void tick()
{
if (boxHeight < Game.height / 2)
{
boxHeight += Game.height / 25;
} else
{
boxHeight = Game.height;
}
if (boxWidth < Game.width / 2)
{
boxWidth += Game.width / 25;
} else
{
boxWidth = Game.width;
}
nameEntry.tick();
}
public void render(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
renderHelp.tintedBox(g2d, Color.black, 0.7f, (int) (Game.width / 2 - boxWidth),
(int) (Game.height / 2 - boxHeight), (int) (boxWidth * 2), (int) (boxHeight * 2));
if (boxWidth >= Game.width / 2 && boxHeight >= Game.height / 2)
{
//g.drawImage(art.pauseScreen, (Game.width / 2 - art.pauseScreen.getWidth() / 2),
// (Game.height / 2 - 150), null);
renderHelp.outlinedText((Graphics2D) g, font, "Controls", 0.9f, Color.black, Color.red,
(Game.width / 2)-260, (Game.height / 2)-120);
nameEntry.render(g);
}
}
public void onDelete()
{
}
}
| gpl-3.0 |
openflexo-team/gina | flexographicutils/src/main/java/org/openflexo/jedit/FMLTokenMarker.java | 4845 | /*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.jedit;
/*
* JavaTokenMarker.java - Java token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
/**
* Java token marker.
*
* @author Slava Pestov
* @version $Id: JavaTokenMarker.java,v 1.2 2011/09/12 11:47:08 gpolet Exp $
*/
public class FMLTokenMarker extends CTokenMarker {
public FMLTokenMarker() {
super(false, getKeywords());
}
public static KeywordMap getKeywords() {
if (javaKeywords == null) {
javaKeywords = new KeywordMap(false);
javaKeywords.add("ViewDefinition", Token.KEYWORD1);
javaKeywords.add("ModelSlot", Token.KEYWORD1);
javaKeywords.add("VirtualModel", Token.KEYWORD1);
javaKeywords.add("FlexoConcept", Token.KEYWORD1);
javaKeywords.add("PatternRole", Token.KEYWORD1);
javaKeywords.add("ActionScheme", Token.KEYWORD3);
javaKeywords.add("CreationScheme", Token.KEYWORD3);
javaKeywords.add("DeletionScheme", Token.KEYWORD3);
javaKeywords.add("SynchronizationScheme", Token.KEYWORD3);
javaKeywords.add("DropScheme", Token.KEYWORD3);
javaKeywords.add("LinkScheme", Token.KEYWORD3);
javaKeywords.add("CloningScheme", Token.KEYWORD3);
javaKeywords.add("MatchFlexoConceptInstance", Token.KEYWORD4);
javaKeywords.add("SelectFlexoConceptInstance", Token.KEYWORD4);
javaKeywords.add("conformTo", Token.KEYWORD2);
javaKeywords.add("type", Token.KEYWORD2);
javaKeywords.add("uri", Token.KEYWORD2);
javaKeywords.add("as", Token.KEYWORD2);
javaKeywords.add("from", Token.KEYWORD2);
javaKeywords.add("where", Token.KEYWORD2);
javaKeywords.add("match", Token.KEYWORD2);
javaKeywords.add("in", Token.KEYWORD2);
javaKeywords.add("using", Token.KEYWORD2);
javaKeywords.add("byte", Token.KEYWORD1);
javaKeywords.add("char", Token.KEYWORD1);
javaKeywords.add("short", Token.KEYWORD1);
javaKeywords.add("int", Token.KEYWORD1);
javaKeywords.add("long", Token.KEYWORD1);
javaKeywords.add("float", Token.KEYWORD1);
javaKeywords.add("double", Token.KEYWORD1);
javaKeywords.add("boolean", Token.KEYWORD1);
javaKeywords.add("void", Token.KEYWORD1);
javaKeywords.add("class", Token.KEYWORD1);
javaKeywords.add("interface", Token.KEYWORD1);
javaKeywords.add("abstract", Token.KEYWORD1);
javaKeywords.add("final", Token.KEYWORD1);
javaKeywords.add("private", Token.KEYWORD1);
javaKeywords.add("protected", Token.KEYWORD1);
javaKeywords.add("public", Token.KEYWORD1);
javaKeywords.add("static", Token.KEYWORD1);
javaKeywords.add("synchronized", Token.KEYWORD1);
javaKeywords.add("native", Token.KEYWORD1);
javaKeywords.add("volatile", Token.KEYWORD1);
javaKeywords.add("transient", Token.KEYWORD1);
javaKeywords.add("break", Token.KEYWORD1);
javaKeywords.add("case", Token.KEYWORD1);
javaKeywords.add("continue", Token.KEYWORD1);
javaKeywords.add("default", Token.KEYWORD1);
javaKeywords.add("do", Token.KEYWORD1);
javaKeywords.add("else", Token.KEYWORD1);
javaKeywords.add("for", Token.KEYWORD1);
javaKeywords.add("if", Token.KEYWORD1);
javaKeywords.add("instanceof", Token.KEYWORD1);
javaKeywords.add("new", Token.KEYWORD1);
javaKeywords.add("return", Token.KEYWORD1);
javaKeywords.add("switch", Token.KEYWORD1);
javaKeywords.add("while", Token.KEYWORD1);
javaKeywords.add("throw", Token.KEYWORD1);
javaKeywords.add("try", Token.KEYWORD1);
javaKeywords.add("catch", Token.KEYWORD1);
javaKeywords.add("extends", Token.KEYWORD1);
javaKeywords.add("finally", Token.KEYWORD1);
javaKeywords.add("implements", Token.KEYWORD1);
javaKeywords.add("throws", Token.KEYWORD1);
javaKeywords.add("this", Token.KEYWORD1);
javaKeywords.add("null", Token.KEYWORD1);
javaKeywords.add("super", Token.KEYWORD1);
javaKeywords.add("true", Token.KEYWORD1);
javaKeywords.add("false", Token.KEYWORD1);
}
return javaKeywords;
}
// private members
private static KeywordMap javaKeywords;
}
| gpl-3.0 |
ProjektMedInf/WiFiSDCryptoLocker | app/src/androidTest/java/io/github/projektmedinf/wifisdcryptolocker/UserServiceImplTest.java | 2033 | package io.github.projektmedinf.wifisdcryptolocker;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import io.github.projektmedinf.wifisdcryptolocker.data.dao.UserDao;
import io.github.projektmedinf.wifisdcryptolocker.data.dao.impl.UserDaoImpl;
import io.github.projektmedinf.wifisdcryptolocker.model.User;
import io.github.projektmedinf.wifisdcryptolocker.service.UserService;
import io.github.projektmedinf.wifisdcryptolocker.service.impl.UserServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class UserServiceImplTest {
private static final String VALID_USER_NAME = "validUser";
private static final String INVALID_USER_NAME = "invalidUser";
private UserService userService;
private User validUser;
@Before
public void setUp() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
userService = new UserServiceImpl(appContext);
UserDao userDao = new UserDaoImpl(appContext);
validUser = new User();
validUser.setUsername(VALID_USER_NAME);
validUser.setPassword("12345");
userDao.insertUser(validUser);
validUser = null;
validUser = userDao.getUserByUserName(VALID_USER_NAME);
}
@Test
public void shouldReturnUserMatchingTheGivenUserName() throws Exception {
assertThat(userService.getUserByUserName(VALID_USER_NAME), is(validUser));
}
@Test
public void shouldReturnNullIfNoMatchWasFound() throws Exception {
assertThat(userService.getUserByUserName(INVALID_USER_NAME), is(nullValue()));
}
}
| gpl-3.0 |
mstrey/lotoNaMao | mobile/Loterias/src/main/java/br/nom/strey/maicon/loterias/quina/QuinaListFragment.java | 9626 | package br.nom.strey.maicon.loterias.quina;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import br.nom.strey.maicon.loterias.R;
import br.nom.strey.maicon.loterias.main.Categories;
import br.nom.strey.maicon.loterias.main.LoteriaDetailActivity;
import br.nom.strey.maicon.loterias.utils.DBHelper;
import br.nom.strey.maicon.loterias.utils.WebService;
public class QuinaListFragment extends Fragment {
private static final String LOGTAG = "MegaListFragment";
private View rootView = null;
private ListView listView_volantes = null;
private Context ctx;
private List<QuinaVolantesVO> listQuinaVolantes;
private QuinaVolantesDAO dao_volantes;
private QuinaVolantesAdapter adapter_volantes;
private MenuItem refresh;
private Menu menu;
private static Integer concurso_max_remote_resultados;
private static final String MAX_CONCURSO = "max_conc";
public QuinaListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOGTAG, "onCreate");
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new CheckVolantesResultado().execute();
getActivity().getActionBar().setTitle(getString(R.string.action_megasena_header_list));
ctx = getActivity().getBaseContext();
rootView = inflater.inflate(R.layout.fragment_quina_list, container, false);
refresh = menu.findItem(R.id.action_update);
listView_volantes = (ListView) rootView.findViewById(R.id.lv_volantes);
dao_volantes = new QuinaVolantesDAO(ctx);
listQuinaVolantes = dao_volantes.getAll();
adapter_volantes = new QuinaVolantesAdapter(getActivity(), listQuinaVolantes, false);
listView_volantes.setAdapter(adapter_volantes);
listView_volantes.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
return rootView;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
ctx = getActivity().getBaseContext();
refresh = menu.findItem(R.id.action_update);
QuinaVolantesDAO dao_volantes = new QuinaVolantesDAO(ctx);
if (dao_volantes.getAll().isEmpty()) {
refresh.setVisible(false);
}
// backUpDB();
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
this.menu = menu;
menu.clear();
menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.action_lista, menu);
super.onCreateOptionsMenu(menu, menuInflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_incluir:
((LoteriaDetailActivity) getActivity()).editQuinaFragment();
return true;
case R.id.action_update:
new CheckVolantesResultado().execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void refreshVolantesList(Boolean exibe_acertos) {
listQuinaVolantes = dao_volantes.getAll();
adapter_volantes = new QuinaVolantesAdapter(getActivity(), listQuinaVolantes, exibe_acertos);
listView_volantes.setAdapter(adapter_volantes);
adapter_volantes.notifyDataSetChanged();
if (listQuinaVolantes.size() > 0) {
refresh.setVisible(true);
} else {
refresh.setVisible(false);
}
}
private void backUpDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//br.nom.strey.maicon.loterias//databases//" + DBHelper.DBNAME;
String backupDBPath = "//data//" + DBHelper.DBNAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(ctx, "Backup Efetuado", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ctx, "Base de origem não localizada: " + currentDBPath, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ctx, "Sem permissão de escrita no SDCARD", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
private class CheckVolantesResultado extends AsyncTask<Void, Void, Void> {
public CheckVolantesResultado() {
}
@Override
protected void onPreExecute() {
if (refresh != null) {
refresh.setActionView(R.layout.actionbar_indeterminate_progress);
}
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
if (refresh != null) {
refresh.setActionView(null);
}
refreshVolantesList(true);
super.onPostExecute(aVoid);
}
@Override
protected Void doInBackground(Void... voids) {
QuinaVolantesDAO dao_volantes = new QuinaVolantesDAO(ctx);
List<QuinaVolantesVO> volantes_para_conferir = dao_volantes.getAll();
ArrayList<Integer> concursos_para_conferir = dao_volantes.getConcursosParaConferir();
QuinaResultadosDAO dao_resultado = new QuinaResultadosDAO(ctx);
if (!concursos_para_conferir.isEmpty()) {
for (Integer concurso : concursos_para_conferir) {
if (!dao_resultado.existeResultado(concurso)) {
if (WebService.isConnected(ctx) != WebService.DISCONNECTED) {
StringBuffer strUrl = new StringBuffer("http://maicon.strey.nom.br/");
strUrl.append("loto/");
strUrl.append("getResults.php");
strUrl.append("?loto=");
strUrl.append(URLEncoder.encode(Categories.QUINA));
strUrl.append("&concurso=");
strUrl.append(concurso);
try {
URL url = new URL(strUrl.toString());
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String str_json = in.readLine();
Log.d(LOGTAG, "str_json: " + str_json);
JSONObject obj_json = new JSONObject(str_json);
if (concurso > 0) {
QuinaResultadosVO vo_resultado = new QuinaResultadosVO();
vo_resultado.setJson(obj_json);
if (dao_resultado.existe(vo_resultado.getConcurso())) {
dao_resultado.update(vo_resultado);
} else {
dao_resultado.insert(vo_resultado);
}
} else {
concurso_max_remote_resultados = obj_json.getInt(MAX_CONCURSO);
Log.d(LOGTAG, MAX_CONCURSO + "_remote: " + concurso_max_remote_resultados);
}
} catch (Exception e) {
concurso_max_remote_resultados = 1;
e.printStackTrace();
}
} else {
Toast.makeText(ctx, getString(R.string.conexao_nao_identificada), Toast.LENGTH_LONG).show();
}
}
}
for (QuinaVolantesVO vo_volante : volantes_para_conferir) {
vo_volante.confereResultado(ctx);
dao_volantes = new QuinaVolantesDAO(ctx);
dao_volantes.update(vo_volante);
}
}
// backUpDB();
return null;
}
}
}
| gpl-3.0 |
raydelto/itla_racer | src/edu/itla/itlaracer/graphics/TrackLane.java | 444 | package edu.itla.itlaracer.graphics;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class TrackLane extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
ImageIcon image = new ImageIcon("track_lane.png");
super.setOpaque(false);
g.drawImage(image.getImage(), 0, 0, null);
super.paintComponent(g);
}
}
| gpl-3.0 |
HDsettings/shop_java_project | videogameShop/src/dao/DAOLineaCompra.java | 2272 | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import data.ConnectionDB;
import model.LineaCompra;
import model.Producto;
public class DAOLineaCompra implements DAOInterface<LineaCompra,String> {
@Override
public LineaCompra findById(String id) {
LineaCompra l = null;
try
{
BasicDataSource basicDataSource = ConnectionDB.getInstancia().getPool();
Connection conexion = basicDataSource.getConnection();
String query = "select * from lineacompra where login = ?" ;
PreparedStatement s = conexion.prepareStatement(query);
s.setString(1,id);
ResultSet rs = s.executeQuery ();
if (rs.next())
{
l = new LineaCompra();
l.setId(rs.getString(1));
l.setIdcompra(rs.getString(2));
l.setCantidad(rs.getInt(3));
l.setSubtotal(rs.getFloat(4));
}
conexion.close();
}catch (Exception ex)
{
System.out.println ("Error"+ex.getMessage());
}
return l;
}
public int insert(LineaCompra l){
Connection connection = null;
int i=0;
try
{
BasicDataSource basicDataSource = ConnectionDB.getInstancia().getPool();
Connection conexion = basicDataSource.getConnection();
PreparedStatement s = connection.prepareStatement("INSERT INTO lineacompra VALUES (?,?,?,?)");
s.setString(1, l.getId());
s.setString(2, l.getIdcompra());
s.setInt(3, l.getCantidad());
s.setFloat(4, l.getSubtotal());
i=s.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return i;
}
@Override
public List<LineaCompra> findAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public int delete(LineaCompra ov) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(LineaCompra ov) {
// TODO Auto-generated method stub
return 0;
}
}
| gpl-3.0 |
miquelbeltran/android-german-prepositions | app/src/test/java/com/beltranfebrer/germanprepositions/ui/menu/MenuActivityTest.java | 2262 | package com.beltranfebrer.germanprepositions.ui.menu;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import com.beltranfebrer.germanprepositions.BuildConfig;
import com.beltranfebrer.germanprepositions.R;
import com.beltranfebrer.germanprepositions.ui.learningsession.LearnActivity;
import com.beltranfebrer.germanprepositions.ui.menu.MenuActivity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
import static junit.framework.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Shadows.shadowOf;
/**
* Created by miquel on 09.02.16.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MenuActivityTest {
private MenuActivity activity;
@Before
public void setUp() throws Exception {
activity = Robolectric.setupActivity(MenuActivity.class);
}
@Test
public void testListeners() throws Exception {
Button button = (Button) activity.findViewById(R.id.buttonNewSession);
assertTrue(button.hasOnClickListeners());
button = (Button) activity.findViewById(R.id.buttonStatistics);
assertTrue(button.hasOnClickListeners());
}
@Test
public void testClickStart() throws Exception {
activity.findViewById(R.id.buttonNewSession).performClick();
Intent expectedIntent = new Intent(activity, LearnActivity.class);
Intent actualIntent = shadowOf(activity).getNextStartedActivity();
// TODO: Somehow this test always fails with the SNAPSHOT version of the Robolectric
//assertThat(actualIntent).isEqualTo(expectedIntent);
}
@Test
public void testClickStatistics() throws Exception {
activity.findViewById(R.id.buttonStatistics).performClick();
// TODO
//Intent expectedIntent = new Intent(activity, StatisticsActivity.class);
//assertEquals(expectedIntent, shadowOf(activity).getNextStartedActivity());
}
}
| gpl-3.0 |
garrickbrazil/Oakland-Scheduler | src/Scheduler.java | 16657 | /*
This file is part of Oakland-Scheduler.
Oakland-Scheduler 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.
Oakland-Scheduler 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 Oakland-Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
/********************************************************************
* Class: Scheduler
* Purpose: holds dynamic courses and related functions
/*******************************************************************/
public class Scheduler implements Serializable {
private static final long serialVersionUID = 1L; // serialization version
private Map<String, List<Course>> catalog; // full mapping of all courses
private List<String> courseIDs; // course ID list
private List<String> currentCourseList; // current selected course
private boolean loaded; // currently loaded latest information
private boolean exception; // whether or not an exception occurred
private String termIn; // term currently in
/********************************************************************
* Constructor: Scheduler
* Purpose: default constructor for scheduler object
/*******************************************************************/
public Scheduler(){
// Defaults
this.catalog = new HashMap<String, List<Course>>();
this.courseIDs = new ArrayList<String>();
this.currentCourseList = new ArrayList<String>();
MainApplication.courseChecks = new HashMap<String, Boolean>();
this.termIn = "";
}
/********************************************************************
* Method: resetCourses
* Purpose: resets all courses to be blank for loading of new terms
/*******************************************************************/
public void resetCourses(){
// Defaults
this.catalog = new HashMap<String, List<Course>>();
this.courseIDs = new ArrayList<String>();
this.currentCourseList = new ArrayList<String>();
MainApplication.courseChecks = new HashMap<String, Boolean>();
this.termIn = "";
}
/********************************************************************
* Method: storeDynamicCourses()
* Purpose: store all dynamic courses to memory
/*******************************************************************/
public boolean storeDynamicCourse(String coursePrefix, DefaultHttpClient client, String term){
try {
// Debug message
//System.out.println("Storing " + coursePrefix);
this.termIn = term;
// Parameters for GET call
String params = "?rsts=dummy&crn=dummy&term_in=" + term
+ "&sel_subj=dummy&sel_day=dummy&sel_schd=dummy&sel_insm=dummy&sel_camp=dummy"
+ "&sel_levl=dummy&sel_sess=dummy&sel_instr=dummy&sel_ptrm=dummy&sel_attr=dummy"
+ "&sel_subj=" + coursePrefix + "&sel_crse=&sel_title=&sel_schd=%25&sel_from_cred=&sel_to_cred="
+ "&sel_camp=%25&sel_levl=%25&sel_ptrm=%25&sel_instr=%25&sel_attr=%25&begin_hh=0&"
+ "begin_mi=0&begin_ap=a&end_hh=0&end_mi=0&end_ap=a&SUB_BTN=Section+Search&path=1";
// Create GET call with correct referer
HttpGet courseSections = new HttpGet("https://sail.oakland.edu/PROD/bwskfcls.P_GetCrse_Advanced" + params);
courseSections.setHeader("Referer", "https://sail.oakland.edu/PROD/bwskfcls.P_GetCrse");
// Execute
HttpResponse response = client.execute(courseSections);
// Get main container of courses
Elements mainContainer = Jsoup.parse(response.getEntity().getContent(), "UTF-8", "https://sail.oakland.edu").getElementsByClass("datadisplaytable");
// Valid container ?
if(mainContainer.size() > 0 && mainContainer.get(0).getElementsByTag("tbody").size() > 0){
// Get courses offered for subject
Elements coursesOffered = mainContainer.get(0).getElementsByTag("tbody").get(0).children();
// Remove first two rows (headers)
if(coursesOffered.size() > 0) coursesOffered.remove(0);
if(coursesOffered.size() > 0) coursesOffered.remove(0);
// Properties
String courseName = "", courseID = "", instructor = "";
String location = "", time = "", days = "";
boolean closed = false, nr = false, sr = false;
double credits = 0; int crn = 0;
Course currentCourse = new Course();
String room = "";
// Go through all courses offered
for(int j = 0; j < coursesOffered.size(); j++) {
boolean courseFailed = false;
// Get all sections
Elements e = coursesOffered.get(j).getElementsByTag("td");
// Correctly formatted line ?
if(e.size() == 20
&& !e.get(1).text().replace("\u00a0","").equals("")
&& !e.get(2).text().replace("\u00a0","").equals("")
&& !e.get(3).text().replace("\u00a0","").equals("")
&& !e.get(4).text().replace("\u00a0","").equals("")
&& !e.get(5).text().replace("\u00a0","").equals("")
&& !e.get(6).text().replace("\u00a0","").equals("")
&& !e.get(7).text().replace("\u00a0","").equals("")
&& !e.get(8).text().replace("\u00a0","").equals("")
&& !e.get(9).text().replace("\u00a0","").equals("")
&& !e.get(16).text().replace("\u00a0","").equals("")
&& !e.get(18).text().replace("\u00a0","").equals("")
&& (e.get(8).text().contains("M")
|| e.get(8).text().contains("T")
|| e.get(8).text().contains("W")
|| e.get(8).text().contains("R")
|| e.get(8).text().contains("F"))
&& TimeBlock.isConvertable(e.get(9).text())){
// Store information (numbers are based on HTML table)
courseID = e.get(2).text() + " " + e.get(3).text();
courseName = e.get(7).text();
days = e.get(8).text();
time = e.get(9).text();
instructor = e.get(16).text();
room = e.get(18).text();
closed = e.get(0).text().contains("C");
nr = e.get(0).text().contains("NR");
sr = e.get(0).text().contains("SR");
location = e.get(5).text();
try{
// Convert CRN and credits
crn = Integer.parseInt(e.get(1).text());
credits = Double.parseDouble(e.get(6).text());
}
catch(Exception ex){
// Set invalid values
crn = 0;
credits = -1;
courseFailed = true;
}
// Special case for lab
if(credits == 0.0) courseID += "L";
if (!courseFailed){
// Create course
currentCourse = new Course(courseName, courseID, crn, credits, closed, nr, sr);
// Create meeting
Meeting currentMeeting = new Meeting(currentCourse, time, days, location,instructor, room, 0);
currentCourse.getMeetings().add(currentMeeting);
if(this.catalog.get(courseID) == null){
// Brand new course set
List<Course> courseSet = new ArrayList<Course>();
courseSet.add(currentCourse);
this.catalog.put(courseID, courseSet);
this.courseIDs.add(courseID);
}
else{
// Simply add the course
this.catalog.get(courseID).add(currentCourse);
}
}
// Only meeting information (missing column info)
else if(e.size() == 20
&& (e.get(8).text().contains("M")
|| e.get(8).text().contains("T")
|| e.get(8).text().contains("W")
|| e.get(8).text().contains("R")
|| e.get(8).text().contains("F"))
&& TimeBlock.isConvertable(e.get(9).text())
&& currentCourse.getMeetings().size() > 0){
// Update subcourse info
days = e.get(8).text();
time = e.get(9).text();
instructor = e.get(16).text();
room = e.get(18).text();
Meeting currentSub = new Meeting(currentCourse, time,days,location,instructor, room, currentCourse.getMeetings().size());
currentCourse.getMeetings().add(currentSub);
}
}
}
}
// Updated loaded status
this.loaded = true;
return true;
}
// Print all exceptions
catch(Exception e){
e.printStackTrace();
this.loaded = false;
return false;
}
}
/********************************************************************
* Method: generatePermutations
* Purpose: generates all working permutations for current list (3rd Implementation)
/*******************************************************************/
public List<List<Course>> generatePermutations(List<List<Course>> workingSet){
// Try to persuade GC to run
System.gc();
Runtime.getRuntime().gc();
try{
// Reset exception
exception = false;
// Initialize three sets
// One as a current iteration working area and another as iteration results
// and last as memory for checking course sets
//List<List<Course>> workingSet = new ArrayList<List<Course>>();
workingSet.clear();
List<List<Course>> newSet = new ArrayList<List<Course>>();
List<Course> cloneSet = new ArrayList<Course>();
// Memory for meeting lists
List<Meeting> courseSubs = new ArrayList<Meeting>();
// For each course
for(String courseID : this.currentCourseList){
// For each section in the course
for(Course course : this.catalog.get(courseID)){
if(workingSet.size() == 0){
testClasses(new ArrayList<Course>(),course,cloneSet, courseSubs);
newSet.add(cloneSet);
cloneSet = new ArrayList<Course>();
}
else{
// Check all current workingSets
for(List<Course> courseSet : workingSet){
// If fits into working set then add to newSet
if(testClasses(courseSet, course, cloneSet,courseSubs)){
newSet.add(cloneSet);
cloneSet = new ArrayList<Course>();
}
else{
cloneSet.clear();
}
}
}
if(exception) break;
}
if(exception) break;
// Update working set
List<List<Course>> tempSet = workingSet;
workingSet = newSet;
newSet = tempSet;
newSet.clear();
}
// Return working set
this.exception = false;
return workingSet;
}
catch(java.lang.OutOfMemoryError e){
this.exception = true;
System.out.println("Out of memory.");
}
return null;
}
/********************************************************************
* Method: testClasses
* Purpose: tests if classes work together
/*******************************************************************/
public boolean testClasses(List<Course> coursesOrig, Course courseCmpOrig, List<Course> clone, List<Meeting> courseSubs){
try{
// Add course
clone.add(courseCmpOrig);
// Generate a complete list of sub courses
courseSubs.clear();
for(Course courselist : coursesOrig){
// Add course to cloned list
clone.add(courselist);
// Add all sub courses
for(Meeting course : courselist.getMeetings()) courseSubs.add(course);
}
// Add sub courses from compare course (except for first one)
for (Meeting courseCmp : courseCmpOrig.getMeetings()){
// Get time
TimeBlock cmpBlock = courseCmp.getTime();
if(cmpBlock == null) return false;
// Get time info to minutes
int startC = cmpBlock.getStartHours() * 60 + cmpBlock.getStartMin();
int endC = cmpBlock.getEndHours() * 60 + cmpBlock.getEndMin();
int uniqueCrn = courseCmp.getCourseReference().getCRN()*1000 + courseCmp.getMeetingNumber();
String crnS = "";
// Check all sub courses against the compare course
for(Meeting course : courseSubs){
int currentUniqueCRN = course.getCourseReference().getCRN() * 1000 + course.getMeetingNumber();
// Sort crn string as smallest crn first (for hashing value)
if (uniqueCrn < currentUniqueCRN){
// Correct order
crnS = uniqueCrn + (currentUniqueCRN + "");
}
else crnS = (currentUniqueCRN + "") + uniqueCrn;
// Check if the comparison has already been done
if(MainApplication.courseChecks.containsKey(crnS)){
// If conflict, then simply return false
if (!MainApplication.courseChecks.get(crnS)) return false;
}
// Courses have never been compared
else {
// Get time information for comparison block
TimeBlock block = course.getTime();
if(block == null) return false;
// Start for block B
int startB = block.getStartHours() * 60 + block.getStartMin();
int endB = block.getEndHours() * 60 + block.getEndMin();
// Times overlap?
if(startB < endC && endB > startC){
// Days also over lap?
if ((course.M && courseCmp.M) || (course.T && courseCmp.T) || (course.W && courseCmp.W)
|| (course.R && courseCmp.R) || (course.F && courseCmp.F)){
// Store comparison and return false
MainApplication.courseChecks.put(crnS, false);
return false;
}
else{
// Store comparison as successful
MainApplication.courseChecks.put(crnS, true);
}
}
else{
// Store comparison as successful
MainApplication.courseChecks.put(crnS, true);
}
}
}
}
// At least one course must exist for schedule to be successful
return coursesOrig.size() > 0;
}
catch(java.lang.OutOfMemoryError e){
exception = true;
return false;
}
}
/********************************************************************
* Method: getPreInfo
* Purpose: gets the prequisite information for a course
/*******************************************************************/
public String getPreInfo(String courseID){
String html = "Could not get prerequisite information.";
String courseSubject = "";
String courseNumber = "";
try{
courseSubject = courseID.split(" ")[0];
courseNumber = courseID.split(" ")[1].replaceAll("L", "");
// Create client
DefaultHttpClient client = new DefaultHttpClient();
HttpPost termPage = new HttpPost("https://sail.oakland.edu/PROD/bwckctlg.p_display_courses?term_in=" + termIn + "&one_subj=" + courseSubject + "&sel_crse_strt="+ courseNumber + "&sel_crse_end=" + courseNumber + "&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=");
termPage.setHeader("Referer", "https://sail.oakland.edu/PROD/twbkwbis.P_WWWLogin");
HttpResponse response = client.execute(termPage);
Elements mainContainer = Jsoup.parse(response.getEntity().getContent(), "UTF-8", "https://sail.oakland.edu").getElementsByClass("datadisplaytable");
if(mainContainer.size() > 0 && mainContainer.get(0).getElementsByClass("ntdefault").size() > 0
&& mainContainer.get(0).getElementsByClass("ntdefault").get(0).textNodes().size() > 0){
// Return first text node (prereq info)
String infoBlock = mainContainer.get(0).getElementsByClass("ntdefault").get(0).textNodes().get(0).text();
if(infoBlock.contains("Prerequisite: ")){
return infoBlock.split("Prerequisite: ")[infoBlock.split("Prerequisite: ").length - 1];
}
else if(infoBlock.contains("Prerequisite(s): ")){
return infoBlock.split("Prerequisite: ")[infoBlock.split("Prerequisite: ").length - 1];
}
}
}
catch(Exception e){}
return html;
}
/********************************************************************
* Accessors
* Purpose: get the corresponding data
/*******************************************************************/
public Map<String, List<Course>> getCatalog(){ return this.catalog; }
public List<String> getCourseIDs() { return this.courseIDs; }
public boolean getLoaded(){ return this.loaded; }
public List<String> getCurrentCourseList(){ return this.currentCourseList; }
}
| gpl-3.0 |
VojtechBruza/parasim | extensions/computation-lifecycle-api/src/main/java/org/sybila/parasim/computation/lifecycle/api/RemoteMutableStatus.java | 1888 | /**
* Copyright 2011-2016, Sybila, Systems Biology Laboratory and individual
* contributors by the @authors tag.
*
* This file is part of Parasim.
*
* Parasim is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sybila.parasim.computation.lifecycle.api;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.UUID;
import org.sybila.parasim.model.Mergeable;
/**
* @author <a href="mailto:xpapous1@fi.muni.cz">Jan Papousek</a>
*/
public interface RemoteMutableStatus extends Remote {
/**
* Number of done computation instances.
*/
long getDone() throws RemoteException;
/**
* Number of currently computing computation instances.
*/
long getComputing() throws RemoteException;
/**
* Number of remaining (not done) computation instances.
*/
long getRemaining() throws RemoteException;
/**
* Checks whether the computation is finished.
*/
boolean isFinished() throws RemoteException;
void compute(UUID node, java.util.concurrent.Future event) throws RemoteException;
void done(UUID node, Mergeable event) throws RemoteException;
void emit(UUID node, Computation computation) throws RemoteException;
void balance(UUID node, Computation computation) throws RemoteException;
}
| gpl-3.0 |
tbrooks8/quasar | quasar-core/src/jdk7/java/co/paralleluniverse/strands/channels/SendPort.java | 3989 | /*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2013-2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.strands.channels;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.strands.Timeout;
import java.util.concurrent.TimeUnit;
/**
* A channel's producer-side interface.
*
* @param Message the type of messages that can be sent to this channel.
* @author pron
*/
public interface SendPort<Message> extends Port<Message>, AutoCloseable {
/**
* Sends a message to the channel, possibly blocking until there's room available in the channel.
*
* If the channel is full, this method may block, throw an exception, silently drop the message, or displace an old message from
* the channel. The behavior is determined by the channel's {@link Channels.OverflowPolicy OverflowPolicy}, set at construction time.
*
* @param message
* @throws SuspendExecution
*/
void send(Message message) throws SuspendExecution, InterruptedException;
/**
* Sends a message to the channel, possibly blocking until there's room available in the channel, but never longer than the
* specified timeout.
*
* If the channel is full, this method may block, throw an exception, silently drop the message, or displace an old message from
* the channel. The behavior is determined by the channel's {@link Channels.OverflowPolicy OverflowPolicy}, set at construction time.
*
* @param message
* @param timeout the maximum duration this method is allowed to wait.
* @param unit the timeout's time unit
* @return {@code true} if the message has been sent successfully; {@code false} if the timeout has expired.
* @throws SuspendExecution
*/
boolean send(Message message, long timeout, TimeUnit unit) throws SuspendExecution, InterruptedException;
/**
* Sends a message to the channel, possibly blocking until there's room available in the channel, but never longer than the
* specified timeout.
*
* If the channel is full, this method may block, throw an exception, silently drop the message, or displace an old message from
* the channel. The behavior is determined by the channel's {@link Channels.OverflowPolicy OverflowPolicy}, set at construction time.
*
* @param message
* @param timeout the method will not block for longer than the amount remaining in the {@link Timeout}
* @return {@code true} if the message has been sent successfully; {@code false} if the timeout has expired.
* @throws SuspendExecution
*/
boolean send(Message message, Timeout timeout) throws SuspendExecution, InterruptedException;
/**
* Sends a message to the channel if the channel has room available. This method never blocks.
* <p>
* @param message
* @return {@code true} if the message has been sent; {@code false} otherwise.
*/
boolean trySend(Message message);
/**
* Closes the channel so that no more messages could be sent to it. Messages already sent to the channel will still be received.
*/
@Override
void close();
/**
* Closes the channel so that no more messages could be sent to it, and signifies an exception occurred in the producer.
* The exception will be thrown when the consumer calls {@link ReceivePort}'s {@code receive} or {@code tryReceive},
* wrapped by a {@link ProducerException}.
* Messages already sent to the channel prior to calling this method will still be received.
*/
void close(Throwable t);
}
| gpl-3.0 |
quaap/Primary | app/src/main/java/com/quaap/primary/base/component/Keyboard.java | 7466 | package com.quaap.primary.base.component;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Build;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.quaap.primary.R;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Created by tom on 12/29/16.
* <p>
* Copyright (C) 2016 tom
* <p>
* 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.
* <p>
* 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.
*/
public class Keyboard {
private static final String KEY_BACKSP = "\u0008";
private static final String KEY_DONE = "\n";
private final Context mContext;
private final Map<String,String> mKeyMap = new HashMap<>();
private Keyboard(Context context) {
mContext = context;
}
private Keyboard(Context context, Map<String, String> keyMap) {
mContext = context;
mKeyMap.putAll(keyMap);
}
public synchronized static void showKeyboard(Context context, final EditText editText, ViewGroup parentlayout) {
new Keyboard(context).showKeyboard(editText, parentlayout);
}
public synchronized static void showKeyboard(Context context, final EditText editText, ViewGroup parentlayout, Map<String,String> keyMap) {
new Keyboard(context, keyMap).showKeyboard(editText, parentlayout);
}
public synchronized static void showNumberpad(Context context, final EditText editText, ViewGroup parentlayout) {
new Keyboard(context).showNumberpad(editText, parentlayout);
}
public synchronized static void showNumberpad(Context context, final EditText editText, ViewGroup parentlayout, Map<String,String> keyMap) {
new Keyboard(context, keyMap).showNumberpad(editText, parentlayout);
}
public synchronized static void hideKeys(ViewGroup parentlayout) {
parentlayout.removeAllViews();
}
private void showKeyboard(final EditText editText, ViewGroup parentlayout) {
String[] keys = mContext.getResources().getStringArray(R.array.keyboard_keys);
int rows = mContext.getResources().getInteger(R.integer.keyboard_rows);
showKeys(editText, parentlayout, keys, rows);
}
private void showNumberpad(final EditText editText, ViewGroup parentlayout) {
String[] keys = mContext.getResources().getStringArray(R.array.keypad_keys);
int rows = mContext.getResources().getInteger(R.integer.keypad_rows);
showKeys(editText, parentlayout, keys, rows);
}
private void showKeys(final EditText editText, ViewGroup parentlayout, String[] keys, int rows) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
} else {
try {
final Method method = EditText.class.getMethod(
"setShowSoftInputOnFocus"
, boolean.class);
method.setAccessible(true);
method.invoke(editText, false);
} catch (Exception e) {
// ignore
}
}
parentlayout.removeAllViews();
LinearLayout glayout = new LinearLayout(mContext);
glayout.setOrientation(LinearLayout.VERTICAL);
glayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
glayout.setBackgroundColor(Color.WHITE);
glayout.setPadding(2, 2, 2, 2);
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int cols = keys.length / rows;
if (keys.length % 2 != 0) cols += 1;
// float xfac = .95f;
// int orientation = mContext.getResources().getConfiguration().orientation;
// if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// xfac = .83f;
// }
// int keywidth = (int) (size.x / cols * xfac);
// int keyheight = (int) (keywidth * 1.4);
//
// if (keyheight > 100) keyheight = 100;
System.out.println("size: " + size.x + ", " + size.y);
LinearLayout rowlayout = new LinearLayout(mContext);
rowlayout.setOrientation(LinearLayout.HORIZONTAL);
glayout.addView(rowlayout);
int num=0;
for (String k : keys) {
if (num++ % cols == 0) {
rowlayout = new LinearLayout(mContext);
rowlayout.setOrientation(LinearLayout.HORIZONTAL);
glayout.addView(rowlayout);
}
if (mKeyMap.containsKey(k)) {
k = mKeyMap.get(k);
}
TextView key = new TextView(mContext);
key.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
key.setClickable(true);
key.setPadding(4, 4, 4, 4);
key.setGravity(Gravity.CENTER);
key.setBackgroundResource(android.R.drawable.btn_default_small);
//key.setTextSize((int) (keyheight / 3.5));
key.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
key.setTypeface(null, Typeface.BOLD);
//key.setMinimumWidth(0);
//key.setMinimumHeight(0);
//key.setHeight(keyheight);
//key.setWidth(keywidth);
if (k.equals(KEY_BACKSP)) {
key.setText("\u2190");
//key.setWidth(keywidth+5);
} else if (k.equals(KEY_DONE)) {
key.setText("\u2713");
key.setTextColor(Color.rgb(0, 160, 0));
//key.setWidth(keywidth+5);
} else if (k.equals(" ")) {
key.setText("\u2423");
} else {
key.setText(k);
}
key.setTag(k);
key.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String k = (String) view.getTag();
if (k.equals(KEY_BACKSP)) {
editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
} else if (k.equals(KEY_DONE)) {
editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
} else {
editText.getText().insert(editText.getSelectionStart(), k);
}
}
});
rowlayout.addView(key);
}
parentlayout.addView(glayout);
editText.requestFocus();
}
}
| gpl-3.0 |
lynn9388/data-monitor | app/src/main/java/com/lynn9388/datamonitor/fragment/MobileDataFragment.java | 13132 | /*
* MobileDataFragment
* Copyright (C) 2016 Lynn
*
* 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.lynn9388.datamonitor.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.simplelist.MaterialSimpleListAdapter;
import com.afollestad.materialdialogs.simplelist.MaterialSimpleListItem;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.lynn9388.datamonitor.NetworkService;
import com.lynn9388.datamonitor.R;
import com.lynn9388.datamonitor.util.NetworkUtil;
import com.lynn9388.datamonitor.util.TrafficUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
/**
* A simple {@link Fragment} subclass.
*/
public class MobileDataFragment extends Fragment {
public static String sDataLeftThisMonthPrefKey = "pref_key_data_left_this_month";
private static String[] sNetworkUsageTodayPrefKeys = {
"pref_key_2g_today", "pref_key_3g_today", "pref_key_4g_today"
};
private static String[] sNetworkUsageThisMonthPrefKeys = {
"pref_key_2g_this_month", "pref_key_3g_this_month", "pref_key_4g_this_month"
};
private static String sUsagePercentagePrefKey = "pref_key_usage_percentage";
private static String[] sPanelValuePrefKeys = {
"pref_key_panel0", "pref_key_panel1", "pref_key_panel2", "pref_key_panel3"
};
private static NetworkUtil.NetworkType[] sNetworkTypes = {
NetworkUtil.NetworkType.NETWORK_TYPE_2G,
NetworkUtil.NetworkType.NETWORK_TYPE_3G,
NetworkUtil.NetworkType.NETWORK_TYPE_4G
};
private PieChart mChart;
private View[] mPanels;
private int[] mColors;
private SharedPreferences mSharedPreferences;
private Handler mHandler;
private TimerTask mTimerTask;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mobile_data, container, false);
mChart = (PieChart) view.findViewById(R.id.pie_chart);
mChart.setUsePercentValues(true);
mChart.getLegend().setEnabled(false);
mChart.setDescription("");
mChart.setCenterTextSize(14f);
mChart.animateY(3000, Easing.EasingOption.EaseInOutQuad);
mPanels = new View[4];
int[] panelViewIds = {R.id.panel0, R.id.panel1, R.id.panel2, R.id.panel3};
int[] titleStringIds = {
R.string.used_today, R.string.used_this_month,
R.string.remaining_this_month, R.string.till_next_settlement
};
for (int i = 0; i < mPanels.length; i++) {
mPanels[i] = view.findViewById(panelViewIds[i]);
TextView titleView = (TextView) mPanels[i].findViewById(R.id.title);
titleView.setText(getString(titleStringIds[i]));
}
mPanels[0].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = getString(R.string.dialog_used_today_title);
showDialog(title, sNetworkUsageTodayPrefKeys);
}
});
mPanels[1].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = getString(R.string.dialog_used_this_month_title);
showDialog(title, sNetworkUsageThisMonthPrefKeys);
}
});
mColors = new int[4];
mColors[0] = ContextCompat.getColor(getContext(), R.color.color2GSend);
mColors[1] = ContextCompat.getColor(getContext(), R.color.color3GSend);
mColors[2] = ContextCompat.getColor(getContext(), R.color.color4GSend);
mColors[3] = Color.GRAY;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
return view;
}
@Override
public void onResume() {
super.onResume();
updateViews();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
updateViews();
}
}
};
mTimerTask = new TimerTask() {
@Override
public void run() {
updateData();
mHandler.sendEmptyMessage(0);
}
};
new Timer().scheduleAtFixedRate(mTimerTask, 0, NetworkService.LOG_INTERVAL);
}
@Override
public void onPause() {
super.onPause();
mTimerTask.cancel();
mHandler.removeMessages(0);
}
private void updateData() {
// Get settings of data plan and used data error
String dataPlanSetting =
mSharedPreferences.getString(SettingsFragment.PREF_KEY_DATA_PLAN, "0");
String usedDataErrorSetting =
mSharedPreferences.getString(SettingsFragment.PREF_KEY_USED_DATA_ERROR, "0");
long dataPlan = Long.valueOf(dataPlanSetting) * 1024 * 1024;
long usedDataError = (long) (Float.valueOf(usedDataErrorSetting) * 1024 * 1024);
Date now = new Date();
SharedPreferences.Editor editor = mSharedPreferences.edit();
long usedToday = 0;
long usedThisMonth = 0;
for (int i = 0; i < sNetworkTypes.length; i++) {
long dataUsage = TrafficUtil.getTotalDataUsage(getContext(), sNetworkTypes[i],
TrafficUtil.getStartOfDay(now), TrafficUtil.getEndOfDay(now));
editor.putLong(sNetworkUsageTodayPrefKeys[i], dataUsage);
usedToday += dataUsage;
dataUsage = TrafficUtil.getTotalDataUsage(getContext(), sNetworkTypes[i],
TrafficUtil.getStartOfMonth(now), TrafficUtil.getEndOfMonth(now));
editor.putLong(sNetworkUsageThisMonthPrefKeys[i], dataUsage);
usedThisMonth += dataUsage;
}
editor.putString(sPanelValuePrefKeys[0], TrafficUtil.getReadableValue(usedToday));
editor.putString(SettingsFragment.PREF_KEY_USED_DATA_IN_LOG,
String.valueOf(usedThisMonth / (1024f * 1024f)));
usedThisMonth += usedDataError;
editor.putString(SettingsFragment.PREF_KEY_USED_DATA,
String.format(Locale.getDefault(), "%.2f", usedThisMonth / (1024f * 1024f)));
editor.putString(sPanelValuePrefKeys[1], TrafficUtil.getReadableValue(usedThisMonth));
long leftThisMonth = dataPlan - usedThisMonth;
if (leftThisMonth < 0) {
leftThisMonth = 0;
}
editor.putLong(sDataLeftThisMonthPrefKey, leftThisMonth);
editor.putString(sPanelValuePrefKeys[2], TrafficUtil.getReadableValue(leftThisMonth));
Calendar calendar = Calendar.getInstance();
int daysLeft = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
- calendar.get(Calendar.DAY_OF_MONTH);
editor.putString(sPanelValuePrefKeys[3],
String.valueOf(daysLeft) + (daysLeft > 1 ? " Days" : " Day"));
float usagePercentage = 100f * usedThisMonth / dataPlan;
editor.putFloat(sUsagePercentagePrefKey, usagePercentage);
editor.apply();
}
private void updateViews() {
mChart.setCenterText(generatePieCenterText());
mChart.setData(generatePieData());
mChart.invalidate();
for (int i = 0; i < mPanels.length; i++) {
TextView valueView = (TextView) mPanels[i].findViewById(R.id.value);
valueView.setText(mSharedPreferences.getString(sPanelValuePrefKeys[i], "--"));
}
}
private SpannableString generatePieCenterText() {
float usagePercentage = mSharedPreferences.getFloat(sUsagePercentagePrefKey, 0f);
int warningPercent = mSharedPreferences.getInt(SettingsFragment.PREF_KEY_WARNING_PERCENT, 50);
if (0 <= usagePercentage && usagePercentage < warningPercent * 0.8) {
mColors[3] = ContextCompat.getColor(getContext(), R.color.colorSufficiency);
} else if (usagePercentage < warningPercent) {
mColors[3] = ContextCompat.getColor(getContext(), R.color.colorNormal);
} else {
mColors[3] = ContextCompat.getColor(getContext(), R.color.colorLack);
}
String percentageValue = String.format(Locale.getDefault(), "%.2f %%", usagePercentage);
SpannableString s = new SpannableString(percentageValue + "\n"
+ getString(R.string.chart_mobile_data_message));
s.setSpan(new RelativeSizeSpan(2f), 0, percentageValue.length(), 0);
s.setSpan(new ForegroundColorSpan(mColors[3]), 0, s.length(), 0);
return s;
}
private PieData generatePieData() {
ArrayList<Entry> entries1 = new ArrayList<>();
ArrayList<String> xVals = new ArrayList<>();
int index = 0;
int[] colors = new int[4];
for (int i = 0; i < 4; i++) {
long dataUsage;
if (i != 3) {
dataUsage = mSharedPreferences.getLong(sNetworkUsageThisMonthPrefKeys[i], 0L);
} else {
dataUsage = mSharedPreferences.getLong(sDataLeftThisMonthPrefKey, 0L);
}
colors[i] = mColors[i];
if (dataUsage > 0) {
entries1.add(new Entry(dataUsage, index));
if (i != 3) {
xVals.add(sNetworkTypes[i].toString());
} else {
xVals.add(getString(R.string.chart_mobile_data_left));
}
colors[index] = mColors[i];
index++;
}
}
PieDataSet dataSet = new PieDataSet(entries1, "Mobile Data");
dataSet.setColors(colors);
dataSet.setValueTextColor(Color.WHITE);
dataSet.setValueTextSize(12f);
PieData pieData = new PieData(xVals, dataSet);
pieData.setValueFormatter(new PercentFormatter());
return pieData;
}
private void showDialog(String title, String[] prefKeys) {
Context context = getContext();
final MaterialSimpleListAdapter adapter = new MaterialSimpleListAdapter(context);
long[] dataUsages = new long[3];
for (int i = 0; i < dataUsages.length; i++) {
dataUsages[i] = mSharedPreferences.getLong(prefKeys[i], 0L);
}
adapter.add(new MaterialSimpleListItem.Builder(context)
.content(TrafficUtil.getReadableValue(dataUsages[0]))
.icon(R.drawable.ic_2g)
.iconPaddingDp(8)
.build());
adapter.add(new MaterialSimpleListItem.Builder(context)
.content(TrafficUtil.getReadableValue(dataUsages[1]))
.icon(R.drawable.ic_3g)
.iconPaddingDp(8)
.build());
adapter.add(new MaterialSimpleListItem.Builder(context)
.content(TrafficUtil.getReadableValue(dataUsages[2]))
.icon(R.drawable.ic_4g)
.iconPaddingDp(8)
.build());
new MaterialDialog.Builder(context)
.title(title)
.adapter(adapter, new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View itemView,
int which, CharSequence text) {
MaterialSimpleListItem item = adapter.getItem(which);
}
})
.show();
}
}
| gpl-3.0 |
sp-apertus/openpnp | src/main/java/org/openpnp/machine/reference/driver/GcodeDriver.java | 49165 | package org.openpnp.machine.reference.driver;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import org.openpnp.gui.MainFrame;
import org.openpnp.gui.support.Icons;
import org.openpnp.gui.support.PropertySheetWizardAdapter;
import org.openpnp.machine.reference.ReferenceActuator;
import org.openpnp.machine.reference.ReferenceDriver;
import org.openpnp.machine.reference.ReferenceHead;
import org.openpnp.machine.reference.ReferenceHeadMountable;
import org.openpnp.machine.reference.ReferenceMachine;
import org.openpnp.machine.reference.ReferenceNozzle;
import org.openpnp.machine.reference.ReferenceNozzleTip;
import org.openpnp.machine.reference.ReferencePasteDispenser;
import org.openpnp.machine.reference.driver.wizards.GcodeDriverConsole;
import org.openpnp.machine.reference.driver.wizards.GcodeDriverGcodes;
import org.openpnp.machine.reference.driver.wizards.GcodeDriverSettings;
import org.openpnp.model.Configuration;
import org.openpnp.model.LengthUnit;
import org.openpnp.model.Location;
import org.openpnp.model.Named;
import org.openpnp.model.Part;
import org.openpnp.spi.Head;
import org.openpnp.spi.HeadMountable;
import org.openpnp.spi.Nozzle;
import org.openpnp.spi.PropertySheetHolder;
import org.openpnp.spi.base.SimplePropertySheetHolder;
import org.pmw.tinylog.Logger;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Commit;
import com.google.common.base.Joiner;
@Root
public class GcodeDriver extends AbstractSerialPortDriver implements Named, Runnable {
public enum CommandType {
COMMAND_CONFIRM_REGEX,
POSITION_REPORT_REGEX,
COMMAND_ERROR_REGEX,
CONNECT_COMMAND,
ENABLE_COMMAND,
DISABLE_COMMAND,
POST_VISION_HOME_COMMAND,
HOME_COMMAND("Id", "Name"),
HOME_COMPLETE_REGEX(true),
PUMP_ON_COMMAND,
PUMP_OFF_COMMAND,
MOVE_TO_COMMAND(true, "Id", "Name", "FeedRate", "X", "Y", "Z", "Rotation"),
MOVE_TO_COMPLETE_REGEX(true),
PICK_COMMAND(true, "Id", "Name", "VacuumLevelPartOn", "VacuumLevelPartOff"),
PLACE_COMMAND(true, "Id", "Name"),
ACTUATE_BOOLEAN_COMMAND(true, "Id", "Name", "Index", "BooleanValue", "True", "False"),
ACTUATE_DOUBLE_COMMAND(true, "Id", "Name", "Index", "DoubleValue", "IntegerValue"),
ACTUATOR_READ_COMMAND(true, "Id", "Name", "Index"),
ACTUATOR_READ_REGEX(true),
PRE_DISPENSE_COMMAND(false, "DispenseTime"),
DISPENSE_COMMAND(false, "DispenseTime"),
POST_DISPENSE_COMMAND(false, "DispenseTime");
final boolean headMountable;
final String[] variableNames;
private CommandType() {
this(false);
}
private CommandType(boolean headMountable) {
this(headMountable, new String[] {});
}
private CommandType(String... variableNames) {
this(false, variableNames);
}
private CommandType(boolean headMountable, String... variableNames) {
this.headMountable = headMountable;
this.variableNames = variableNames;
}
public boolean isHeadMountable() {
return headMountable;
}
}
public static class Command {
@Attribute(required = false)
public String headMountableId;
@Attribute(required = true)
public CommandType type;
@ElementList(required = false, inline = true, entry = "text", data = true)
public ArrayList<String> commands = new ArrayList<>();
public Command(String headMountableId, CommandType type, String text) {
this.headMountableId = headMountableId;
this.type = type;
setCommand(text);
}
public void setCommand(String text) {
this.commands.clear();
if (text != null) {
text = text.trim();
text = text.replaceAll("\r", "");
String[] commands = text.split("\n");
this.commands.addAll(Arrays.asList(commands));
}
}
public String getCommand() {
return Joiner.on('\n').join(commands);
}
private Command() {
}
}
@Attribute(required = false)
protected LengthUnit units = LengthUnit.Millimeters;
@Attribute(required = false)
protected int maxFeedRate = 1000;
@Attribute(required = false)
protected double backlashOffsetX = -1;
@Attribute(required = false)
protected double backlashOffsetY = -1;
@Attribute(required = false)
protected double nonSquarenessFactor = 0;
@Attribute(required = false)
protected double backlashFeedRateFactor = 0.1;
@Attribute(required = false)
protected int timeoutMilliseconds = 5000;
@Attribute(required = false)
protected int connectWaitTimeMilliseconds = 3000;
@Attribute(required = false)
protected boolean visualHomingEnabled = true;
@Element(required = false)
protected Location homingFiducialLocation = new Location(LengthUnit.Millimeters);
@ElementList(required = false, inline = true)
public ArrayList<Command> commands = new ArrayList<>();
@ElementList(required = false)
protected List<GcodeDriver> subDrivers = new ArrayList<>();
@ElementList(required = false)
protected List<Axis> axes = new ArrayList<>();
@Attribute(required = false)
protected String name = "GcodeDriver";
private Thread readerThread;
private boolean disconnectRequested;
private boolean connected;
private LinkedBlockingQueue<String> responseQueue = new LinkedBlockingQueue<>();
private Set<Nozzle> pickedNozzles = new HashSet<>();
private GcodeDriver parent = null;
@Commit
public void commit() {
for (GcodeDriver driver : subDrivers) {
driver.parent = this;
}
}
public void createDefaults() {
axes = new ArrayList<>();
axes.add(new Axis("x", Axis.Type.X, 0, "*"));
axes.add(new Axis("y", Axis.Type.Y, 0, "*"));
axes.add(new Axis("z", Axis.Type.Z, 0, "*"));
axes.add(new Axis("rotation", Axis.Type.Rotation, 0, "*"));
commands = new ArrayList<>();
commands.add(new Command(null, CommandType.COMMAND_CONFIRM_REGEX, "^ok.*"));
commands.add(new Command(null, CommandType.CONNECT_COMMAND, "G21 ; Set millimeters mode\nG90 ; Set absolute positioning mode\nM82 ; Set absolute mode for extruder"));
commands.add(new Command(null, CommandType.HOME_COMMAND, "G28 ; Home all axes"));
commands.add(new Command(null, CommandType.MOVE_TO_COMMAND, "G0 {X:X%.4f} {Y:Y%.4f} {Z:Z%.4f} {Rotation:E%.4f} F{FeedRate:%.0f} ; Send standard Gcode move\nM400 ; Wait for moves to complete before returning"));
}
public synchronized void connect() throws Exception {
super.connect();
connected = false;
readerThread = new Thread(this);
readerThread.setDaemon(true);
readerThread.start();
// Wait a bit while the controller starts up
Thread.sleep(connectWaitTimeMilliseconds);
// Consume any startup messages
try {
while (!sendCommand(null, 250).isEmpty()) {
}
}
catch (Exception e) {
}
// Disable the machine
setEnabled(false);
// Send startup Gcode
sendGcode(getCommand(null, CommandType.CONNECT_COMMAND));
connected = true;
}
@Override
public void setEnabled(boolean enabled) throws Exception {
if (enabled && !connected) {
connect();
}
if (connected) {
if (enabled) {
sendGcode(getCommand(null, CommandType.ENABLE_COMMAND));
}
else {
sendGcode(getCommand(null, CommandType.DISABLE_COMMAND));
}
}
for (ReferenceDriver driver : subDrivers) {
driver.setEnabled(enabled);
}
}
@Override
public void dispense(ReferencePasteDispenser dispenser,Location startLocation,Location endLocation,long dispenseTimeMilliseconds) throws Exception {
Logger.debug("dispense({}, {}, {}, {})", new Object[] {dispenser, startLocation, endLocation, dispenseTimeMilliseconds});
String command = getCommand(null, CommandType.PRE_DISPENSE_COMMAND);
command = substituteVariable(command, "DispenseTime", dispenseTimeMilliseconds);
sendGcode(command);
for (ReferenceDriver driver: subDrivers )
{
driver.dispense(dispenser,startLocation,endLocation,dispenseTimeMilliseconds);
}
command = getCommand(null, CommandType.DISPENSE_COMMAND);
command = substituteVariable(command, "DispenseTime", dispenseTimeMilliseconds);
sendGcode(command);
command = getCommand(null, CommandType.POST_DISPENSE_COMMAND);
command = substituteVariable(command, "DispenseTime", dispenseTimeMilliseconds);
sendGcode(command);
}
@Override
public void home(ReferenceHead head) throws Exception {
// Home is sent with an infinite timeout since it's tough to tell how long it will
// take.
String command = getCommand(null, CommandType.HOME_COMMAND);
command = substituteVariable(command, "Id", head.getId());
command = substituteVariable(command, "Name", head.getName());
long timeout = -1;
List<String> responses = sendGcode(command, timeout);
// Check home complete response against user's regex
String homeCompleteRegex = getCommand(null, CommandType.HOME_COMPLETE_REGEX);
if (homeCompleteRegex != null) {
if (timeout == -1) {
timeout = Long.MAX_VALUE;
}
if (!containsMatch(responses, homeCompleteRegex)) {
long t = System.currentTimeMillis();
boolean done = false;
while (!done && System.currentTimeMillis() - t < timeout) {
done = containsMatch(sendCommand(null, 250), homeCompleteRegex);
}
if (!done) {
// Should never get here but just in case.
throw new Exception("Timed out waiting for home to complete.");
}
}
}
// We need to specially handle X and Y axes to support the non-squareness factor.
Axis xAxis = null;
Axis yAxis = null;
double xHomeCoordinateNonSquare = 0;
double yHomeCoordinate = 0;
for (Axis axis : axes) {
if (axis.getType() == Axis.Type.X) {
xAxis = axis;
xHomeCoordinateNonSquare = axis.getHomeCoordinate();
}
if (axis.getType() == Axis.Type.Y) {
yAxis = axis;
yHomeCoordinate = axis.getHomeCoordinate();
}
}
// Compensate non-squareness factor:
// We are homing to the native controller's non-square coordinate system, this does not
// match OpenPNP's square coordinate system, if the controller's Y home is non-zero.
// The two coordinate systems coincide at Y0 only, see the non-squareness
// transformation. It is not a good idea to change the transformation i.e. for the coordinate
// systems to coincide at Y home, as this would break coordinates captured before this change.
// In order to home the square internal coordinate system we need to account for the
// non-squareness X offset here.
// NOTE this changes nothing in the behavior or the coordinate system of the machine. It just
// sets the internal X coordinate correctly immediately after homing, so we can capture the
// home location correctly. Without this compensation the discrepancy between internal and
// machines coordinates was resolved with the first move, as it is done in absolute mode.
double xHomeCoordinateSquare = xHomeCoordinateNonSquare - nonSquarenessFactor*yHomeCoordinate;
for (Axis axis : axes) {
if (axis == xAxis) {
// for X use the coordinate adjusted for non-squareness.
axis.setCoordinate(xHomeCoordinateSquare);
}
else {
// otherwise just use the standard coordinate.
axis.setCoordinate(axis.getHomeCoordinate());
}
}
for (ReferenceDriver driver : subDrivers) {
driver.home(head);
}
if (visualHomingEnabled) {
/*
* The head camera for nozzle-1 should now be (if everything has homed correctly) directly
* above the homing pin in the machine bed, use the head camera scan for this and make sure
* this is exactly central - otherwise we move the camera until it is, and then reset all
* the axis back to 0,0,0,0 as this is calibrated home.
*/
Part homePart = Configuration.get().getPart("FIDUCIAL-HOME");
if (homePart != null) {
Configuration.get().getMachine().getFiducialLocator()
.getHomeFiducialLocation(homingFiducialLocation, homePart);
// homeOffset contains the offset, but we are not really concerned with that,
// we just reset X,Y back to the home-coordinate at this point.
if (xAxis != null) {
xAxis.setCoordinate(xHomeCoordinateSquare);
}
if (yAxis != null) {
yAxis.setCoordinate(yHomeCoordinate);
}
String g92command = getCommand(null, CommandType.POST_VISION_HOME_COMMAND);
// make sure to use the native non-square X home coordinate.
g92command = substituteVariable(g92command, "X", xHomeCoordinateNonSquare);
g92command = substituteVariable(g92command, "Y", yHomeCoordinate);
sendGcode(g92command, -1);
}
}
}
public Axis getAxis(HeadMountable hm, Axis.Type type) {
for (Axis axis : axes) {
if (axis.getType() == type && (axis.getHeadMountableIds().contains("*")
|| axis.getHeadMountableIds().contains(hm.getId()))) {
return axis;
}
}
return null;
}
public Command getCommand(HeadMountable hm, CommandType type, boolean checkDefaults) {
// If a HeadMountable is specified, see if we can find a match
// for both the HeadMountable ID and the command type.
if (type.headMountable && hm != null) {
for (Command c : commands) {
if (hm.getId().equals(c.headMountableId) && type == c.type) {
return c;
}
}
if (!checkDefaults) {
return null;
}
}
// If not, see if we can find a match for the command type with a
// null or * HeadMountable ID.
for (Command c : commands) {
if ((c.headMountableId == null || c.headMountableId.equals("*")) && type == c.type) {
return c;
}
}
// No matches were found.
return null;
}
public String getCommand(HeadMountable hm, CommandType type) {
Command c = getCommand(hm, type, true);
if (c == null) {
return null;
}
return c.getCommand();
}
public void setCommand(HeadMountable hm, CommandType type, String text) {
Command c = getCommand(hm, type, false);
if (text == null || text.trim().length() == 0) {
if (c != null) {
commands.remove(c);
}
}
else {
if (c == null) {
c = new Command(hm == null ? null : hm.getId(), type, text);
commands.add(c);
}
else {
c.setCommand(text);
}
}
}
@Override
public Location getLocation(ReferenceHeadMountable hm) {
// according main driver
Axis xAxis = getAxis(hm, Axis.Type.X);
Axis yAxis = getAxis(hm, Axis.Type.Y);
Axis zAxis = getAxis(hm, Axis.Type.Z);
Axis rotationAxis = getAxis(hm, Axis.Type.Rotation);
// additional info might be on subdrivers (note that subdrivers can only be one level deep)
for (ReferenceDriver driver : subDrivers) {
GcodeDriver d = (GcodeDriver) driver;
if (d.getAxis(hm, Axis.Type.X) != null) {
xAxis = d.getAxis(hm, Axis.Type.X);
}
if (d.getAxis(hm, Axis.Type.Y) != null) {
yAxis = d.getAxis(hm, Axis.Type.Y);
}
if (d.getAxis(hm, Axis.Type.Z) != null) {
zAxis = d.getAxis(hm, Axis.Type.Z);
}
if (d.getAxis(hm, Axis.Type.Rotation) != null) {
rotationAxis = d.getAxis(hm, Axis.Type.Rotation);
}
}
Location location =
new Location(units, xAxis == null ? 0 : xAxis.getTransformedCoordinate(hm),
yAxis == null ? 0 : yAxis.getTransformedCoordinate(hm),
zAxis == null ? 0 : zAxis.getTransformedCoordinate(hm),
rotationAxis == null ? 0 : rotationAxis.getTransformedCoordinate(hm))
.add(hm.getHeadOffsets());
return location;
}
@Override
public void moveTo(ReferenceHeadMountable hm, Location location, double speed)
throws Exception {
// keep copy for calling subdrivers as to not add offset on offset
Location locationOriginal = location;
location = location.convertToUnits(units);
location = location.subtract(hm.getHeadOffsets());
double x = location.getX();
double y = location.getY();
double z = location.getZ();
double rotation = location.getRotation();
Axis xAxis = getAxis(hm, Axis.Type.X);
Axis yAxis = getAxis(hm, Axis.Type.Y);
Axis zAxis = getAxis(hm, Axis.Type.Z);
Axis rotationAxis = getAxis(hm, Axis.Type.Rotation);
// Handle NaNs, which means don't move this axis for this move. We set the appropriate
// axis reference to null, which we'll check for later.
if (Double.isNaN(x)) {
xAxis = null;
}
if (Double.isNaN(y)) {
yAxis = null;
}
if (Double.isNaN(z)) {
zAxis = null;
}
if (Double.isNaN(rotation)) {
rotationAxis = null;
}
// Only do something if there at least one axis included in the move
if (xAxis != null || yAxis != null || zAxis != null || rotationAxis != null) {
// For each included axis, if the axis has a transform, transform the target coordinate
// to it's raw value.
if (xAxis != null && xAxis.getTransform() != null) {
x = xAxis.getTransform().toRaw(xAxis, hm, x);
}
if (yAxis != null && yAxis.getTransform() != null) {
y = yAxis.getTransform().toRaw(yAxis, hm, y);
}
if (zAxis != null && zAxis.getTransform() != null) {
z = zAxis.getTransform().toRaw(zAxis, hm, z);
}
if (rotationAxis != null && rotationAxis.getTransform() != null) {
rotation = rotationAxis.getTransform().toRaw(rotationAxis, hm, rotation);
}
String command = getCommand(hm, CommandType.MOVE_TO_COMMAND);
command = substituteVariable(command, "Id", hm.getId());
command = substituteVariable(command, "Name", hm.getName());
command = substituteVariable(command, "FeedRate", maxFeedRate * speed);
command = substituteVariable(command, "BacklashFeedRate", maxFeedRate * speed * backlashFeedRateFactor);
/**
* NSF gets applied to X and is multiplied by Y
*
*/
boolean includeX = false, includeY = false, includeZ = false, includeRotation = false;
// Primary checks to see if an axis should move
if (xAxis != null && xAxis.getCoordinate() != x) {
includeX = true;
}
if (yAxis != null && yAxis.getCoordinate() != y) {
includeY = true;
}
if (zAxis != null && zAxis.getCoordinate() != z) {
includeZ = true;
}
if (rotationAxis != null && rotationAxis.getCoordinate() != rotation) {
includeRotation = true;
}
// If Y is moving and there is a non squareness factor we also need to move X, even if
// no move was intended for X.
if (includeY && nonSquarenessFactor != 0 && xAxis != null) {
includeX = true;
}
if (includeX) {
command = substituteVariable(command, "X", x + nonSquarenessFactor * y);
command = substituteVariable(command, "BacklashOffsetX", x + backlashOffsetX + nonSquarenessFactor * y); // Backlash Compensation
if (xAxis.getPreMoveCommand() != null) {
String preMoveCommand = xAxis.getPreMoveCommand();
preMoveCommand = substituteVariable(preMoveCommand, "Coordinate", xAxis.getCoordinate());
sendGcode(preMoveCommand);
}
xAxis.setCoordinate(x);
}
else {
command = substituteVariable(command, "X", null);
command = substituteVariable(command, "BacklashOffsetX", null); // Backlash Compensation
}
if (includeY) {
command = substituteVariable(command, "Y", y);
command = substituteVariable(command, "BacklashOffsetY", y + backlashOffsetY); // Backlash Compensation
if (yAxis.getPreMoveCommand() != null) {
String preMoveCommand = yAxis.getPreMoveCommand();
preMoveCommand = substituteVariable(preMoveCommand, "Coordinate", yAxis.getCoordinate());
sendGcode(preMoveCommand);
}
}
else {
command = substituteVariable(command, "Y", null);
command = substituteVariable(command, "BacklashOffsetY", null); // Backlash Compensation
}
if (includeZ) {
command = substituteVariable(command, "Z", z);
if (zAxis.getPreMoveCommand() != null) {
String preMoveCommand = zAxis.getPreMoveCommand();
preMoveCommand = substituteVariable(preMoveCommand, "Coordinate", zAxis.getCoordinate());
sendGcode(preMoveCommand);
}
}
else {
command = substituteVariable(command, "Z", null);
}
if (includeRotation) {
command = substituteVariable(command, "Rotation", rotation);
if (rotationAxis.getPreMoveCommand() != null) {
String preMoveCommand = rotationAxis.getPreMoveCommand();
preMoveCommand = substituteVariable(preMoveCommand, "Coordinate", rotationAxis.getCoordinate());
sendGcode(preMoveCommand);
}
}
else {
command = substituteVariable(command, "Rotation", null);
}
// Only give a command when move is necessary
if (includeX || includeY || includeZ || includeRotation) {
List<String> responses = sendGcode(command);
/*
* If moveToCompleteRegex is specified we need to wait until we match the regex in a
* response before continuing. We first search the initial responses from the
* command for the regex. If it's not found we then collect responses for up to
* timeoutMillis while searching the responses for the regex. As soon as it is
* matched we continue. If it's not matched within the timeout we throw an
* Exception.
*/
String moveToCompleteRegex = getCommand(hm, CommandType.MOVE_TO_COMPLETE_REGEX);
if (moveToCompleteRegex != null) {
if (!containsMatch(responses, moveToCompleteRegex)) {
long t = System.currentTimeMillis();
boolean done = false;
while (!done && System.currentTimeMillis() - t < timeoutMilliseconds) {
done = containsMatch(sendCommand(null, 250), moveToCompleteRegex);
}
if (!done) {
throw new Exception("Timed out waiting for move to complete.");
}
}
}
// And save the final values on the axes.
if (xAxis != null) {
xAxis.setCoordinate(x);
}
if (yAxis != null) {
yAxis.setCoordinate(y);
}
if (zAxis != null) {
zAxis.setCoordinate(z);
}
if (rotationAxis != null) {
rotationAxis.setCoordinate(rotation);
}
} // there is a move
} // there were axes involved
// regardless of any action above the subdriver needs its actions based on original input
for (ReferenceDriver driver : subDrivers) {
driver.moveTo(hm, locationOriginal, speed);
}
}
private boolean containsMatch(List<String> responses, String regex) {
for (String response : responses) {
if (response.matches(regex)) {
return true;
}
}
return false;
}
@Override
public void pick(ReferenceNozzle nozzle) throws Exception {
pickedNozzles.add(nozzle);
if (pickedNozzles.size() > 0) {
sendGcode(getCommand(nozzle, CommandType.PUMP_ON_COMMAND));
}
String command = getCommand(nozzle, CommandType.PICK_COMMAND);
command = substituteVariable(command, "Id", nozzle.getId());
command = substituteVariable(command, "Name", nozzle.getName());
ReferenceNozzleTip nt = nozzle.getNozzleTip();
command = substituteVariable(command, "VacuumLevelPartOn", nt.getVacuumLevelPartOn());
command = substituteVariable(command, "VacuumLevelPartOff", nt.getVacuumLevelPartOff());
sendGcode(command);
for (ReferenceDriver driver : subDrivers) {
driver.pick(nozzle);
}
}
@Override
public void place(ReferenceNozzle nozzle) throws Exception {
ReferenceNozzleTip nt = nozzle.getNozzleTip();
String command = getCommand(nozzle, CommandType.PLACE_COMMAND);
command = substituteVariable(command, "Id", nozzle.getId());
command = substituteVariable(command, "Name", nozzle.getName());
command = substituteVariable(command, "VacuumLevelPartOn", nt.getVacuumLevelPartOn());
command = substituteVariable(command, "VacuumLevelPartOff", nt.getVacuumLevelPartOff());
sendGcode(command);
pickedNozzles.remove(nozzle);
if (pickedNozzles.size() < 1) {
sendGcode(getCommand(nozzle, CommandType.PUMP_OFF_COMMAND));
}
for (ReferenceDriver driver : subDrivers) {
driver.place(nozzle);
}
}
@Override
public void actuate(ReferenceActuator actuator, boolean on) throws Exception {
String command = getCommand(actuator, CommandType.ACTUATE_BOOLEAN_COMMAND);
command = substituteVariable(command, "Id", actuator.getId());
command = substituteVariable(command, "Name", actuator.getName());
command = substituteVariable(command, "Index", actuator.getIndex());
command = substituteVariable(command, "BooleanValue", on);
command = substituteVariable(command, "True", on ? on : null);
command = substituteVariable(command, "False", on ? null : on);
sendGcode(command);
for (ReferenceDriver driver : subDrivers) {
driver.actuate(actuator, on);
}
}
@Override
public void actuate(ReferenceActuator actuator, double value) throws Exception {
String command = getCommand(actuator, CommandType.ACTUATE_DOUBLE_COMMAND);
command = substituteVariable(command, "Id", actuator.getId());
command = substituteVariable(command, "Name", actuator.getName());
command = substituteVariable(command, "Index", actuator.getIndex());
command = substituteVariable(command, "DoubleValue", value);
command = substituteVariable(command, "IntegerValue", (int) value);
sendGcode(command);
for (ReferenceDriver driver : subDrivers) {
driver.actuate(actuator, value);
}
}
@Override
public String actuatorRead(ReferenceActuator actuator) throws Exception {
String command = getCommand(actuator, CommandType.ACTUATOR_READ_COMMAND);
String regex = getCommand(actuator, CommandType.ACTUATOR_READ_REGEX);
if (command == null || regex == null) {
// If the command or regex is null we'll query the subdrivers. The first
// to respond with a non-null value wins.
for (ReferenceDriver driver : subDrivers) {
String val = driver.actuatorRead(actuator);
if (val != null) {
return val;
}
}
// If none of the subdrivers returned a value there's nothing left to
// do, so return null.
return null;
}
command = substituteVariable(command, "Id", actuator.getId());
command = substituteVariable(command, "Name", actuator.getName());
command = substituteVariable(command, "Index", actuator.getIndex());
List<String> responses = sendGcode(command);
for (String line : responses) {
if (line.matches(regex)) {
Logger.trace("actuatorRead response: {}", line);
Matcher matcher = Pattern.compile(regex).matcher(line);
matcher.matches();
try {
String s = matcher.group("Value");
return s;
}
catch (Exception e) {
throw new Exception("Failed to read Actuator " + actuator.getName(), e);
}
}
}
return null;
}
public synchronized void disconnect() {
disconnectRequested = true;
connected = false;
try {
if (readerThread != null && readerThread.isAlive()) {
readerThread.join(3000);
}
}
catch (Exception e) {
Logger.error("disconnect()", e);
}
try {
super.disconnect();
}
catch (Exception e) {
Logger.error("disconnect()", e);
}
disconnectRequested = false;
}
@Override
public void close() throws IOException {
super.close();
for (ReferenceDriver driver : subDrivers) {
driver.close();
}
}
protected List<String> sendGcode(String gCode) throws Exception {
return sendGcode(gCode, timeoutMilliseconds);
}
protected List<String> sendGcode(String gCode, long timeout) throws Exception {
if (gCode == null) {
return new ArrayList<>();
}
List<String> responses = new ArrayList<>();
for (String command : gCode.split("\n")) {
command = command.trim();
if (command.length() == 0) {
continue;
}
responses.addAll(sendCommand(command, timeout));
}
return responses;
}
public List<String> sendCommand(String command) throws Exception {
return sendCommand(command, timeoutMilliseconds);
}
public List<String> sendCommand(String command, long timeout) throws Exception {
List<String> responses = new ArrayList<>();
// Read any responses that might be queued up so that when we wait
// for a response to a command we actually wait for the one we expect.
responseQueue.drainTo(responses);
Logger.debug("sendCommand({}, {})...", command, timeout);
// Send the command, if one was specified
if (command != null) {
Logger.trace("[{}] >> {}", portName, command);
output.write(command.getBytes());
output.write("\n".getBytes());
}
// Collect responses till we find one with the confirmation or we timeout. Return
// the collected responses.
if (timeout == -1) {
timeout = Long.MAX_VALUE;
}
long t = System.currentTimeMillis();
boolean found = false;
boolean foundError = false;
String errorResponse = "";
// Loop until we've timed out
while (System.currentTimeMillis() - t < timeout) {
// Wait to see if a response came in. We wait up until the number of millis remaining
// in the timeout.
String response = responseQueue.poll(timeout - (System.currentTimeMillis() - t),
TimeUnit.MILLISECONDS);
// If no response yet, try again.
if (response == null) {
continue;
}
// Store the response that was received
responses.add(response);
// If the response is an ok or error we're done
if (response.matches(getCommand(null, CommandType.COMMAND_CONFIRM_REGEX))) {
found = true;
break;
}
if (getCommand(null, CommandType.COMMAND_ERROR_REGEX) != null) {
if (response.matches(getCommand(null, CommandType.COMMAND_ERROR_REGEX))) {
foundError = true;
errorResponse = response;
break;
}
}
}
// If a command was specified and no confirmation was found it's a timeout error.
if (command != null & foundError) {
throw new Exception("Controller raised an error: " + errorResponse);
}
if (command != null && !found) {
throw new Exception("Timeout waiting for response to " + command);
}
// Read any additional responses that came in after the initial one.
responseQueue.drainTo(responses);
Logger.debug("sendCommand({} {}, {}) => {}",
new Object[] {portName, command, timeout == Long.MAX_VALUE ? -1 : timeout, responses});
return responses;
}
public void run() {
while (!disconnectRequested) {
String line;
try {
line = readLine().trim();
}
catch (TimeoutException ex) {
continue;
}
catch (IOException e) {
Logger.error("Read error", e);
return;
}
line = line.trim();
Logger.trace("[{}] << {}", portName, line);
if (!processPositionReport(line)) {
responseQueue.offer(line);
}
}
}
private boolean processPositionReport(String line) {
if (getCommand(null, CommandType.POSITION_REPORT_REGEX) == null) {
return false;
}
if (!line.matches(getCommand(null, CommandType.POSITION_REPORT_REGEX))) {
return false;
}
Logger.trace("Position report: {}", line);
Matcher matcher =
Pattern.compile(getCommand(null, CommandType.POSITION_REPORT_REGEX)).matcher(line);
matcher.matches();
for (Axis axis : axes) {
try {
String s = matcher.group(axis.getName());
Double d = Double.valueOf(s);
axis.setCoordinate(d);
}
catch (Exception e) {
Logger.warn("Error processing position report for axis {}: {}", axis.getName(), e);
}
}
ReferenceMachine machine = ((ReferenceMachine) Configuration.get().getMachine());
for (Head head : Configuration.get().getMachine().getHeads()) {
machine.fireMachineHeadActivity(head);
}
return true;
}
/**
* Find matches of variables in the format {Name:Format} and replace them with the specified
* value formatted using String.format with the specified Format. Format is optional and
* defaults to %s. A null value replaces the variable with "".
*/
static protected String substituteVariable(String command, String name, Object value) {
if (command == null) {
return command;
}
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\\{(\\w+)(?::(.+?))?\\}").matcher(command);
while (matcher.find()) {
String n = matcher.group(1);
if (!n.equals(name)) {
continue;
}
String format = matcher.group(2);
if (format == null) {
format = "%s";
}
String v = "";
if (value != null) {
v = String.format((Locale) null, format, value);
}
matcher.appendReplacement(sb, v);
}
matcher.appendTail(sb);
return sb.toString();
}
@Override
public String getPropertySheetHolderTitle() {
return getName() == null ? "GcodeDriver" : getName();
}
@Override
public PropertySheetHolder[] getChildPropertySheetHolders() {
ArrayList<PropertySheetHolder> children = new ArrayList<>();
if (parent == null) {
children.add(new SimplePropertySheetHolder("Sub-Drivers", subDrivers));
}
return children.toArray(new PropertySheetHolder[] {});
}
@Override
public PropertySheet[] getPropertySheets() {
return new PropertySheet[] {
new PropertySheetWizardAdapter(new GcodeDriverGcodes(this), "Gcode"),
new PropertySheetWizardAdapter(new GcodeDriverSettings(this), "General Settings"),
new PropertySheetWizardAdapter(new GcodeDriverConsole(this), "Console"),
new PropertySheetWizardAdapter(super.getConfigurationWizard(), "Serial")
};
}
@Override
public Action[] getPropertySheetHolderActions() {
if (parent == null) {
return new Action[] {addSubDriverAction};
}
else {
return new Action[] {deleteSubDriverAction};
}
}
public Action addSubDriverAction = new AbstractAction() {
{
putValue(SMALL_ICON, Icons.add);
putValue(NAME, "Add Sub-Driver...");
putValue(SHORT_DESCRIPTION, "Add a new sub-driver.");
}
@Override
public void actionPerformed(ActionEvent arg0) {
GcodeDriver driver = new GcodeDriver();
driver.commands.add(new Command(null, CommandType.COMMAND_CONFIRM_REGEX, "^ok.*"));
driver.parent = GcodeDriver.this;
subDrivers.add(driver);
fireIndexedPropertyChange("subDrivers", subDrivers.size() - 1, null, driver);
}
};
public Action deleteSubDriverAction = new AbstractAction() {
{
putValue(SMALL_ICON, Icons.delete);
putValue(NAME, "Delete Sub-Driver...");
putValue(SHORT_DESCRIPTION, "Delete the selected sub-driver.");
}
@Override
public void actionPerformed(ActionEvent arg0) {
int ret = JOptionPane.showConfirmDialog(MainFrame.get(),
"Are you sure you want to delete the selected sub-driver?",
"Delete Sub-Driver?", JOptionPane.YES_NO_OPTION);
if (ret == JOptionPane.YES_OPTION) {
parent.subDrivers.remove(GcodeDriver.this);
parent.fireIndexedPropertyChange("subDrivers", subDrivers.size() - 1, GcodeDriver.this, null);
}
}
};
public LengthUnit getUnits() {
return units;
}
public void setUnits(LengthUnit units) {
this.units = units;
}
public double getBacklashOffsetX() {
return backlashOffsetX;
}
public void setBacklashOffsetX(double BacklashOffsetX) {
this.backlashOffsetX = BacklashOffsetX;
}
public double getBacklashOffsetY() {
return backlashOffsetY;
}
public void setBacklashOffsetY(double BacklashOffsetY) {
this.backlashOffsetY = BacklashOffsetY;
}
public double getBacklashFeedRateFactor() {
return backlashFeedRateFactor;
}
public void setBacklashFeedRateFactor(double BacklashFeedRateFactor) {
this.backlashFeedRateFactor = BacklashFeedRateFactor;
}
public void setNonSquarenessFactor(double NonSquarenessFactor) {
this.nonSquarenessFactor = NonSquarenessFactor;
}
public double getNonSquarenessFactor() {
return this.nonSquarenessFactor;
}
public int getMaxFeedRate() {
return maxFeedRate;
}
public void setMaxFeedRate(int maxFeedRate) {
this.maxFeedRate = maxFeedRate;
}
public int getTimeoutMilliseconds() {
return timeoutMilliseconds;
}
public void setTimeoutMilliseconds(int timeoutMilliseconds) {
this.timeoutMilliseconds = timeoutMilliseconds;
}
public int getConnectWaitTimeMilliseconds() {
return connectWaitTimeMilliseconds;
}
public void setConnectWaitTimeMilliseconds(int connectWaitTimeMilliseconds) {
this.connectWaitTimeMilliseconds = connectWaitTimeMilliseconds;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
firePropertyChange("name", null, getName());
}
public boolean isVisualHomingEnabled() {
return visualHomingEnabled;
}
public void setVisualHomingEnabled(boolean visualHomingEnabled) {
this.visualHomingEnabled = visualHomingEnabled;
}
public static class Axis {
public enum Type {
X,
Y,
Z,
Rotation
};
@Attribute
private String name;
@Attribute
private Type type;
@Attribute(required = false)
private double homeCoordinate = 0;
@ElementList(required = false)
private Set<String> headMountableIds = new HashSet<String>();
@Element(required = false)
private AxisTransform transform;
@Element(required = false, data = true)
private String preMoveCommand;
/**
* Stores the current value for this axis.
*/
private double coordinate = 0;
public Axis() {
}
public Axis(String name, Type type, double homeCoordinate, String... headMountableIds) {
this.name = name;
this.type = type;
this.homeCoordinate = homeCoordinate;
this.headMountableIds.addAll(Arrays.asList(headMountableIds));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public double getCoordinate() {
return coordinate;
}
public void setCoordinate(double coordinate) {
this.coordinate = coordinate;
}
public double getHomeCoordinate() {
return homeCoordinate;
}
public void setHomeCoordinate(double homeCoordinate) {
this.homeCoordinate = homeCoordinate;
}
public double getTransformedCoordinate(HeadMountable hm) {
if (this.transform != null) {
return transform.toTransformed(this, hm, this.coordinate);
}
return this.coordinate;
}
public Set<String> getHeadMountableIds() {
return headMountableIds;
}
public void setHeadMountableIds(Set<String> headMountableIds) {
this.headMountableIds = headMountableIds;
}
public AxisTransform getTransform() {
return transform;
}
public void setTransform(AxisTransform transform) {
this.transform = transform;
}
public String getPreMoveCommand() {
return preMoveCommand;
}
public void setPreMoveCommand(String preMoveCommand) {
this.preMoveCommand = preMoveCommand;
}
}
public interface AxisTransform {
/**
* Transform the specified raw coordinate into it's corresponding transformed coordinate.
* The transformed coordinate is what the user sees, while the raw coordinate is what the
* motion controller sees.
*
* @param hm
* @param rawCoordinate
* @return
*/
public double toTransformed(Axis axis, HeadMountable hm, double rawCoordinate);
/**
* Transform the specified transformed coordinate into it's corresponding raw coordinate.
* The transformed coordinate is what the user sees, while the raw coordinate is what the
* motion controller sees.
*
* @param hm
* @param transformedCoordinate
* @return
*/
public double toRaw(Axis axis, HeadMountable hm, double transformedCoordinate);
}
/**
* An AxisTransform for heads with dual linear Z axes powered by one motor. The two Z axes are
* defined as normal and negated. Normal gets the raw coordinate value and negated gets the same
* value negated. So, as normal moves up, negated moves down.
*/
public static class NegatingTransform implements AxisTransform {
@Element
private String negatedHeadMountableId;
@Override
public double toTransformed(Axis axis, HeadMountable hm, double rawCoordinate) {
if (hm.getId().equals(negatedHeadMountableId)) {
return -rawCoordinate;
}
return rawCoordinate;
}
@Override
public double toRaw(Axis axis, HeadMountable hm, double transformedCoordinate) {
// Since we're just negating the value of the coordinate we can just
// use the same function.
return toTransformed(axis, hm, transformedCoordinate);
}
}
public static class CamTransform implements AxisTransform {
@Element
private String negatedHeadMountableId;
@Attribute(required = false)
private double camRadius = 24;
@Attribute(required = false)
private double camWheelRadius = 9.5;
@Attribute(required = false)
private double camWheelGap = 2;
@Override
public double toTransformed(Axis axis, HeadMountable hm, double rawCoordinate) {
double transformed = Math.sin(Math.toRadians(rawCoordinate)) * camRadius;
if (hm.getId().equals(negatedHeadMountableId)) {
transformed = -transformed;
}
transformed += camWheelRadius + camWheelGap;
return transformed;
}
@Override
public double toRaw(Axis axis, HeadMountable hm, double transformedCoordinate) {
double raw = (transformedCoordinate - camWheelRadius - camWheelGap) / camRadius;
raw = Math.min(Math.max(raw, -1), 1);
raw = Math.toDegrees(Math.asin(raw));
if (hm.getId().equals(negatedHeadMountableId)) {
raw = -raw;
}
return raw;
}
}
}
| gpl-3.0 |
nicomda/AI | Othello/src/othello/algoritmo/AlgoritmoPodaAlfaBeta.java | 4165 | /*
*/
package othello.algoritmo;
import othello.Utils.Casilla;
import othello.Utils.Heuristica;
import othello.Utils.Tablero;
import java.util.ArrayList;
/**
*
* @author gusamasan
*/
public class AlgoritmoPodaAlfaBeta extends Algoritmo{
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/** Constructores **************************************************/
private int playerColor;
public AlgoritmoPodaAlfaBeta(){
}
/*******************************************************************/
@Override
public Tablero obtenerNuevaConfiguracionTablero( Tablero tablero, short turno ){
System.out.println( "analizando siguiente jugada con ALFABETA" );
this.playerColor=turno;
Tablero tableroJugada=tablero.copiarTablero();
try{
int beta = Integer.MAX_VALUE;
int alfa = Integer.MIN_VALUE;
alfaBeta(tableroJugada, this.getProfundidad(), playerColor, alfa, beta);
Thread.sleep( 1000 );
}
catch( Exception e ){
e.printStackTrace();
}
return( tableroJugada );
}
/**
*
* Éste es el método que tenemos que implementar.
*
* Algoritmo AlfaBeta para determinar cuál es el siguiente mejor movimiento
*
* @param tablero
* Configuración actual del tablero
* @param prof
* Profundidad de búsqueda
* @param jugadorActual
* Nos indica a qué jugador (FICHA_BLANCA ó FICHA_NEGRA) le toca
* @param alfa
* @param beta
* Parámetros alfa y beta del algoritmo
* @return
*/
public int alfaBeta(Tablero tablero, int prof, int jugadorActual, int alfa, int beta)
{
// si el juego llega al final o no puede buscar mas
if (tablero.EsFinalDeJuego()|| prof==0)
{
int value= Heuristica.h2(tablero, playerColor);
return value;
}
// Si este jugador no puede jugar, pasa el turno
if (!tablero.PuedeJugar(jugadorActual))
{
int value = alfaBeta(tablero, prof, -jugadorActual, alfa, beta);
return value;
}
// cogemos las casillas en las cuales podemos jugar
ArrayList<Casilla> casillas = tablero.generarMovimiento(jugadorActual);
// ahora tenemos que encontrar el mejor movimiento actual
Casilla bestMovement = null;
for (Casilla cas: casillas)
{
// se realiza una copia del objeto tablero.
Tablero currentTablero = tablero.copiarTablero();
// se realiza un movimiento en el tablero creado
if(jugadorActual == 1)
cas.asignarFichaBlanca();
else if (jugadorActual == -1)
cas.asignarFichaNegra();
currentTablero.ponerFicha(cas);
currentTablero.imprimirTablero();
// Se evalua a ver si el movimiento es bueno.
int valorActual = alfaBeta(currentTablero, prof - 1, -jugadorActual, alfa, beta);
// Maximo
if (jugadorActual == this.playerColor)
{
if (valorActual > alfa)
{
alfa = valorActual;
bestMovement = cas;
}
// Es poda?
if (alfa >= beta)
return alfa;
}
// Minimo
else
{
if (valorActual < beta)
{
beta = valorActual;
bestMovement = cas;
}
// Es poda?
if(alfa >= beta)
return beta;
}
}
// Realizar ahora sí el mejor movimiento disponible.
if (bestMovement != null)
{
tablero.ponerFicha(bestMovement);
}
// Devolver el valor para el movimiento
if (jugadorActual == this.playerColor)
return alfa;
else
return beta;
}
}
| gpl-3.0 |
cinash/tasks | api/src/main/java/com/todoroo/andlib/data/AbstractModel.java | 16528 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.data;
import android.content.ContentValues;
import android.os.Parcel;
import android.os.Parcelable;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.PropertyVisitor;
import com.todoroo.andlib.utility.AndroidUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
/**
* <code>AbstractModel</code> represents a row in a database.
* <p>
* A single database can be represented by multiple <code>AbstractModel</code>s
* corresponding to different queries that return a different set of columns.
* Each model exposes a set of properties that it contains.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public abstract class AbstractModel implements Parcelable, Cloneable {
private static final Logger log = LoggerFactory.getLogger(AbstractModel.class);
private static final ContentValuesSavingVisitor saver = new ContentValuesSavingVisitor();
/** id property common to all models */
protected static final String ID_PROPERTY_NAME = "_id"; //$NON-NLS-1$
/** id field common to all models */
public static final LongProperty ID_PROPERTY = new LongProperty(null, ID_PROPERTY_NAME);
/** sentinel for objects without an id */
public static final long NO_ID = 0;
/** prefix for transitories retained in content values */
public static final String RETAIN_TRANSITORY_PREFIX = "retain-trans-"; //$NON-NLS-1$
// --- abstract methods
/** Get the default values for this object */
abstract public ContentValues getDefaultValues();
// --- data store variables and management
/* Data Source Ordering:
*
* In order to return the best data, we want to check first what the user
* has explicitly set (setValues), then the values we have read out of
* the database (values), then defaults (getDefaultValues)
*/
/** User set values */
protected ContentValues setValues = null;
/** Values from database */
protected ContentValues values = null;
/** Transitory Metadata (not saved in database) */
protected HashMap<String, Object> transitoryData = null;
public AbstractModel() {
}
public AbstractModel(TodorooCursor<? extends AbstractModel> cursor) {
readPropertiesFromCursor(cursor);
}
/** Get database-read values for this object */
public ContentValues getDatabaseValues() {
return values;
}
/** Get the user-set values for this object */
public ContentValues getSetValues() {
return setValues;
}
/** Get a list of all field/value pairs merged across data sources */
public ContentValues getMergedValues() {
ContentValues mergedValues = new ContentValues();
ContentValues defaultValues = getDefaultValues();
if(defaultValues != null) {
mergedValues.putAll(defaultValues);
}
if(values != null) {
mergedValues.putAll(values);
}
if(setValues != null) {
mergedValues.putAll(setValues);
}
return mergedValues;
}
/**
* Clear all data on this model
*/
public void clear() {
values = null;
setValues = null;
}
/**
* Transfers all set values into values. This occurs when a task is
* saved - future saves will not need to write all the data as before.
*/
public void markSaved() {
if(values == null) {
values = setValues;
} else if(setValues != null) {
values.putAll(setValues);
}
setValues = null;
}
/**
* Use merged values to compare two models to each other. Must be of
* exactly the same class.
*/
@Override
public boolean equals(Object other) {
if(other == null || other.getClass() != getClass()) {
return false;
}
return getMergedValues().equals(((AbstractModel)other).getMergedValues());
}
@Override
public int hashCode() {
return getMergedValues().hashCode() ^ getClass().hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "\n" + "set values:\n" + setValues + "\n" + "values:\n" + values + "\n";
}
@Override
public AbstractModel clone() {
AbstractModel clone;
try {
clone = (AbstractModel) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
if(setValues != null) {
clone.setValues = new ContentValues(setValues);
}
if(values != null) {
clone.values = new ContentValues(values);
}
return clone;
}
/**
* Reads all properties from the supplied cursor and store
*/
void readPropertiesFromCursor(TodorooCursor<? extends AbstractModel> cursor) {
if (values == null) {
values = new ContentValues();
}
// clears user-set values
setValues = null;
transitoryData = null;
for (Property<?> property : cursor.getProperties()) {
try {
saver.save(property, values, cursor.get(property));
} catch (IllegalArgumentException e) {
// underlying cursor may have changed, suppress
log.error(e.getMessage(), e);
}
}
}
/**
* Reads the given property. Make sure this model has this property!
*/
public synchronized <TYPE> TYPE getValue(Property<TYPE> property) {
Object value;
String columnName = property.getColumnName();
if(setValues != null && setValues.containsKey(columnName)) {
value = setValues.get(columnName);
} else if(values != null && values.containsKey(columnName)) {
value = values.get(columnName);
} else if(getDefaultValues().containsKey(columnName)) {
value = getDefaultValues().get(columnName);
} else {
throw new UnsupportedOperationException(
"Model Error: Did not read property " + property.name); //$NON-NLS-1$
}
// resolve properties that were retrieved with a different type than accessed
try {
if(value instanceof String && property instanceof LongProperty) {
return (TYPE) Long.valueOf((String) value);
} else if(value instanceof String && property instanceof IntegerProperty) {
return (TYPE) Integer.valueOf((String) value);
} else if(value instanceof Integer && property instanceof LongProperty) {
return (TYPE) Long.valueOf(((Number) value).longValue());
}
return (TYPE) value;
} catch (NumberFormatException e) {
log.error(e.getMessage(), e);
return (TYPE) getDefaultValues().get(property.name);
}
}
/**
* Utility method to get the identifier of the model, if it exists.
*
* @return {@value #NO_ID} if this model was not added to the database
*/
abstract public long getId();
protected long getIdHelper(LongProperty id) {
if(setValues != null && setValues.containsKey(id.name)) {
return setValues.getAsLong(id.name);
} else if(values != null && values.containsKey(id.name)) {
return values.getAsLong(id.name);
} else {
return NO_ID;
}
}
public void setId(long id) {
if (setValues == null) {
setValues = new ContentValues();
}
if(id == NO_ID) {
clearValue(ID_PROPERTY);
} else {
setValues.put(ID_PROPERTY_NAME, id);
}
}
/**
* @return true if this model has found Jesus (i.e. the database)
*/
public boolean isSaved() {
return getId() != NO_ID;
}
/**
* @return true if setValues or values contains this property
*/
public boolean containsValue(Property<?> property) {
if(setValues != null && setValues.containsKey(property.getColumnName())) {
return true;
}
if(values != null && values.containsKey(property.getColumnName())) {
return true;
}
return false;
}
/**
* @return true if setValues or values contains this property, and the value
* stored is not null
*/
public boolean containsNonNullValue(Property<?> property) {
if(setValues != null && setValues.containsKey(property.getColumnName())) {
return setValues.get(property.getColumnName()) != null;
}
if(values != null && values.containsKey(property.getColumnName())) {
return values.get(property.getColumnName()) != null;
}
return false;
}
// --- data storage
/**
* Check whether the user has changed this property value and it should be
* stored for saving in the database
*/
protected synchronized <TYPE> boolean shouldSaveValue(
Property<TYPE> property, TYPE newValue) {
// we've already decided to save it, so overwrite old value
if (setValues.containsKey(property.getColumnName())) {
return true;
}
// values contains this key, we should check it out
if(values != null && values.containsKey(property.getColumnName())) {
TYPE value = getValue(property);
if (value == null) {
if (newValue == null) {
return false;
}
} else if (value.equals(newValue)) {
return false;
}
}
// otherwise, good to save
return true;
}
/**
* Sets the given property. Make sure this model has this property!
*/
public synchronized <TYPE> void setValue(Property<TYPE> property,
TYPE value) {
if (setValues == null) {
setValues = new ContentValues();
}
if (!shouldSaveValue(property, value)) {
return;
}
saver.save(property, setValues, value);
}
/**
* Merges content values with those coming from another source
*/
public synchronized void mergeWith(ContentValues other) {
if (setValues == null) {
setValues = new ContentValues();
}
setValues.putAll(other);
}
/**
* Merges set values with those coming from another source,
* keeping the existing value if one already exists
*/
public synchronized void mergeWithoutReplacement(ContentValues other) {
if (setValues == null) {
setValues = new ContentValues();
}
for (Entry<String, Object> item : other.valueSet()) {
if (setValues.containsKey(item.getKey())) {
continue;
}
AndroidUtilities.putInto(setValues, item.getKey(), item.getValue());
}
}
/**
* Clear the key for the given property
*/
public synchronized void clearValue(Property<?> property) {
if(setValues != null && setValues.containsKey(property.getColumnName())) {
setValues.remove(property.getColumnName());
}
if(values != null && values.containsKey(property.getColumnName())) {
values.remove(property.getColumnName());
}
}
// --- setting and retrieving flags
public synchronized void putTransitory(String key, Object value) {
if(transitoryData == null) {
transitoryData = new HashMap<>();
}
transitoryData.put(key, value);
}
public Object getTransitory(String key) {
if(transitoryData == null) {
return null;
}
return transitoryData.get(key);
}
public Object clearTransitory(String key) {
if (transitoryData == null) {
return null;
}
return transitoryData.remove(key);
}
// --- Convenience wrappers for using transitories as flags
public boolean checkTransitory(String flag) {
Object trans = getTransitory(flag);
return trans != null;
}
public boolean checkAndClearTransitory(String flag) {
Object trans = clearTransitory(flag);
return trans != null;
}
// --- property management
/**
* Looks inside the given class and finds all declared properties
*/
protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) {
ArrayList<Property<?>> properties = new ArrayList<>();
if(cls.getSuperclass() != AbstractModel.class) {
properties.addAll(Arrays.asList(generateProperties(
(Class<? extends AbstractModel>) cls.getSuperclass())));
}
// a property is public, static & extends Property
for(Field field : cls.getFields()) {
if((field.getModifiers() & Modifier.STATIC) == 0) {
continue;
}
if(!Property.class.isAssignableFrom(field.getType())) {
continue;
}
try {
if(((Property<?>) field.get(null)).table == null) {
continue;
}
properties.add((Property<?>) field.get(null));
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return properties.toArray(new Property<?>[properties.size()]);
}
/**
* Visitor that saves a value into a content values store
*
* @author Tim Su <tim@todoroo.com>
*
*/
public static class ContentValuesSavingVisitor implements PropertyVisitor<Void, Object> {
private ContentValues store;
public synchronized void save(Property<?> property, ContentValues newStore, Object value) {
this.store = newStore;
// we don't allow null values, as they indicate unset properties
// when the database was written
if(value != null) {
property.accept(this, value);
}
}
@Override
public Void visitInteger(Property<Integer> property, Object value) {
store.put(property.getColumnName(), (Integer) value);
return null;
}
@Override
public Void visitLong(Property<Long> property, Object value) {
store.put(property.getColumnName(), (Long) value);
return null;
}
@Override
public Void visitString(Property<String> property, Object value) {
store.put(property.getColumnName(), (String) value);
return null;
}
}
// --- parcelable helpers
/**
* {@inheritDoc}
*/
@Override
public int describeContents() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(setValues, 0);
dest.writeParcelable(values, 0);
}
/**
* Parcelable creator helper
*/
protected static final class ModelCreator<TYPE extends AbstractModel>
implements Parcelable.Creator<TYPE> {
private final Class<TYPE> cls;
public ModelCreator(Class<TYPE> cls) {
super();
this.cls = cls;
}
/**
* {@inheritDoc}
*/
@Override
public TYPE createFromParcel(Parcel source) {
TYPE model;
try {
model = cls.newInstance();
} catch (IllegalAccessException | InstantiationException e) {
throw new RuntimeException(e);
}
model.setValues = source.readParcelable(ContentValues.class.getClassLoader());
model.values = source.readParcelable(ContentValues.class.getClassLoader());
return model;
}
/**
* {@inheritDoc}
*/
@Override
public TYPE[] newArray(int size) {
return (TYPE[]) Array.newInstance(cls, size);
}
}
}
| gpl-3.0 |
maandree/jash | src/se/kth/maandree/jash/lineread/LineHistory.java | 2825 | /**
* jash - Just another shell
*
* Copyright (C) 2012 Mattias Andrée (maandree@kth.se)
*
* jash 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.
*
* jash 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 jash. If not, see <http://www.gnu.org/licenses/>.
*/
package se.kth.maandree.jash.lineread;
import java.io.*;
import java.util.*;
/**
* Line input history
*
* @author Mattias Andrée, <a href="mailto:maandree@kth.se">maandree@kth.se</a>
*/
public class LineHistory implements LineHistoryInterface
{
/**
* Constructor
*
* @param file The history file
* @param soft Soft history limit, in number of lines; after truncation
* @param hard Hard history limit, in number of lines; when to truncate
*/
public LineHistory(final String file, final int soft, final int hard) throws IOException
{
this.file = file;
this.soft = soft;
this.hard = hard;
this.lines = new ArrayList<int[]>();
//TODO populate
this.ptr = this.lines.size();
}
/**
* The history file
*/
public final String file;
/**
* Soft history limit, in number of lines; after truncation
*/
public int soft;
/**
* Hard history limit, in number of lines; when to truncate
*/
public int hard;
/**
* Line history
*/
public ArrayList<int[]> lines;
/**
* Line history pointer
*/
public int ptr;
/**
* {@inheritDoc}
*/
public synchronized int[] up(final boolean page, final int[] current)
{
try
{
//TODO
}
catch (final Throwable err)
{
//That's too bad
}
return null;
}
/**
* {@inheritDoc}
*/
public synchronized int[] down(final boolean page, final int[] current)
{
try
{
//TODO
}
catch (final Throwable err)
{
//That's too bad
}
return null;
}
/**
* {@inheritDoc}
*/
public synchronized int[] enter(final int[] current)
{
try
{
return current; //TODO
}
catch (final Throwable err)
{
//That's too bad
return current;
}
}
/**
* {@inheritDoc}
*/
public synchronized int[] search(final int[] beginning)
{
try
{
//TODO
}
catch (final Throwable err)
{
//That's too bad
}
return null;
}
}
| gpl-3.0 |
Codegence/aurora | src/main/java/com/codegence/aurora/server/Server.java | 1436 | package com.codegence.aurora.server;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Created by lmorganti on 19/02/16.
*/
@DynamoDBTable(tableName = "cgServers")
@AllArgsConstructor
@NoArgsConstructor
public class Server {
private String serverID;
private String playerID;
@Setter
@NotEmpty
private String nickName;
@Setter
@NotEmpty
private String url;
@DynamoDBHashKey
@DynamoDBAutoGeneratedKey
public String getServerID() {
return serverID;
}
@DynamoDBAttribute
public String getNickName() {
return nickName;
}
@DynamoDBAttribute
@JsonIgnore
public String getPlayerID() {
return playerID;
}
@DynamoDBAttribute
public String getUrl() {
return url;
}
@JsonIgnore
public void setServerID(String serverID) {
this.serverID = serverID;
}
@JsonIgnore
public void setPlayerID(String playerID) {
this.playerID = playerID;
}
}
| gpl-3.0 |
kizax/ArrivingLateRecordApp | src/edu/tcfsh/arrivinglaterecordapp/SearchingStudentFragment.java | 5700 | package edu.tcfsh.arrivinglaterecordapp;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import edu.tcfsh.arrivinglaterecordapp.R;
import jxl.Cell;
import jxl.CellType;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class SearchingStudentFragment extends Fragment {
private ArrayList<StudentRecord> studentRecordList;
private TextView statusText;
private EditText regexEditText;
private ListView searchingResultListView;
private Button commitButton;
private ArrayList<StudentRecord> searchingResultList;
private SearchingResultArrayAdapter searchingResultArrayAdapter;
OnSearchingResultSelectedListener mCallback;
public SearchingStudentFragment(){
}
public interface OnSearchingResultSelectedListener {
public void onStudentRecordSelected(StudentRecord studentRecord);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnSearchingResultSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSearchingResultSelectedListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.searching_student_fragment,
container, false);
initialize(rootView);
initializeFileWriter();
setListener();
return rootView;
}
private void initialize(View rootView) {
regexEditText = (EditText) rootView.findViewById(R.id.regexEditText);
statusText = (TextView) rootView.findViewById(R.id.statusText);
searchingResultListView = (ListView) rootView.findViewById(R.id.searchingResultList);
commitButton = (Button) rootView.findViewById(R.id.saveFileButton);
studentRecordList = new ArrayList<StudentRecord>();
searchingResultList = new ArrayList<StudentRecord>();
searchingResultArrayAdapter = new SearchingResultArrayAdapter(searchingResultListView.getContext(),
searchingResultList, mCallback);
searchingResultListView.setAdapter(searchingResultArrayAdapter);
}
private void initializeFileWriter() {
// 指定xls存檔檔名
String studentDataFileName = getStudentFileFileName();
File SDCardpath = Environment.getExternalStorageDirectory();
File studentData = new File(SDCardpath.getAbsolutePath() + "/student/"
+ studentDataFileName);
// 讀取學生名條
try {
if (studentData.exists()) {
Workbook workbook = Workbook.getWorkbook(studentData);
Sheet sheet = workbook.getSheet(0);
int index = 1;
while (index < sheet.getRows()) {
int gradeNum = 0;
int classNum = 0;
int studentId = 0;
String studentName = "";
int num = 0;
Cell studentIdCell = sheet.getCell(0, index);
if (studentIdCell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) studentIdCell;
studentId = (int) nc.getValue();
}
Cell gradeAndClassCell = sheet.getCell(1, index);
if (gradeAndClassCell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) gradeAndClassCell;
int gradeAndClass = (int) nc.getValue();
gradeNum = gradeAndClass / 100;
classNum = gradeAndClass % 100;
}
Cell numCell = sheet.getCell(2, index);
if (numCell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) numCell;
num = (int) nc.getValue();
}
Cell studentNameCell = sheet.getCell(3, index);
if (studentNameCell.getType() == CellType.LABEL) {
LabelCell lc = (LabelCell) studentNameCell;
studentName = lc.getString();
}
StudentRecord studentRecord = new StudentRecord(gradeNum,
classNum, num, studentId, studentName);
studentRecordList.add(studentRecord);
index++;
}
} else {
statusText.setText("學生名條檔案不存在");
}
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
View.OnClickListener commitButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String regex = regexEditText.getText().toString();
statusText.setText("您的查詢:" + regex);
regexEditText.setText("");
searchingResultList.clear();
switch (regex.length()) {
case 2:
case 3:
case 4:
for (StudentRecord studentRecord : studentRecordList) {
if (studentRecord.matchStudentName(regex)) {
searchingResultList.add(studentRecord);
}
}
break;
case 5:
for (StudentRecord studentRecord : studentRecordList) {
if (studentRecord.matchStudentNum(regex)) {
searchingResultList.add(studentRecord);
}
}
break;
case 6:
for (StudentRecord studentRecord : studentRecordList) {
if (studentRecord.matchStudentID(regex)) {
searchingResultList.add(studentRecord);
}
}
break;
}
searchingResultArrayAdapter.notifyDataSetChanged();
}
};
private void setListener() {
commitButton.setOnClickListener(commitButtonListener);
}
private String getStudentFileFileName() {
String studentDataFileName = "studentData.xls";
return studentDataFileName;
}
} | gpl-3.0 |
RagingFury200/MantaroSox | src/main/java/net/kodehawa/mantarobot/commands/anime/CharacterData.java | 828 | package net.kodehawa.mantarobot.commands.anime;
public class CharacterData {
public Boolean favourite = null;
public Integer id = null;
public String image_url_lge = null;
public String image_url_med = null;
public String info = null;
public String name_alt = null;
public String name_first = null;
public String name_japanese = null;
public String name_last = null;
public Integer getId() {
return id;
}
public String getImage_url_lge() {
return image_url_lge;
}
public String getImage_url_med() {
return image_url_med;
}
public String getInfo() {
return info;
}
public String getName_alt() {
return name_alt;
}
public String getName_first() {
return name_first;
}
public String getName_japanese() {
return name_japanese;
}
public String getName_last() {
return name_last;
}
}
| gpl-3.0 |
hessan/artenus | src/main/java/com/annahid/libs/artenus/Artenus.java | 9599 | /*
* This file is part of the Artenus 2D Framework.
* Copyright (C) 2015 Hessan Feghhi
*
* 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.
*
* Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.annahid.libs.artenus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import com.annahid.libs.artenus.graphics.TextureManager;
import com.annahid.libs.artenus.graphics.rendering.ShaderManager;
import com.annahid.libs.artenus.internal.core.StageImpl;
import com.annahid.libs.artenus.sound.SoundManager;
import com.annahid.libs.artenus.core.Stage;
import com.annahid.libs.artenus.unified.Stores;
import com.annahid.libs.artenus.unified.UnifiedServices;
import com.annahid.libs.artenus.unified.AdLayout;
import java.lang.ref.WeakReference;
/**
* The abstract superclass of a typical Artenus SDK activity. This class should be
* extended by the game application and the {@code init()} method must be implemented
* to handle basic initializations and retrieving the stage.
*
* @author Hessan Feghhi
*/
public abstract class Artenus extends Activity {
/**
* Holds the Artenus instance. Only one instance should exist per application.
* This instance is assigned not in the constructor, but when its context is ready.
*/
private static WeakReference<Artenus> instance = null;
/**
* Indicates whether the default splash screen will be displayed. This value can be set by
* calling the protected constructor.
*/
private static boolean hideIntro;
/**
* Holds the app-store as specified in the Android manifest file.
*/
private static Stores manifestStore;
/**
* Holds a reference to the default stage.
*/
private WeakReference<StageImpl> stage;
/**
* Holds the audio manager used for mapping volume keys to media volume.
*/
private AudioManager audio;
/**
* Indicates whether the app is out-focused.
*/
private boolean hasOutFocused = false;
/**
* Creates a new instance of Artenus activity.
*
* @param hideIntro A value indicating whether to hide the initial splash screen
*/
protected Artenus(boolean hideIntro) {
Artenus.hideIntro = hideIntro;
}
/**
* Creates a new instance of Artenus activity.
*/
protected Artenus() {
this(false);
}
/**
* Gets the currently running instance of {@code Artenus}.
*
* @return The running instance
*/
public static Artenus getInstance() {
if (instance == null) {
throw new IllegalStateException("Artenus instance does not exist!");
}
return instance.get();
}
/**
* Determines whether an intro screen should be displayed before the game.
*
* @return true if there should be an intro, false otherwise
*/
public static boolean shouldHideIntro() {
return hideIntro;
}
/**
* Gets the store preference specified in the application manifest for unified services.
*
* @return Store identifier
*
* @see com.annahid.libs.artenus.unified.UnifiedServices
*/
public static Stores getManifestAppStore() {
return manifestStore;
}
/**
* Gets the game stage. Each game has only one stage, where its different scenes are displayed.
*
* @return The stage
*/
public Stage getStage() {
return stage.get();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = new WeakReference<>(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(
getPackageName(),
PackageManager.GET_META_DATA
);
final String store = ai.metaData.getString("com.annahid.libs.artenus.APP_STORE");
manifestStore = Stores.NONE;
if (store != null) {
switch (store) {
case "google":
manifestStore = Stores.GOOGLE;
break;
case "amazon":
manifestStore = Stores.AMAZON;
break;
case "bazaar":
manifestStore = Stores.BAZAAR;
break;
case "cando":
manifestStore = Stores.CANDO;
break;
case "samsung":
manifestStore = Stores.SAMSUNG;
break;
}
}
} catch (PackageManager.NameNotFoundException | NullPointerException e) {
manifestStore = Stores.NONE;
}
if (!SoundManager.isContextInitialized()) {
SoundManager.initContext(this);
}
setContentView(R.layout.game_layout);
stage = new WeakReference<>((StageImpl) findViewById(R.id.gameStage));
ShaderManager.register(TextureManager.getShaderProgram());
init(stage.get());
UnifiedServices unified = UnifiedServices.getInstance();
if (unified == null) {
unified = UnifiedServices.getInstance(0);
}
if (unified.hasServices(UnifiedServices.SERVICE_ADS)) {
unified.getAdManager().setAdLayout((AdLayout) stage.get().getParent());
}
unified.onCreate(this);
}
@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (stage != null && stage.get() != null && stage.get().onBackButton()) {
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
hasOutFocused = true;
} else if (hasOutFocused) {
SoundManager.resumeMusic();
hasOutFocused = false;
}
}
/**
* Exits the game or application. This is the recommended method to exit within the framework.
*/
@SuppressWarnings("UnusedDeclaration")
public final void exit() {
System.exit(0);
}
@Override
protected void onPause() {
super.onPause();
stage.get().onPause();
SoundManager.pauseMusic();
UnifiedServices.getInstance().onPause();
}
@Override
protected void onResume() {
super.onResume();
if (!hasOutFocused) {
SoundManager.resumeMusic();
}
stage.get().onResume();
UnifiedServices.getInstance().onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
UnifiedServices.getInstance().onDestroy(this);
TextureManager.unloadAll();
SoundManager.unloadAll();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UnifiedServices.getInstance().onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onStop() {
super.onStop();
UnifiedServices.getInstance().onStop();
}
@Override
protected void onStart() {
super.onStart();
UnifiedServices.getInstance().onStart();
}
/**
* Initializes the game. Subclasses should implement this method and use it as an entry point to
* load textures and other resources into the framework.
*
* @param stage The stage for the game
*/
protected abstract void init(Stage stage);
}
| gpl-3.0 |
abeym/incubator | Trials/java8-concurrency/src/com/ab/concurrent/samples/ScheduledExecutorSample.java | 2146 | package com.ab.concurrent.samples;
import java.util.concurrent.*;
import java.util.logging.Logger;
/**
* Created by Abey on 1/12/2017.
*/
public class ScheduledExecutorSample {
private static Logger log = Logger.getLogger(ScheduledExecutorSample.class.getName());
public static void main(String... args)
{
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
ScheduledExecutorService executor2 = Executors.newScheduledThreadPool(1);
ScheduledExecutorService executor3 = Executors.newScheduledThreadPool(1);
Runnable task = () -> log.info("Scheduling: " + System.nanoTime());
try {
ScheduledFuture<?> future = executor.schedule(createTask("Task One"), 3, TimeUnit.SECONDS);
ScheduledFuture<?> future2 = executor2.scheduleAtFixedRate(createTask("Task Multi fixed rate "), 1, 1, TimeUnit.SECONDS);
ScheduledFuture<?> future3 = executor3.scheduleWithFixedDelay(createTask("Task Multi with delay"), 1, 1, TimeUnit.SECONDS);
TimeUnit.MILLISECONDS.sleep(1337);
long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
log.info("Remaining Delay: " + remainingDelay);
TimeUnit.MINUTES.sleep(2);
} catch (InterruptedException e) {
log.severe("InterruptedException " + e);
e.printStackTrace();
}
shutdown(executor);
shutdown(executor2);
shutdown(executor3);
}
private static Runnable createTask(String msg)
{
return ()-> log.info(msg);
}
private static void shutdown(ExecutorService executor)
{
//shutdown
try {
Thread.sleep(TimeUnit.SECONDS.toSeconds(20));
log.info("Shutting down executor...");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.info("executor interrupted");
} finally {
if (!executor.isTerminated())
log.info("cancel non-finished tasks");
executor.shutdownNow();
}
}
}
| gpl-3.0 |
Carrotlord/MintChime-Editor | builtin/system/Inveigle.java | 734 | package builtin.system;
import builtin.BuiltinSub;
import gui.Constants;
import gui.Mint;
import gui.MintException;
import gui.Pointer;
import gui.SmartList;
/**
* @author Oliver Chu
*/
public class Inveigle extends BuiltinSub {
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
Pointer p = args.get(0);
if (p.type == Constants.STR_TYPE) {
Mint.seduced = !Mint.seduced;
return Constants.MINT_NULL;
}
if (p.value == 1 &&
(p.type == Constants.INT_TYPE || p.type == Constants.TRUTH_TYPE)) {
Mint.seduced = true;
} else {
Mint.seduced = false;
}
return Constants.MINT_NULL;
}
}
| gpl-3.0 |
brucejohnson/studiofx | src/main/java/org/renjin/studiofx/console/ConsoleFx.java | 19434 | /*
* NMRFx Processor : A Program for Processing NMR Data
* Copyright (C) 2004-2017 One Moon Scientific, Inc., Westfield, N.J., USA
*
* 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/>.
*/
/*
* 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 org.renjin.studiofx.console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import static javafx.scene.input.KeyCode.ENTER;
import static javafx.scene.input.KeyCode.S;
import javafx.scene.input.KeyCombination;
import static javafx.scene.input.KeyCombination.CONTROL_DOWN;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.stage.PopupWindow;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.vfs2.FileSystemException;
import org.fxmisc.richtext.InlineCssTextArea;
import org.fxmisc.richtext.Paragraph;
import static org.fxmisc.richtext.TwoDimensional.Bias.Forward;
import org.fxmisc.wellbehaved.event.EventHandlerHelper;
import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
import static org.fxmisc.wellbehaved.event.EventPattern.keyTyped;
import org.renjin.script.RenjinScriptEngine;
import org.renjin.script.RenjinScriptEngineFactory;
import org.renjin.studiofx.FXMLController;
import org.renjin.studiofx.StudioSession;
/**
*
* @author brucejohnson
*/
public class ConsoleFx implements RichConsole, Runnable {
static Clipboard clipBoard = Clipboard.getSystemClipboard();
public static RenjinScriptEngine renjinEngine = null;
InlineCssTextArea outputArea;
protected final List<String> history = new ArrayList<>();
protected int historyPointer = 0;
String prompt = "> ";
boolean renjinMode = false;
private OutputStream outPipe;
private InputStream inPipe;
private InputStream in;
private PrintStream out;
private NameCompletion nameCompletion;
final int SHOW_AMBIG_MAX = 10;
CommandList commandList;
Map<String, Function> interpreters = new HashMap<>();
Function function = null;
public ConsoleFx() {
this(null, null);
}
public ConsoleFx(InputStream cin, OutputStream cout) {
outPipe = cout;
if (outPipe == null) {
outPipe = new PipedOutputStream();
try {
in = new PipedInputStream((PipedOutputStream) outPipe);
} catch (IOException e) {
print("Console internal error (1)...", Color.RED);
}
}
inPipe = cin;
if (inPipe == null) {
PipedOutputStream pout = new PipedOutputStream();
out = new PrintStream(pout);
try {
inPipe = new ConsoleFx.BlockingPipedInputStream(pout);
} catch (IOException e) {
print("Console internal error: " + e);
}
}
// Start the inpipe watcher
new Thread(this).start();
}
public void initInterpreter(StudioSession session) {
Repl interpreter = null;
try {
interpreter = new Repl(this, session);
} catch (FileSystemException ex) {
Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
new Thread(interpreter).start();
}
private void print(String s) {
runOnFxThread(() -> outputArea.appendText(s));
}
static String cssColor(Color color) {
int red = (int) (color.getRed() * 255);
int green = (int) (color.getGreen() * 255);
int blue = (int) (color.getBlue() * 255);
return "rgb(" + red + ", " + green + ", " + blue + ")";
}
private void print(String s, Color color) {
runOnFxThread(() -> {
// consoleArea.appendText(s);
// Set<String> style = Collections.singleton("-fx-fill: " + cssColor(color) + ";");
// Set<String> style = Collections.singleton("keyword");
// ReadOnlyStyledDocument sDoc = ReadOnlyStyledDocument.fromString(s, style);
// System.out.println("style " + sDoc.getStyleOfChar(2));
// consoleArea.append(sDoc);
int start = outputArea.getLength();
outputArea.appendText(s);
int end = outputArea.getLength();
outputArea.setStyle(start, end, "-fx-fill: " + cssColor(color));
});
}
public InputStream getInputStream() {
return in;
}
public Reader getIn() {
return new InputStreamReader(in);
}
public PrintStream getOut() {
return out;
}
public PrintStream getErr() {
return out;
}
private void inPipeWatcher() throws IOException {
byte[] ba = new byte[256]; // arbitrary blocking factor
int read;
while ((read = inPipe.read(ba)) != -1) {
print(new String(ba, 0, read));
//text.repaint();
}
// println("Console: Input closed...");
}
public void run() {
try {
inPipeWatcher();
} catch (IOException e) {
print("Console: I/O Error: " + e + "\n", Color.RED);
}
}
@Override
public void print(Object o, java.awt.Color color) {
}
@Override
public void setNameCompletion(NameCompletion nc) {
nameCompletion = nc;
commandList = new CommandList(this);
}
@Override
public void setWaitFeedback(boolean on) {
}
@Override
public void println(Object o) {
}
@Override
public void print(Object o) {
}
@Override
public void error(Object o) {
}
@Override
public int getCharactersPerLine() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
class ConsoleOutputStream extends OutputStream {
@Override
public void write(int b) throws IOException {
runOnFxThread(() -> outputArea.appendText(String.valueOf((char) b)));
}
}
public static void runOnFxThread(final Runnable runnable) {
Objects.requireNonNull(runnable, "runnable");
if (Platform.isFxApplicationThread()) {
runnable.run();
} else {
Platform.runLater(runnable);
}
}
public void banner() {
String banner = "Welcome";
runOnFxThread(() -> outputArea.appendText(banner + "\n"));
}
public void prompt() {
runOnFxThread(() -> outputArea.appendText(prompt));
runOnFxThread(() -> outputArea.positionCaret(outputArea.getLength()));
}
public void save() {
System.out.println("save");
}
public void typed(KeyEvent keyEvent) {
if (keyEvent.isShortcutDown()) {
return;
}
String keyString = keyEvent.getCharacter();
if ((keyString != null) && (keyString.length() > 0)) {
char keyChar = keyString.charAt(0);
if (!Character.isISOControl(keyChar)) {
int caretPosition = outputArea.getCaretPosition();
int nParagraphs = outputArea.getParagraphs().size();
outputArea.insertText(caretPosition, keyString);
}
}
PopupWindow popup = outputArea.getPopupWindow();
if ((popup != null) && popup.isShowing()) {
checkCommand();
}
}
public void delete() {
int nChar = outputArea.getLength();
int col = outputArea.getCaretColumn();
int pos = outputArea.getCaretPosition();
if (col > prompt.length()) {
outputArea.deleteText(pos - 1, pos);
}
}
public void historyUp() {
historyPointer--;
if (historyPointer < 0) {
historyPointer = 0;
}
getHistory();
}
public void historyDown() {
historyPointer++;
if (historyPointer > history.size()) {
historyPointer = history.size();
}
getHistory();
}
public void getHistory() {
int nParagraphs = outputArea.getParagraphs().size();
Paragraph para = outputArea.getParagraph(nParagraphs - 1);
int nChar = para.length();
para.delete(prompt.length(), nChar);
String historyString = "";
if (historyPointer < history.size()) {
historyString = history.get(historyPointer);
}
int nChars = outputArea.getLength();
int paraStart = nChars - para.length();
outputArea.replaceText(paraStart + prompt.length(), nChars, historyString);
}
public void paste(KeyEvent event) {
String string = clipBoard.getString();
if (string != null) {
outputArea.appendText(string);
}
}
public void copy(KeyEvent event) {
String text = outputArea.getSelectedText();
ClipboardContent content = new ClipboardContent();
content.putString(text);
clipBoard.setContent(content);
}
public static RenjinScriptEngine getRenjin() {
if (renjinEngine == null) {
RenjinScriptEngineFactory renjinFactory = new RenjinScriptEngineFactory();
renjinEngine = renjinFactory.getScriptEngine();
}
return renjinEngine;
}
private String getCurrentLine() {
int nParagraphs = outputArea.getParagraphs().size();
Paragraph para = outputArea.getParagraph(nParagraphs - 1);
String command = para.toString();
if (command.startsWith(prompt)) {
command = command.substring(prompt.length());
}
command = command.trim();
command = command.replace("\0", "");
return command;
}
void complete(String command) {
String part = getCurrentLine();
outputArea.appendText(command.substring(part.length()) + "()");
int length = outputArea.getLength();
outputArea.positionCaret(length - 1);
}
private void checkCommand() {
String part = getCurrentLine();
if (nameCompletion == null) {
return;
}
int i = part.length() - 1;
// Character.isJavaIdentifierPart() How convenient for us!!
while (i >= 0
&& (Character.isJavaIdentifierPart(part.charAt(i))
|| part.charAt(i) == '.')) {
i--;
}
part = part.substring(i + 1);
if (part.length() < 2) // reasonable completion length
{
return;
}
//System.out.println("completing part: "+part);
// no completion
String[] complete = nameCompletion.completeName(part);
if (complete.length == 0) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
// Found one completion (possibly what we already have)
if (complete.length == 1 && !complete.equals(part)) {
complete(complete[0]);
PopupWindow popup = outputArea.getPopupWindow();
if ((popup != null) && popup.isShowing()) {
popup.hide();
}
return;
}
String commonPrefix = StringUtils.getCommonPrefix(complete);
if (commonPrefix.length() > part.length()) {
outputArea.appendText(commonPrefix.substring(part.length()));
}
commandList.setContent(complete);
commandList.show(outputArea);
}
public void enter() {
String command = getCurrentLine();
if (command.length() > 0) {
history.add(command);
historyPointer = history.size();
}
outputArea.appendText("\n");
command += '\n';
acceptLine(command);
}
public void caret(Integer oldValue, Integer newValue) {
int pos = outputArea.getCaretPosition();
int col = outputArea.getCaretColumn();
int startPar = outputArea.offsetToPosition(pos, Forward).getMajor();
int nParagraphs = outputArea.getParagraphs().size();
if (startPar != (nParagraphs - 1)) {
outputArea.positionCaret(oldValue);
} else if (col < prompt.length()) {
outputArea.positionCaret(pos + (prompt.length() - col));
}
}
public void setInterpreter(String name) {
function = interpreters.get(name);
}
private void acceptLine(String line) {
StringBuilder buf = new StringBuilder();
int lineLength = line.length();
for (int i = 0; i < lineLength; i++) {
char c = line.charAt(i);
buf.append(c);
}
line = buf.toString();
if (line.trim().startsWith("interp(\"") && line.trim().endsWith("\")")) {
String cmd = line.trim().substring(8);
String interpName = cmd.substring(0, cmd.length() - 2);
System.out.println("interp " + interpName);
if (interpName.equals("renjin")) {
function = null;
} else {
function = interpreters.get(interpName);
}
return;
}
if (outPipe == null) {
print("Console internal error: cannot output ...", Color.RED);
} else {
try {
if (function != null) {
if (function != null) {
function.apply(line);
getOut().print("> ");
}
} else {
outPipe.write(line.getBytes());
outPipe.flush();
}
} catch (IOException e) {
outPipe = null;
throw new RuntimeException("Console pipe broken...", e);
}
}
}
public void setOutputArea(InlineCssTextArea outputArea) {
this.outputArea = outputArea;
}
public void addInterpreter(String name, Function<String, String> function) {
interpreters.put(name, function);
this.function = function;
}
public void addHandler() {
// this.interpreter = interpreter;
outputArea.setEditable(false);
//interpreter.setOut(new ConsoleOutputStream());
//interpreter.setErr(new ConsoleOutputStream());
EventHandler<? super KeyEvent> ctrlS = EventHandlerHelper
.on(keyPressed(S, CONTROL_DOWN)).act(event -> save())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), ctrlS);
EventHandler<? super KeyEvent> enter = EventHandlerHelper
.on(keyPressed(ENTER)).act(event -> enter())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), enter);
EventHandler<? super KeyEvent> backSpace = EventHandlerHelper
.on(keyPressed(KeyCode.BACK_SPACE)).act(event -> delete())
.create();
EventHandler<? super KeyEvent> delete = EventHandlerHelper
.on(keyPressed(KeyCode.DELETE)).act(event -> delete())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), delete);
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), backSpace);
EventHandler<? super KeyEvent> tab = EventHandlerHelper
.on(keyPressed(KeyCode.TAB)).act(event -> checkCommand())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), tab);
EventHandler<? super KeyEvent> paste = EventHandlerHelper
.on(keyPressed(KeyCode.V, KeyCombination.SHORTCUT_DOWN)).act(event -> paste(event))
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), paste);
EventHandler<? super KeyEvent> copy = EventHandlerHelper
.on(keyPressed(KeyCode.C, KeyCombination.SHORTCUT_DOWN)).act(event -> copy(event))
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), copy);
EventHandler<? super KeyEvent> historyUp = EventHandlerHelper
.on(keyPressed(KeyCode.UP)).act(event -> historyUp())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), historyUp);
EventHandler<? super KeyEvent> historyDown = EventHandlerHelper
.on(keyPressed(KeyCode.DOWN)).act(event -> historyDown())
.create();
EventHandlerHelper.install(outputArea.onKeyPressedProperty(), historyDown);
EventHandler<? super KeyEvent> charTyped = EventHandlerHelper
.on(keyTyped()).act(event -> typed(event))
.create();
EventHandlerHelper.install(outputArea.onKeyTypedProperty(), charTyped);
outputArea.caretPositionProperty().addListener((ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) -> {
caret(oldValue, newValue);
});
}
public static class BlockingPipedInputStream extends PipedInputStream {
boolean closed;
public BlockingPipedInputStream(PipedOutputStream pout)
throws IOException {
super(pout);
}
public synchronized int read() throws IOException {
if (closed) {
throw new IOException("stream closed");
}
while (super.in < 0) { // While no data */
notifyAll(); // Notify any writers to wake up
try {
wait(750);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
// This is what the superclass does.
int ret = buffer[super.out++] & 0xFF;
if (super.out >= buffer.length) {
super.out = 0;
}
if (super.in == super.out) {
super.in = -1;
/* now empty */
}
return ret;
}
public void close() throws IOException {
closed = true;
super.close();
}
}
}
| gpl-3.0 |
sklarman/grakn | grakn-factory/titan-factory/src/test/java/ai/grakn/factory/TitanInternalFactoryTest.java | 8366 | /*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.factory;
import ai.grakn.Grakn;
import ai.grakn.GraknTxType;
import ai.grakn.exception.GraknValidationException;
import ai.grakn.graph.internal.GraknTitanGraph;
import ai.grakn.util.Schema;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.schema.TitanManagement;
import com.thinkaurelius.titan.graphdb.database.StandardTitanGraph;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class TitanInternalFactoryTest extends TitanTestBase{
private static TitanGraph sharedGraph;
@BeforeClass
public static void setupClass() throws InterruptedException {
sharedGraph = titanGraphFactory.open(GraknTxType.WRITE).getTinkerPopGraph();
}
@Test
public void testGraphConfig() throws InterruptedException {
TitanManagement management = sharedGraph.openManagement();
//Test Composite Indices
String byId = "by" + Schema.ConceptProperty.ID.name();
String byIndex = "by" + Schema.ConceptProperty.INDEX.name();
String byValueString = "by" + Schema.ConceptProperty.VALUE_STRING.name();
String byValueLong = "by" + Schema.ConceptProperty.VALUE_LONG.name();
String byValueDouble = "by" + Schema.ConceptProperty.VALUE_DOUBLE.name();
String byValueBoolean = "by" + Schema.ConceptProperty.VALUE_BOOLEAN.name();
assertEquals(byId, management.getGraphIndex(byId).toString());
assertEquals(byIndex, management.getGraphIndex(byIndex).toString());
assertEquals(byValueString, management.getGraphIndex(byValueString).toString());
assertEquals(byValueLong, management.getGraphIndex(byValueLong).toString());
assertEquals(byValueDouble, management.getGraphIndex(byValueDouble).toString());
assertEquals(byValueBoolean, management.getGraphIndex(byValueBoolean).toString());
//Text Edge Indices
ResourceBundle keys = ResourceBundle.getBundle("indices-edges");
Set<String> keyString = keys.keySet();
for(String label : keyString){
assertNotNull(management.getEdgeLabel(label));
}
//Test Properties
Arrays.stream(Schema.ConceptProperty.values()).forEach(property ->
assertNotNull(management.getPropertyKey(property.name())));
Arrays.stream(Schema.EdgeProperty.values()).forEach(property ->
assertNotNull(management.getPropertyKey(property.name())));
//Test Labels
Arrays.stream(Schema.BaseType.values()).forEach(label -> assertNotNull(management.getVertexLabel(label.name())));
}
@Test
public void testSingleton(){
TitanInternalFactory factory = new TitanInternalFactory("anothertest", Grakn.IN_MEMORY, TEST_PROPERTIES);
GraknTitanGraph mg1 = factory.open(GraknTxType.BATCH);
mg1.close();
GraknTitanGraph mg2 = factory.open(GraknTxType.WRITE);
GraknTitanGraph mg3 = factory.open(GraknTxType.BATCH);
assertEquals(mg1, mg3);
assertEquals(mg1.getTinkerPopGraph(), mg3.getTinkerPopGraph());
assertTrue(mg1.isBatchLoadingEnabled());
assertFalse(mg2.isBatchLoadingEnabled());
assertNotEquals(mg1, mg2);
assertNotEquals(mg1.getTinkerPopGraph(), mg2.getTinkerPopGraph());
StandardTitanGraph standardTitanGraph1 = (StandardTitanGraph) mg1.getTinkerPopGraph();
StandardTitanGraph standardTitanGraph2 = (StandardTitanGraph) mg2.getTinkerPopGraph();
assertTrue(standardTitanGraph1.getConfiguration().isBatchLoading());
assertFalse(standardTitanGraph2.getConfiguration().isBatchLoading());
}
@Test
public void testBuildIndexedGraphWithCommit() throws Exception {
Graph graph = getGraph();
addConcepts(graph);
graph.tx().commit();
assertIndexCorrect(graph);
}
@Test
public void testBuildIndexedGraphWithoutCommit() throws Exception {
Graph graph = getGraph();
addConcepts(graph);
assertIndexCorrect(graph);
}
@Test
public void testMultithreadedRetrievalOfGraphs(){
Set<Future> futures = new HashSet<>();
ExecutorService pool = Executors.newFixedThreadPool(10);
TitanInternalFactory factory = new TitanInternalFactory("simplekeyspace", Grakn.IN_MEMORY, TEST_PROPERTIES);
for(int i = 0; i < 200; i ++) {
futures.add(pool.submit(() -> {
GraknTitanGraph graph = factory.open(GraknTxType.WRITE);
assertFalse("Grakn graph is closed", graph.isClosed());
assertFalse("Internal tinkerpop graph is closed", graph.getTinkerPopGraph().isClosed());
graph.putEntityType("A Thing");
try {
graph.close();
} catch (GraknValidationException e) {
e.printStackTrace();
}
}));
}
boolean exceptionThrown = false;
for (Future future: futures){
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
exceptionThrown = true;
}
assertFalse(exceptionThrown);
}
}
@Test
public void testGraphNotClosed() throws GraknValidationException {
TitanInternalFactory factory = new TitanInternalFactory("stuff", Grakn.IN_MEMORY, TEST_PROPERTIES);
GraknTitanGraph graph = factory.open(GraknTxType.WRITE);
assertFalse(graph.getTinkerPopGraph().isClosed());
graph.putEntityType("A Thing");
graph.close();
graph = factory.open(GraknTxType.WRITE);
assertFalse(graph.getTinkerPopGraph().isClosed());
graph.putEntityType("A Thing");
}
private static TitanGraph getGraph() {
String name = UUID.randomUUID().toString().replaceAll("-", "");
titanGraphFactory = new TitanInternalFactory(name, Grakn.IN_MEMORY, TEST_PROPERTIES);
Graph graph = titanGraphFactory.open(GraknTxType.WRITE).getTinkerPopGraph();
assertThat(graph, instanceOf(TitanGraph.class));
return (TitanGraph) graph;
}
private void addConcepts(Graph graph) {
Vertex vertex1 = graph.addVertex();
vertex1.property("ITEM_IDENTIFIER", "www.grakn.com/action-movie/");
vertex1.property(Schema.ConceptProperty.VALUE_STRING.name(), "hi there");
Vertex vertex2 = graph.addVertex();
vertex2.property(Schema.ConceptProperty.VALUE_STRING.name(), "hi there");
}
private void assertIndexCorrect(Graph graph) {
assertEquals(2, graph.traversal().V().has(Schema.ConceptProperty.VALUE_STRING.name(), "hi there").count().next().longValue());
assertFalse(graph.traversal().V().has(Schema.ConceptProperty.VALUE_STRING.name(), "hi").hasNext());
}
} | gpl-3.0 |
jfinkels/jmona | jmona-model/src/test/java/jmona/impl/mutation/ElementwiseMutationFunctionTester.java | 2667 | /**
* ElementwiseMutationFunctionTester.java
*
* Copyright 2009, 2010 Jeffrey Finkelstein
*
* This file is part of jmona.
*
* jmona 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.
*
* jmona 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
* jmona. If not, see <http://www.gnu.org/licenses/>.
*/
package jmona.impl.mutation;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.util.List;
import jmona.MutationFunction;
import jmona.impl.example.ExampleIndividual;
import jmona.impl.example.ExampleMutationFunction;
import org.junit.Test;
/**
* Test class for the ElementwiseMutationFunction class.
*
* @author Jeffrey Finkelstein
* @since 0.1
*/
public class ElementwiseMutationFunctionTester {
/** Zero. */
public static final double ZERO_DELTA = 0.0;
/**
* Test method for
* {@link jmona.impl.mutation.ElementwiseMutationFunction#setElementMutationFunction(jmona.MutationFunction)}
* .
*/
@Test
public void testSetElementMutationFunction() {
final ElementwiseMutationFunction<ExampleIndividual, List<ExampleIndividual>> function = new ElementwiseMutationFunction<ExampleIndividual, List<ExampleIndividual>>() {
@Override
public void mutate(final List<ExampleIndividual> object) {
// intentionally unimplemented
}
};
function.setElementMutationFunction(new ExampleMutationFunction());
}
/**
* Test method for
* {@link jmona.impl.mutation.ElementwiseMutationFunction#elementMutationFunction()}
* .
*/
@Test
public void testElementMutationFunction() {
final ElementwiseMutationFunction<ExampleIndividual, List<ExampleIndividual>> function = new ElementwiseMutationFunction<ExampleIndividual, List<ExampleIndividual>>() {
@Override
public void mutate(final List<ExampleIndividual> object) {
// intentionally unimplemented
}
};
assertNull(function.elementMutationFunction());
final MutationFunction<ExampleIndividual> elementMutationFunction = new ExampleMutationFunction();
function.setElementMutationFunction(elementMutationFunction);
assertSame(elementMutationFunction, function.elementMutationFunction());
}
}
| gpl-3.0 |
skurski/know-how | src/main/java/know/how/core/jrunner/multithreading/test/ThreadTutor2.java | 983 | package know.how.core.jrunner.multithreading.test;
import org.junit.Test;
public class ThreadTutor2 {
static StringBuffer buf = new StringBuffer();
static void log(String s) {
buf.append(s+"\n");
}
static class TestThread implements Runnable {
String threadName;
public TestThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i=0;i<100;i++) {
log(threadName+":"+i);
// Thread.yield();
}
}
}
@Test
public void testThread() throws InterruptedException {
Thread t1 =new Thread(new TestThread("t1"));
Thread t2 = new Thread(new TestThread("t2"));
System.out.println("Starting threads");
t2.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished");
System.out.println(buf);
}
}
| gpl-3.0 |
CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/PowbFinancialExpenditureManager.java | 2977 | /*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO 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.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.data.manager;
import org.cgiar.ccafs.marlo.data.model.PowbFinancialExpenditure;
import java.util.List;
/**
* @author Christian Garcia
*/
public interface PowbFinancialExpenditureManager {
/**
* This method removes a specific powbFinancialExpenditure value from the database.
*
* @param powbFinancialExpenditureId is the powbFinancialExpenditure identifier.
* @return true if the powbFinancialExpenditure was successfully deleted, false otherwise.
*/
public void deletePowbFinancialExpenditure(long powbFinancialExpenditureId);
/**
* This method validate if the powbFinancialExpenditure identify with the given id exists in the system.
*
* @param powbFinancialExpenditureID is a powbFinancialExpenditure identifier.
* @return true if the powbFinancialExpenditure exists, false otherwise.
*/
public boolean existPowbFinancialExpenditure(long powbFinancialExpenditureID);
/**
* This method gets a list of powbFinancialExpenditure that are active
*
* @return a list from PowbFinancialExpenditure null if no exist records
*/
public List<PowbFinancialExpenditure> findAll();
/**
* This method gets a powbFinancialExpenditure object by a given powbFinancialExpenditure identifier.
*
* @param powbFinancialExpenditureID is the powbFinancialExpenditure identifier.
* @return a PowbFinancialExpenditure object.
*/
public PowbFinancialExpenditure getPowbFinancialExpenditureById(long powbFinancialExpenditureID);
/**
* This method saves the information of the given powbFinancialExpenditure
*
* @param powbFinancialExpenditure - is the powbFinancialExpenditure object with the new information to be added/updated.
* @return a number greater than 0 representing the new ID assigned by the database, 0 if the powbFinancialExpenditure was
* updated
* or -1 is some error occurred.
*/
public PowbFinancialExpenditure savePowbFinancialExpenditure(PowbFinancialExpenditure powbFinancialExpenditure);
}
| gpl-3.0 |
clecoued/Aura_mobile_app | app/src/main/java/com/wearablesensor/aura/data_repository/models/PhysioSignalModel.java | 3875 | /**
* @file PhysioSignalModel.java
* @author clecoued <clement.lecouedic@aura.healthcare>
* @version 1.0
*
*
* @section LICENSE
*
* Aura Mobile Application
* Copyright (C) 2017 Aura Healthcare
*
* 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/>
*
* @section DESCRIPTION
*
* abstract data model for physiological sigmal sample
*/
package com.wearablesensor.aura.data_repository.models;
import java.util.UUID;
public class PhysioSignalModel {
protected String mUuid; // sample data uuid
protected String mDeviceAdress; // device adress uuid
protected String mUser; // user uuid
protected String mTimestamp; // timestamp formatted on Iso8601
protected String mType; // data type
protected PhysioSignalModel() {
}
protected PhysioSignalModel(String iDeviceAdress, String iTimestamp, String iType) {
mUuid = UUID.randomUUID().toString();
mDeviceAdress = iDeviceAdress;
mUser = null;
mTimestamp = iTimestamp;
mType = iType;
}
protected PhysioSignalModel(String iUuid, String iDeviceAdress, String iUser, String iTimestamp, String iType) {
mUuid = iUuid;
mDeviceAdress = iDeviceAdress;
mUser = iUser;
mTimestamp = iTimestamp;
mType = iType;
}
public String getUuid(){
return mUuid;
}
public void setUuid(String iUuid){
mUuid = iUuid;
}
public String getDeviceAdress(){
return mDeviceAdress;
}
public void setDeviceAdress(String iDeviceAdress){
mDeviceAdress = iDeviceAdress;
}
public String getUser(){
return mUser;
}
public void setUser(String iUser){
mUser = iUser;
}
public String getTimestamp(){
return mTimestamp;
}
public void setTimestamp(String iTimestamp){
mTimestamp = iTimestamp;
}
public String getType(){
return mType;
}
public void setType(String iType){
mType = iType;
}
@Override
public String toString(){
return mTimestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PhysioSignalModel that = (PhysioSignalModel) o;
if (mUuid != null ? !mUuid.equals(that.mUuid) : that.mUuid != null) return false;
if (mDeviceAdress != null ? !mDeviceAdress.equals(that.mDeviceAdress) : that.mDeviceAdress != null)
return false;
if (mUser != null ? !mUser.equals(that.mUser) : that.mUser != null) return false;
if (mTimestamp != null ? !mTimestamp.equals(that.mTimestamp) : that.mTimestamp != null)
return false;
return mType != null ? mType.equals(that.mType) : that.mType == null;
}
@Override
public int hashCode() {
int result = mUuid != null ? mUuid.hashCode() : 0;
result = 31 * result + (mDeviceAdress != null ? mDeviceAdress.hashCode() : 0);
result = 31 * result + (mUser != null ? mUser.hashCode() : 0);
result = 31 * result + (mTimestamp != null ? mTimestamp.hashCode() : 0);
result = 31 * result + (mType != null ? mType.hashCode() : 0);
return result;
}
} | gpl-3.0 |
seijikun/POL-POM-5 | src/main/java/com/playonlinux/ui/impl/javafx/setupwindow/StepRepresentationMenu.java | 2120 | /*
* Copyright (C) 2015 PÂRIS Quentin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.playonlinux.ui.impl.javafx.setupwindow;
import com.playonlinux.core.messages.CancelerSynchronousMessage;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import java.util.List;
public class StepRepresentationMenu extends StepRepresentationMessage {
final List<String> menuItems;
final ListView<String> listViewWidget;
public StepRepresentationMenu(SetupWindowJavaFXImplementation parent, CancelerSynchronousMessage messageWaitingForResponse, String textToShow,
List<String> menuItems) {
super(parent, messageWaitingForResponse, textToShow);
this.menuItems = menuItems;
this.listViewWidget = new ListView<>();
}
@Override
protected void drawStepContent() {
super.drawStepContent();
listViewWidget.setItems(FXCollections.observableArrayList(menuItems));
listViewWidget.setLayoutX(10);
listViewWidget.setLayoutY(40);
listViewWidget.setPrefSize(500, 240);
this.addToContentPanel(listViewWidget);
}
@Override
protected void setStepEvents() {
this.setNextButtonAction(event ->
((CancelerSynchronousMessage) this.getMessageAwaitingForResponse()).
setResponse(listViewWidget.getFocusModel().getFocusedItem())
);
}
}
| gpl-3.0 |
sblit/sblit | src/net/sblit/configuration/KeyConfiguration.java | 1427 | package net.sblit.configuration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import net.sblit.crypto.SymmetricEncryption;
public class KeyConfiguration {
public static final String KEY_CONFIGURATION_FILE = "/symmetricKey.txt";
private String configurationFile;
private byte[] key;
private String os;
public KeyConfiguration(String configurationDirectory, String os) {
this.os = os;
configurationFile = configurationDirectory + KEY_CONFIGURATION_FILE;
if (new File(configurationFile).exists()) {
try {
key = Files.readAllBytes(Paths.get(configurationFile));
} catch (IOException e) {
e.printStackTrace();
}
} else {
key = SymmetricEncryption.generateKey();
saveKey(key);
}
}
public byte[] getKey() {
return key;
}
private void saveKey(byte[] key) {
File f = new File(configurationFile);
try {
f.createNewFile();
if (os.contains("Windows"))
Runtime.getRuntime()
.exec("attrib +H "
+ new File(configurationFile).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(f);
fos.write(key);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void setKey(byte[] key) {
this.key = key;
File f = new File(configurationFile);
f.delete();
saveKey(key);
}
}
| gpl-3.0 |
andrewpaterson/Foxy | src/net/engine/cel/CelStore.java | 525 | package net.engine.cel;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CelStore
{
private Map<String, List<Cel>> cels;
public CelStore()
{
cels = new LinkedHashMap<>();
}
public List<Cel> get(String name)
{
return cels.get(name);
}
public void addCels(String name, List<Cel> cels)
{
List<Cel> storedCelHelper = this.cels.get(name);
if (storedCelHelper == null)
{
this.cels.put(name, cels);
}
}
}
| gpl-3.0 |
danielhams/mad-java | 1PROJECTS/COMPONENTDESIGNER/component-designer-test/src/test/uk/co/modularaudio/service/ioandrendering/TestSubRackDestruction.java | 3842 | /**
*
* Copyright (C) 2015 - Daniel Hams, Modular Audio Limited
* daniel.hams@gmail.com
*
* Mad 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.
*
* Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package test.uk.co.modularaudio.service.ioandrendering;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.support.GenericApplicationContext;
import test.uk.co.modularaudio.service.TestConstants;
import uk.co.modularaudio.componentdesigner.ComponentDesigner;
import uk.co.modularaudio.componentdesigner.controller.front.ComponentDesignerFrontController;
import uk.co.modularaudio.mads.subrack.mu.SubRackMadDefinition;
import uk.co.modularaudio.service.madcomponent.MadComponentService;
import uk.co.modularaudio.service.rack.RackService;
import uk.co.modularaudio.util.audio.gui.mad.rack.RackDataModel;
import uk.co.modularaudio.util.audio.mad.MadDefinition;
import uk.co.modularaudio.util.audio.mad.MadParameterDefinition;
public class TestSubRackDestruction
{
// private static Log log = LogFactory.getLog( TestSubRackDestruction.class.getName() );
private final ComponentDesigner componentDesigner;
private GenericApplicationContext applicationContext;
private ComponentDesignerFrontController componentDesignerFrontController;
// private RenderingController renderingController;
// private UserPreferencesController userPreferencesController;
// private RackController rackController;
private RackService rackService;
// private GraphService graphService;
private MadComponentService componentService;
public TestSubRackDestruction()
{
componentDesigner = new ComponentDesigner();
}
public void go() throws Exception
{
componentDesigner.setupApplicationContext( TestConstants.CDTEST_PROPERTIES,
null, null,
true, true );
applicationContext = componentDesigner.getApplicationContext();
// Grab the necessary controller references
componentDesignerFrontController = applicationContext.getBean( ComponentDesignerFrontController.class );
// renderingController = applicationContext.getBean( RenderingController.class );
// userPreferencesController = applicationContext.getBean( UserPreferencesController.class );
// rackController = applicationContext.getBean( RackController.class );
rackService = applicationContext.getBean( RackService.class );
// graphService = applicationContext.getBean( GraphService.class );
componentService = applicationContext.getBean( MadComponentService.class );
final RackDataModel rootRack = rackService.createNewRackDataModel( "Root Rack", "", 16, 16, true );
final MadDefinition<?,?> subRackDef = componentService.findDefinitionById( SubRackMadDefinition.DEFINITION_ID );
final Map<MadParameterDefinition,String> emptyParamValues = new HashMap<MadParameterDefinition,String>();
rackService.createComponent( rootRack, subRackDef, emptyParamValues, "Sub Rack" );
rackService.dumpRack( rootRack );
rackService.destroyRackDataModel( rootRack );
// Do stuff
componentDesignerFrontController.ensureRenderingStoppedBeforeExit();
componentDesigner.destroyApplicationContext();
}
/**
* @param args
*/
public static void main( final String[] args )
throws Exception
{
final TestSubRackDestruction tester = new TestSubRackDestruction();
tester.go();
}
}
| gpl-3.0 |
mrlolethan/Buttered-Pixel-Dungeon | src/com/mrlolethan/butteredpd/sprites/ItemSpriteSheet.java | 9920 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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.mrlolethan.butteredpd.sprites;
public class ItemSpriteSheet {
// Row definers
private static final int ROW1 = 0*16;
private static final int ROW2 = 1*16;
private static final int ROW3 = 2*16;
private static final int ROW4 = 3*16;
private static final int ROW5 = 4*16;
private static final int ROW6 = 5*16;
private static final int ROW7 = 6*16;
private static final int ROW8 = 7*16;
private static final int ROW9 = 8*16;
private static final int ROW10 = 9*16;
private static final int ROW11 = 10*16;
private static final int ROW12 = 11*16;
private static final int ROW13 = 12*16;
private static final int ROW14 = 13*16;
private static final int ROW15 = 14*16;
private static final int ROW16 = 15*16;
//Row One: Items which can't be obtained
//null warning occupies space 0, should only show up if there's a bug.
public static final int NULLWARN = ROW1+0;
public static final int DEWDROP = ROW1+1;
public static final int PETAL = ROW1+2;
public static final int SANDBAG = ROW1+3;
// Heaps (containers)
public static final int BONES = ROW1+4;
public static final int REMAINS = ROW1+5;
public static final int TOMB = ROW1+6;
public static final int GRAVE = ROW1+7;
public static final int CHEST = ROW1+8;
public static final int LOCKED_CHEST = ROW1+9;
public static final int CRYSTAL_CHEST = ROW1+10;
// Placeholders
public static final int WEAPON = ROW1+11;
public static final int ARMOR = ROW1+12;
public static final int RING = ROW1+13;
public static final int SMTH = ROW1+14;
//Row Two: Miscellaneous single use items
public static final int GOLD = ROW2+0;
public static final int TORCH = ROW2+1;
public static final int STYLUS = ROW2+2;
public static final int ANKH = ROW2+3;
// Keys
public static final int IRON_KEY = ROW2+4;
public static final int GOLDEN_KEY = ROW2+5;
public static final int SKELETON_KEY = ROW2+6;
//Boss Rewards
public static final int BEACON = ROW2+7;
public static final int MASTERY = ROW2+8;
public static final int KIT = ROW2+9;
public static final int AMULET = ROW2+10;
public static final int WEIGHT = ROW2+11;
public static final int BOMB = ROW2+12;
public static final int DBL_BOMB= ROW2+13;
public static final int HONEYPOT= ROW2+14;
public static final int SHATTPOT= ROW2+15;
//Row Three: Melee weapons
public static final int KNUCKLEDUSTER = ROW3+0;
public static final int DAGGER = ROW3+1;
public static final int SHORT_SWORD = ROW3+2;
public static final int MAGES_STAFF = ROW3+3;
public static final int QUARTERSTAFF = ROW3+4;
public static final int SPEAR = ROW3+5;
public static final int MACE = ROW3+6;
public static final int SWORD = ROW3+7;
public static final int BATTLE_AXE = ROW3+8;
public static final int LONG_SWORD = ROW3+9;
public static final int WAR_HAMMER = ROW3+10;
public static final int GLAIVE = ROW3+11;
//Row Four: Missile weapons
public static final int DART = ROW4+0;
public static final int BOOMERANG = ROW4+1;
public static final int INCENDIARY_DART = ROW4+2;
public static final int SHURIKEN = ROW4+3;
public static final int CURARE_DART = ROW4+4;
public static final int JAVELIN = ROW4+5;
public static final int TOMAHAWK = ROW4+6;
//Row Five: Armors
public static final int ARMOR_CLOTH = ROW5+0;
public static final int ARMOR_LEATHER = ROW5+1;
public static final int ARMOR_MAIL = ROW5+2;
public static final int ARMOR_SCALE = ROW5+3;
public static final int ARMOR_PLATE = ROW5+4;
public static final int ARMOR_WARRIOR = ROW5+5;
public static final int ARMOR_MAGE = ROW5+6;
public static final int ARMOR_ROGUE = ROW5+7;
public static final int ARMOR_HUNTRESS = ROW5+8;
//Row Six: Wands
public static final int WAND_MAGIC_MISSILE = ROW6+0;
public static final int WAND_FIREBOLT = ROW6+1;
public static final int WAND_FROST = ROW6+2;
public static final int WAND_LIGHTNING = ROW6+3;
public static final int WAND_DISINTEGRATION = ROW6+4;
public static final int WAND_PRISMATIC_LIGHT= ROW6+5;
public static final int WAND_VENOM = ROW6+6;
public static final int WAND_LIVING_EARTH = ROW6+7;
public static final int WAND_BLAST_WAVE = ROW6+8;
public static final int WAND_CORRUPTION = ROW6+9;
public static final int WAND_WARDING = ROW6+10;
public static final int WAND_REGROWTH = ROW6+11;
public static final int WAND_TRANSFUSION = ROW6+12;
//Row Seven: Rings
public static final int RING_GARNET = ROW7+0;
public static final int RING_RUBY = ROW7+1;
public static final int RING_TOPAZ = ROW7+2;
public static final int RING_EMERALD = ROW7+3;
public static final int RING_ONYX = ROW7+4;
public static final int RING_OPAL = ROW7+5;
public static final int RING_TOURMALINE = ROW7+6;
public static final int RING_SAPPHIRE = ROW7+7;
public static final int RING_AMETHYST = ROW7+8;
public static final int RING_QUARTZ = ROW7+9;
public static final int RING_AGATE = ROW7+10;
public static final int RING_DIAMOND = ROW7+11;
//Row Eight: Artifacts with Static Images
public static final int ARTIFACT_CLOAK = ROW8+0;
public static final int ARTIFACT_ARMBAND = ROW8+1;
public static final int ARTIFACT_CAPE = ROW8+2;
public static final int ARTIFACT_TALISMAN = ROW8+3;
public static final int ARTIFACT_HOURGLASS = ROW8+4;
public static final int ARTIFACT_TOOLKIT = ROW8+5;
public static final int ARTIFACT_SPELLBOOK = ROW8+6;
public static final int ARTIFACT_BEACON = ROW8+7;
public static final int ARTIFACT_CHAINS = ROW8+8;
//Row Nine: Artifacts with Dynamic Images
public static final int ARTIFACT_HORN1 = ROW9+0;
public static final int ARTIFACT_HORN2 = ROW9+1;
public static final int ARTIFACT_HORN3 = ROW9+2;
public static final int ARTIFACT_HORN4 = ROW9+3;
public static final int ARTIFACT_CHALICE1 = ROW9+4;
public static final int ARTIFACT_CHALICE2 = ROW9+5;
public static final int ARTIFACT_CHALICE3 = ROW9+6;
public static final int ARTIFACT_SANDALS = ROW9+7;
public static final int ARTIFACT_SHOES = ROW9+8;
public static final int ARTIFACT_BOOTS = ROW9+9;
public static final int ARTIFACT_GREAVES = ROW9+10;
public static final int ARTIFACT_ROSE1 = ROW9+11;
public static final int ARTIFACT_ROSE2 = ROW9+12;
public static final int ARTIFACT_ROSE3 = ROW9+13;
//Row Ten: Scrolls
public static final int SCROLL_KAUNAN = ROW10+0;
public static final int SCROLL_SOWILO = ROW10+1;
public static final int SCROLL_LAGUZ = ROW10+2;
public static final int SCROLL_YNGVI = ROW10+3;
public static final int SCROLL_GYFU = ROW10+4;
public static final int SCROLL_RAIDO = ROW10+5;
public static final int SCROLL_ISAZ = ROW10+6;
public static final int SCROLL_MANNAZ = ROW10+7;
public static final int SCROLL_NAUDIZ = ROW10+8;
public static final int SCROLL_BERKANAN = ROW10+9;
public static final int SCROLL_ODAL = ROW10+10;
public static final int SCROLL_TIWAZ = ROW10+11;
//Row Eleven: Potions
public static final int POTION_CRIMSON = ROW11+0;
public static final int POTION_AMBER = ROW11+1;
public static final int POTION_GOLDEN = ROW11+2;
public static final int POTION_JADE = ROW11+3;
public static final int POTION_TURQUOISE = ROW11+4;
public static final int POTION_AZURE = ROW11+5;
public static final int POTION_INDIGO = ROW11+6;
public static final int POTION_MAGENTA = ROW11+7;
public static final int POTION_BISTRE = ROW11+8;
public static final int POTION_CHARCOAL = ROW11+9;
public static final int POTION_SILVER = ROW11+10;
public static final int POTION_IVORY = ROW11+11;
//Row Twelve: Seeds
public static final int SEED_ROTBERRY = ROW12+0;
public static final int SEED_FIREBLOOM = ROW12+1;
public static final int SEED_STARFLOWER = ROW12+2;
public static final int SEED_BLINDWEED = ROW12+3;
public static final int SEED_SUNGRASS = ROW12+4;
public static final int SEED_ICECAP = ROW12+5;
public static final int SEED_STORMVINE = ROW12+6;
public static final int SEED_SORROWMOSS = ROW12+7;
public static final int SEED_DREAMFOIL = ROW12+8;
public static final int SEED_EARTHROOT = ROW12+9;
public static final int SEED_FADELEAF = ROW12+10;
public static final int SEED_BLANDFRUIT = ROW12+11;
//Row Thirteen: Food
public static final int MEAT = ROW13+0;
public static final int STEAK = ROW13+1;
public static final int OVERPRICED = ROW13+2;
public static final int CARPACCIO = ROW13+3;
public static final int BLANDFRUIT = ROW13+4;
public static final int RATION = ROW13+5;
public static final int PASTY = ROW13+6;
//Row Fourteen: Quest Items
public static final int SKULL = ROW14+0;
public static final int DUST = ROW14+1;
public static final int PICKAXE = ROW14+2;
public static final int ORE = ROW14+3;
public static final int TOKEN = ROW14+4;
//Row Fifteen: Containers/Bags
public static final int VIAL = ROW15+0;
public static final int POUCH = ROW15+1;
public static final int HOLDER = ROW15+2;
public static final int BANDOLIER = ROW15+3;
public static final int HOLSTER = ROW15+4;
//Row Sixteen: Unused
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_caption_Choice117.java | 830 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Content_caption_Choice117 extends Content_caption_Choice1 {
public Content_caption_Choice117(Element_code element_code, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<Element_code>("element_code", element_code)
}, firstToken, lastToken);
}
public Content_caption_Choice117(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new Content_caption_Choice117(cloneProperties(),firstToken,lastToken);
}
public Element_code getElement_code() {
return ((PropertyOne<Element_code>)getProperty("element_code")).getValue();
}
}
| gpl-3.0 |
GeorgH93/Bukkit_MarriageMaster | MarriageMaster-API/src/at/pcgamingfreaks/MarriageMaster/API/MarriagePlayer.java | 7766 | /*
* Copyright (C) 2020 GeorgH93
*
* 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 at.pcgamingfreaks.MarriageMaster.API;
import at.pcgamingfreaks.Message.IMessage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
public interface MarriagePlayer<MARRIAGE extends Marriage, MARRIAGE_PLAYER extends MarriagePlayer, PLAYER, MESSAGE extends IMessage>
{
/**
* Gets the Bukkit offline player that is represented by this marriage player data.
*
* @return The Bukkit player represented by this marriage player.
*/
@NotNull PLAYER getPlayer();
/**
* Gets the name of the player represented by this marriage player data.
*
* @return The name of the player represented by this marriage player.
*/
@NotNull String getName();
/**
* Gets the UUID of the player.
*
* @return The UUID of the player.
*/
@NotNull UUID getUUID();
/**
* Checks if the player is online.
*
* @return True if the player is online, false if not.
*/
boolean isOnline();
/**
* Gets the display name of the player represented by this marriage player data.
*
* @return The display name of the player represented by this marriage player.
*/
@NotNull String getDisplayName();
/**
* Checks if a player has a certain permission.
*
* @param permission The permission to check.
* @return True if the player has the permission. False if not.
*/
boolean hasPermission(@NotNull String permission);
/**
* Checks if the represented player is a priest.
* If the player is online the check will include the players permissions (Permissions.PRIEST permission).
* If the player is offline only the database will be checked.
*
* @return True if the player is a priest. False if not.
*/
boolean isPriest();
void setPriest(boolean set);
/**
* Checks if the player is sharing his backpack with his partner.
*
* @return True if the player is sharing the backpack. False if not.
*/
boolean isSharingBackpack();
/**
* Sets the sharing status of the players backpack.
*
* @param share True if the backpack should be shared. False if not.
*/
void setShareBackpack(boolean share);
/**
* Checks if the player has set his private marry chat as default chat.
* This method is thread safe!
*
* @return True when messages written in the chat will be used as private messages. False if not.
*/
boolean isPrivateChatDefault();
/**
* Sets how chat messages get treated.
* This method is thread safe!
*
* @param enable True if chat messages should be treated as private messages. False if not.
*/
void setPrivateChatDefault(boolean enable);
/**
* Gets the partner that should receive the private message.
* This method is thread safe!
*
* @return Returns the marriage for the targeted partner.
*/
@Nullable MARRIAGE getPrivateChatTarget();
/**
* Allows to change the target of private messages (when multi partner marriage is enabled).
* This method is thread safe!
*
* @param target The target which should receive the private messages in the future.
*/
void setPrivateChatTarget(@Nullable MARRIAGE_PLAYER target);
/**
* Allows to change the target of private messages (when multi partner marriage is enabled).
* This method is thread safe!
*
* @param target The target which should receive the private messages in the future.
*/
void setPrivateChatTarget(@Nullable MARRIAGE target);
/**
* Checks if a player is married.
*
* @return True if the player is married. False if not.
*/
boolean isMarried();
/**
* Checks if the player is married with a given player.
*
* @param player The player to be checked.
* @return True if they are married. False if not.
*/
boolean isPartner(@NotNull PLAYER player);
/**
* Checks if the player is married with a given player.
*
* @param player The player to be checked.
* @return True if they are married. False if not.
*/
boolean isPartner(@NotNull MARRIAGE_PLAYER player);
/**
* Gets the partner of the player.
* If multi marriage is enabled this will deliver 1 partner. If you need all of his partners use the getPartners function.
*
* @return The partner of the player. null if not married.
*/
@Nullable MARRIAGE_PLAYER getPartner();
/**
* Gets the partner of the player from his name.
*
* @param name The name of the partner to be retrieved.
* @return The partner of the player. null if not married.
*/
@Nullable MARRIAGE_PLAYER getPartner(String name);
/**
* Gets the partner of the player from his uuid.
*
* @param uuid The UUID of the partner to be retrieved.
* @return The partner of the player. null if not married.
*/
@Nullable MARRIAGE_PLAYER getPartner(UUID uuid);
/**
* Gets the marriage data for the player.
*
* @return The marriage data of the player. null if he is not married.
*/
@Nullable MARRIAGE getMarriageData();
/**
* Gets all the partners of the player.
* If multi marriage is not enabled this will also return the partner of the player.
*
* @return A {@link Collection} containing all partners of a player. Empty list if not married.
*/
@NotNull Collection<? extends MARRIAGE_PLAYER> getPartners();
/**
* Gets the marriage data for all of the players partners.
* If multi marriage is not enabled this will also return the marriage data for the player.
*
* @return A {@link Collection} containing the marriage data of the player for all his partners. Empty list if not married.
*/
@NotNull Collection<? extends MARRIAGE> getMultiMarriageData();
/**
* Checks if the player is married with the other player and returns the corresponding marriage data if they are.
*
* @param player The player the marriage should get for.
* @return The marriage data for this partner. null if not married with this player.
*/
@Nullable MARRIAGE getMarriageData(@NotNull MARRIAGE_PLAYER player);
/**
* Gets the partners of the player matching a given string.
*
* @param namePart Part of the partners name. Null to get all.
* @return The partners matching the given string.
*/
@NotNull List<String> getMatchingPartnerNames(@Nullable String namePart);
/**
* Gets a list of all the players partners that are currently online.
*
* @return List of all online partners.
*/
default @NotNull Collection<? extends MARRIAGE_PLAYER> getOnlinePartners()
{
List<MARRIAGE_PLAYER> onlinePartners = new LinkedList<>();
getPartners().forEach(partner -> { if(partner.isOnline()) onlinePartners.add(partner); });
return onlinePartners;
}
/**
* Sends a message to the player.
*
* @param message The message to be sent to the player.
* @param args The arguments for the placeholders of the message.
*/
void send(@NotNull MESSAGE message, @Nullable Object... args);
/**
* Sends a message to the player.
*
* @param message The message to be sent to the player.
* @param args The arguments for the placeholders of the message.
*/
void sendMessage(@NotNull MESSAGE message, @Nullable Object... args);
} | gpl-3.0 |
jub77/grafikon | grafikon-gui/src/main/java/net/parostroj/timetable/gui/views/ColorTextPane.java | 725 | package net.parostroj.timetable.gui.views;
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.*;
/**
* Colored text pane.
*
* @author jub
*/
public class ColorTextPane extends JTextPane {
private static final long serialVersionUID = 1L;
public void append(Color c, String s) {
setEditable(true);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
int len = getDocument().getLength();
setCaretPosition(len);
setCharacterAttributes(aset, false);
replaceSelection(s);
setCaretPosition(0);
setEditable(false);
}
}
| gpl-3.0 |
igd-geo/slf4j-plus | de.fhg.igd.slf4jplus.ui.errorlog/src/de/fhg/igd/slf4jplus/ui/errorlog/CustomMultiStatus.java | 2111 | // Fraunhofer Institute for Computer Graphics Research (IGD)
// Department Graphical Information Systems (GIS)
//
// Copyright (c) 2015 Fraunhofer IGD
//
// This file is part of slf4j-plus.
//
// slf4j-plus is free software: you can redistribute
// it and/or modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// slf4j-plus is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with slf4j-plus.
// If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.slf4jplus.ui.errorlog;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* MultiStatus that allows setting all its children at once.
*
* @author Simon Templer
*/
public class CustomMultiStatus extends Status {
private IStatus[] children;
/**
* Create a multi-status.
*
* @param pluginId the unique identifier of the relevant plug-in
* @param code the plug-in-specific status code, or <code>OK</code>
* @param message a human-readable message, localized to the
* current locale
* @param exception a low-level exception, or <code>null</code> if not
* applicable
*/
public CustomMultiStatus(String pluginId, int code,
String message, Throwable exception) {
super(OK, pluginId, code, message, exception);
}
/**
* Set the given status array as the status' children
*
* @param children the children to set
*/
public void setChildren(IStatus[] children) {
this.children = children;
for (IStatus child : children) {
if (child.getSeverity() > getSeverity()) {
setSeverity(child.getSeverity());
}
}
}
@Override
public IStatus[] getChildren() {
return children;
}
@Override
public boolean isMultiStatus() {
return true;
}
}
| gpl-3.0 |
5GSD/AIMSICDL | AIMSICD/src/main/java/zz/aimsicd/lite/receiver/BootCompletedReceiver.java | 1232 | /* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project
* -----------------------------------------------------------
* LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o
* -----------------------------------------------------------
*/
package zz.aimsicd.lite.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import zz.aimsicd.lite.R;
import zz.aimsicd.lite.service.AimsicdService;
public class BootCompletedReceiver extends BroadcastReceiver {
public static final String TAG = "AICDL";
public static final String mTAG = "XXX";
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences(
AimsicdService.SHARED_PREFERENCES_BASENAME, 0);
final String AUTO_START = context.getString(R.string.pref_autostart_key);
boolean mAutoStart = prefs.getBoolean(AUTO_START, false);
if (mAutoStart) {
Log.i(TAG, mTAG + "System booted starting service.");
context.startService(new Intent(context, AimsicdService.class));
}
}
}
| gpl-3.0 |
NJU-HouseWang/nju-eas-client | src/main/java/NJU/HouseWang/nju_eas_client/ui/MainUI/DeptADUI/DeptCoursePanel.java | 4134 | package NJU.HouseWang.nju_eas_client.ui.MainUI.DeptADUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.Bar.FunctionBar;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.Button.FunctionBtn;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.Button.RefreshBtn;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.ComboBox.GradeBox;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.Panel.SubPanel;
import NJU.HouseWang.nju_eas_client.ui.CommonUI.Table.CommonTable;
import NJU.HouseWang.nju_eas_client.ui.MainUI.ExportUI.ExportUI;
import NJU.HouseWang.nju_eas_client.uiLogic.DeptADUILogic;
import NJU.HouseWang.nju_eas_client.vo.Feedback;
public class DeptCoursePanel extends JPanel {
private DeptADUILogic logic = new DeptADUILogic();
private FunctionBar fbar = new FunctionBar();
private FunctionBtn[] fBtn = new FunctionBtn[2];
private SubPanel coup = new SubPanel("本院课程列表", 940, 480);
private GradeBox gradeChooser = new GradeBox();
private RefreshBtn refreshBtn = new RefreshBtn();
private DefaultTableModel dtm = new DefaultTableModel(40, 5);
private CommonTable table = new CommonTable(dtm);
private String[] head = null;
private String[][] content = null;
public DeptCoursePanel() {
setLayout(null);
setBackground(Color.white);
fbar.setLocation(0, 0);
fBtn[0] = new FunctionBtn("ModifyBtn");
fBtn[1] = new FunctionBtn("ExportBtn");
for (int i = 0; i < fBtn.length; i++) {
fbar.add(fBtn[i]);
}
add(fbar);
coup.setLocation(30, 70);
gradeChooser.setPreferredSize(new Dimension(120, 20));
gradeChooser.setFont(new Font("微软雅黑", Font.BOLD, 14));
coup.getTopPanel().add(gradeChooser);
refreshBtn.setPreferredSize(new Dimension(24, 24));
coup.getTopPanel().add(refreshBtn);
DefaultTableCellRenderer r = new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Object.class, r);
coup.getCenterPanel().setLayout(new BorderLayout());
coup.getCenterPanel().add(new JScrollPane(table), BorderLayout.CENTER);
add(coup);
setListener();
}
private void setListener() {
refreshBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showTable();
}
});
fBtn[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectRowNum = table.getSelectedRow();
if (table.getSelectedRowCount() == 1 && selectRowNum != -1) {
String[] origin = new String[table.getColumnCount()];
for (int i = 0; i < origin.length; i++) {
origin[i] = (String) table.getValueAt(selectRowNum, i);
}
new EditCourseUI("课程", head, origin);
} else {
JOptionPane.showMessageDialog(null,
Feedback.SELECTION_ERROR.getContent());
}
}
});
fBtn[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ExportUI(head, content);
}
});
}
private void showTable() {
head = null;
content = null;
table.clearSelection();
dtm = new DefaultTableModel(0, 5);
table.setModel(dtm);
table.updateUI();
Object fb = logic.showCourseListHead();
if (fb instanceof Feedback) {
JOptionPane.showMessageDialog(null, ((Feedback) fb).getContent());
} else if (fb instanceof String[]) {
head = (String[]) fb;
fb = logic.showCourseListContent((String) gradeChooser
.getSelectedItem());
if (fb instanceof Feedback) {
JOptionPane.showMessageDialog(null,
((Feedback) fb).getContent());
} else if (fb instanceof String[][]) {
content = (String[][]) fb;
}
}
dtm.setDataVector(content, head);
table.updateUI();
}
} | gpl-3.0 |
AvaPirA/uber-snake | src/com/avapir/snake/Actors/NPC/Seed.java | 2577 | package com.avapir.snake.Actors.NPC;
import java.awt.Graphics;
import com.avapir.snake.Actors.CellElement;
import com.avapir.snake.Actors.Updater;
import com.avapir.snake.Actors.PC.Snake;
import com.avapir.snake.Core.Core;
import com.avapir.snake.Core.Painter;
import com.avapir.snake.UI.Objects.Sprite;
/**
* Objects of this class creates randomly as food.<br>
* Then some was gathered it will appear as snake`s (who got this {@link Seed})
* {@link Snake#weapon}
*
* @author Alpen Ditrix
*/
public class Seed extends CellElement {
/**
* Types of {@link Seed}
*
* @author Alpen Ditrix
*/
public enum SeedType {
/**
* Player will be able to install wall in few seconds at requested
* place.
*/
WALL,
/**
* It will explode at requested place
*/
BOMB
}
private SeedType type;
private int power;
private static Sprite bomb = new Sprite("/img/cells/bomb-seed.png", 0, 0);
/**
* How much seeds already at field
*/
private static int seedsCounter;
private static final int MAX_SEEDS = CellElement.SIZE_HORIZONTAL
* CellElement.SIZE_VERTICAL / 512;
/**
* On every {@link Updater}`s cycle it gives a chance to spawn yet one, or
* maybe few seeds (but less than {@link CellElement#SIZE_HORIZONTAL}*@link
* {@link CellElement#SIZE_VERTICAL}/512)<br>
* Chance to appear at least something at one time is 1%
*/
public static void tryToSpawn() {
int max = MAX_SEEDS - seedsCounter;
if (max > -1) {
int chances = Core.r.nextInt(5);
for (; chances < 5; chances++) {
int res = Core.r.nextInt(10000);
if (res > 9900) {
res -= 9900;
int[] o = CellElement.randomEmptyXandY();
if (res < 30) {
new Seed(SeedType.BOMB, o[0], o[1]);
} else if (res < 100) {
new Seed(SeedType.WALL, o[0], o[1]);
}
}
}
}
}
/**
* Creates new seed and locates it on field
*
* @param t
* type
* @param x
* @param y
*/
public Seed(SeedType t, int x, int y) {
super(x, y, false);
type = t;
power = Core.r.nextInt(50) + Core.r.nextInt(50);
seedsCounter++;
}
@Override
public void draw(Graphics g) {
int x = this.x * CELL_SIZE;
int y = this.y * CELL_SIZE + Painter.getTopPanelHeight();
switch (type) {
case BOMB:
bomb.draw(g, x, y);
}
}
/**
* @return {@link #power}
*/
public int getPower() {
return power;
}
/**
* @return type of this {@link Seed}
*/
public SeedType getType() {
return type;
}
}
| gpl-3.0 |
rcgroot/open-gpstracker | studio/app/src/androidTest/java/nl/sogeti/android/gpstracker/tests/demo/OpenGPSTrackerDemo.java | 9825 | /*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.demo;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver;
import nl.sogeti.android.gpstracker.viewer.LoggerMap;
/**
* @author rene (c) Jan 22, 2009, Sogeti B.V.
* @version $Id$
*/
public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<LoggerMap> {
private static final int ZOOM_LEVEL = 16;
private static final Class<LoggerMap> CLASS = LoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private LoggerMap mLoggermap;
private MapView mMapView;
private MockGPSLoggerDriver mSender;
public OpenGPSTrackerDemo() {
super(PACKAGE, CLASS);
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.mLoggermap = getActivity();
this.mMapView = (MapView) this.mLoggermap.findViewById(nl.sogeti.android.gpstracker.R.id.myMapView);
this.mSender = new MockGPSLoggerDriver();
}
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Start tracking and allow it to go on for 30 seconds
*
* @throws InterruptedException
*/
@LargeTest
public void testTracking() throws InterruptedException {
a_introSingelUtrecht30Seconds();
c_startRoute10Seconds();
d_showDrawMethods30seconds();
e_statistics10Seconds();
f_showPrecision30seconds();
g_stopTracking10Seconds();
h_shareTrack30Seconds();
i_finish10Seconds();
}
@SmallTest
public void a_introSingelUtrecht30Seconds() throws InterruptedException {
this.mMapView.getController().setZoom(ZOOM_LEVEL);
Thread.sleep(1 * 1000);
// Browse the Utrecht map
sendMessage("Selecting a previous recorded track");
Thread.sleep(1 * 1000);
this.sendKeys("MENU DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("L");
Thread.sleep(2 * 1000);
sendMessage("The walk around the \"singel\" in Utrecht");
this.sendKeys("DPAD_CENTER");
Thread.sleep(2 * 1000);
Thread.sleep(2 * 1000);
sendMessage("Scrolling about");
this.mMapView.getController().animateTo(new GeoPoint(52095829, 5118599));
Thread.sleep(2 * 1000);
this.mMapView.getController().animateTo(new GeoPoint(52096778, 5125090));
Thread.sleep(2 * 1000);
this.mMapView.getController().animateTo(new GeoPoint(52085117, 5128255));
Thread.sleep(2 * 1000);
this.mMapView.getController().animateTo(new GeoPoint(52081517, 5121646));
Thread.sleep(2 * 1000);
this.mMapView.getController().animateTo(new GeoPoint(52093535, 5116711));
Thread.sleep(2 * 1000);
this.sendKeys("G G");
Thread.sleep(5 * 1000);
}
@SmallTest
public void c_startRoute10Seconds() throws InterruptedException {
sendMessage("Lets start a new route");
Thread.sleep(1 * 1000);
this.sendKeys("MENU DPAD_RIGHT DPAD_LEFT");
Thread.sleep(2 * 1000);
this.sendKeys("T");//Toggle start/stop tracker
Thread.sleep(1 * 1000);
this.mMapView.getController().setZoom(ZOOM_LEVEL);
this.sendKeys("D E M O SPACE R O U T E ENTER");
Thread.sleep(5 * 1000);
sendMessage("The GPS logger is already running as a background service");
Thread.sleep(5 * 1000);
this.sendKeys("ENTER");
this.sendKeys("T T T T");
Thread.sleep(30 * 1000);
this.sendKeys("G G");
}
@SmallTest
public void d_showDrawMethods30seconds() throws InterruptedException {
sendMessage("Track drawing color has different options");
this.mMapView.getController().setZoom(ZOOM_LEVEL);
this.sendKeys("MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("S");
Thread.sleep(3 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_UP DPAD_UP DPAD_UP DPAD_UP");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(1 * 1000);
this.sendKeys("BACK");
sendMessage("Plain green");
Thread.sleep(15 * 1000);
this.sendKeys("MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("S");
Thread.sleep(3 * 1000);
this.sendKeys("MENU");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_UP DPAD_UP DPAD_UP DPAD_UP");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_DOWN DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_UP");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(2 * 1000);
this.sendKeys("BACK");
sendMessage("Average speeds drawn");
Thread.sleep(15 * 1000);
}
@SmallTest
public void e_statistics10Seconds() throws InterruptedException {
// Show of the statistics screen
sendMessage("Lets look at some statistics");
this.sendKeys("MENU DPAD_RIGHT DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("E");
Thread.sleep(2 * 1000);
sendMessage("Shows the basics on time, speed and distance");
Thread.sleep(10 * 1000);
this.sendKeys("BACK");
}
@SmallTest
public void f_showPrecision30seconds() throws InterruptedException {
this.mMapView.getController().setZoom(ZOOM_LEVEL);
sendMessage("There are options on the precision of tracking");
this.sendKeys("MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("S");
Thread.sleep(3 * 1000);
this.sendKeys("DPAD_DOWN DPAD_DOWN");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_UP DPAD_UP");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_DOWN DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_UP");
Thread.sleep(1 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(1 * 1000);
this.sendKeys("BACK");
sendMessage("Course will drain the battery the least");
Thread.sleep(5 * 1000);
sendMessage("Fine will store the best track");
Thread.sleep(10 * 1000);
}
@SmallTest
public void g_stopTracking10Seconds() throws InterruptedException {
this.mMapView.getController().setZoom(ZOOM_LEVEL);
Thread.sleep(5 * 1000);
// Stop tracking
sendMessage("Stopping tracking");
this.sendKeys("MENU DPAD_RIGHT DPAD_LEFT");
Thread.sleep(2 * 1000);
this.sendKeys("T");
Thread.sleep(2 * 1000);
sendMessage("Is the track stored?");
Thread.sleep(1 * 1000);
this.sendKeys("MENU DPAD_RIGHT");
Thread.sleep(2 * 1000);
this.sendKeys("L");
this.sendKeys("DPAD_DOWN DPAD_DOWN");
Thread.sleep(2 * 1000);
this.sendKeys("DPAD_CENTER");
Thread.sleep(2 * 1000);
}
private void h_shareTrack30Seconds() {
// TODO Auto-generated method stub
}
@SmallTest
public void i_finish10Seconds() throws InterruptedException {
this.mMapView.getController().setZoom(ZOOM_LEVEL);
this.sendKeys("G G");
Thread.sleep(1 * 1000);
this.sendKeys("G G");
Thread.sleep(1 * 1000);
this.sendKeys("G G");
sendMessage("Thank you for watching this demo.");
Thread.sleep(10 * 1000);
Thread.sleep(5 * 1000);
}
private void sendMessage(String string) {
this.mSender.sendSMS(string);
}
}
| gpl-3.0 |
databrary/datavyu | src/main/java/org/datavyu/controllers/DeleteCellController.java | 2247 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.datavyu.controllers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.datavyu.Datavyu;
import org.datavyu.models.db.Cell;
import org.datavyu.views.discrete.SpreadSheetPanel;
import java.util.List;
/**
* Controller for deleting cells from the database.
*/
public final class DeleteCellController {
/** The logger for this class. */
private static final Logger logger = LogManager.getLogger(DeleteCellController.class);
/**
* Constructor.
*
* @param cellsToDelete Cells to delete from the spreadsheet.
*/
public DeleteCellController(final List<Cell> cellsToDelete) {
logger.info("Delete cells: " + cellsToDelete);
// The spreadsheet is the view for this controller.
SpreadSheetPanel view = (SpreadSheetPanel) Datavyu.getView().getComponent();
view.deselectAll();
for (Cell cell : cellsToDelete) {
// Check if the cell we are deleting is the last created cell. Default this back to 0 if it is.
if (cell.equals(Datavyu.getProjectController().getLastCreatedCell())) {
Datavyu.getProjectController().setLastCreatedCell(null);
}
// Check if the cell we are deleting is the last selected cell. Default this back to 0 if it is.
if (cell.equals(Datavyu.getProjectController().getLastSelectedCell())) {
Datavyu.getProjectController().setLastSelectedCell(null);
}
Datavyu.getProjectController().getDataStore().removeCell(cell);
}
}
}
| gpl-3.0 |
heroandtn3/bGwtGson | src/com/sangnd/gwt/gson/client/Car.java | 1578 | /*
* Copyright 2013 heroandtn3 (heroandtn3 [at] gmail.com)
*
* This file is part of bGwtGson.
* bGwtGson 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.
* bGwtGson 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 bGwtGson. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package com.sangnd.gwt.gson.client;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author heroandtn3
*
*/
public class Car implements Serializable, IsSerializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String color;
private long value;
/**
*
*/
public Car() {
}
public Car(String name, String color, long value) {
this.name = name;
this.color = color;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
}
| gpl-3.0 |
vertigo17/Cerberus | source/src/main/java/org/cerberus/servlet/crud/countryenvironment/ReadCountryEnvParam.java | 16564 | /**
* Cerberus Copyright (C) 2013 - 2017 cerberustesting
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus 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.
*
* Cerberus 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 Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.servlet.crud.countryenvironment;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.cerberus.crud.entity.CountryEnvParam;
import org.cerberus.engine.entity.MessageEvent;
import org.cerberus.crud.service.ICountryEnvParamService;
import org.cerberus.enums.MessageEventEnum;
import org.cerberus.exception.CerberusException;
import org.cerberus.util.ParameterParserUtil;
import org.cerberus.util.answer.AnswerItem;
import org.cerberus.util.answer.AnswerList;
import org.cerberus.util.answer.AnswerUtil;
import org.cerberus.util.servlet.ServletUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.owasp.html.PolicyFactory;
import org.owasp.html.Sanitizers;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
*
* @author cerberus
*/
@WebServlet(name = "ReadCountryEnvParam", urlPatterns = {"/ReadCountryEnvParam"})
public class ReadCountryEnvParam extends HttpServlet {
private static final Logger LOG = LogManager.getLogger(ReadCountryEnvParam.class);
private ICountryEnvParamService cepService;
private final String OBJECT_NAME = "ReadCountryEnvParam";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
* @throws org.cerberus.exception.CerberusException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, CerberusException {
String echo = request.getParameter("sEcho");
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
response.setCharacterEncoding("utf8");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
// Default message to unexpected error.
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
/**
* Parsing and securing all required parameters.
*/
String system = policy.sanitize(request.getParameter("system"));
String country = policy.sanitize(request.getParameter("country"));
String environment = policy.sanitize(request.getParameter("environment"));
String build = policy.sanitize(request.getParameter("build"));
String revision = policy.sanitize(request.getParameter("revision"));
String active = policy.sanitize(request.getParameter("active"));
String envGp = policy.sanitize(request.getParameter("envgp"));
boolean unique = ParameterParserUtil.parseBooleanParam(request.getParameter("unique"), false);
boolean forceList = ParameterParserUtil.parseBooleanParam(request.getParameter("forceList"), false);
String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
// Global boolean on the servlet that define if the user has permition to edit and delete object.
boolean userHasPermissions = request.isUserInRole("Integrator");
// Init Answer with potencial error from Parsing parameter.
AnswerItem answer = new AnswerItem<>(msg);
try {
JSONObject jsonResponse = new JSONObject();
if ((request.getParameter("system") != null) && (request.getParameter("country") != null) && (request.getParameter("environment") != null) && !(forceList)) {
answer = findCountryEnvParamByKey(system, country, environment, appContext, userHasPermissions);
jsonResponse = (JSONObject) answer.getItem();
} else if (unique) {
answer = findUniqueEnvironmentList(system, active, appContext, userHasPermissions);
jsonResponse = (JSONObject) answer.getItem();
} else if (!Strings.isNullOrEmpty(columnName) && request.getParameter("system") != null) {
answer = findDistinctValuesOfColumn(system, appContext, request, columnName);
jsonResponse = (JSONObject) answer.getItem();
} else { // Default behaviour, we return the list of objects.
answer = findCountryEnvParamList(country, environment, build, revision, active, envGp, appContext, userHasPermissions, request);
jsonResponse = (JSONObject) answer.getItem();
}
jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", answer.getResultMessage().getDescription());
jsonResponse.put("sEcho", echo);
response.getWriter().print(jsonResponse.toString());
} catch (JSONException e) {
LOG.warn(e);
//returns a default error message with the json format that is able to be parsed by the client-side
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (CerberusException ex) {
LOG.warn(ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (CerberusException ex) {
LOG.warn(ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private AnswerItem<JSONObject> findCountryEnvParamList(String country, String environment, String build, String revision, String active, String envGp, ApplicationContext appContext, boolean userHasPermissions, HttpServletRequest request) throws JSONException {
AnswerItem<JSONObject> item = new AnswerItem<>();
JSONObject object = new JSONObject();
cepService = appContext.getBean(ICountryEnvParamService.class);
int startPosition = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0"));
int length = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0"));
/*int sEcho = Integer.valueOf(request.getParameter("sEcho"));*/
String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
int columnToSortParameter = Integer.parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_0"), "0"));
String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "system,country,environment,description,build,revision,distriblist,emailbodyrevision,type,emailbodychain,emailbodydisableenvironment,active,maintenanceact,maintenancestr,maintenanceeend");
String columnToSort[] = sColumns.split(",");
String columnName = columnToSort[columnToSortParameter];
String sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_0"), "asc");
List<String> individualLike = new ArrayList<>(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
List<String> systems = ParameterParserUtil.parseListParamAndDecodeAndDeleteEmptyValue(request.getParameterValues("system"), Arrays.asList("DEFAULT"), "UTF-8");
Map<String, List<String>> individualSearch = new HashMap<String, List<String>>();
for (int a = 0; a < columnToSort.length; a++) {
if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
List<String> search = new ArrayList<>(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
if (individualLike.contains(columnToSort[a])) {
individualSearch.put(columnToSort[a] + ":like", search);
} else {
individualSearch.put(columnToSort[a], search);
}
}
}
AnswerList<CountryEnvParam> resp = cepService.readByVariousByCriteria(systems, country, environment, build, revision, active, envGp, startPosition, length, columnName, sort, searchParameter, individualSearch);
JSONArray jsonArray = new JSONArray();
if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
for (CountryEnvParam cep : (List<CountryEnvParam>) resp.getDataList()) {
jsonArray.put(convertCountryEnvParamtoJSONObject(cep));
}
}
object.put("hasPermissions", userHasPermissions);
object.put("contentTable", jsonArray);
object.put("iTotalRecords", resp.getTotalRows());
object.put("iTotalDisplayRecords", resp.getTotalRows());
item.setItem(object);
item.setResultMessage(resp.getResultMessage());
return item;
}
private AnswerItem<JSONObject> findUniqueEnvironmentList(String system, String active, ApplicationContext appContext, boolean userHasPermissions) throws JSONException {
AnswerItem<JSONObject> item = new AnswerItem<>();
JSONObject object = new JSONObject();
cepService = appContext.getBean(ICountryEnvParamService.class);
AnswerList<CountryEnvParam> resp = cepService.readDistinctEnvironmentByVarious(system, null, null, null, null, null);
JSONArray jsonArray = new JSONArray();
if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
for (CountryEnvParam cep : (List<CountryEnvParam>) resp.getDataList()) {
jsonArray.put(convertCountryEnvParamtoJSONObject(cep));
}
}
object.put("contentTable", jsonArray);
object.put("iTotalRecords", resp.getTotalRows());
object.put("iTotalDisplayRecords", resp.getTotalRows());
object.put("hasPermissions", userHasPermissions);
item.setItem(object);
item.setResultMessage(resp.getResultMessage());
return item;
}
private AnswerItem<JSONObject> findCountryEnvParamByKey(String system, String country, String environment, ApplicationContext appContext, boolean userHasPermissions) throws JSONException, CerberusException {
AnswerItem<JSONObject> item = new AnswerItem<>();
JSONObject object = new JSONObject();
ICountryEnvParamService libService = appContext.getBean(ICountryEnvParamService.class);
//finds the CountryEnvParam
AnswerItem answer = libService.readByKey(system, country, environment);
if (answer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
//if the service returns an OK message then we can get the item and convert it to JSONformat
CountryEnvParam lib = (CountryEnvParam) answer.getItem();
JSONObject response = convertCountryEnvParamtoJSONObject(lib);
object.put("contentTable", response);
}
object.put("hasPermissions", userHasPermissions);
item.setItem(object);
item.setResultMessage(answer.getResultMessage());
return item;
}
private JSONObject convertCountryEnvParamtoJSONObject(CountryEnvParam cep) throws JSONException {
Gson gson = new Gson();
String defaultTime = "00:00:00";
JSONObject result = new JSONObject(gson.toJson(cep));
if ((cep.getMaintenanceStr() == null) || (cep.getMaintenanceStr().equalsIgnoreCase(defaultTime))) {
result.put("maintenanceStr", defaultTime);
}
if ((cep.getMaintenanceEnd() == null) || (cep.getMaintenanceEnd().equalsIgnoreCase(defaultTime))) {
result.put("maintenanceEnd", defaultTime);
}
return result;
}
private AnswerItem<JSONObject> findDistinctValuesOfColumn(String system, ApplicationContext appContext, HttpServletRequest request, String columnName) throws JSONException {
AnswerItem<JSONObject> answer = new AnswerItem<>();
JSONObject object = new JSONObject();
cepService = appContext.getBean(ICountryEnvParamService.class);
String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "system,country,environment,description,build,revision,distriblist,emailbodyrevision,type,emailbodychain,emailbodydisableenvironment,active,maintenanceact,maintenancestr,maintenanceeend");
String columnToSort[] = sColumns.split(",");
List<String> individualLike = new ArrayList<>(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
Map<String, List<String>> individualSearch = new HashMap<>();
for (int a = 0; a < columnToSort.length; a++) {
if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
List<String> search = new ArrayList<>(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
if (individualLike.contains(columnToSort[a])) {
individualSearch.put(columnToSort[a] + ":like", search);
} else {
individualSearch.put(columnToSort[a], search);
}
}
}
List<String> systems = ParameterParserUtil.parseListParamAndDecodeAndDeleteEmptyValue(request.getParameterValues("system"), Arrays.asList("DEFAULT"), "UTF-8");
AnswerList cepList = cepService.readDistinctValuesByCriteria(systems, searchParameter, individualSearch, columnName);
object.put("distinctValues", cepList.getDataList());
answer.setItem(object);
answer.setResultMessage(cepList.getResultMessage());
return answer;
}
}
| gpl-3.0 |
kadircet/CENG | 232/logisim-ceng232-20090616_source_from_cfr/com/cburch/logisim/file/LoadedLibrary.java | 8869 | /*
* Decompiled with CFR 0_114.
*/
package com.cburch.logisim.file;
import com.cburch.logisim.circuit.Circuit;
import com.cburch.logisim.comp.Component;
import com.cburch.logisim.comp.ComponentFactory;
import com.cburch.logisim.data.Attribute;
import com.cburch.logisim.data.AttributeSet;
import com.cburch.logisim.data.Location;
import com.cburch.logisim.file.LibraryEvent;
import com.cburch.logisim.file.LibraryEventSource;
import com.cburch.logisim.file.LibraryListener;
import com.cburch.logisim.file.LibraryManager;
import com.cburch.logisim.file.LogisimFile;
import com.cburch.logisim.file.MouseMappings;
import com.cburch.logisim.file.Options;
import com.cburch.logisim.file.ToolbarData;
import com.cburch.logisim.proj.Project;
import com.cburch.logisim.proj.Projects;
import com.cburch.logisim.tools.AddTool;
import com.cburch.logisim.tools.Library;
import com.cburch.logisim.tools.Tool;
import com.cburch.logisim.util.EventSourceWeakSupport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class LoadedLibrary
extends Library
implements LibraryEventSource {
private Library base;
private boolean dirty = false;
private MyListener myListener;
private EventSourceWeakSupport listeners;
LoadedLibrary(Library base) {
this.myListener = new MyListener();
this.listeners = new EventSourceWeakSupport();
while (base instanceof LoadedLibrary) {
base = ((LoadedLibrary)base).base;
}
this.base = base;
if (base instanceof LibraryEventSource) {
((LibraryEventSource)((Object)base)).addLibraryListener(this.myListener);
}
}
@Override
public void addLibraryListener(LibraryListener l) {
this.listeners.add(l);
}
@Override
public void removeLibraryListener(LibraryListener l) {
this.listeners.remove(l);
}
@Override
public String getName() {
return this.base.getName();
}
@Override
public String getDisplayName() {
return this.base.getDisplayName();
}
@Override
public boolean isDirty() {
return this.dirty || this.base.isDirty();
}
@Override
public List getTools() {
return this.base.getTools();
}
@Override
public List getLibraries() {
return this.base.getLibraries();
}
void setDirty(boolean value) {
if (this.dirty != value) {
this.dirty = value;
this.fireLibraryEvent(6, this.isDirty() ? Boolean.TRUE : Boolean.FALSE);
}
}
Library getBase() {
return this.base;
}
void setBase(Library value) {
if (this.base instanceof LibraryEventSource) {
((LibraryEventSource)((Object)this.base)).removeLibraryListener(this.myListener);
}
Library old = this.base;
this.base = value;
this.resolveChanges(old);
if (this.base instanceof LibraryEventSource) {
((LibraryEventSource)((Object)this.base)).addLibraryListener(this.myListener);
}
}
private void fireLibraryEvent(int action, Object data) {
this.fireLibraryEvent(new LibraryEvent(this, action, data));
}
private void fireLibraryEvent(LibraryEvent event) {
if (event.getSource() != this) {
event = new LibraryEvent(this, event.getAction(), event.getData());
}
Iterator it = this.listeners.iterator();
while (it.hasNext()) {
LibraryListener l = (LibraryListener)it.next();
l.libraryChanged(event);
}
}
private void resolveChanges(Library old) {
if (this.listeners.size() == 0) {
return;
}
if (!this.base.getDisplayName().equals(old.getDisplayName())) {
this.fireLibraryEvent(5, this.base.getDisplayName());
}
HashSet changes = new HashSet(old.getLibraries());
changes.removeAll(this.base.getLibraries());
Iterator it = changes.iterator();
while (it.hasNext()) {
this.fireLibraryEvent(3, it.next());
}
changes.clear();
changes.addAll(this.base.getLibraries());
changes.removeAll(old.getLibraries());
it = changes.iterator();
while (it.hasNext()) {
this.fireLibraryEvent(2, it.next());
}
HashMap<ComponentFactory, ComponentFactory> componentMap = new HashMap<ComponentFactory, ComponentFactory>();
HashMap<Object, Tool> toolMap = new HashMap<Object, Tool>();
for (Tool oldTool : old.getTools()) {
Tool newTool = this.base.getTool(oldTool.getName());
toolMap.put(oldTool, newTool);
if (!(oldTool instanceof AddTool)) continue;
ComponentFactory oldFactory = ((AddTool)oldTool).getFactory();
toolMap.put(oldFactory, newTool);
if (newTool != null && newTool instanceof AddTool) {
ComponentFactory newFactory = ((AddTool)newTool).getFactory();
componentMap.put(oldFactory, newFactory);
continue;
}
componentMap.put(oldFactory, null);
}
LoadedLibrary.replaceAll(componentMap, toolMap);
changes.clear();
changes.addAll(old.getTools());
changes.removeAll(toolMap.keySet());
Iterator it2 = changes.iterator();
while (it2.hasNext()) {
this.fireLibraryEvent(1, it2.next());
}
changes.clear();
changes.addAll(this.base.getTools());
changes.removeAll(toolMap.values());
it2 = changes.iterator();
while (it2.hasNext()) {
this.fireLibraryEvent(0, it2.next());
}
}
private static void replaceAll(HashMap componentMap, HashMap toolMap) {
for (Project proj : Projects.getOpenProjects()) {
Tool oldTool = proj.getTool();
Circuit oldCircuit = proj.getCurrentCircuit();
if (toolMap.containsKey(oldTool)) {
proj.setTool((Tool)toolMap.get(oldTool));
}
if (componentMap.containsKey(oldCircuit)) {
proj.setCurrentCircuit((Circuit)componentMap.get(oldCircuit));
}
LoadedLibrary.replaceAll(proj.getLogisimFile(), componentMap, toolMap);
}
for (LogisimFile file : LibraryManager.instance.getLogisimLibraries()) {
LoadedLibrary.replaceAll(file, componentMap, toolMap);
}
}
private static void replaceAll(LogisimFile file, HashMap componentMap, HashMap toolMap) {
file.getOptions().getToolbarData().replaceAll(toolMap);
file.getOptions().getMouseMappings().replaceAll(toolMap);
for (Object tool : file.getTools()) {
ComponentFactory circuit;
if (!(tool instanceof AddTool) || !((circuit = ((AddTool)tool).getFactory()) instanceof Circuit)) continue;
LoadedLibrary.replaceAll((Circuit)circuit, componentMap);
}
}
private static void replaceAll(Circuit circuit, HashMap componentMap) {
ArrayList<Component> toReplace = null;
for (Component comp : circuit.getNonWires()) {
if (!componentMap.containsKey(comp.getFactory())) continue;
if (toReplace == null) {
toReplace = new ArrayList<Component>();
}
toReplace.add(comp);
}
if (toReplace == null) {
return;
}
int n = toReplace.size();
for (int i = 0; i < n; ++i) {
Component comp2 = (Component)toReplace.get(i);
circuit.remove(comp2);
ComponentFactory factory = (ComponentFactory)componentMap.get(comp2.getFactory());
if (factory == null) continue;
AttributeSet newAttrs = LoadedLibrary.createAttributes(factory, comp2.getAttributeSet());
circuit.add(factory.createComponent(comp2.getLocation(), newAttrs));
}
}
private static AttributeSet createAttributes(ComponentFactory factory, AttributeSet src) {
AttributeSet dest = factory.createAttributeSet();
LoadedLibrary.copyAttributes(dest, src);
return dest;
}
static void copyAttributes(AttributeSet dest, AttributeSet src) {
for (Attribute destAttr : dest.getAttributes()) {
Attribute srcAttr = src.getAttribute(destAttr.getName());
if (srcAttr == null) continue;
dest.setValue(destAttr, src.getValue(srcAttr));
}
}
private class MyListener
implements LibraryListener {
private MyListener() {
}
@Override
public void libraryChanged(LibraryEvent event) {
LoadedLibrary.this.fireLibraryEvent(event);
}
}
}
| gpl-3.0 |
MenuFinder/AndroidClient | app/src/main/java/cat/udl/menufinder/fragments/SubscriptionsFragment.java | 5205 | package cat.udl.menufinder.fragments;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import cat.udl.menufinder.R;
import cat.udl.menufinder.activities.DetailRestaurantActivity;
import cat.udl.menufinder.activities.HomeActivity;
import cat.udl.menufinder.activities.ReviewRestaurantActivity;
import cat.udl.menufinder.adapters.RestaurantsAdapter;
import cat.udl.menufinder.application.MasterFragment;
import cat.udl.menufinder.models.AccountSubscription;
import cat.udl.menufinder.models.Restaurant;
import cat.udl.menufinder.utils.Utils;
import static cat.udl.menufinder.utils.Constants.KEY_RESTAURANT;
public class SubscriptionsFragment extends MasterFragment {
protected RestaurantsAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_restaurants, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
configHeader();
configList();
}
protected void configHeader() {
}
protected void configList() {
RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.list);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(
getActivity(), DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(itemDecoration);
DefaultItemAnimator animator = new DefaultItemAnimator();
animator.setAddDuration(1000);
recyclerView.setItemAnimator(animator);
List<Restaurant> restaurants = getRestaurants();
adapter = new RestaurantsAdapter(getActivity(), restaurants, new RestaurantsFragment.OnRestaurantClickListener() {
@Override
public void onRestaurantClick(Restaurant restaurant, View view) {
DetailRestaurantFragment fragment = (DetailRestaurantFragment) getFragmentManager()
.findFragmentById(R.id.detail_fragment);
if (fragment != null && fragment.isInLayout()) {
fragment.update(restaurant);
} else {
Intent intent = new Intent(getActivity(), DetailRestaurantActivity.class);
intent.putExtra(KEY_RESTAURANT, restaurant);
if (Build.VERSION.SDK_INT >= 21) {
View image = view.findViewById(R.id.image);
ActivityOptionsCompat activityOptionsCompat =
ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
image, getString(R.string.image_restaurant));
startActivity(intent, activityOptionsCompat.toBundle());
} else {
startActivity(intent);
}
}
}
@Override
public void onShareClick(Restaurant restaurant) {
startActivity(Utils.getShareIntent(getString(R.string.share_text, restaurant.getName())));
}
@Override
public void onViewMapClick(Restaurant restaurant) {
HomeActivity activity = (HomeActivity) getActivity();
activity.loadFragment(R.id.content, RestaurantMapFragment.newInstance(restaurant));
}
@Override
public void onReViewClick(Restaurant restaurant) {
Intent intent = new Intent(getActivity(), ReviewRestaurantActivity.class);
intent.putExtra(KEY_RESTAURANT, restaurant);
startActivity(intent);
}
@Override
public void onFavouriteClick(Restaurant restaurant, boolean checked) {
AccountSubscription subscription = new AccountSubscription(getMasterApplication().getUsername(), restaurant.getId());
if (checked) getDbManager().addAccountSubscription(subscription);
else getDbManager().deleteAccountSubscription(subscription);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
public List<Restaurant> getRestaurants() {
return getDbManager().getSubscribedRestaurantsOfAccount(getMasterApplication().getUsername());
}
public interface OnRestaurantClickListener {
void onRestaurantClick(Restaurant restaurant, View view);
void onShareClick(Restaurant restaurant);
void onViewMapClick(Restaurant restaurant);
void onReViewClick(Restaurant restaurant);
void onFavouriteClick(Restaurant restaurant, boolean checked);
}
}
| gpl-3.0 |
arraydev/snap-desktop | snap-ui/src/main/java/org/esa/snap/framework/ui/product/spectrum/SpectrumChooser.java | 17928 | package org.esa.snap.framework.ui.product.spectrum;
import com.bc.ceres.swing.TableLayout;
import com.jidesoft.swing.TristateCheckBox;
import org.esa.snap.framework.datamodel.Band;
import org.esa.snap.framework.ui.DecimalTableCellRenderer;
import org.esa.snap.framework.ui.ModalDialog;
import org.esa.snap.framework.ui.UIUtils;
import org.esa.snap.framework.ui.product.LoadSaveRasterDataNodesConfigurationsComponent;
import org.esa.snap.framework.ui.product.LoadSaveRasterDataNodesConfigurationsProvider;
import org.esa.snap.framework.ui.tool.ToolButtonFactory;
import org.esa.snap.util.ArrayUtils;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SpectrumChooser extends ModalDialog implements LoadSaveRasterDataNodesConfigurationsComponent {
private static final int band_selected_index = 0;
private static final int band_name_index = 1;
private static final int band_description_index = 2;
private static final int band_wavelength_index = 3;
private static final int band_bandwidth_ndex = 4;
private static final int band_unit_index = 5;
private final String[] band_columns =
new String[]{"", "Band name", "Band description", "Spectral wavelength (nm)", "Spectral bandwidth (nm)", "Unit"};
private final static ImageIcon[] icons = new ImageIcon[]{
UIUtils.loadImageIcon("icons/PanelDown12.png"),
UIUtils.loadImageIcon("icons/PanelUp12.png"),
};
private final static ImageIcon[] roll_over_icons = new ImageIcon[]{
ToolButtonFactory.createRolloverIcon(icons[0]),
ToolButtonFactory.createRolloverIcon(icons[1]),
};
private final DisplayableSpectrum[] originalSpectra;
private DisplayableSpectrum[] spectra;
private static SpectrumSelectionAdmin selectionAdmin;
private static boolean selectionChangeLock;
private JPanel spectraPanel;
private final JPanel[] bandTablePanels;
private final JTable[] bandTables;
private final TristateCheckBox[] tristateCheckBoxes;
private boolean[] collapsed;
private TableLayout spectraPanelLayout;
public SpectrumChooser(Window parent, DisplayableSpectrum[] originalSpectra) {
super(parent, "Available Spectra", ModalDialog.ID_OK_CANCEL_HELP, "spectrumChooser");
if (originalSpectra != null) {
this.originalSpectra = originalSpectra;
List<DisplayableSpectrum> spectraWithBands = new ArrayList<>();
for (DisplayableSpectrum spectrum : originalSpectra) {
if (spectrum.hasBands()) {
spectraWithBands.add(spectrum);
}
}
this.spectra = spectraWithBands.toArray(new DisplayableSpectrum[spectraWithBands.size()]);
} else {
this.originalSpectra = new DisplayableSpectrum[0];
this.spectra = new DisplayableSpectrum[0];
}
selectionAdmin = new SpectrumSelectionAdmin();
selectionChangeLock = false;
bandTables = new JTable[spectra.length];
collapsed = new boolean[spectra.length];
Arrays.fill(collapsed, true);
bandTablePanels = new JPanel[spectra.length];
tristateCheckBoxes = new TristateCheckBox[spectra.length];
initUI();
}
private void initUI() {
final JPanel content = new JPanel(new BorderLayout());
initSpectraPanel();
final JScrollPane spectraScrollPane = new JScrollPane(spectraPanel);
spectraScrollPane.getVerticalScrollBar().setUnitIncrement(20);
spectraScrollPane.getHorizontalScrollBar().setUnitIncrement(20);
content.add(spectraScrollPane, BorderLayout.CENTER);
LoadSaveRasterDataNodesConfigurationsProvider provider = new LoadSaveRasterDataNodesConfigurationsProvider(this);
AbstractButton loadButton = provider.getLoadButton();
AbstractButton saveButton = provider.getSaveButton();
TableLayout layout = new TableLayout(1);
layout.setTablePadding(4, 4);
JPanel buttonPanel = new JPanel(layout);
buttonPanel.add(loadButton);
buttonPanel.add(saveButton);
buttonPanel.add(layout.createVerticalSpacer());
content.add(buttonPanel, BorderLayout.EAST);
setContent(content);
}
private void initSpectraPanel() {
spectraPanelLayout = new TableLayout(7);
spectraPanelLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
spectraPanelLayout.setTableWeightY(0.0);
spectraPanelLayout.setTableWeightX(1.0);
spectraPanelLayout.setColumnWeightX(0, 0.0);
spectraPanelLayout.setColumnWeightX(1, 0.0);
spectraPanelLayout.setTablePadding(3, 3);
spectraPanel = new JPanel(spectraPanelLayout);
spectraPanel.add(new JLabel(""));
spectraPanel.add(new JLabel(""));
spectraPanel.add(new JLabel("Spectrum Name"));
spectraPanel.add(new JLabel("Unit"));
spectraPanel.add(new JLabel("Line Style"));
spectraPanel.add(new JLabel("Symbol"));
spectraPanel.add(new JLabel("Symbol Size"));
for (int i = 0; i < spectra.length; i++) {
selectionAdmin.evaluateSpectrumSelections(spectra[i]);
addSpectrumComponentsToSpectraPanel(i);
spectraPanelLayout.setCellColspan((i * 2) + 2, 1, 6);
spectraPanel.add(new JLabel());
bandTablePanels[i] = new JPanel(new BorderLayout());
bandTablePanels[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
spectraPanel.add(bandTablePanels[i]);
bandTables[i] = createBandsTable(i);
}
spectraPanel.add(spectraPanelLayout.createVerticalSpacer());
spectraPanel.updateUI();
}
private void addSpectrumComponentsToSpectraPanel(int index) {
DisplayableSpectrum spectrum = spectra[index];
ImageIcon strokeIcon;
if (spectrum.isDefaultOrRemainingBandsSpectrum()) {
strokeIcon = new ImageIcon();
} else {
strokeIcon = SpectrumStrokeProvider.getStrokeIcon(spectrum.getLineStyle());
}
AbstractButton collapseButton = ToolButtonFactory.createButton(icons[0], false);
collapseButton.addActionListener(new CollapseListener(index));
final ImageIcon shapeIcon = SpectrumShapeProvider.getShapeIcon(spectrum.getSymbolIndex());
spectraPanel.add(collapseButton);
final TristateCheckBox tristateCheckBox = new TristateCheckBox();
tristateCheckBox.setState(selectionAdmin.getState(index));
tristateCheckBox.addActionListener(new TristateCheckboxListener(index));
tristateCheckBoxes[index] = tristateCheckBox;
spectraPanel.add(tristateCheckBox);
final JLabel spectrumNameLabel = new JLabel(spectrum.getName());
Font font = spectrumNameLabel.getFont();
font = new Font(font.getName(), Font.BOLD, font.getSize());
spectrumNameLabel.setFont(font);
spectraPanel.add(spectrumNameLabel);
spectraPanel.add(new JLabel(spectrum.getUnit()));
JComboBox<ImageIcon> strokeComboBox;
if (spectrum.isDefaultOrRemainingBandsSpectrum()) {
strokeComboBox = new JComboBox<>(new ImageIcon[]{strokeIcon});
strokeComboBox.setEnabled(false);
} else {
strokeComboBox = new JComboBox<>(SpectrumStrokeProvider.getStrokeIcons());
strokeComboBox.addActionListener(
e -> spectrum.setLineStyle(
SpectrumStrokeProvider.getStroke((ImageIcon) strokeComboBox.getSelectedItem())));
}
strokeComboBox.setPreferredSize(new Dimension(100, 20));
strokeComboBox.setSelectedItem(strokeIcon);
spectraPanel.add(strokeComboBox);
JComboBox<ImageIcon> shapeComboBox = new JComboBox<>(SpectrumShapeProvider.getShapeIcons());
JComboBox<Integer> shapeSizeComboBox = new JComboBox<>(SpectrumShapeProvider.getScaleGrades());
shapeComboBox.setPreferredSize(new Dimension(100, 20));
shapeSizeComboBox.setPreferredSize(new Dimension(100, 20));
shapeComboBox.setSelectedItem(shapeIcon);
shapeComboBox.addActionListener(e -> {
final int shapeIndex = SpectrumShapeProvider.getShape((ImageIcon) shapeComboBox.getSelectedItem());
spectrum.setSymbolIndex(shapeIndex);
if (shapeIndex == SpectrumShapeProvider.EMPTY_SHAPE_INDEX) {
shapeSizeComboBox.setSelectedItem("");
} else {
shapeSizeComboBox.setSelectedItem(spectrum.getSymbolSize());
}
});
spectraPanel.add(shapeComboBox);
shapeSizeComboBox.setSelectedItem(spectrum.getSymbolSize());
shapeSizeComboBox.addActionListener(e -> {
final String selectedItem = shapeSizeComboBox.getSelectedItem().toString();
if (!selectedItem.equals("")) {
spectrum.setSymbolSize(Integer.parseInt(selectedItem));
}
});
spectraPanel.add(shapeSizeComboBox);
}
private void toggleCollapsed(int index) {
final boolean isCollapsed = !collapsed[index];
collapsed[index] = isCollapsed;
int rowIndex = (index * 2) + 2;
if (isCollapsed) {
spectraPanelLayout.setRowFill(rowIndex, TableLayout.Fill.HORIZONTAL);
spectraPanelLayout.setRowWeightY(rowIndex, 0.0);
bandTablePanels[index].removeAll();
} else {
spectraPanelLayout.setRowFill(rowIndex, TableLayout.Fill.BOTH);
spectraPanelLayout.setRowWeightY(rowIndex, 1.0);
bandTablePanels[index].add(bandTables[index].getTableHeader(), BorderLayout.NORTH);
bandTablePanels[index].add(bandTables[index], BorderLayout.CENTER);
}
bandTablePanels[index].updateUI();
spectraPanel.updateUI();
}
private JTable createBandsTable(int index) {
DisplayableSpectrum spectrum = spectra[index];
final Band[] spectralBands = spectrum.getSpectralBands();
Object[][] spectrumData = new Object[spectralBands.length][band_columns.length];
for (int i = 0; i < spectralBands.length; i++) {
Band spectralBand = spectralBands[i];
final boolean selected = spectrum.isBandSelected(i) && spectrum.isSelected();
spectrumData[i][band_selected_index] = selected;
spectrumData[i][band_name_index] = spectralBand.getName();
spectrumData[i][band_description_index] = spectralBand.getDescription();
spectrumData[i][band_wavelength_index] = spectralBand.getSpectralWavelength();
spectrumData[i][band_bandwidth_ndex] = spectralBand.getSpectralBandwidth();
spectrumData[i][band_unit_index] = spectralBand.getUnit();
}
final BandTableModel bandTableModel = new BandTableModel(spectrumData, band_columns);
bandTableModel.addTableModelListener(e -> {
e.getSource();
if (e.getColumn() == band_selected_index) {
final DisplayableSpectrum spectrum1 = spectra[index];
final int bandRow = e.getFirstRow();
final Boolean selected = (Boolean) bandTableModel.getValueAt(bandRow, e.getColumn());
spectrum1.setBandSelected(bandRow, selected);
if (!selectionChangeLock) {
selectionChangeLock = true;
selectionAdmin.setBandSelected(index, bandRow, selected);
selectionAdmin.updateSpectrumSelectionState(index, selectionAdmin.getState(index));
tristateCheckBoxes[index].setState(selectionAdmin.getState(index));
spectrum1.setSelected(selectionAdmin.isSpectrumSelected(index));
selectionChangeLock = false;
}
}
});
JTable bandsTable = new JTable(bandTableModel);
bandsTable.setRowSorter(new TableRowSorter<>(bandTableModel));
final TableColumn selectionColumn = bandsTable.getColumnModel().getColumn(band_selected_index);
final JCheckBox selectionCheckBox = new JCheckBox();
selectionColumn.setCellEditor(new DefaultCellEditor(selectionCheckBox));
selectionColumn.setMinWidth(20);
selectionColumn.setMaxWidth(20);
BooleanRenderer booleanRenderer = new BooleanRenderer();
selectionColumn.setCellRenderer(booleanRenderer);
final TableColumn wavelengthColumn = bandsTable.getColumnModel().getColumn(band_wavelength_index);
wavelengthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
final TableColumn bandwidthColumn = bandsTable.getColumnModel().getColumn(band_bandwidth_ndex);
bandwidthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
return bandsTable;
}
private void updateBandsTable(int index) {
final TableModel tableModel = bandTables[index].getModel();
for (int i = 0; i < tableModel.getRowCount(); i++) {
tableModel.setValueAt(selectionAdmin.isBandSelected(index, i), i, band_selected_index);
}
}
public DisplayableSpectrum[] getSpectra() {
return originalSpectra;
}
@Override
public void setReadRasterDataNodeNames(String[] readRasterDataNodeNames) {
for (JTable bandTable : bandTables) {
BandTableModel bandTableModel = (BandTableModel) bandTable.getModel();
for (int j = 0; j < bandTableModel.getRowCount(); j++) {
String bandName = bandTableModel.getValueAt(j, band_name_index).toString();
boolean selected = ArrayUtils.isMemberOf(bandName, readRasterDataNodeNames);
bandTableModel.setValueAt(selected, j, band_selected_index);
}
}
}
@Override
public String[] getRasterDataNodeNamesToWrite() {
List<String> bandNames = new ArrayList<>();
for (JTable bandTable : bandTables) {
BandTableModel bandTableModel = (BandTableModel) bandTable.getModel();
for (int j = 0; j < bandTableModel.getRowCount(); j++) {
if ((boolean) bandTableModel.getValueAt(j, band_selected_index)) {
bandNames.add(bandTableModel.getValueAt(j, band_name_index).toString());
}
}
}
return bandNames.toArray(new String[bandNames.size()]);
}
private static class BandTableModel extends DefaultTableModel {
private BandTableModel(Object[][] spectrumData, String[] bandColumns) {
super(spectrumData, bandColumns);
}
@Override
public boolean isCellEditable(int row, int column) {
return column == band_selected_index;
}
}
private class BooleanRenderer extends JCheckBox implements TableCellRenderer {
private BooleanRenderer() {
this.setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());
}
boolean selected = (Boolean) value;
setSelected(selected);
return this;
}
}
private class CollapseListener implements ActionListener {
private final int index;
CollapseListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
final Object source = e.getSource();
if (source instanceof AbstractButton) {
AbstractButton collapseButton = (AbstractButton) source;
toggleCollapsed(index);
if (collapsed[index]) {
collapseButton.setIcon(icons[0]);
collapseButton.setRolloverIcon(roll_over_icons[0]);
} else {
collapseButton.setIcon(icons[1]);
collapseButton.setRolloverIcon(roll_over_icons[1]);
}
}
}
}
private class TristateCheckboxListener implements ActionListener {
private final int index;
TristateCheckboxListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
if (!selectionChangeLock) {
selectionChangeLock = true;
selectionAdmin.updateSpectrumSelectionState(index, tristateCheckBoxes[index].getState());
tristateCheckBoxes[index].setState(selectionAdmin.getState(index));
updateBandsTable(index);
spectra[index].setSelected(selectionAdmin.isSpectrumSelected(index));
selectionChangeLock = false;
}
}
}
}
| gpl-3.0 |
unSinn/thermik | src/ch/ma3/thermik/Gui.java | 2259 | package ch.ma3.thermik;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Gui extends JFrame implements MouseMotionListener, InfoProvider {
private static final long serialVersionUID = 1516156985634156156L;
private BufferedImage heightImage;
private BufferedImage thermikImage;
private ConcurrentLinkedQueue<InfoProvider> infoProviders;
private String info = "";
private int mouseX;
private int mouseY;
public Gui(BufferedImage heightImage) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Thermik");
infoProviders = new ConcurrentLinkedQueue<>();
addInfoProvider(this);
this.heightImage = heightImage;
thermikImage = generatePlaceholderThermikMap();
ImagePanel imagePanel = new ImagePanel();
imagePanel.addMouseMotionListener(this);
this.add(imagePanel);
setSize(heightImage.getWidth(), heightImage.getHeight() * 2);
setVisible(true);
}
public void addInfoProvider(InfoProvider infoProvider) {
this.infoProviders.add(infoProvider);
}
public void setThermikImage(BufferedImage newThermikImage) {
this.thermikImage = newThermikImage;
}
private BufferedImage generatePlaceholderThermikMap() {
return new BufferedImage(heightImage.getWidth(),
heightImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
}
private class ImagePanel extends JPanel {
private static final long serialVersionUID = -2773961843687530433L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(heightImage, null, 0, 0);
g2d.drawImage(thermikImage, null, 0, heightImage.getHeight());
int line = 20;
for (InfoProvider i : infoProviders) {
g2d.drawString(i.getInfo(mouseX, mouseY), 10, line);
line += 12;
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
// unused
}
@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
@Override
public String getInfo(int x, int y) {
return "MouseX: " + mouseX + ", MouseY: " + mouseY;
}
}
| gpl-3.0 |
chungkwong/JSchemeMin | src/com/github/chungkwong/jschememin/primitive/Apply.java | 1565 | /*
* Copyright (C) 2016 Chan Chung Kwong <1m02math@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.chungkwong.jschememin.primitive;
import com.github.chungkwong.jschememin.*;
import com.github.chungkwong.jschememin.type.*;
/**
* Correspoding to the primitive apply in Scheme
* @author Chan Chung Kwong <1m02math@126.com>
*/
public class Apply extends BasicConstruct{
public static final Apply INSTANCE=new Apply();
private Apply(){
super(new ScmSymbol("apply"));
}
@Override
public void call(SchemeEnvironment env,Continuation cont,Object pointer,ScmPairOrNil param){
ScmListBuilder buf=new ScmListBuilder();
Evaluable proc=(Evaluable)ScmList.first(param);
ScmPair curr=(ScmPair)((ScmPair)param).getCdr();
for(;curr.getCdr() instanceof ScmPair;curr=(ScmPair)curr.getCdr()){
buf.add(curr.getCar());
}
ScmList.forEach(curr.getCar(),(o)->buf.add(o));
cont.callTail(proc,(ScmPairOrNil)buf.toList(),env);
}
} | gpl-3.0 |
acmyonghua/eucalyptus | clc/modules/block-storage-common/src/main/java/com/eucalyptus/blockstorage/exceptions/SnapshotTooLargeException.java | 3904 | /*************************************************************************
* Copyright 2009-2013 Eucalyptus Systems, 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; version 3 of the License.
*
* 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/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
************************************************************************/
package com.eucalyptus.blockstorage.exceptions;
import com.eucalyptus.util.EucalyptusCloudException;
@SuppressWarnings("serial")
public class SnapshotTooLargeException extends EucalyptusCloudException {
public SnapshotTooLargeException() {
super("SnapshotTooLarge");
}
public SnapshotTooLargeException(String snapshotId, int maxSizeInGB) {
super("Snapshot " + snapshotId + " exceeds the maximum allowed snapshot size of " + maxSizeInGB + "GB");
}
public SnapshotTooLargeException(Throwable ex) {
super("SnapshotTooLarge", ex);
}
public SnapshotTooLargeException(String message, Throwable ex) {
super(message, ex);
}
}
| gpl-3.0 |
chvink/kilomek | megamek/src/megamek/common/ConvFighter.java | 3951 | /*
* MegaAero - Copyright (C) 2007 Jay Lawson
* 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.
*/
/*
* Created on Jun 12, 2008
*
*/
package megamek.common;
/**
* @author Jay Lawson
*/
public class ConvFighter extends Aero {
/**
*
*/
private static final long serialVersionUID = 6297668284292929409L;
@Override
public boolean doomedInVacuum() {
return true;
}
@Override
public boolean doomedInSpace() {
return true;
}
@Override
public int getHeatCapacity() {
return 999;
}
@Override
public int getFuelUsed(int thrust) {
int overThrust = Math.max(thrust - getWalkMP(), 0);
int safeThrust = thrust - overThrust;
int used = safeThrust + (2 * overThrust);
if(!getEngine().isFusion()) {
used = (int)Math.floor(safeThrust * 0.5) + overThrust;
} else if(game.getOptions().booleanOption("stratops_conv_fusion_bonus")) {
used = (int)Math.floor(safeThrust * 0.5) + (2 * overThrust);
}
return used;
}
@Override
public double getBVTypeModifier() {
if (hasStealth()) {
return 1.4;
}
return 1.1;
}
@Override
public double getCost(boolean ignoreAmmo) {
double cost = 0;
// add in cockpit
double avionicsWeight = Math.ceil(weight / 5) / 2;
cost += 4000 * avionicsWeight;
// add VSTOL gear if applicable
if (isVSTOL()) {
double vstolWeight = Math.ceil(weight / 10) / 2;
cost += 5000 * vstolWeight;
}
// Structural integrity
cost += 4000 * getSI();
// additional flight systems (attitude thruster and landing gear)
cost += 25000 + (10 * getWeight());
// engine
cost += (getEngine().getBaseCost() * getEngine().getRating() * weight) / 75.0;
// fuel tanks
cost += (200 * getFuel()) / 160.0;
// armor
if (hasPatchworkArmor()) {
for (int loc = 0; loc < locations(); loc++) {
cost += getArmorWeight(loc) * EquipmentType.getArmorCost(armorType[loc]);
}
}
else {
cost += getArmorWeight() * EquipmentType.getArmorCost(armorType[0]);
}
// heat sinks
int sinkCost = 2000 + (4000 * getHeatType());// == HEAT_DOUBLE ? 6000:
// 2000;
cost += sinkCost * getHeatSinks();
// weapons
cost += getWeaponsAndEquipmentCost(ignoreAmmo);
// power amplifiers, if any
cost += 20000 * getPowerAmplifierWeight();
// omni multiplier (leaving this in for now even though conventional fighters
// don't make for legal omnis)
double omniMultiplier = 1;
if (isOmni()) {
omniMultiplier = 1.25f;
}
double weightMultiplier = 1 + (weight / 200.0);
return Math.round(cost * omniMultiplier * weightMultiplier);
}
@Override
protected int calculateWalk() {
if (isPrimitive()) {
double rating = getEngine().getRating();
rating /= 1.2;
if ((rating % 5) != 0) {
return (int) (((rating - (rating % 5)) + 5) / (int) weight);
}
return (int) (rating / (int) weight);
}
return (getEngine().getRating() / (int) weight);
}
public long getEntityType(){
return Entity.ETYPE_AERO | Entity.ETYPE_CONV_FIGHTER;
}
} | gpl-3.0 |
alejostenuki/mobuk | src/com/tenuki/mobuk/ext/uk/orange/particulares/UKOrangeCamelSIM31.java | 3065 | /*
* This file is part of mobuk.
*
* Plan 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.
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNUKS 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 mobuk. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tenuki.mobuk.ext.uk.orange.particulares;
import java.util.ArrayList;
import com.tenuki.mobuk.core.Chargeable;
import com.tenuki.mobuk.core.call.Call;
import com.tenuki.mobuk.core.message.ChargeableMessage;
import com.tenuki.mobuk.core.msisdn.MsisdnType;
import com.tenuki.mobuk.core.plan.PlanChargeable;
import com.tenuki.mobuk.core.plan.PlanSummary;
import com.tenuki.mobuk.core.sms.Sms;
import com.tenuki.mobuk.ext.uk.orange.UKOrange;
/**
* Orange @L.
*
* @author sanz
*/
public class UKOrangeCamelSIM31 extends UKOrange {
private double monthFee = 31;
private double initialPrice = 0.00;
private double pricePerSecond = 0.35/ 60;
private double smsPrice = 0.12;
private int maxSecondsMonth = 1200 * 60;
private int maxFreeSMS = 50000;
private double internet = 1;
public String getPlanName() {
return "Camel SIM 31 (12mon)";
}
public String getPlanURL() {
return "http://shop.orange.co.uk/mobile-phones/price-plans/pay-monthly";
}
public PlanSummary process(ArrayList<Chargeable> data) {
PlanSummary ret = new PlanSummary(this);
ret.addPlanCall(new PlanChargeable(new ChargeableMessage(ChargeableMessage.MESSAGE_MONTH_FEE), monthFee, this.getCurrency()));
int smsSent = 0;
int secondsTotal = 0;
for (Chargeable chargeable : data) {
if (chargeable.getChargeableType() == Chargeable.CHARGEABLE_TYPE_CALL) {
Call call = (Call) chargeable;
if (call.getType() != Call.CALL_TYPE_SENT) {
continue;
}
double callPrice = 0;
if (call.getContact().getMsisdnType() == MsisdnType.UK_SPECIAL_ZER0) {
callPrice = 0;
} else {
secondsTotal += call.getDuration();
boolean insidePlan = secondsTotal <= maxSecondsMonth;
if (!insidePlan) {
long duration = (secondsTotal > maxSecondsMonth) && (secondsTotal - call.getDuration() <= maxSecondsMonth)? secondsTotal - maxSecondsMonth : call.getDuration();
callPrice += initialPrice + (duration * pricePerSecond);
}
}
ret.addPlanCall(new PlanChargeable(call, callPrice, this.getCurrency()));
} else if (chargeable.getChargeableType() == Chargeable.CHARGEABLE_TYPE_SMS) {
Sms sms = (Sms) chargeable;
if (sms.getType() == Sms.SMS_TYPE_RECEIVED) {
continue;
}
smsSent++;
ret.addPlanCall(new PlanChargeable(chargeable, (smsSent > maxFreeSMS)?smsPrice:0, this.getCurrency()));
}
}
return ret;
}
} | gpl-3.0 |
asoem/greyfish | greyfish-core/src/main/java/org/asoem/greyfish/core/agent/BasicContext.java | 2008 | /*
* Copyright (C) 2015 The greyfish authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.asoem.greyfish.core.agent;
import org.asoem.greyfish.core.environment.DiscreteTimeEnvironment;
/**
* A SimulationContext is the link between an {@link Agent} and a {@link org.asoem.greyfish.core.environment.DiscreteTimeEnvironment}.
* If an agent got activated a newly created context will be set for this agent.
*/
public interface BasicContext<S extends DiscreteTimeEnvironment<A>, A extends Agent<?>> extends Context<S, A> {
/**
* The step at which this agent was inserted into the getSimulation.
*
* @return the activation step
*/
long getActivationStep();
/**
* Get the age of this agent. Same as calling {@code getSimulation().getSteps() - getActivationStep()}
*
* @return the difference between the activation step and current step
*/
long getAge();
/**
* Get the current getSimulation step. Delegates to {@link org.asoem.greyfish.core.environment.DiscreteTimeEnvironment#getTime()}
*
* @return the number of executed steps in the getSimulation
*/
long getSimulationStep();
/**
* Get the current simulation time. <p>Same as calling {@code getSimulation().getTime()}</p>
*
* @return the current time of the simulation
*/
long getTime();
String simulationName();
}
| gpl-3.0 |
Gooair/groovesquid | src/main/java/org/farng/mp3/id3/ID3v2_2.java | 20569 | package org.farng.mp3.id3;
import org.farng.mp3.AbstractMP3Tag;
import org.farng.mp3.InvalidTagException;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagConstant;
import org.farng.mp3.TagException;
import org.farng.mp3.TagNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Iterator;
/**
* <p class=t> The two biggest design goals were to be able to implement ID3v2 without disturbing old software too much
* and that ID3v2 should be expandable. </p>
* <p/>
* <p class=t> The first criterion is met by the simple fact that the <a href="#mpeg">MPEG</a> decoding software uses a
* syncsignal, embedded in the audiostream, to 'lock on to' the audio. Since the ID3v2 tag doesn't contain a valid
* syncsignal, no software will attempt to play the tag. If, for any reason, coincidence make a syncsignal appear within
* the tag it will be taken care of by the 'unsynchronisation scheme' described in section 5. </p>
* <p/>
* <p class=t> The second criterion has made a more noticeable impact on the design of the ID3v2 tag. It is constructed
* as a container for several information blocks, called frames, whose format need not be known to the software that
* encounters them. At the start of every frame there is an identifier that explains the frames's format and content,
* and a size descriptor that allows software to skip unknown frames. </p>
* <p/>
* <p class=t> If a total revision of the ID3v2 tag should be needed, there is a version number and a size descriptor in
* the ID3v2 header. </p>
* <p/>
* <p class=t> The ID3 tag described in this document is mainly targeted to files encoded with <a href="#mpeg">MPEG-2
* layer I, MPEG-2 layer II, MPEG-2 layer III</a> and MPEG-2.5, but may work with other types of encoded audio. </p>
* <p/>
* <p class=t> The bitorder in ID3v2 is most significant bit first (MSB). The byteorder in multibyte numbers is most
* significant byte first (e.g. $12345678 would be encoded $12 34 56 78). </p>
* <p/>
* <p class=t> It is permitted to include padding after all the final frame (at the end of the ID3 tag), making the size
* of all the frames together smaller than the size given in the head of the tag. A possible purpose of this padding is
* to allow for adding a few additional frames or enlarge existing frames within the tag without having to rewrite the
* entire file. The value of the padding bytes must be $00.<br> </p>
* <p/>
* <p class=t> <i>Padding is good as it increases the write speed when there is already a tag present in a file. If the
* new tag is one byte longer than the previous tag, than the extra byte can be taken from the padding, instead of
* having to shift the entire file one byte. Padding is of course bad in that it increases the size of the file, but if
* the amount of padding is wisely chosen (with clustersize in mind), the impact on filesystems will be virtually none.
* As the contents is $00, it is also easy for modems and other transmission devices/protocols to compress the padding.
* Having a $00 filled padding also increases the ability to recover erroneous tags.</i> </p> <p class=t> The ID3v2 tag
* header, which should be the first information in the file, is 10 bytes as follows: </p>
* <p/>
* <p><center> <table border=0> <tr><td nowrap>ID3/file identifier</td><td rowspan=3> </td><td
* width="100%">"ID3"</td></tr> <tr><td>ID3 version</td><td>$02 00</td></tr> <tr><td>ID3
* flags</td><td>%xx000000</td></tr> <tr><td>ID3 size</td><td>4 * </td><td>%0xxxxxxx</td></tr> </table> </center>
* <p/>
* <p class=t> The first three bytes of the tag are always "ID3" to indicate that this is an ID3 tag, directly followed
* by the two version bytes. The first byte of ID3 version is it's major version, while the second byte is its revision
* number. All revisions are backwards compatible while major versions are not. If software with ID3v2 and below support
* should encounter version three or higher it should simply ignore the whole tag. Version and revision will never be
* $FF. </p>
* <p/>
* <p class=t><i> In the first draft of ID3v2 the identifier was "TAG", just as in ID3v1. It was later changed to "MP3"
* as I thought of the ID3v2 as the fileheader MP3 had always been missing. When it became appearant than ID3v2 was
* going towards a general purpose audio header the identifier was changed to "ID3". </i></p>
* <p/>
* <p class=t> The first bit (bit 7) in the 'ID3 flags' is indicating whether or not <a
* href="#sec5">unsynchronisation</a> is used; a set bit indicates usage. </p>
* <p/>
* <p class=t> The second bit (bit 6) is indicating whether or not compression is used; a set bit indicates usage. Since
* no compression scheme has been decided yet, the ID3 decoder (for now) should just ignore the entire tag if the
* compression bit is set. </p>
* <p/>
* <p class=t><i> Currently, zlib compression is being considered for the compression, in an effort to stay out of the
* all-too-common marsh of patent trouble. Have a look at the additions draft for the latest developments. </i></p>
* <p/>
* <p class=t> The ID3 tag size is encoded with four bytes where the first bit (bit 7) is set to zero in every byte,
* making a total of 28 bits. The zeroed bits are ignored, so a 257 bytes long tag is represented as $00 00 02 01. </p>
* <p/>
* <p class=t><i> We really gave it a second thought several times before we introduced these awkward size descriptions.
* The reason is that we thought it would be even worse to have a file header with no set size (as we wanted to
* unsynchronise the header if there were any false synchronisations in it). An easy way of calculating the tag size is
* A*2^21+B*2^14+C*2^7+D = A*2097152+B*16384+C*128+D, where A is the first byte, B the second, C the third and D the
* fourth byte. </i></p>
* <p/>
* <p class=t> The ID3 tag size is the size of the complete tag after unsychronisation, including padding, excluding the
* header (total tag size - 10). The reason to use 28 bits (representing up to 256MB) for size description is that we
* don't want to run out of space here. </p>
* <p/>
* <p class=t> An ID3v2 tag can be detected with the following pattern:<br> $49 44 33 yy yy xx
* zz zz zz zz <br> Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80. </p>
*
* @author Eric Farng
* @version $Revision: 1.5 $
*/
public class ID3v2_2 extends AbstractID3v2 {
protected boolean compression = false;
protected boolean unsynchronization = false;
/**
* Creates a new ID3v2_2 object.
*/
public ID3v2_2() {
super();
setMajorVersion((byte) 2);
setRevision((byte) 2);
}
/**
* Creates a new ID3v2_2 object.
*/
public ID3v2_2(final ID3v2_2 copyObject) {
super(copyObject);
this.compression = copyObject.compression;
this.unsynchronization = copyObject.unsynchronization;
}
/**
* Creates a new ID3v2_2 object.
*/
public ID3v2_2(final AbstractMP3Tag mp3tag) {
if (mp3tag != null) {
final ID3v2_4 convertedTag;
if ((mp3tag instanceof ID3v2_3 == false) && (mp3tag instanceof ID3v2_2 == true)) {
throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument");
} else if (mp3tag instanceof ID3v2_4) {
convertedTag = (ID3v2_4) mp3tag;
} else {
convertedTag = new ID3v2_4(mp3tag);
}
this.compression = convertedTag.compression;
this.unsynchronization = convertedTag.unsynchronization;
final AbstractID3v2 id3tag = convertedTag;
final Iterator iterator = id3tag.getFrameIterator();
AbstractID3v2Frame frame;
ID3v2_2Frame newFrame;
while (iterator.hasNext()) {
frame = (AbstractID3v2Frame) iterator.next();
newFrame = new ID3v2_2Frame(frame);
this.setFrame(newFrame);
}
}
}
/**
* Creates a new ID3v2_2 object.
*/
public ID3v2_2(final RandomAccessFile file) throws TagException, IOException {
this.read(file);
}
public String getIdentifier() {
return "ID3v2_2.20";
}
public int getSize() {
int size = 3 + 2 + 1 + 4;
final Iterator iterator = getFrameIterator();
ID3v2_2Frame frame;
while (iterator.hasNext()) {
frame = (ID3v2_2Frame) iterator.next();
size += frame.getSize();
}
return size;
}
public void append(final AbstractMP3Tag tag) {
if (tag instanceof ID3v2_2) {
this.unsynchronization = ((ID3v2_2) tag).unsynchronization;
this.compression = ((ID3v2_2) tag).compression;
}
super.append(tag);
}
public boolean equals(final Object obj) {
if ((obj instanceof ID3v2_2) == false) {
return false;
}
final ID3v2_2 id3v2_2 = (ID3v2_2) obj;
if (this.compression != id3v2_2.compression) {
return false;
}
if (this.unsynchronization != id3v2_2.unsynchronization) {
return false;
}
return super.equals(obj);
}
public void overwrite(final AbstractMP3Tag tag) {
if (tag instanceof ID3v2_2) {
this.unsynchronization = ((ID3v2_2) tag).unsynchronization;
this.compression = ((ID3v2_2) tag).compression;
}
super.overwrite(tag);
}
public void read(final RandomAccessFile file) throws TagException, IOException {
final int size;
ID3v2_2Frame next;
final byte[] buffer = new byte[4];
if (seek(file) == false) {
throw new TagNotFoundException("ID3v2.20 tag not found");
}
// read the major and minor @version number & flags byte
file.read(buffer, 0, 3);
if ((buffer[0] != 2) || (buffer[1] != 0)) {
throw new TagNotFoundException(getIdentifier() + " tag not found");
}
setMajorVersion(buffer[0]);
setRevision(buffer[1]);
this.unsynchronization = (buffer[2] & TagConstant.MASK_V22_UNSYNCHRONIZATION) != 0;
this.compression = (buffer[2] & TagConstant.MASK_V22_COMPRESSION) != 0;
// read the size
file.read(buffer, 0, 4);
size = byteArrayToSize(buffer);
this.clearFrameMap();
final long filePointer = file.getFilePointer();
// read all frames
this.setFileReadBytes(size);
resetPaddingCounter();
while ((file.getFilePointer() - filePointer) <= size) {
try {
next = new ID3v2_2Frame(file);
final String id = next.getIdentifier();
if (this.hasFrame(id)) {
this.appendDuplicateFrameId(id + "; ");
this.incrementDuplicateBytes(getFrame(id).getSize());
}
this.setFrame(next);
} catch (InvalidTagException ex) {
if (ex.getMessage().equals("Found empty frame")) {
this.incrementEmptyFrameBytes(10);
} else {
this.incrementInvalidFrameBytes();
}
}
}
this.setPaddingSize(getPaddingCounter());
/**
* int newSize = this.getSize(); if ((this.padding + newSize - 10) !=
* size) { System.out.println("WARNING: Tag sizes don't add up");
* System.out.println("ID3v2.20 tag size : " + newSize);
* System.out.println("ID3v2.20 padding : " + this.padding);
* System.out.println("ID3v2.20 total : " + (this.padding + newSize));
* System.out.println("ID3v2.20 file size: " + size); }
*/
}
public boolean seek(final RandomAccessFile file) throws IOException {
final byte[] buffer = new byte[3];
file.seek(0);
// read the tag if it exists
file.read(buffer, 0, 3);
final String tag = new String(buffer, 0, 3);
if (tag.equals("ID3") == false) {
return false;
}
// read the major and minor @version number
file.read(buffer, 0, 2);
// read back the @version bytes so we can read and save them later
file.seek(file.getFilePointer() - 2);
return ((buffer[0] == 2) && (buffer[1] == 0));
}
public String toString() {
final Iterator iterator = this.getFrameIterator();
ID3v2_2Frame frame;
String str = getIdentifier() + " - " + this.getSize() + " bytes\n";
str += ("compression = " + this.compression + "\n");
str += ("unsynchronization = " + this.unsynchronization + "\n");
while (iterator.hasNext()) {
frame = (ID3v2_2Frame) iterator.next();
str += (frame.toString() + "\n");
}
return str + "\n";
}
public void write(final AbstractMP3Tag tag) {
if (tag instanceof ID3v2_2) {
this.unsynchronization = ((ID3v2_2) tag).unsynchronization;
this.compression = ((ID3v2_2) tag).compression;
}
super.write(tag);
}
public void write(final RandomAccessFile file) throws IOException {
final String str;
ID3v2_2Frame frame;
final Iterator iterator;
final byte[] buffer = new byte[6];
final MP3File mp3 = new MP3File();
mp3.seekMP3Frame(file);
final long mp3start = file.getFilePointer();
file.seek(0);
// write the first 10 tag bytes
str = "ID3";
for (int i = 0; i < str.length(); i++) {
buffer[i] = (byte) str.charAt(i);
}
buffer[3] = 2;
buffer[4] = 0;
if (this.unsynchronization) {
buffer[5] |= TagConstant.MASK_V22_UNSYNCHRONIZATION;
}
if (this.compression) {
buffer[5] |= TagConstant.MASK_V22_COMPRESSION;
}
file.write(buffer);
//write size;
file.write(sizeToByteArray((int) mp3start - 10));
// write all frames
iterator = this.getFrameIterator();
while (iterator.hasNext()) {
frame = (ID3v2_2Frame) iterator.next();
frame.write(file);
}
}
public String getSongTitle() {
String text = "";
AbstractID3v2Frame frame = getFrame("TIT2");
if (frame != null) {
FrameBodyTIT2 body = (FrameBodyTIT2) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getLeadArtist() {
String text = "";
AbstractID3v2Frame frame = getFrame("TPE1");
if (frame != null) {
FrameBodyTPE1 body = (FrameBodyTPE1) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getAlbumTitle() {
String text = "";
AbstractID3v2Frame frame = getFrame("TALB");
if (frame != null) {
FrameBodyTALB body = (FrameBodyTALB) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getYearReleased() {
String text = "";
AbstractID3v2Frame frame = getFrame("TYER");
if (frame != null) {
FrameBodyTYER body = (FrameBodyTYER) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getSongComment() {
String text = "";
AbstractID3v2Frame frame = getFrame("COMM" + ((char) 0) + "eng" + ((char) 0) + "");
if (frame != null) {
FrameBodyCOMM body = (FrameBodyCOMM) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getSongGenre() {
String text = "";
AbstractID3v2Frame frame = getFrame("TCON");
if (frame != null) {
FrameBodyTCON body = (FrameBodyTCON) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getTrackNumberOnAlbum() {
String text = "";
AbstractID3v2Frame frame = getFrame("TRCK");
if (frame != null) {
FrameBodyTRCK body = (FrameBodyTRCK) frame.getBody();
text = body.getText();
}
return text.trim();
}
public String getSongLyric() {
String text = "";
AbstractID3v2Frame frame = getFrame("SYLT");
if (frame != null) {
FrameBodySYLT body = (FrameBodySYLT) frame.getBody();
text = body.getLyric();
}
if (text == "") {
frame = getFrame("USLT" + ((char) 0) + "eng" + ((char) 0) + "");
if (frame != null) {
FrameBodyUSLT body = (FrameBodyUSLT) frame.getBody();
text = body.getLyric();
}
}
return text.trim();
}
public String getAuthorComposer() {
String text = "";
AbstractID3v2Frame frame = getFrame("TCOM");
if (frame != null) {
FrameBodyTCOM body = (FrameBodyTCOM) frame.getBody();
text = body.getText();
}
return text.trim();
}
public void setSongTitle(String songTitle) {
AbstractID3v2Frame field = getFrame("TIT2");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTIT2((byte) 0, songTitle.trim()));
setFrame(field);
} else {
((FrameBodyTIT2) field.getBody()).setText(songTitle.trim());
}
}
public void setLeadArtist(String leadArtist) {
AbstractID3v2Frame field = getFrame("TPE1");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTPE1((byte) 0, leadArtist.trim()));
setFrame(field);
} else {
((FrameBodyTPE1) field.getBody()).setText(leadArtist.trim());
}
}
public void setAlbumTitle(String albumTitle) {
AbstractID3v2Frame field = getFrame("TALB");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTALB((byte) 0, albumTitle.trim()));
setFrame(field);
} else {
((FrameBodyTALB) field.getBody()).setText(albumTitle.trim());
}
}
public void setYearReleased(String yearReleased) {
AbstractID3v2Frame field = getFrame("TYER");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTYER((byte) 0, yearReleased.trim()));
setFrame(field);
} else {
((FrameBodyTYER) field.getBody()).setText(yearReleased.trim());
}
}
public void setSongComment(String songComment) {
AbstractID3v2Frame field = getFrame("COMM");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyCOMM((byte) 0, "eng", "", songComment.trim()));
setFrame(field);
} else {
((FrameBodyCOMM) field.getBody()).setText(songComment.trim());
}
}
public void setSongGenre(String songGenre) {
AbstractID3v2Frame field = getFrame("TCON");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTCON((byte) 0, songGenre.trim()));
setFrame(field);
} else {
((FrameBodyTCON) field.getBody()).setText(songGenre.trim());
}
}
public void setTrackNumberOnAlbum(String trackNumberOnAlbum) {
AbstractID3v2Frame field = getFrame("TRCK");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTRCK((byte) 0, trackNumberOnAlbum.trim()));
setFrame(field);
} else {
((FrameBodyTRCK) field.getBody()).setText(trackNumberOnAlbum.trim());
}
}
public void setSongLyric(String songLyrics) {
AbstractID3v2Frame field = getFrame("USLT");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyUSLT((byte) 0, "ENG", "", songLyrics.trim()));
setFrame(field);
} else {
((FrameBodyUSLT) field.getBody()).setLyric(songLyrics.trim());
}
}
public void setAuthorComposer(String authorComposer) {
AbstractID3v2Frame field = getFrame("TCOM");
if (field == null) {
field = new ID3v2_2Frame(new FrameBodyTCOM((byte) 0, authorComposer.trim()));
setFrame(field);
} else {
((FrameBodyTCOM) field.getBody()).setText(authorComposer.trim());
}
}
} | gpl-3.0 |
railbu/jshoper3x | src/com/jshop/vo/GoodsCategoryPathVo.java | 544 | package com.jshop.vo;
import java.io.Serializable;
/**
* 商品分类递归路径
*
* @author sdywcd
*
*/
public class GoodsCategoryPathVo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4395258175126073759L;
private String name;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| gpl-3.0 |
mini024/HeatStress | app/src/main/java/com/example/jessicamcavazoserhard/heatstress/adapter/WeatherCardAdapter.java | 5025 | /**
Heat Stress is an Android health app.
Copyright (C) 2017 Heat Stress Team
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.example.jessicamcavazoserhard.heatstress.adapter;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.jessicamcavazoserhard.heatstress.R;
import com.example.jessicamcavazoserhard.heatstress.model.WeatherCard;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sabba on 3/19/2017.
*/
public class WeatherCardAdapter extends RecyclerView.Adapter<WeatherCardAdapter.WeatherCardHolder>{
private List<WeatherCard> listData;
private LayoutInflater inflater;
int card_green, card_red, card_orange, card_yellow;
public WeatherCardAdapter(List<WeatherCard> listData, Context c){
inflater = LayoutInflater.from(c);
this.listData = listData;
}
@Override
public WeatherCardAdapter.WeatherCardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.hourly_wether_card, parent, false);
return new WeatherCardHolder(view);
}
@Override
public void onBindViewHolder(WeatherCardHolder holder, int position) {
WeatherCard item = listData.get(position);
holder.hour.setText(item.getsHour());
holder.temp.setText(String.valueOf(item.getiTemperature())+" °F");
holder.hum.setText(String.valueOf(item.getiHumidity())+" %");
switch (item.getsWeather()){
case "Rainy": holder.weather_icon.setImageResource(R.drawable.rain);
break;
case "Clear": holder.weather_icon.setImageResource(R.drawable.sun);
break;
case "Partly Cloudy": holder.weather_icon.setImageResource(R.drawable.sun_cloud);
break;
case "Mostly Cloudy": holder.weather_icon.setImageResource(R.drawable.sun_cloud);
break;
case "Cloudy": holder.weather_icon.setImageResource(R.drawable.cloud);
break;
case "Windy": holder.weather_icon.setImageResource(R.drawable.wind);
break;
case "Snowy": holder.weather_icon.setImageResource(R.drawable.snow);
break;
}
switch (item.getColor()){
case "red":
holder.card.setBackgroundColor(card_red);
break;
case "orange":
holder.card.setBackgroundColor(card_orange);
break;
case "yellow":
holder.card.setBackgroundColor(card_yellow);
break;
default:
holder.card.setBackgroundColor(card_green);
break;
}
holder.temp_icon.setImageResource(R.drawable.temp);
holder.hum_icon.setImageResource(R.drawable.drops);
}
public void setListData(ArrayList<WeatherCard> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
@Override
public int getItemCount() {
return listData.size();
}
class WeatherCardHolder extends RecyclerView.ViewHolder{
ImageView weather_icon, temp_icon, hum_icon;
TextView hour, temp, hum;
View container;
RelativeLayout card;
public WeatherCardHolder(View itemView) {
super(itemView);
weather_icon = (ImageView)itemView.findViewById(R.id.iv_weather_card);
temp_icon = (ImageView)itemView.findViewById(R.id.iv_temp_card);
hum_icon = (ImageView)itemView.findViewById(R.id.iv_hum_card);
hour = (TextView)itemView.findViewById(R.id.tv_hour_card);
temp = (TextView) itemView.findViewById(R.id.tv_temp_card);
hum = (TextView) itemView.findViewById(R.id.tv_hum_card);
card = (RelativeLayout)itemView.findViewById(R.id.card);
container = (View)itemView.findViewById(R.id.cont_item_root);
card_green = Color.parseColor("#5CB04F");
card_orange = Color.parseColor("#F59323");
card_red = Color.parseColor("#E35349");
card_yellow = Color.parseColor("#FED849");
}
}
}
| gpl-3.0 |
Shadorc/Shadbot | src/main/java/com/shadorc/shadbot/command/owner/LoggerCmd.java | 2261 | package com.shadorc.shadbot.command.owner;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.shadorc.shadbot.command.CommandException;
import com.shadorc.shadbot.core.command.*;
import com.shadorc.shadbot.object.Emoji;
import com.shadorc.shadbot.utils.DiscordUtil;
import discord4j.rest.util.ApplicationCommandOptionType;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import static com.shadorc.shadbot.Shadbot.DEFAULT_LOGGER;
public class LoggerCmd extends SubCmd {
private enum LogLevel {
OFF,
TRACE,
DEBUG,
INFO,
WARN,
ERROR
}
public LoggerCmd(final GroupCmd groupCmd) {
super(groupCmd, CommandCategory.OWNER, CommandPermission.OWNER, "logger",
"Change the level of a logger");
this.addOption(option -> option.name("name")
.description("Can be 'root' to change root logger")
.required(true)
.type(ApplicationCommandOptionType.STRING.getValue()));
this.addOption(option -> option.name("level")
.description("The new logger level")
.required(true)
.type(ApplicationCommandOptionType.STRING.getValue())
.choices(DiscordUtil.toOptions(LogLevel.class)));
}
@Override
public Mono<?> execute(Context context) {
final String name = context.getOptionAsString("name").orElseThrow();
final LogLevel logLevel = context.getOptionAsEnum(LogLevel.class, "level").orElseThrow();
final Level level = Level.toLevel(logLevel.name(), null);
if (level == null) {
return Mono.error(new CommandException("`%s` in not a valid level.".formatted(logLevel)));
}
final Logger logger;
if ("root".equalsIgnoreCase(name)) {
logger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
} else {
logger = (Logger) LoggerFactory.getLogger(name);
}
logger.setLevel(level);
DEFAULT_LOGGER.info("Logger '{}' set to level {}", name, level);
return context.createFollowupMessage(Emoji.INFO, "Logger `%s` set to level `%s`.".formatted(name, level));
}
}
| gpl-3.0 |
angecab10/travelport-uapi-tutorial | src/com/travelport/schema/common_v28_0/TypeSource.java | 1475 |
package com.travelport.schema.common_v28_0;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for typeSource.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="typeSource">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Agency"/>
* <enumeration value="BranchGroup"/>
* <enumeration value="Branch"/>
* <enumeration value="Agent"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "typeSource")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:09:21-06:00", comment = "JAXB RI v2.2.6")
public enum TypeSource {
@XmlEnumValue("Agency")
AGENCY("Agency"),
@XmlEnumValue("BranchGroup")
BRANCH_GROUP("BranchGroup"),
@XmlEnumValue("Branch")
BRANCH("Branch"),
@XmlEnumValue("Agent")
AGENT("Agent");
private final String value;
TypeSource(String v) {
value = v;
}
public String value() {
return value;
}
public static TypeSource fromValue(String v) {
for (TypeSource c: TypeSource.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| gpl-3.0 |
lerv22/Security-Manager | MonitorAuditoria/src/java/Services/LastEvents.java | 1911 | package Services;
import Beans.Logs;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LastEvents extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
if ("events".equals(request.getParameter("call"))) {
String s;
if (Beans.DBConnector.conectDB()) {
s = Beans.DBConnector.ResumenAudit();
} else {
s = "[{\"User\":\"No data\", \"Statement\":\"No data\", \"SQL\":\"No data\",\"Date\":\"No data\",\"State\":\"No data\"}]";
}
Logs.logAudit("consult");
out.print(s);
}
} catch (SQLException ex) {
Logger.getLogger(LastEvents.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| gpl-3.0 |
Nushio/ArenaClient | src/net/k3rnel/arena/client/backend/FileLoader.java | 1624 | /**
* This file is part of Distro Wars (Client).
*
* Distro Wars (Client) 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.
* Distro Wars (Client) 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 Distro Wars (Client). If not, see <http://www.gnu.org/licenses/>.
*/
package net.k3rnel.arena.client.backend;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* A simple file loader to make our lives easier
* @author ZombieBear
*
*/
public class FileLoader {
/**
* Loads a file as an InputStream
* @param path
* @return an InputStream of a file
* @throws FileNotFoundException
*/
public static InputStream loadFile(String path) throws FileNotFoundException {
return new FileInputStream(path);
}
/**
* Loads a text file and gets it ready for parsing
* @param path
* @return a BufferedReader for a text file
* @throws FileNotFoundException
*/
public static BufferedReader loadTextFile(String path) throws FileNotFoundException {
return new BufferedReader(new InputStreamReader(loadFile(path)));
}
}
| gpl-3.0 |
AftonTroll/Avoidance | src/se/chalmers/avoidance/core/collisionhandlers/WallCollisionHandler.java | 5223 | /*
* Copyright (c) 2012 Jakob Svensson
*
* This file is part of Avoidance.
*
* Avoidance 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.
*
* Avoidance 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 Avoidance. If not, see <http://www.gnu.org/licenses/>.
*
*/
package se.chalmers.avoidance.core.collisionhandlers;
import se.chalmers.avoidance.core.components.Size;
import se.chalmers.avoidance.core.components.Sound;
import se.chalmers.avoidance.core.components.Transform;
import se.chalmers.avoidance.core.components.Velocity;
import se.chalmers.avoidance.util.Utils;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.World;
/**
* Handles collisions between the player and a wall.
*
* @author Jakob Svensson
* @author Markus Ekström
*/
public class WallCollisionHandler implements CollisionHandler {
private ComponentMapper<Velocity> velocityMapper;
private ComponentMapper<Transform> transformMapper;
private ComponentMapper<Size> sizeMapper;
private ComponentMapper<Sound> soundMapper;
private Transform playerTransform;
private Size playerSize;
private float wallWidth;
private float wallHeight;
private float wallX;
private float wallY;
private float angle;
private float newAngle;
/**
* Constructs a WallCollisionHandler
*
* @param world
* The world.
*/
public WallCollisionHandler(World world) {
velocityMapper = ComponentMapper.getFor(Velocity.class, world);
transformMapper = ComponentMapper.getFor(Transform.class, world);
sizeMapper = ComponentMapper.getFor(Size.class, world);
soundMapper = ComponentMapper.getFor(Sound.class, world);
}
/**
* Handles collision between moving entities and walls
*
* @param movingEntity
* the moving entity
* @param wall
* the wall
*/
public void handleCollision(Entity movingEntity, Entity wall) {
Size wallSize = sizeMapper.get(wall);
Transform wallTransform = transformMapper.get(wall);
Velocity playerVelocity = velocityMapper.get(movingEntity);
playerSize = sizeMapper.get(movingEntity);
playerTransform = transformMapper.get(movingEntity);
Sound sound = soundMapper.get(wall);
if (sound != null) {
sound.setPlaying(true);
}
wallWidth = wallSize.getWidth();
wallHeight = wallSize.getHeight();
wallX = wallTransform.getX();
wallY = wallTransform.getY();
angle = playerVelocity.getAngle();
newAngle = angle;
// Check if player collides with horizontal side or vertical side
if (playerTransform.getX() + playerSize.getWidth() / 2 > wallX
&& playerTransform.getX() + playerSize.getWidth() / 2 < wallX
+ wallWidth) {
handleHorisontalSideCollision();
} else if (playerTransform.getY() + playerSize.getHeight() / 2 > wallY
&& playerTransform.getY() + playerSize.getHeight() / 2 < wallY
+ wallHeight) {
handleVerticalSideCollision();
} else {
// Corner or almost corner collision
handleCornerCollison();
}
playerVelocity.setAngle(newAngle);
}
private void handleHorisontalSideCollision() {
newAngle = flipVertical(angle);
if (angle > Math.PI) {
// Collision on lower side of the wall
playerTransform.setY(wallY + wallHeight);
} else {
// Collision on upper side of the wall
playerTransform.setY(wallY - playerSize.getHeight());
}
}
private void handleVerticalSideCollision() {
newAngle = flipHorizontal(angle);
if (angle > Math.PI / 2 && angle < (Math.PI * 3) / 2) {
// Collision on right side of wall
playerTransform.setX(wallX + wallWidth);
} else {
// Collision on left side of wall
playerTransform.setX(wallX - playerSize.getWidth());
}
}
private void handleCornerCollison() {
if (playerTransform.getX() > wallX) {
if (playerTransform.getY() > wallY) {
// Collision near lower right corner
playerTransform.setX(wallX + wallWidth);
playerTransform.setY(wallY + wallHeight);
} else {
// Collision near upper right corner
playerTransform.setX(wallX + wallWidth);
playerTransform.setY(wallY - playerSize.getHeight());
}
} else {
if (playerTransform.getY() > wallY) {
// Collision near lower left corner
playerTransform.setX(wallX - playerSize.getWidth());
playerTransform.setY(wallY + wallHeight);
} else {
// Collision near upper left corner
playerTransform.setX(wallX - playerSize.getWidth());
playerTransform.setY(wallY - playerSize.getHeight());
}
}
newAngle = Utils.reverseAngle(angle);
}
private float flipVertical(float angle) {
return angle * -1;
}
private float flipHorizontal(float angle) {
// Translate and then flip vertical
newAngle = angle + (float) Math.PI / 2;
newAngle = flipVertical(newAngle);
newAngle -= Math.PI / 2;
return newAngle;
}
}
| gpl-3.0 |
Ahaochan/invoice | ahao-spring-boot-swagger/src/main/java/moe/ahao/spring/boot/swagger/controller/UserController.java | 2931 | package moe.ahao.spring.boot.swagger.controller;
import io.swagger.annotations.*;
import moe.ahao.spring.boot.swagger.entity.User;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping(value = "/users")
@Api(value = "没用的属性", tags = {"功能分组1", "功能分组2"})
public class UserController {
@ApiOperation(value = "@ApiOperation的简单使用", notes = "Api详细说明", hidden = false,
response = User.class, responseContainer = "List",
produces = "响应体(Response content type), application/json, application/xml",
consumes = "请求体(Parameter content type), application/json, application/xml"
)
@GetMapping
public List<User> apiOperation(@RequestBody User user) {
return Collections.singletonList(new User());
}
@ApiOperation(value = "@ApiImplicitParam的简单使用",response = User.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "主键id", example = "1", required = true, dataTypeClass = Long.class, paramType = "path"),
@ApiImplicitParam(name = "sex", value = "性别", example = "男", defaultValue = "男", allowableValues = "男, 女", required = true, dataTypeClass = String.class, paramType = "query"),
@ApiImplicitParam(name = "password", value = "密码", example = "abc", required = true, dataTypeClass = Long.class, paramType = "query")
})
@PostMapping(value = "/apiImplicitParam/{id}")
public User apiImplicitParam(@PathVariable Long id, @RequestParam String sex, @RequestParam String password) {
return new User();
}
@ApiOperation(value = "@ApiParam的简单使用")
@PutMapping(value = "/apiParam/{id}")
public User apiParam(@ApiParam(name = "id", value = "主键id", example = "1", required = true, type = "java.lang.Long") @PathVariable Long id,
@ApiParam(name = "sex", value = "性别", example = "男", defaultValue = "男", allowableValues = "男, 女", required = true, type = "java.lang.String") @RequestParam String sex,
@ApiParam(name = "password", value = "密码", example = "abc", required = true, type = "java.lang.Long") @RequestParam String password) {
return new User();
}
@ApiOperation(value = "@ApiResponses的简单使用")
@ApiResponses({
@ApiResponse(code = 200, message = "成功", response = User.class, responseContainer = "List"),
@ApiResponse(code = 401, message = "网站没找到", response = String.class),
@ApiResponse(code = 404, message = "网站没找到", response = String.class),
@ApiResponse(code = 500, message = "服务器错误", response = String.class)
})
@DeleteMapping(value = "/apiResponses")
public Object apiResponses() {
return new User();
}
}
| gpl-3.0 |
RWTH-i5-IDSG/steve-plugsurfing | src/main/java/de/rwth/idsg/steve/web/dto/ocpp15/SendLocalListParams.java | 1640 | package de.rwth.idsg.steve.web.dto.ocpp15;
import de.rwth.idsg.steve.web.dto.common.MultipleChargePointSelect;
import lombok.Getter;
import lombok.Setter;
import ocpp.cp._2012._06.UpdateType;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Sevket Goekay <goekay@dbis.rwth-aachen.de>
* @since 03.01.2015
*/
@Setter
@Getter
public class SendLocalListParams extends MultipleChargePointSelect {
@NotNull(message = "List version is required")
private Integer listVersion;
@NotNull(message = "Update Type is required")
private UpdateType updateType = UpdateType.FULL;
private List<String> deleteList;
private List<String> addUpdateList;
@AssertTrue(message = "When Update Type is DIFFERENTIAL, either Add/Update or Delete list should not be empty")
public boolean isValidWhenDifferential() {
return UpdateType.FULL.equals(updateType) || !getDeleteList().isEmpty() || !getAddUpdateList().isEmpty();
}
@AssertTrue(message = "The Add/Update and Delete lists should have no elements in common")
public boolean isDisjoint() {
return Collections.disjoint(getDeleteList(), getAddUpdateList());
}
public List<String> getDeleteList() {
if (deleteList == null) {
deleteList = new ArrayList<>();
}
return deleteList;
}
public List<String> getAddUpdateList() {
if (addUpdateList == null) {
addUpdateList = new ArrayList<>();
}
return addUpdateList;
}
}
| gpl-3.0 |
OmniEvo/android_frameworks_base | services/core/java/com/android/server/BluetoothManagerService.java | 79048 | /*
* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
* Not a Contribution.
*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetooth;
import android.bluetooth.IBluetoothCallback;
import android.bluetooth.IBluetoothGatt;
import android.bluetooth.IBluetoothHeadset;
import android.bluetooth.IBluetoothManager;
import android.bluetooth.IBluetoothManagerCallback;
import android.bluetooth.IBluetoothProfileServiceConnection;
import android.bluetooth.IBluetoothStateChangeCallback;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.database.ContentObserver;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
class BluetoothManagerService extends IBluetoothManager.Stub {
private static final String TAG = "BluetoothManagerService";
private static final boolean DBG = false;
private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
private static final String EXTRA_ACTION="action";
private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
//Maximum msec to wait for service restart
private static final int SERVICE_RESTART_TIME_MS = 200;
//Maximum msec to wait for restart due to error
private static final int ERROR_RESTART_TIME_MS = 3000;
//Maximum msec to delay MESSAGE_USER_SWITCHED
private static final int USER_SWITCHED_TIME_MS = 200;
// Delay for the addProxy function in msec
private static final int ADD_PROXY_DELAY_MS = 100;
private static final int MESSAGE_ENABLE = 1;
private static final int MESSAGE_DISABLE = 2;
private static final int MESSAGE_REGISTER_ADAPTER = 20;
private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
private static final int MESSAGE_BLUETOOTH_STATE_CHANGE=60;
private static final int MESSAGE_TIMEOUT_BIND =100;
private static final int MESSAGE_TIMEOUT_UNBIND =101;
private static final int MESSAGE_GET_NAME_AND_ADDRESS=200;
private static final int MESSAGE_SAVE_NAME_AND_ADDRESS=201;
private static final int MESSAGE_USER_SWITCHED = 300;
private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
private static final int MAX_SAVE_RETRIES=3;
private static final int MAX_ERROR_RESTART_RETRIES=6;
// Bluetooth persisted setting is off
private static final int BLUETOOTH_OFF=0;
// Bluetooth persisted setting is on
// and Airplane mode won't affect Bluetooth state at start up
private static final int BLUETOOTH_ON_BLUETOOTH=1;
// Bluetooth persisted setting is on
// but Airplane mode will affect Bluetooth state at start up
// and Airplane mode will have higher priority.
private static final int BLUETOOTH_ON_AIRPLANE=2;
private static final int SERVICE_IBLUETOOTH = 1;
private static final int SERVICE_IBLUETOOTHGATT = 2;
private static final String[] DEVICE_TYPE_NAMES = new String[] {
"???",
"BR/EDR",
"LE",
"DUAL"
};
private final Context mContext;
private static int mBleAppCount = 0;
// Locks are not provided for mName and mAddress.
// They are accessed in handler or broadcast receiver, same thread context.
private String mAddress;
private String mName;
private final ContentResolver mContentResolver;
private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
private IBluetooth mBluetooth;
private IBluetoothGatt mBluetoothGatt;
private boolean mBinding;
private boolean mUnbinding;
// used inside handler thread
private boolean mQuietEnable = false;
// configuarion from external IBinder call which is used to
// synchronize with broadcast receiver.
private boolean mQuietEnableExternal;
// configuarion from external IBinder call which is used to
// synchronize with broadcast receiver.
private boolean mEnableExternal;
// used inside handler thread
private boolean mEnable;
private int mState;
private final BluetoothHandler mHandler;
private int mErrorRecoveryRetryCounter;
private final int mSystemUiUid;
// Save a ProfileServiceConnections object for each of the bound
// bluetooth profile services
private final Map <Integer, ProfileServiceConnections> mProfileServices =
new HashMap <Integer, ProfileServiceConnections>();
private void registerForAirplaneMode(IntentFilter filter) {
final ContentResolver resolver = mContext.getContentResolver();
final String airplaneModeRadios = Settings.Global.getString(resolver,
Settings.Global.AIRPLANE_MODE_RADIOS);
final String toggleableRadios = Settings.Global.getString(resolver,
Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
if (mIsAirplaneSensitive) {
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
}
}
private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
@Override
public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
mHandler.sendMessage(msg);
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
if (newName != null) {
storeNameAndAddress(newName, null);
}
} else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
synchronized(mReceiver) {
if (isBluetoothPersistedStateOn()) {
if (isAirplaneModeOn()) {
persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
} else {
persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
}
}
int st = BluetoothAdapter.STATE_OFF;
if (mBluetooth != null) {
try {
st = mBluetooth.getState();
} catch (RemoteException e) {
Log.e(TAG,"Unable to call getState", e);
}
}
Log.d(TAG, "state" + st);
if (isAirplaneModeOn()) {
// Clear registered LE apps to force shut-off
synchronized (this) {
mBleAppCount = 0;
mBleApps.clear();
}
if (st == BluetoothAdapter.STATE_BLE_ON) {
//if state is BLE_ON make sure you trigger disableBLE part
try {
if (mBluetooth != null) {
mBluetooth.onBrEdrDown();
mEnableExternal = false;
}
} catch(RemoteException e) {
Log.e(TAG,"Unable to call onBrEdrDown", e);
}
} else if (st == BluetoothAdapter.STATE_ON){
// disable without persisting the setting
Log.d(TAG, "Calling disable");
sendDisableMsg();
}
} else if (mEnableExternal) {
// enable without persisting the setting
Log.d(TAG, "Calling enable");
sendEnableMsg(mQuietEnableExternal);
}
}
}
}
};
BluetoothManagerService(Context context) {
mHandler = new BluetoothHandler(IoThread.get().getLooper());
mContext = context;
mBluetooth = null;
mBluetoothGatt = null;
mBinding = false;
mUnbinding = false;
mEnable = false;
mState = BluetoothAdapter.STATE_OFF;
mQuietEnableExternal = false;
mEnableExternal = false;
mAddress = null;
mName = null;
mErrorRecoveryRetryCounter = 0;
mContentResolver = context.getContentResolver();
// Observe BLE scan only mode settings change.
registerForBleScanModeChange();
mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
registerForAirplaneMode(filter);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
mContext.registerReceiver(mReceiver, filter);
loadStoredNameAndAddress();
if (isBluetoothPersistedStateOn()) {
mEnableExternal = true;
}
int sysUiUid = -1;
try {
sysUiUid = mContext.getPackageManager().getPackageUid("com.android.systemui",
UserHandle.USER_OWNER);
} catch (PackageManager.NameNotFoundException e) {
// Some platforms, such as wearables do not have a system ui.
Log.w(TAG, "Unable to resolve SystemUI's UID.", e);
}
mSystemUiUid = sysUiUid;
}
/**
* Returns true if airplane mode is currently on
*/
private final boolean isAirplaneModeOn() {
return Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
}
/**
* Returns true if the Bluetooth saved state is "on"
*/
private final boolean isBluetoothPersistedStateOn() {
return Settings.Global.getInt(mContentResolver,
Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
}
/**
* Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
*/
private final boolean isBluetoothPersistedStateOnBluetooth() {
return Settings.Global.getInt(mContentResolver,
Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
}
/**
* Save the Bluetooth on/off state
*
*/
private void persistBluetoothSetting(int value) {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.BLUETOOTH_ON,
value);
}
/**
* Returns true if the Bluetooth Adapter's name and address is
* locally cached
* @return
*/
private boolean isNameAndAddressSet() {
return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
}
/**
* Retrieve the Bluetooth Adapter's name and address and save it in
* in the local cache
*/
private void loadStoredNameAndAddress() {
if (DBG) Log.d(TAG, "Loading stored name and address");
if (mContext.getResources().getBoolean
(com.android.internal.R.bool.config_bluetooth_address_validation) &&
Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
// if the valid flag is not set, don't load the address and name
if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
return;
}
mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
}
/**
* Save the Bluetooth name and address in the persistent store.
* Only non-null values will be saved.
* @param name
* @param address
*/
private void storeNameAndAddress(String name, String address) {
if (name != null) {
Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
mName = name;
if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
}
if (address != null) {
Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
mAddress=address;
if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
}
if ((name != null) && (address != null)) {
Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
}
}
public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
if (callback == null) {
Log.w(TAG, "Callback is null in registerAdapter");
return null;
}
Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
msg.obj = callback;
mHandler.sendMessage(msg);
synchronized(mConnection) {
return mBluetooth;
}
}
public void unregisterAdapter(IBluetoothManagerCallback callback) {
if (callback == null) {
Log.w(TAG, "Callback is null in unregisterAdapter");
return;
}
mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
"Need BLUETOOTH permission");
Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
msg.obj = callback;
mHandler.sendMessage(msg);
}
public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
"Need BLUETOOTH permission");
Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
msg.obj = callback;
mHandler.sendMessage(msg);
}
public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
"Need BLUETOOTH permission");
Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
msg.obj = callback;
mHandler.sendMessage(msg);
}
public boolean isEnabled() {
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!checkIfCallerIsForegroundUser())) {
Log.w(TAG,"isEnabled(): not allowed for non-active and non system user");
return false;
}
synchronized(mConnection) {
try {
return (mBluetooth != null && mBluetooth.isEnabled());
} catch (RemoteException e) {
Log.e(TAG, "isEnabled()", e);
}
}
return false;
}
class ClientDeathRecipient implements IBinder.DeathRecipient {
public void binderDied() {
if (DBG) Log.d(TAG, "Binder is dead - unregister Ble App");
if (mBleAppCount > 0) --mBleAppCount;
if (mBleAppCount == 0) {
if (DBG) Log.d(TAG, "Disabling LE only mode after application crash");
try {
if (mBluetooth != null) {
mBluetooth.onBrEdrDown();
}
} catch(RemoteException e) {
Log.e(TAG,"Unable to call onBrEdrDown", e);
}
}
}
}
/** Internal death rec list */
Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
@Override
public boolean isBleScanAlwaysAvailable() {
try {
return (Settings.Global.getInt(mContentResolver,
Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
} catch (SettingNotFoundException e) {
}
return false;
}
// Monitor change of BLE scan only mode settings.
private void registerForBleScanModeChange() {
ContentObserver contentObserver = new ContentObserver(null) {
@Override
public void onChange(boolean selfChange) {
if (!isBleScanAlwaysAvailable()) {
disableBleScanMode();
clearBleApps();
try {
if (mBluetooth != null) mBluetooth.onBrEdrDown();
} catch (RemoteException e) {
Log.e(TAG, "error when disabling bluetooth", e);
}
}
}
};
mContentResolver.registerContentObserver(
Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
false, contentObserver);
}
// Disable ble scan only mode.
private void disableBleScanMode() {
try {
if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
if (DBG) Log.d(TAG, "Reseting the mEnable flag for clean disable");
mEnable = false;
}
} catch (RemoteException e) {
Log.e(TAG, "getState()", e);
}
}
public int updateBleAppCount(IBinder token, boolean enable) {
if (enable) {
ClientDeathRecipient r = mBleApps.get(token);
if (r == null) {
ClientDeathRecipient deathRec = new ClientDeathRecipient();
try {
token.linkToDeath(deathRec, 0);
} catch (RemoteException ex) {
throw new IllegalArgumentException("Wake lock is already dead.");
}
mBleApps.put(token, deathRec);
synchronized (this) {
++mBleAppCount;
}
if (DBG) Log.d(TAG, "Registered for death Notification");
}
} else {
ClientDeathRecipient r = mBleApps.get(token);
if (r != null) {
// Unregister death recipient as the app goes away.
token.unlinkToDeath(r, 0);
mBleApps.remove(token);
synchronized (this) {
if (mBleAppCount > 0) --mBleAppCount;
}
if (DBG) Log.d(TAG, "Unregistered for death Notification");
}
}
if (DBG) Log.d(TAG, "Updated BleAppCount" + mBleAppCount);
if (mBleAppCount == 0 && mEnable) {
disableBleScanMode();
}
return mBleAppCount;
}
// Clear all apps using BLE scan only mode.
private void clearBleApps() {
synchronized (this) {
mBleApps.clear();
mBleAppCount = 0;
}
}
/** @hide*/
public boolean isBleAppPresent() {
if (DBG) Log.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
return (mBleAppCount > 0);
}
/**
* Action taken when GattService is turned off
*/
private void onBluetoothGattServiceUp() {
if (DBG) Log.d(TAG,"BluetoothGatt Service is Up");
try{
if (isBleAppPresent() == false && mBluetooth != null
&& mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
mBluetooth.onLeServiceUp();
// waive WRITE_SECURE_SETTINGS permission check
long callingIdentity = Binder.clearCallingIdentity();
persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Binder.restoreCallingIdentity(callingIdentity);
}
} catch(RemoteException e) {
Log.e(TAG,"Unable to call onServiceUp", e);
}
}
/**
* Inform BluetoothAdapter instances that BREDR part is down
* and turn off all service and stack if no LE app needs it
*/
private void sendBrEdrDownCallback() {
if (DBG) Log.d(TAG,"Calling sendBrEdrDownCallback callbacks");
if(mBluetooth == null) {
Log.w(TAG, "Bluetooth handle is null");
return;
}
if (isBleAppPresent() == false) {
try {
mBluetooth.onBrEdrDown();
} catch(RemoteException e) {
Log.e(TAG, "Call to onBrEdrDown() failed.", e);
}
} else {
// Need to stay at BLE ON. Disconnect all Gatt connections
try{
mBluetoothGatt.unregAll();
} catch(RemoteException e) {
Log.e(TAG, "Unable to disconnect all apps.", e);
}
}
}
/** @hide*/
public void getNameAndAddress() {
if (DBG) {
Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
" mBinding = " + mBinding);
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
mHandler.sendMessage(msg);
}
public boolean enableNoAutoConnect()
{
mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH ADMIN permission");
if (DBG) {
Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
" mBinding = " + mBinding);
}
int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
if (callingAppId != Process.NFC_UID) {
throw new SecurityException("no permission to enable Bluetooth quietly");
}
synchronized(mReceiver) {
mQuietEnableExternal = true;
mEnableExternal = true;
sendEnableMsg(true);
}
return true;
}
public boolean enable() {
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!checkIfCallerIsForegroundUser())) {
Log.w(TAG,"enable(): not allowed for non-active and non system user");
return false;
}
mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH ADMIN permission");
if (DBG) {
Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
" mBinding = " + mBinding);
}
synchronized(mReceiver) {
mQuietEnableExternal = false;
mEnableExternal = true;
// waive WRITE_SECURE_SETTINGS permission check
sendEnableMsg(false);
}
if (DBG) Log.d(TAG, "enable returning");
return true;
}
public boolean disable(boolean persist) {
mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!checkIfCallerIsForegroundUser())) {
Log.w(TAG,"disable(): not allowed for non-active and non system user");
return false;
}
if (DBG) {
Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
" mBinding = " + mBinding);
}
synchronized(mReceiver) {
if (persist) {
// waive WRITE_SECURE_SETTINGS permission check
long callingIdentity = Binder.clearCallingIdentity();
persistBluetoothSetting(BLUETOOTH_OFF);
Binder.restoreCallingIdentity(callingIdentity);
}
mEnableExternal = false;
sendDisableMsg();
}
return true;
}
public void unbindAndFinish() {
if (DBG) {
Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
" mBinding = " + mBinding);
}
synchronized (mConnection) {
if (mUnbinding) return;
mUnbinding = true;
if (mBluetooth != null) {
if (!mConnection.isGetNameAddressOnly()) {
//Unregister callback object
try {
mBluetooth.unregisterCallback(mBluetoothCallback);
} catch (RemoteException re) {
Log.e(TAG, "Unable to unregister BluetoothCallback",re);
}
}
if (DBG) Log.d(TAG, "Sending unbind request.");
mBluetooth = null;
//Unbind
mContext.unbindService(mConnection);
mUnbinding = false;
mBinding = false;
} else {
mUnbinding=false;
}
mBluetoothGatt = null;
}
}
public IBluetoothGatt getBluetoothGatt() {
// sync protection
return mBluetoothGatt;
}
@Override
public boolean bindBluetoothProfileService(int bluetoothProfile,
IBluetoothProfileServiceConnection proxy) {
if (!mEnable) {
if (DBG) {
Log.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
", while Bluetooth was disabled");
}
return false;
}
synchronized (mProfileServices) {
ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
if (psc == null) {
if (DBG) {
Log.d(TAG, "Creating new ProfileServiceConnections object for"
+ " profile: " + bluetoothProfile);
}
if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
Intent intent = new Intent(IBluetoothHeadset.class.getName());
psc = new ProfileServiceConnections(intent);
if (!psc.bindService()) return false;
mProfileServices.put(new Integer(bluetoothProfile), psc);
}
}
// Introducing a delay to give the client app time to prepare
Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
addProxyMsg.arg1 = bluetoothProfile;
addProxyMsg.obj = proxy;
mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
return true;
}
@Override
public void unbindBluetoothProfileService(int bluetoothProfile,
IBluetoothProfileServiceConnection proxy) {
synchronized (mProfileServices) {
ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
if (psc == null) {
return;
}
psc.removeProxy(proxy);
}
}
private void unbindAllBluetoothProfileServices() {
synchronized (mProfileServices) {
for (Integer i : mProfileServices.keySet()) {
ProfileServiceConnections psc = mProfileServices.get(i);
try {
mContext.unbindService(psc);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
}
psc.removeAllProxies();
}
mProfileServices.clear();
}
}
/**
* Send enable message and set adapter name and address. Called when the boot phase becomes
* PHASE_SYSTEM_SERVICES_READY.
*/
public void handleOnBootPhase() {
if (DBG) Log.d(TAG, "Bluetooth boot completed");
if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
sendEnableMsg(mQuietEnableExternal);
}
if (!isNameAndAddressSet()) {
// Sync the Bluetooth name and address from the Bluetooth Adapter
if (DBG) Log.d(TAG, "Retrieving Bluetooth Adapter name and address...");
getNameAndAddress();
}
}
/**
* Called when switching to a different foreground user.
*/
public void handleOnSwitchUser(int userHandle) {
if (DBG) Log.d(TAG, "Bluetooth user switched");
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0));
}
/**
* This class manages the clients connected to a given ProfileService
* and maintains the connection with that service.
*/
final private class ProfileServiceConnections implements ServiceConnection,
IBinder.DeathRecipient {
final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
new RemoteCallbackList <IBluetoothProfileServiceConnection>();
IBinder mService;
ComponentName mClassName;
Intent mIntent;
boolean mInvokingProxyCallbacks = false;
ProfileServiceConnections(Intent intent) {
mService = null;
mClassName = null;
mIntent = intent;
}
private boolean bindService() {
if (mIntent != null && mService == null &&
doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
msg.obj = this;
mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
return true;
}
Log.w(TAG, "Unable to bind with intent: " + mIntent);
return false;
}
private void addProxy(IBluetoothProfileServiceConnection proxy) {
mProxies.register(proxy);
if (mService != null) {
try{
proxy.onServiceConnected(mClassName, mService);
} catch (RemoteException e) {
Log.e(TAG, "Unable to connect to proxy", e);
}
} else {
if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
msg.obj = this;
mHandler.sendMessage(msg);
}
}
}
private void removeProxy(IBluetoothProfileServiceConnection proxy) {
if (proxy != null) {
if (mProxies.unregister(proxy)) {
try {
proxy.onServiceDisconnected(mClassName);
} catch (RemoteException e) {
Log.e(TAG, "Unable to disconnect proxy", e);
}
}
} else {
Log.w(TAG, "Trying to remove a null proxy");
}
}
private void removeAllProxies() {
onServiceDisconnected(mClassName);
mProxies.kill();
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// remove timeout message
mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
mService = service;
mClassName = className;
try {
mService.linkToDeath(this, 0);
} catch (RemoteException e) {
Log.e(TAG, "Unable to linkToDeath", e);
}
if (mInvokingProxyCallbacks) {
Log.e(TAG, "Proxy callbacks already in progress.");
return;
}
mInvokingProxyCallbacks = true;
final int n = mProxies.beginBroadcast();
try {
for (int i = 0; i < n; i++) {
try {
mProxies.getBroadcastItem(i).onServiceConnected(className, service);
} catch (RemoteException e) {
Log.e(TAG, "Unable to connect to proxy", e);
}
}
} finally {
mProxies.finishBroadcast();
mInvokingProxyCallbacks = false;
}
}
@Override
public void onServiceDisconnected(ComponentName className) {
if (mService == null) return;
mService.unlinkToDeath(this, 0);
mService = null;
mClassName = null;
if (mInvokingProxyCallbacks) {
Log.e(TAG, "Proxy callbacks already in progress.");
return;
}
mInvokingProxyCallbacks = true;
final int n = mProxies.beginBroadcast();
try {
for (int i = 0; i < n; i++) {
try {
mProxies.getBroadcastItem(i).onServiceDisconnected(className);
} catch (RemoteException e) {
Log.e(TAG, "Unable to disconnect from proxy", e);
}
}
} finally {
mProxies.finishBroadcast();
mInvokingProxyCallbacks = false;
}
}
@Override
public void binderDied() {
if (DBG) {
Log.w(TAG, "Profile service for profile: " + mClassName
+ " died.");
}
onServiceDisconnected(mClassName);
// Trigger rebind
Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
msg.obj = this;
mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
}
}
private void sendBluetoothStateCallback(boolean isUp) {
try {
int n = mStateChangeCallbacks.beginBroadcast();
if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
for (int i=0; i <n;i++) {
try {
mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
} catch (RemoteException e) {
Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
}
}
} finally {
mStateChangeCallbacks.finishBroadcast();
}
}
/**
* Inform BluetoothAdapter instances that Adapter service is up
*/
private void sendBluetoothServiceUpCallback() {
if (!mConnection.isGetNameAddressOnly()) {
if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
try {
int n = mCallbacks.beginBroadcast();
Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
for (int i=0; i <n;i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
} catch (RemoteException e) {
Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
}
}
} finally {
mCallbacks.finishBroadcast();
}
}
}
/**
* Inform BluetoothAdapter instances that Adapter service is down
*/
private void sendBluetoothServiceDownCallback() {
if (!mConnection.isGetNameAddressOnly()) {
if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
try {
int n = mCallbacks.beginBroadcast();
Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
for (int i=0; i <n;i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
} catch (RemoteException e) {
Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
}
}
} finally {
mCallbacks.finishBroadcast();
}
}
}
public String getAddress() {
mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
"Need BLUETOOTH permission");
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!checkIfCallerIsForegroundUser())) {
Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
return null;
}
if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
!= PackageManager.PERMISSION_GRANTED) {
return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
}
synchronized(mConnection) {
if (mBluetooth != null) {
try {
return mBluetooth.getAddress();
} catch (RemoteException e) {
Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
}
}
}
// mAddress is accessed from outside.
// It is alright without a lock. Here, bluetooth is off, no other thread is
// changing mAddress
return mAddress;
}
public String getName() {
mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
"Need BLUETOOTH permission");
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!checkIfCallerIsForegroundUser())) {
Log.w(TAG,"getName(): not allowed for non-active and non system user");
return null;
}
synchronized(mConnection) {
if (mBluetooth != null) {
try {
return mBluetooth.getName();
} catch (RemoteException e) {
Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
}
}
}
// mName is accessed from outside.
// It alright without a lock. Here, bluetooth is off, no other thread is
// changing mName
return mName;
}
private class BluetoothServiceConnection implements ServiceConnection {
private boolean mGetNameAddressOnly;
public void setGetNameAddressOnly(boolean getOnly) {
mGetNameAddressOnly = getOnly;
}
public boolean isGetNameAddressOnly() {
return mGetNameAddressOnly;
}
public void onServiceConnected(ComponentName className, IBinder service) {
if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
// TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
msg.arg1 = SERVICE_IBLUETOOTH;
// } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
} else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
msg.arg1 = SERVICE_IBLUETOOTHGATT;
} else {
Log.e(TAG, "Unknown service connected: " + className.getClassName());
return;
}
msg.obj = service;
mHandler.sendMessage(msg);
}
public void onServiceDisconnected(ComponentName className) {
// Called if we unexpected disconnected.
if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
className.getClassName());
Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
msg.arg1 = SERVICE_IBLUETOOTH;
} else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
msg.arg1 = SERVICE_IBLUETOOTHGATT;
} else {
Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
return;
}
mHandler.sendMessage(msg);
}
}
private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
private class BluetoothHandler extends Handler {
public BluetoothHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
if (DBG) Log.d (TAG, "Message: " + msg.what);
switch (msg.what) {
case MESSAGE_GET_NAME_AND_ADDRESS: {
if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
synchronized(mConnection) {
//Start bind request
if ((mBluetooth == null) && (!mBinding)) {
if (DBG) Log.d(TAG, "Binding to service to get name and address");
mConnection.setGetNameAddressOnly(true);
//Start bind timeout and bind
Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Intent i = new Intent(IBluetooth.class.getName());
if (!doBind(i, mConnection,
Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
UserHandle.CURRENT)) {
mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
} else {
mBinding = true;
}
}
else {
Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
saveMsg.arg1 = 0;
if (mBluetooth != null) {
mHandler.sendMessage(saveMsg);
} else {
// if enable is also called to bind the service
// wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
}
}
}
break;
}
case MESSAGE_SAVE_NAME_AND_ADDRESS: {
boolean unbind = false;
if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
synchronized(mConnection) {
if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
try {
mBluetooth.enable();
} catch (RemoteException e) {
Log.e(TAG,"Unable to call enable()",e);
}
}
}
if (mBluetooth != null && !mConnection.isGetNameAddressOnly()) waitForOnOff(true, false);
synchronized(mConnection) {
if (mBluetooth != null) {
String name = null;
String address = null;
try {
name = mBluetooth.getName();
address = mBluetooth.getAddress();
} catch (RemoteException re) {
Log.e(TAG,"",re);
}
if (name != null && address != null) {
storeNameAndAddress(name,address);
if (mConnection.isGetNameAddressOnly()) {
unbind = true;
}
} else {
if (msg.arg1 < MAX_SAVE_RETRIES) {
Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
retryMsg.arg1= 1+msg.arg1;
if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
} else {
Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
if (mConnection.isGetNameAddressOnly()) {
unbind = true;
}
}
}
if (!mEnable && !mConnection.isGetNameAddressOnly()) {
try {
mBluetooth.disable();
} catch (RemoteException e) {
Log.e(TAG,"Unable to call disable()",e);
}
}
} else {
// rebind service by Request GET NAME AND ADDRESS
// if service is unbinded by disable or
// MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
mHandler.sendMessage(getMsg);
}
}
if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
waitForOnOff(false, true);
}
if (unbind) {
unbindAndFinish();
}
break;
}
case MESSAGE_ENABLE:
if (DBG) {
Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
}
mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
mEnable = true;
handleEnable(msg.arg1 == 1);
break;
case MESSAGE_DISABLE:
mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
if (mEnable && mBluetooth != null) {
waitForOnOff(true, false);
mEnable = false;
handleDisable();
waitForOnOff(false, false);
} else {
mEnable = false;
handleDisable();
}
break;
case MESSAGE_REGISTER_ADAPTER:
{
IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
boolean added = mCallbacks.register(callback);
Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
}
break;
case MESSAGE_UNREGISTER_ADAPTER:
{
IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
boolean removed = mCallbacks.unregister(callback);
Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
break;
}
case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
{
IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
if (callback != null) {
mStateChangeCallbacks.register(callback);
}
break;
}
case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
{
IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
if (callback != null) {
mStateChangeCallbacks.unregister(callback);
}
break;
}
case MESSAGE_ADD_PROXY_DELAYED:
{
ProfileServiceConnections psc = mProfileServices.get(
new Integer(msg.arg1));
if (psc == null) {
break;
}
IBluetoothProfileServiceConnection proxy =
(IBluetoothProfileServiceConnection) msg.obj;
psc.addProxy(proxy);
break;
}
case MESSAGE_BIND_PROFILE_SERVICE:
{
ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
if (psc == null) {
break;
}
psc.bindService();
break;
}
case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
{
if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
IBinder service = (IBinder) msg.obj;
synchronized(mConnection) {
if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
onBluetoothGattServiceUp();
break;
} // else must be SERVICE_IBLUETOOTH
//Remove timeout
mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
mBinding = false;
mBluetooth = IBluetooth.Stub.asInterface(service);
try {
boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
}
} catch (RemoteException e) {
Log.e(TAG,"Unable to call configHciSnoopLog", e);
}
if (mConnection.isGetNameAddressOnly()) {
//Request GET NAME AND ADDRESS
Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
mHandler.sendMessage(getMsg);
if (!mEnable) return;
}
mConnection.setGetNameAddressOnly(false);
//Register callback object
try {
mBluetooth.registerCallback(mBluetoothCallback);
} catch (RemoteException re) {
Log.e(TAG, "Unable to register BluetoothCallback",re);
}
//Inform BluetoothAdapter instances that service is up
sendBluetoothServiceUpCallback();
//Do enable request
try {
if (mQuietEnable == false) {
if(!mBluetooth.enable()) {
Log.e(TAG,"IBluetooth.enable() returned false");
}
}
else
{
if(!mBluetooth.enableNoAutoConnect()) {
Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
}
}
} catch (RemoteException e) {
Log.e(TAG,"Unable to call enable()",e);
}
}
if (!mEnable) {
waitForOnOff(true, false);
handleDisable();
waitForOnOff(false, false);
}
break;
}
case MESSAGE_TIMEOUT_BIND: {
Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
synchronized(mConnection) {
mBinding = false;
}
break;
}
case MESSAGE_BLUETOOTH_STATE_CHANGE:
{
int prevState = msg.arg1;
int newState = msg.arg2;
if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
mState = newState;
bluetoothStateChangeHandler(prevState, newState);
// handle error state transition case from TURNING_ON to OFF
// unbind and rebind bluetooth service and enable bluetooth
if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
(newState == BluetoothAdapter.STATE_OFF) &&
(mBluetooth != null) && mEnable) {
recoverBluetoothServiceFromError();
}
if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
(newState == BluetoothAdapter.STATE_BLE_ON) &&
(mBluetooth != null) && mEnable) {
recoverBluetoothServiceFromError();
}
if (newState == BluetoothAdapter.STATE_ON ||
newState == BluetoothAdapter.STATE_BLE_ON) {
// bluetooth is working, reset the counter
if (mErrorRecoveryRetryCounter != 0) {
Log.w(TAG, "bluetooth is recovered from error");
mErrorRecoveryRetryCounter = 0;
}
}
break;
}
case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
{
Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
synchronized(mConnection) {
if (msg.arg1 == SERVICE_IBLUETOOTH) {
// if service is unbinded already, do nothing and return
if (mBluetooth == null) break;
mBluetooth = null;
} else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
mBluetoothGatt = null;
break;
} else {
Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
break;
}
}
if (mEnable) {
mEnable = false;
// Send a Bluetooth Restart message
Message restartMsg = mHandler.obtainMessage(
MESSAGE_RESTART_BLUETOOTH_SERVICE);
mHandler.sendMessageDelayed(restartMsg,
SERVICE_RESTART_TIME_MS);
}
if (!mConnection.isGetNameAddressOnly()) {
sendBluetoothServiceDownCallback();
// Send BT state broadcast to update
// the BT icon correctly
if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
(mState == BluetoothAdapter.STATE_ON)) {
bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
BluetoothAdapter.STATE_TURNING_OFF);
mState = BluetoothAdapter.STATE_TURNING_OFF;
}
if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
BluetoothAdapter.STATE_OFF);
}
mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
mState = BluetoothAdapter.STATE_OFF;
}
break;
}
case MESSAGE_RESTART_BLUETOOTH_SERVICE:
{
Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
+" Restart IBluetooth service");
/* Enable without persisting the setting as
it doesnt change when IBluetooth
service restarts */
mEnable = true;
handleEnable(mQuietEnable);
break;
}
case MESSAGE_TIMEOUT_UNBIND:
{
Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
synchronized(mConnection) {
mUnbinding = false;
}
break;
}
case MESSAGE_USER_SWITCHED:
{
if (DBG) {
Log.d(TAG, "MESSAGE_USER_SWITCHED");
}
mHandler.removeMessages(MESSAGE_USER_SWITCHED);
/* disable and enable BT when detect a user switch */
if (mEnable && mBluetooth != null) {
synchronized (mConnection) {
if (mBluetooth != null) {
//Unregister callback object
try {
mBluetooth.unregisterCallback(mBluetoothCallback);
} catch (RemoteException re) {
Log.e(TAG, "Unable to unregister",re);
}
}
}
if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
// MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
mState = BluetoothAdapter.STATE_OFF;
}
if (mState == BluetoothAdapter.STATE_OFF) {
bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
mState = BluetoothAdapter.STATE_TURNING_ON;
}
waitForOnOff(true, false);
if (mState == BluetoothAdapter.STATE_TURNING_ON) {
bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
}
unbindAllBluetoothProfileServices();
// disable
handleDisable();
// Pbap service need receive STATE_TURNING_OFF intent to close
bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
BluetoothAdapter.STATE_TURNING_OFF);
waitForOnOff(false, true);
bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
BluetoothAdapter.STATE_OFF);
sendBluetoothServiceDownCallback();
synchronized (mConnection) {
if (mBluetooth != null) {
mBluetooth = null;
//Unbind
mContext.unbindService(mConnection);
}
mBluetoothGatt = null;
}
SystemClock.sleep(100);
mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
mState = BluetoothAdapter.STATE_OFF;
// enable
handleEnable(mQuietEnable);
} else if (mBinding || mBluetooth != null) {
Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
userMsg.arg2 = 1 + msg.arg2;
// if user is switched when service is being binding
// delay sending MESSAGE_USER_SWITCHED
mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
if (DBG) {
Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
}
}
break;
}
}
}
}
private void handleEnable(boolean quietMode) {
mQuietEnable = quietMode;
synchronized(mConnection) {
if ((mBluetooth == null) && (!mBinding)) {
//Start bind timeout and bind
Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
mConnection.setGetNameAddressOnly(false);
Intent i = new Intent(IBluetooth.class.getName());
if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
UserHandle.CURRENT)) {
mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
} else {
mBinding = true;
}
} else if (mBluetooth != null) {
if (mConnection.isGetNameAddressOnly()) {
// if GetNameAddressOnly is set, we can clear this flag,
// so the service won't be unbind
// after name and address are saved
mConnection.setGetNameAddressOnly(false);
//Register callback object
try {
mBluetooth.registerCallback(mBluetoothCallback);
} catch (RemoteException re) {
Log.e(TAG, "Unable to register BluetoothCallback",re);
}
//Inform BluetoothAdapter instances that service is up
sendBluetoothServiceUpCallback();
}
//Enable bluetooth
try {
if (!mQuietEnable) {
if(!mBluetooth.enable()) {
Log.e(TAG,"IBluetooth.enable() returned false");
}
}
else {
if(!mBluetooth.enableNoAutoConnect()) {
Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
}
}
} catch (RemoteException e) {
Log.e(TAG,"Unable to call enable()",e);
}
}
}
}
boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
intent.setComponent(comp);
if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Log.e(TAG, "Fail to bind to: " + intent);
return false;
}
return true;
}
private void handleDisable() {
synchronized(mConnection) {
// don't need to disable if GetNameAddressOnly is set,
// service will be unbinded after Name and Address are saved
if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
if (DBG) Log.d(TAG,"Sending off request.");
try {
if(!mBluetooth.disable()) {
Log.e(TAG,"IBluetooth.disable() returned false");
}
} catch (RemoteException e) {
Log.e(TAG,"Unable to call disable()",e);
}
}
}
}
private boolean checkIfCallerIsForegroundUser() {
int foregroundUser;
int callingUser = UserHandle.getCallingUserId();
int callingUid = Binder.getCallingUid();
long callingIdentity = Binder.clearCallingIdentity();
UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
UserInfo ui = um.getProfileParent(callingUser);
int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
int callingAppId = UserHandle.getAppId(callingUid);
boolean valid = false;
try {
foregroundUser = ActivityManager.getCurrentUser();
valid = (callingUser == foregroundUser) ||
parentUser == foregroundUser ||
callingAppId == Process.NFC_UID ||
callingAppId == mSystemUiUid;
if (DBG) {
Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
+ " callingUser=" + callingUser
+ " parentUser=" + parentUser
+ " foregroundUser=" + foregroundUser);
}
} finally {
Binder.restoreCallingIdentity(callingIdentity);
}
return valid;
}
private void sendBleStateChanged(int prevState, int newState) {
if (DBG) Log.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
// Send broadcast message to everyone else
Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
}
private void bluetoothStateChangeHandler(int prevState, int newState) {
boolean isStandardBroadcast = true;
if (prevState != newState) {
//Notify all proxy objects first of adapter state change
if (newState == BluetoothAdapter.STATE_BLE_ON
|| newState == BluetoothAdapter.STATE_OFF) {
boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
&& newState == BluetoothAdapter.STATE_BLE_ON);
if (newState == BluetoothAdapter.STATE_OFF) {
// If Bluetooth is off, send service down event to proxy objects, and unbind
if (DBG) Log.d(TAG, "Bluetooth is complete turn off");
if (canUnbindBluetoothService()) {
if (DBG) Log.d(TAG, "Good to unbind!");
sendBluetoothServiceDownCallback();
unbindAndFinish();
sendBleStateChanged(prevState, newState);
// Don't broadcast as it has already been broadcast before
isStandardBroadcast = false;
}
} else if (!intermediate_off) {
// connect to GattService
if (DBG) Log.d(TAG, "Bluetooth is in LE only mode");
if (mBluetoothGatt != null) {
if (DBG) Log.d(TAG, "Calling BluetoothGattServiceUp");
onBluetoothGattServiceUp();
} else {
if (DBG) Log.d(TAG, "Binding Bluetooth GATT service");
if (mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
Intent i = new Intent(IBluetoothGatt.class.getName());
doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
}
}
sendBleStateChanged(prevState, newState);
//Don't broadcase this as std intent
isStandardBroadcast = false;
} else if (intermediate_off){
if (DBG) Log.d(TAG, "Intermediate off, back to LE only mode");
// For LE only mode, broadcast as is
sendBleStateChanged(prevState, newState);
sendBluetoothStateCallback(false); // BT is OFF for general users
// Broadcast as STATE_OFF
newState = BluetoothAdapter.STATE_OFF;
sendBrEdrDownCallback();
}
} else if (newState == BluetoothAdapter.STATE_ON) {
boolean isUp = (newState==BluetoothAdapter.STATE_ON);
sendBluetoothStateCallback(isUp);
sendBleStateChanged(prevState, newState);
} else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
|| newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
sendBleStateChanged(prevState, newState);
isStandardBroadcast = false;
} else if (newState == BluetoothAdapter.STATE_TURNING_ON
|| newState == BluetoothAdapter.STATE_TURNING_OFF) {
sendBleStateChanged(prevState, newState);
}
if (isStandardBroadcast) {
if (prevState == BluetoothAdapter.STATE_BLE_ON) {
// Show prevState of BLE_ON as OFF to standard users
prevState = BluetoothAdapter.STATE_OFF;
}
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
}
}
}
/**
* if on is true, wait for state become ON
* if off is true, wait for state become OFF
* if both on and off are false, wait for state not ON
*/
private boolean waitForOnOff(boolean on, boolean off) {
int i = 0;
while (i < 10) {
synchronized(mConnection) {
try {
if (mBluetooth == null) break;
if (on) {
if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
} else if (off) {
if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
} else {
if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
}
} catch (RemoteException e) {
Log.e(TAG, "getState()", e);
break;
}
}
if (on || off) {
SystemClock.sleep(300);
} else {
SystemClock.sleep(50);
}
i++;
}
Log.e(TAG,"waitForOnOff time out");
return false;
}
private void sendDisableMsg() {
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
}
private void sendEnableMsg(boolean quietMode) {
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
quietMode ? 1 : 0, 0));
}
private boolean canUnbindBluetoothService() {
synchronized(mConnection) {
//Only unbind with mEnable flag not set
//For race condition: disable and enable back-to-back
//Avoid unbind right after enable due to callback from disable
//Only unbind with Bluetooth at OFF state
//Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
try {
if (mEnable || (mBluetooth == null)) return false;
if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
} catch (RemoteException e) {
Log.e(TAG, "getState()", e);
}
}
return false;
}
private void recoverBluetoothServiceFromError() {
Log.e(TAG,"recoverBluetoothServiceFromError");
synchronized (mConnection) {
if (mBluetooth != null) {
//Unregister callback object
try {
mBluetooth.unregisterCallback(mBluetoothCallback);
} catch (RemoteException re) {
Log.e(TAG, "Unable to unregister",re);
}
}
}
SystemClock.sleep(500);
// disable
handleDisable();
waitForOnOff(false, true);
sendBluetoothServiceDownCallback();
synchronized (mConnection) {
if (mBluetooth != null) {
mBluetooth = null;
//Unbind
mContext.unbindService(mConnection);
}
mBluetoothGatt = null;
}
mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
mState = BluetoothAdapter.STATE_OFF;
mEnable = false;
if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
// Send a Bluetooth Restart message to reenable bluetooth
Message restartMsg = mHandler.obtainMessage(
MESSAGE_RESTART_BLUETOOTH_SERVICE);
mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
} else {
// todo: notify user to power down and power up phone to make bluetooth work.
}
}
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
writer.println("Bluetooth Status");
writer.println(" enabled: " + mEnable);
writer.println(" state: " + mState);
writer.println(" address: " + mAddress);
writer.println(" name: " + mName + "\n");
writer.flush();
if (mBluetooth == null) {
writer.println("Bluetooth Service not connected");
} else {
ParcelFileDescriptor pfd = null;
try {
writer.println("Bonded devices:");
for (BluetoothDevice device : mBluetooth.getBondedDevices()) {
writer.println(" " + device.getAddress() +
" [" + DEVICE_TYPE_NAMES[device.getType()] + "] " +
device.getName());
}
writer.flush();
pfd = ParcelFileDescriptor.dup(fd);
mBluetooth.dump(pfd);
} catch (RemoteException re) {
writer.println("RemoteException while calling Bluetooth Service");
} catch (IOException ioe) {
writer.println("IOException attempting to dup() fd");
} finally {
if (pfd != null) {
try {
pfd.close();
} catch (IOException ioe) {
writer.println("IOException attempting to close() fd");
}
}
}
}
}
}
| gpl-3.0 |
Keniobyte/PoliceReportsMobile | app/src/main/java/com/keniobyte/bruino/minsegapp/features/police_report/PoliceReportActivity.java | 15049 | package com.keniobyte.bruino.minsegapp.features.police_report;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.lib.recaptcha.ReCaptcha;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.kbeanie.multipicker.api.ImagePicker;
import com.kbeanie.multipicker.api.Picker;
import com.kbeanie.multipicker.api.callbacks.ImagePickerCallback;
import com.kbeanie.multipicker.api.entity.ChosenImage;
import com.keniobyte.bruino.minsegapp.MainActivity;
import com.keniobyte.bruino.minsegapp.R;
import com.keniobyte.bruino.minsegapp.features.police_report.adapter.MediaResultAdapter;
import com.keniobyte.bruino.minsegapp.models.PoliceReport;
import com.keniobyte.bruino.minsegapp.views.components.NestedListView;
import com.keniobyte.bruino.minsegapp.utils.CaptchaDialog;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nucleus.factory.RequiresPresenter;
/**
* @author bruino
* @version 02/01/17.
*/
@RequiresPresenter(PoliceReportPresenter.class)
public class PoliceReportActivity extends AppCompatActivity implements IPoliceReportView, IPoliceReportPresenter.onListAttachmentsListener {
public String TAG = getClass().getSimpleName();
@BindView(R.id.myToolbar) Toolbar toolbar;
@BindView(R.id.namePerpetratorEditText) EditText namePerpetratorEditText;
@BindView(R.id.datetimeButton) Button datetimeButton;
@BindView(R.id.descriptionEditText) @NotEmpty(trim = true) EditText descriptionEditText;
@BindView(R.id.attachmentsListView) NestedListView attachmentsListView;
@BindDrawable(R.drawable.ic_arrow_back_white_24dp) Drawable arrowBack;
@BindString(R.string.police_report_drugs) String titlePoliceReportDrugs;
@BindString(R.string.police_report_aircraft) String titlePoliceReportAircraft;
@BindString(R.string.police_report_affairs) String titlePoliceReportAffairs;
@BindString(R.string.police_report_online) String titlePoliceReportOnline;
@BindString(R.string.other_police_report) String titleOtherPoliceReport;
@BindString(R.string.anonymous) String anonymous;
@BindString(R.string.accept) String ok;
@BindString(R.string.sending) String progressDialogTitle;
@BindString(R.string.wait_please) String progressDialogMessage;
@BindString(R.string.send_success) String messageSuccess;
@BindString(R.string.messageComplete) String message;
private Context context = this;
private PoliceReportInteractor interactor;
private PoliceReportPresenter presenter;
private Validator validator;
private Calendar calendar;
private ImagePicker imagePicker;
private List<ChosenImage> images;
private MediaResultAdapter adapter;
private ProgressDialog progressDialog;
private CaptchaDialog captchaDialog;
final ReCaptcha.OnVerifyAnswerListener onVerifyAnswerListener = new ReCaptcha.OnVerifyAnswerListener() {
@Override
public void onAnswerVerified(boolean success) {
if (success) {
presenter.sendPoliceReport();
} else {
presenter.reloadCaptcha();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.police_report_activity_form);
ButterKnife.bind(this);
calendar = Calendar.getInstance();
validator = new Validator(this);
validator.setValidationListener(new Validator.ValidationListener() {
@Override
public void onValidationSucceeded() {
presenter.captcha();
}
@Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
// Display error messages ;)
if (view instanceof EditText) {
((EditText) view).setError(message);
}
}
}
});
setTitleToolbar();
toolbar.setNavigationIcon(arrowBack);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
setSupportActionBar(toolbar);
progressDialog = new ProgressDialog(context);
progressDialog.setTitle(progressDialogTitle);
progressDialog.setMessage(progressDialogMessage);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
captchaDialog = new CaptchaDialog();
captchaDialog.setOnVerifyAnswerListener(onVerifyAnswerListener);
interactor = new PoliceReportInteractor(this);
presenter = new PoliceReportPresenter(interactor);
presenter.addView(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_police_report_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_attachedment:
pickImageSingle();
return true;
case R.id.action_send_police_report:
validator.validate();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public String getPerpetrator() {
return namePerpetratorEditText.getText().toString();
}
@Override
public Calendar getIncidentDate() {
return calendar;
}
@Override
public String getIncidentDescription() {
return descriptionEditText.getText().toString();
}
@Override
public List<String> getArrayPathsAtachments() {
List<String> paths = new ArrayList<String>();
if (images != null) {
for (ChosenImage image : images) {
paths.add(image.getOriginalPath());
}
}
return paths;
}
@Override
public Double getLatitude() {
return getIntent().getExtras().getDouble("latitude");
}
@Override
public Double getLongitude() {
return getIntent().getExtras().getDouble("longitude");
}
@Override
public Float getBearing() {
return getIntent().getExtras().getFloat("bearing");
}
@Override
public Float getTilt() {
return getIntent().getExtras().getFloat("tilt");
}
@Override
public String getAddress() {
return getIntent().getExtras().getString("address");
}
@Override
public String getTypePoliceReport() {
return getIntent().getExtras().getString("type_report");
}
@Override
public void createListAttachments() {
attachmentsListView.setAdapter(adapter);
}
@Override
public void onItemDelete(int position) {
images.remove(position);
adapter.notifyDataSetChanged();
}
@Override
public MediaResultAdapter createMediaResultAdapter(List<ChosenImage> images) {
return new MediaResultAdapter(images, context, this);
}
@Override
public void sendPoliceReportMessageError(int rStringMessage) {
new AlertDialog.Builder(this)
.setMessage(rStringMessage)
.setCancelable(true)
.setPositiveButton(ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
}
@Override
public void sendPoliceReportMessageSuccess() {
new AlertDialog.Builder(this)
.setMessage(messageSuccess)
.setPositiveButton(ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
navigationToHome();
}
})
.show();
}
final DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
calendar.set(year, month, day);
TimePickerDialog timePickerDialog = new TimePickerDialog(context
, onTimeSetListener
, calendar.get(Calendar.HOUR_OF_DAY)
, calendar.get(Calendar.MINUTE)
, true);
timePickerDialog.setCancelable(true);
timePickerDialog.show();
}
};
final TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
presenter.onSetDatetime();
}
};
@Override
public void showDatetimePicker() {
DatePickerDialog datePickerDialog = new DatePickerDialog(context
, onDateSetListener
, calendar.get(Calendar.YEAR)
, calendar.get(Calendar.MONTH)
, calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
datePickerDialog.show();
}
@Override
public void setTextDatetimeButton(String datetime) {
datetimeButton.setText(datetime);
}
@Override
public void showCaptcha() {
captchaDialog.show(getFragmentManager(), "Captcha");
}
@Override
public void hideCaptcha() {
captchaDialog.dismiss();
}
@Override
public void showProgress() {
progressDialog.show();
}
@Override
public void hideProgress() {
progressDialog.dismiss();
}
@Override
public void setProgressDialog(int progress) {
progressDialog.setProgress(progress);
}
@OnClick(R.id.datetimeButton)
public void onClickDatetimeButton() {
presenter.onDatetimeInput();
}
@Override
public void addItemAttachments(List<ChosenImage> images) {
for (ChosenImage image : images) {
this.images.add(image);
}
}
@Override
public void setAdapter(MediaResultAdapter adapter) {
this.adapter = adapter;
}
@Override
public List<ChosenImage> getImages() {
return images;
}
@Override
public void setImages(List<ChosenImage> images) {
this.images = images;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Picker.PICK_IMAGE_DEVICE) {
if (imagePicker == null) {
imagePicker = new ImagePicker(this);
imagePicker.setImagePickerCallback(imagePickerCallback);
}
imagePicker.submit(data);
}
}
}
private void navigationToHome() {
startActivity(new Intent(context, MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
private void setTitleToolbar() {
switch (getTypePoliceReport()) {
case PoliceReport.TYPE_POLICE_REPORT_AFFAIR:
toolbar.setTitle(titlePoliceReportAffairs);
toolbar.setSubtitle(anonymous);
break;
case PoliceReport.TYPE_POLICE_REPORT_AIRCRAFT:
((ViewGroup) namePerpetratorEditText.getParent()).removeView(namePerpetratorEditText);
toolbar.setTitle(titlePoliceReportAircraft);
toolbar.setSubtitle(anonymous);
break;
case PoliceReport.TYPE_POLICE_REPORT_DRUGS:
toolbar.setTitle(titlePoliceReportDrugs);
toolbar.setSubtitle(anonymous);
namePerpetratorEditText.setHint(getString(R.string.perpretator_nickname_optional));
break;
case PoliceReport.TYPE_POLICE_REPORT_ONLINE:
toolbar.setTitle(titlePoliceReportOnline);
break;
case PoliceReport.TYPE_OTHER_POLICE_REPORT:
toolbar.setTitle(titleOtherPoliceReport);
toolbar.setSubtitle(anonymous);
break;
}
}
private ImagePickerCallback imagePickerCallback = new ImagePickerCallback() {
@Override
public void onImagesChosen(List<ChosenImage> list) {
presenter.showAttachFile(list);
}
@Override
public void onError(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
};
public void pickImageSingle() {
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 7);
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 7);
}
} else {
imagePicker = new ImagePicker(this);
//imagePicker.allowMultiple();
imagePicker.setImagePickerCallback(imagePickerCallback);
imagePicker.pickImage();
}
}
}
| gpl-3.0 |
nickbattle/vdmj | vdmj/src/main/java/com/fujitsu/vdmj/runtime/Interpreter.java | 20247 | /*******************************************************************************
*
* Copyright (c) 2016 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ 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.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
* SPDX-License-Identifier: GPL-3.0-or-later
*
******************************************************************************/
package com.fujitsu.vdmj.runtime;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;
import com.fujitsu.vdmj.Settings;
import com.fujitsu.vdmj.in.definitions.INClassDefinition;
import com.fujitsu.vdmj.in.definitions.INNamedTraceDefinition;
import com.fujitsu.vdmj.in.expressions.INExpression;
import com.fujitsu.vdmj.in.modules.INModule;
import com.fujitsu.vdmj.in.statements.INStatement;
import com.fujitsu.vdmj.lex.Dialect;
import com.fujitsu.vdmj.ast.expressions.ASTExpression;
import com.fujitsu.vdmj.ast.lex.LexIdentifierToken;
import com.fujitsu.vdmj.lex.LexLocation;
import com.fujitsu.vdmj.ast.lex.LexNameToken;
import com.fujitsu.vdmj.ast.lex.LexToken;
import com.fujitsu.vdmj.lex.LexTokenReader;
import com.fujitsu.vdmj.lex.Token;
import com.fujitsu.vdmj.messages.Console;
import com.fujitsu.vdmj.messages.ConsoleWriter;
import com.fujitsu.vdmj.messages.VDMErrorsException;
import com.fujitsu.vdmj.pog.ProofObligationList;
import com.fujitsu.vdmj.scheduler.ResourceScheduler;
import com.fujitsu.vdmj.scheduler.SchedulableThread;
import com.fujitsu.vdmj.syntax.ExpressionReader;
import com.fujitsu.vdmj.tc.TCNode;
import com.fujitsu.vdmj.tc.expressions.TCExpression;
import com.fujitsu.vdmj.tc.lex.TCNameToken;
import com.fujitsu.vdmj.tc.statements.TCStatement;
import com.fujitsu.vdmj.tc.types.TCType;
import com.fujitsu.vdmj.traces.CallSequence;
import com.fujitsu.vdmj.traces.TraceFilter;
import com.fujitsu.vdmj.traces.TraceIterator;
import com.fujitsu.vdmj.traces.TraceReductionType;
import com.fujitsu.vdmj.traces.Verdict;
import com.fujitsu.vdmj.typechecker.Environment;
import com.fujitsu.vdmj.typechecker.NameScope;
import com.fujitsu.vdmj.typechecker.TypeChecker;
import com.fujitsu.vdmj.values.Value;
/**
* An abstract VDM interpreter.
*/
abstract public class Interpreter
{
/** The main thread scheduler */
protected ResourceScheduler scheduler;
/** The initial execution context. */
protected RootContext initialContext;
/** A list of breakpoints created. */
protected Map<Integer, Breakpoint> breakpoints;
/** A list of source files loaded. */
protected Map<File, SourceFile> sourceFiles;
/** The number of the next breakpoint to be created. */
protected int nextbreakpoint = 0;
/** A static instance pointer to the interpreter. */
protected static Interpreter instance = null;
/** The saved initial context for trace execution */
protected ByteArrayOutputStream savedInitialContext;
/**
* Create an Interpreter.
*/
protected Interpreter()
{
this.scheduler = new ResourceScheduler();
this.breakpoints = new TreeMap<Integer, Breakpoint>();
this.sourceFiles = new HashMap<File, SourceFile>();
instance = this;
}
/**
* Get the resource scheduler.
*/
public ResourceScheduler getScheduler()
{
return scheduler;
}
/**
* Get the initial root context.
*/
public RootContext getInitialContext()
{
return initialContext;
}
/**
* Get the global environment. In VDM-SL this is for the default module, and
* in VDM++ it is the global class environment.
*/
abstract public Environment getGlobalEnvironment();
/**
* @return The Interpreter instance.
*/
public static Interpreter getInstance()
{
return instance; // NB. last one created
}
/**
* Get the name of the default module or class. Symbols in the default
* module or class do not have to have their names qualified when being
* referred to on the command line.
*
* @return The default name.
*/
abstract public String getDefaultName();
/**
* Get the filename that contains the default module or class.
*
* @return The default file name.
*/
abstract public File getDefaultFile();
/**
* Set the default module or class name.
*
* @param name The default name.
* @throws Exception
*/
abstract public void setDefaultName(String name) throws Exception;
/**
* Initialize the initial context. This means that all definition
* initializers are re-run to put the global environment back into its
* original state. This is run implicitly when the interpreter starts,
* but it can also be invoked explicitly via the "init" command.
*
* @throws Exception
*/
abstract public void init();
/**
* Initialize the context between trace sequences. This is less
* thorough than the full init, since it does not reset the scheduler
* for example.
*/
abstract public void traceInit() throws Exception;
/**
* Parse the line passed, type check it and evaluate it as an expression
* in the initial context.
*
* @param line A VDM expression.
* @return The value of the expression.
* @throws Exception Parser, type checking or runtime errors.
*/
abstract public Value execute(String line) throws Exception;
/**
* Parse the line passed, and evaluate it as an expression in the context
* passed. This is used from debugger breakpoints.
*
* @param line A VDM expression.
* @param ctxt The context in which to evaluate the expression.
* @return The value of the expression.
* @throws Exception Parser or runtime errors.
*/
abstract public Value evaluate(String line, Context ctxt) throws Exception;
/**
* Parse the content of the file passed, type check it and evaluate it as an
* expression in the initial context.
*
* @param file A file containing a VDM expression.
* @return The value of the expression.
* @throws Exception Parser, type checking or runtime errors.
*/
public Value execute(File file) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
line = br.readLine();
}
br.close();
Value result = execute(sb.toString());
SchedulableThread.terminateAll(); // NB not a session (used for tests)
return result;
}
/**
* @return The list of breakpoints currently set.
*/
public Map<Integer, Breakpoint> getBreakpoints()
{
return breakpoints;
}
/**
* @return The list of Catchpoints currently set.
*/
public List<Catchpoint> getCatchpoints()
{
List<Catchpoint> catchers = new Vector<Catchpoint>();
for (Breakpoint bp: breakpoints.values())
{
if (bp instanceof Catchpoint)
{
catchers.add((Catchpoint) bp);
}
}
return catchers;
}
/**
* Get a line of a source file.
*/
public String getSourceLine(LexLocation src)
{
return getSourceLine(src.file, src.startLine);
}
/**
* Get a line of a source file by its location.
*/
public String getSourceLine(File file, int line)
{
return getSourceLine(file, line, ": ");
}
/**
* Get a line of a source file by its location.
*/
public String getSourceLine(File file, int line, String sep)
{
try
{
SourceFile source = getSourceFile(file);
return line + sep + source.getLine(line);
}
catch (IOException e)
{
return "Cannot open source file: " + file;
}
}
/**
* Get an entire source file object.
* @throws IOException
*/
public SourceFile getSourceFile(File file) throws IOException
{
SourceFile source = sourceFiles.get(file);
if (source == null)
{
source = new SourceFile(file);
sourceFiles.put(file, source);
}
return source;
}
/**
* Get a list of all source files.
*/
abstract public Set<File> getSourceFiles();
/**
* Get a list of proof obligations for the loaded specification.
*
* @return A list of POs.
* @throws Exception
*/
abstract public ProofObligationList getProofObligations() throws Exception;
/**
* Find a statement by file name and line number.
*
* @param file The name of the class/module
* @param lineno The line number
* @return A INStatement object if found, else null.
*/
abstract public INStatement findStatement(File file, int lineno);
/**
* Find an expression by file name and line number.
*
* @param file The name of the file
* @param lineno The line number
* @return An INExpression object if found, else null.
*/
abstract public INExpression findExpression(File file, int lineno);
/**
* Find a global environment value by name.
*
* @param name The name of the variable
* @return A Value object if found, else null.
*/
public Value findGlobal(TCNameToken name)
{
return initialContext.check(name);
}
/**
* Set a statement tracepoint. A tracepoint does not stop execution, but
* evaluates and displays an expression before continuing.
*
* @param stmt The statement to trace.
* @param trace The expression to evaluate.
* @return The Breakpoint object created.
*
* @throws Exception INExpression is not valid.
*/
public Breakpoint setTracepoint(INStatement stmt, String trace) throws Exception
{
stmt.breakpoint = new Tracepoint(stmt.location, ++nextbreakpoint, trace);
breakpoints.put(nextbreakpoint, stmt.breakpoint);
return stmt.breakpoint;
}
/**
* Set an expression tracepoint. A tracepoint does not stop execution, but
* evaluates an expression before continuing.
*
* @param exp The expression to trace.
* @param trace The expression to evaluate.
* @return The Breakpoint object created.
* @throws Exception
*/
public Breakpoint setTracepoint(INExpression exp, String trace) throws Exception
{
exp.breakpoint = new Tracepoint(exp.location, ++nextbreakpoint, trace);
breakpoints.put(nextbreakpoint, exp.breakpoint);
return exp.breakpoint;
}
/**
* Set a statement breakpoint. A breakpoint stops execution and allows
* the user to query the environment.
*
* @param stmt The statement at which to stop.
* @param condition The condition when to stop.
* @return The Breakpoint object created.
* @throws Exception
*/
public Breakpoint setBreakpoint(INStatement stmt, String condition) throws Exception
{
stmt.breakpoint = new Stoppoint(stmt.location, ++nextbreakpoint, condition);
breakpoints.put(nextbreakpoint, stmt.breakpoint);
return stmt.breakpoint;
}
/**
* Set an expression breakpoint. A breakpoint stops execution and allows
* the user to query the environment.
*
* @param exp The expression at which to stop.
* @param condition The condition when to stop.
* @return The Breakpoint object created.
* @throws Exception
*
*/
public Breakpoint setBreakpoint(INExpression exp, String condition) throws Exception
{
exp.breakpoint = new Stoppoint(exp.location, ++nextbreakpoint, condition);
breakpoints.put(nextbreakpoint, exp.breakpoint);
return exp.breakpoint;
}
/**
* Set an exception catchpoint. This stops execution at the point that a matching
* exception is thrown.
*
* @param exp The exception value(s) at which to stop, or null for any exception.
* @return The Breakpoint object created.
* @throws Exception
*/
public List<Breakpoint> setCatchpoint(String value) throws Exception
{
List<Breakpoint> values = new Vector<Breakpoint>();
/**
* Parse each expression, so the string value is "canonical".
*/
if (value != null)
{
LexTokenReader ltr = new LexTokenReader(value, Dialect.VDM_SL);
ltr.nextToken();
ExpressionReader er = new ExpressionReader(ltr);
while (ltr.getLast().isNot(Token.EOF))
{
ASTExpression exp = er.readExpression();
Catchpoint catcher = new Catchpoint(exp.toString(), ++nextbreakpoint);
breakpoints.put(nextbreakpoint, catcher);
values.add(catcher);
}
}
else
{
Catchpoint catcher = new Catchpoint(null, ++nextbreakpoint);
breakpoints.put(nextbreakpoint, catcher);
values.add(catcher);
}
return values;
}
/**
* Clear the breakpoint given by the number.
*
* @param bpno The breakpoint number to remove.
* @return The breakpoint object removed, or null.
*/
public Breakpoint clearBreakpoint(int bpno)
{
Breakpoint old = breakpoints.remove(bpno);
if (old != null && !(old instanceof Catchpoint))
{
INStatement stmt = findStatement(old.location.file, old.location.startLine);
if (stmt != null)
{
stmt.breakpoint = new Breakpoint(stmt.location);
}
else
{
INExpression exp = findExpression(old.location.file, old.location.startLine);
assert (exp != null) : "Cannot locate old breakpoint?";
exp.breakpoint = new Breakpoint(exp.location);
}
}
return old; // null if not found
}
public void clearBreakpointHits()
{
for (Entry<Integer, Breakpoint> e: breakpoints.entrySet())
{
e.getValue().clearHits();
}
}
/**
* Parse an expression line into a TC tree, ready to be type checked.
*/
abstract protected TCExpression parseExpression(String line, String module) throws Exception;
/**
* Type check a TC expression tree passed.
*/
public TCType typeCheck(TCNode tree) throws Exception
{
TypeChecker.clearErrors();
TCType type = null;
if (tree instanceof TCExpression)
{
TCExpression exp = (TCExpression)tree;
type = exp.typeCheck(getGlobalEnvironment(), null, NameScope.NAMESANDSTATE, null);
}
else if (tree instanceof TCStatement)
{
TCStatement stmt = (TCStatement)tree;
type = stmt.typeCheck(getGlobalEnvironment(), NameScope.NAMESANDSTATE, null, false);
}
else
{
throw new Exception("Cannot type check " + tree.getClass().getSimpleName());
}
if (TypeChecker.getErrorCount() > 0)
{
throw new VDMErrorsException(TypeChecker.getErrors());
}
return type;
}
/**
* @param classname
*/
public INClassDefinition findClass(String classname)
{
assert false : "findClass cannot be called for executableModules";
return null;
}
/**
* @param module
*/
public INModule findModule(String module)
{
assert false : "findModule cannot be called for classes";
return null;
}
private static ConsoleWriter writer = null;
public static void setTraceOutput(ConsoleWriter pw)
{
writer = pw;
}
abstract public INNamedTraceDefinition findTraceDefinition(TCNameToken name);
abstract public Context getTraceContext(INClassDefinition classdef) throws ValueException;
public void runtrace(String name, int startTest, int endTest, boolean debug)
throws Exception
{
runtrace(name, startTest, endTest, debug, 1.0F, TraceReductionType.NONE, 1234);
}
public boolean runtrace(
String name, int startTest, int endTest, boolean debug,
float subset, TraceReductionType reductionType, long seed)
throws Exception
{
// Trace names have / substituted for _ to make a valid name during the parse
name = name.replaceAll("/", "_");
LexTokenReader ltr = new LexTokenReader(name, Dialect.VDM_SL);
LexToken token = ltr.nextToken();
ltr.close();
TCNameToken lexname = null;
switch (token.type)
{
case NAME:
lexname = new TCNameToken((LexNameToken) token);
if (Settings.dialect == Dialect.VDM_SL &&
!lexname.getModule().equals(getDefaultName()))
{
setDefaultName(lexname.getModule());
}
break;
case IDENTIFIER:
lexname = new TCNameToken(token.location, getDefaultName(), ((LexIdentifierToken)token).name);
break;
default:
throw new Exception("Expecting trace name");
}
INNamedTraceDefinition tracedef = findTraceDefinition(lexname);
if (tracedef == null)
{
throw new Exception("Trace " + lexname + " not found");
}
long before = System.currentTimeMillis();
TraceIterator tests = tracedef.getIterator(getTraceContext(tracedef.classDefinition));
long after = System.currentTimeMillis();
boolean wasCMD = Settings.usingCmdLine;
Settings.usingCmdLine = debug;
if (writer == null)
{
writer = Console.out;
}
final int count = tests.count();
if (endTest > count)
{
throw new Exception("Trace " + lexname + " only has " + count + " tests");
}
if (endTest == 0) // To the end of the tests, if specified as zero
{
endTest = count;
}
if (startTest > 0) // Suppress any reduction if a range specified
{
subset = 1.0F;
reductionType = TraceReductionType.NONE;
}
int testNumber = 1;
int excluded = 0;
boolean failed = false;
TraceFilter filter = new TraceFilter(count, subset, reductionType, seed);
if (filter.getFilteredCount() > 0) // Only known for random reduction
{
writer.print("Generated " + count + " tests, reduced to " + filter.getFilteredCount() + ",");
}
else
{
writer.print("Generated " + count + " tests");
if (subset < 1.0)
{
writer.print(", reduced by " + reductionType + ",");
}
}
writer.println(" in " + (double)(after-before)/1000 + " secs. ");
before = System.currentTimeMillis();
// Not needed with new traces?
// Environment environment = getTraceEnvironment(tracedef.classDefinition);
while (tests.hasMoreTests())
{
CallSequence test = tests.getNextTest();
if (testNumber < startTest || testNumber > endTest || filter.isRemoved(test, testNumber))
{
excluded++;
}
else if (filter.getFilteredBy(test) > 0)
{
excluded++;
writer.println("Test " + testNumber + " = " + test.getCallString(getTraceContext(tracedef.classDefinition)));
writer.println("Test " + testNumber + " FILTERED by test " + filter.getFilteredBy(test));
}
else
{
// test.typeCheck(this, environment); // Not needed with new traces?
traceInit(); // Initialize completely between every run...
List<Object> result = runOneTrace(tracedef.classDefinition, test, debug);
filter.update(result, test, testNumber);
writer.println("Test " + testNumber + " = " + test.getCallString(getTraceContext(tracedef.classDefinition)));
writer.println("Result = " + result);
if (result.lastIndexOf(Verdict.PASSED) == -1)
{
failed = true; // Not passed => failed.
}
}
if (testNumber >= endTest)
{
excluded = count - (endTest - startTest + 1);
break;
}
testNumber++;
}
init();
savedInitialContext = null;
Settings.usingCmdLine = wasCMD;
if (excluded > 0)
{
writer.println("Excluded " + excluded + " tests");
}
long finished = System.currentTimeMillis();
writer.println("Executed in " + (double)(finished-after)/1000 + " secs. ");
return !failed;
}
public abstract List<Object> runOneTrace(INClassDefinition classDefinition, CallSequence test, boolean debug);
abstract public <T extends List<?>> T getTC();
abstract public <T extends List<?>> T getIN();
abstract public <T extends List<?>> T getPO();
}
| gpl-3.0 |
htwg/SIPUCE | socketswitch/src/test/java/de/fhkn/in/uce/socketswitch/SwitchableSocketTest.java | 2749 | package de.fhkn.in.uce.socketswitch;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import de.fhkn.in.uce.socketswitch.test.mocksocket.MockSocket;
public class SwitchableSocketTest {
private MockSocket mockSocket1;
private MockSocket mockSocket2;
private Socket mockSocket1o;
private Socket mockSocket2o;
@Before
public void setUp() throws Exception {
mockSocket1 = new MockSocket(10);
mockSocket2 = new MockSocket(10);
mockSocket1o = mockSocket1.getOppsositeSocket();
mockSocket2o = mockSocket2.getOppsositeSocket();
}
@After
public void tearDown() throws Exception {
mockSocket1.close();
mockSocket2.close();
mockSocket1o.close();
mockSocket2o.close();
}
private SwitchableSocket getSwitchableSocket(Socket socket) throws IOException {
return new TimeoutSwitchableSocket(socket);
}
@Test
public void testMockSocket() throws IOException {
assertDuplexConnection(100, mockSocket1, mockSocket1o);
}
@Test
public void testSwitch() throws IOException, SwitchableException, InterruptedException, TimeoutException {
assertDuplexConnection(100, mockSocket1, mockSocket1o);
System.out.println("TEST Step 1 fin");
final SwitchableSocket sws = getSwitchableSocket(mockSocket1);
final SwitchableSocket swso = getSwitchableSocket(mockSocket1o);
assertDuplexConnection(100, sws, swso);
System.out.println("TEST Step 2 fin");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
swso.switchSocket(mockSocket2, 1000);
} catch (SwitchableException | TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
sws.switchSocket(mockSocket2o, 1000);
t.join();
assertDuplexConnection(100, sws, swso);
}
private void assertDuplexConnection(int bytesToSendCount, Socket socket, Socket oppositeSocket) throws IOException {
byte[] bSend = createDetBytes(bytesToSendCount);
byte[] b = new byte[bytesToSendCount];
socket.getOutputStream().write(bSend);
assertEquals(bytesToSendCount, oppositeSocket.getInputStream().read(b));
assertArrayEquals(bSend, b);
oppositeSocket.getOutputStream().write(bSend);
assertEquals(bytesToSendCount, socket.getInputStream().read(b));
assertArrayEquals(bSend, b);
}
private byte[] createDetBytes(int byteCount) {
byte[] t = new byte[byteCount];
byte b = 0;
for(int i = 0; i < byteCount; i++) {
t[i] = b;
b++;
}
return t;
}
}
| gpl-3.0 |
Zaraka/GruntArbiter | src/main/java/org/shadowrun/models/Squad.java | 1273 | package org.shadowrun.models;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.commons.lang3.StringUtils;
public class Squad implements Observable {
private StringProperty name;
private ObservableList<Character> characters;
public Squad() {
this.characters = FXCollections.observableArrayList();
this.name = new SimpleStringProperty(StringUtils.EMPTY);
}
public ObservableList<Character> getCharacters() {
return characters;
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
@Override
public void addListener(InvalidationListener listener) {
characters = FXCollections.observableList(characters, param -> new Observable[]{param});
characters.addListener(listener);
name.addListener(listener);
}
@Override
public void removeListener(InvalidationListener listener) {
characters.removeListener(listener);
characters.removeListener(listener);
}
}
| gpl-3.0 |
idega/platform2 | src/is/idega/idegaweb/golf/tournament/presentation/TournamentCreator.java | 56131 | /*
* Created on 4.3.2004
*/
package is.idega.idegaweb.golf.tournament.presentation;
import is.idega.idegaweb.golf.access.AccessControl;
import is.idega.idegaweb.golf.entity.Field;
import is.idega.idegaweb.golf.entity.Member;
import is.idega.idegaweb.golf.entity.Scorecard;
import is.idega.idegaweb.golf.entity.StartingtimeFieldConfig;
import is.idega.idegaweb.golf.entity.TeeColor;
import is.idega.idegaweb.golf.entity.Tournament;
import is.idega.idegaweb.golf.entity.TournamentForm;
import is.idega.idegaweb.golf.entity.TournamentGroup;
import is.idega.idegaweb.golf.entity.TournamentGroupHome;
import is.idega.idegaweb.golf.entity.TournamentHome;
import is.idega.idegaweb.golf.entity.TournamentRound;
import is.idega.idegaweb.golf.entity.TournamentRoundHome;
import is.idega.idegaweb.golf.entity.TournamentTournamentGroup;
import is.idega.idegaweb.golf.entity.TournamentType;
import is.idega.idegaweb.golf.entity.Union;
import is.idega.idegaweb.golf.moduleobject.GolfDialog;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import javax.ejb.FinderException;
import com.idega.data.EntityFinder;
import com.idega.data.IDOLookup;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.ui.BackButton;
import com.idega.presentation.ui.BooleanInput;
import com.idega.presentation.ui.DateInput;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.HiddenInput;
import com.idega.presentation.ui.IntegerInput;
import com.idega.presentation.ui.Parameter;
import com.idega.presentation.ui.SelectionBox;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.TextArea;
import com.idega.presentation.ui.TextInput;
import com.idega.presentation.ui.TimeInput;
import com.idega.presentation.ui.TimestampInput;
import com.idega.util.IWTimestamp;
/**
* @author gimmi
*/
public class TournamentCreator extends TournamentBlock {
boolean bIsUpdate;
String sTournamentIdToUpdate;
SubmitButton aframButton = new SubmitButton(localize("tournamnt.next","Next"));
BackButton tilbakaButton = new BackButton();
SubmitButton startingTimeB1;
Parameter entityPar;
Parameter selectedTournament;
protected boolean tournamentMustBeSet() {
return false;
}
public void main(IWContext modinfo)throws Exception{
if (isAdmin() || isClubAdmin()) {
super.setAdminView(TournamentAdministratorWindow.ADMIN_VIEW_CREATE_TOURNAMENT);
try {
checkIfUpdate(modinfo);
//initializeButtons(modinfo);
getAction(modinfo,super.getResourceBundle());
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}else {
add(super.getResourceBundle().getLocalizedString("tournament.no_permission","No permission"));
}
}
public void getAction(IWContext modinfo,IWResourceBundle iwrb) throws Exception {
String mode = modinfo.getParameter("tournament_control_mode");
String action = modinfo.getParameter("tournament_admin_createtournament_action");
if (action == null) {
createTournament(modinfo,iwrb);
}
else if (action.equals("create")) {
createTournament(modinfo,iwrb);
}
else if(action.equals("create_two")) {
createTournament2(modinfo,iwrb);
}
else if (action.equals("tournament_admin_save_tournament")) {
try {
SaveTournament(modinfo,iwrb);
}
catch (Exception e) {
add("Villa í SaveTournament<br>");
add(e.getMessage());
}
}
}
public void checkIfUpdate(IWContext modinfo) {
String sIsUpdate = modinfo.getParameter("tournament_control_mode");
bIsUpdate = false;
boolean remove = false;
if (sIsUpdate != null) {
if (sIsUpdate.equals("edit")) {
bIsUpdate = true;
super.setAdminView(TournamentAdministratorWindow.ADMIN_VIEW_MODIFY_TOURNAMENT);
remove = false;
String tournament_id = modinfo.getParameter("tournament");
if (tournament_id != null) {
sTournamentIdToUpdate = tournament_id;
modinfo.setSessionAttribute("i_golf_tournament_update_id",tournament_id);
}
}
else if (sIsUpdate.equals("create")) {
remove = true;
}
}
else {
String temp_tournament_id = (String) modinfo.getSessionAttribute("i_golf_tournament_update_id");
if (temp_tournament_id != null) {
sTournamentIdToUpdate = temp_tournament_id;
bIsUpdate = true;
remove = false;
}
}
if (remove) {
modinfo.removeSessionAttribute("i_golf_tournament_update_id");
}
}
public void createTournament(IWContext modinfo,IWResourceBundle iwrb) throws SQLException, RemoteException {
String sSelectedTournamentType = "-1";
String sSelectedTournamentForm = "-1";
boolean bSelectedTournamentUseGroups = false;
boolean bSelectedTournamentIsOpen = false;
int row = 1;
boolean useForm = true;
Form dialog = new Form(modinfo.getRequestURI());
add(dialog);
if (bIsUpdate) {
//Tournament tour = ((TournamentHome) IDOLookup.getHomeLegacy(Tournament.class)).findByPrimaryKey(Integer.parseInt(sTournamentIdToUpdate));
dialog.maintainParameter("tournament");
}
else {
}
if (bIsUpdate) {
Tournament[] tournaments = (Tournament[]) ((Tournament) IDOLookup.instanciateEntity(Tournament.class)).findAllByColumnEquals("tournament_id",sTournamentIdToUpdate);
if (tournaments.length < 1) {
useForm = false;
}
}
if (useForm) {
Tournament tournament = null;
if (bIsUpdate) {
try {
tournament = ((TournamentHome) IDOLookup.getHomeLegacy(Tournament.class)).findByPrimaryKey(Integer.parseInt(sTournamentIdToUpdate));
}
catch (FinderException fe) {
throw new SQLException(fe.getMessage());
}
}
Table table = new Table();
dialog.add(table);
table.setBorder(0);
Union union = null;
// CREATE INPUT FIELDS
TextInput tournamentName = new TextInput("tournament_admin_tournment_name","");
tournamentName.setSize(40);
DropdownMenu unions = null;
DropdownMenu fields = null;
Field field;
List fieldList;
if (AccessControl.isClubAdmin(modinfo)) {
try {
union = ((Member) AccessControl.getMember(modinfo)).getMainUnion();
}
catch (FinderException fe) {
throw new SQLException(fe.getMessage());
}
unions = new DropdownMenu("union_");
unions.addMenuElement(union.getID(),union.getName());
fields = new DropdownMenu("tournament_admin_field_id");
fieldList = union.getOwningFields();
if (fieldList != null)
for (int j = 0; j < fieldList.size(); j++) {
field = (Field) fieldList.get(j);
fields.addMenuElement(field.getID(),union.getAbbrevation() + " " +field.getName() );
}
}
else {
Union[] theUnion = (Union[])((Union) IDOLookup.instanciateEntity(Union.class)).findAllOrdered("ABBREVATION");
unions = new DropdownMenu(theUnion);
fields = new DropdownMenu("tournament_admin_field_id");
for (int i = 0; i < theUnion.length; i++) {
fieldList = theUnion[i].getOwningFields();
if (fieldList != null)
for (int j = 0; j < fieldList.size(); j++) {
field = (Field) fieldList.get(j);
fields.addMenuElement(field.getID(),theUnion[i].getAbbrevation() + " " +field.getName() );
}
}
}
TimestampInput firstRegistartionDate = new TimestampInput("tournament_admin_first_registartion_date");
firstRegistartionDate.setYearRange(2001, IWTimestamp.RightNow().getYear() + 5);
TimestampInput lastRegistartionDate = new TimestampInput("tournament_admin_last_registartion_date");
lastRegistartionDate.setYearRange(2001, IWTimestamp.RightNow().getYear() + 5);
DateInput startTime = new DateInput("tournament_admin_start_time");
startTime.setYearRange(2001, IWTimestamp.RightNow().getYear() + 5);
DateInput endTime = new DateInput("tournament_admin_end_time");
endTime.setYearRange(2001, IWTimestamp.RightNow().getYear() + 5);
TournamentType type = (TournamentType) IDOLookup.instanciateEntity(TournamentType.class);
List typeList = type.getVisibleTournamentTypes();
DropdownMenu tournamentTypeDrop = new DropdownMenu(typeList);
TournamentForm form = (TournamentForm) IDOLookup.instanciateEntity(TournamentForm.class);
DropdownMenu tournamentFormDrop = new DropdownMenu(form.findAll());
BooleanInput openTournament = new BooleanInput("tournament_admin_open_tournament");
BooleanInput onlineRegistration = new BooleanInput("tournament_admin_online_registration");
BooleanInput directRegistration = new BooleanInput("tournament_admin_direct_registration");
IntegerInput numberOfDays = new IntegerInput("tournament_admin_number_of_days",1);
numberOfDays.setSize(3);
IntegerInput numberOfRounds = new IntegerInput("tournament_admin_number_of_rounds",1);
numberOfRounds.setSize(3);
IntegerInput numberOfHoles = new IntegerInput("tournament_admin_number_of_holes",18);
numberOfHoles.setSize(3);
List tGroup = getTournamentBusiness(modinfo).getUnionTournamentGroups(union);
SelectionBox tournamentGroups = new SelectionBox(tGroup);
tournamentGroups.setHeight(15);
DropdownMenu numberInGroup = new DropdownMenu("tournament_admin_number_in_group");
numberInGroup.addMenuElement("1","1");
numberInGroup.addMenuElement("2","2");
numberInGroup.addMenuElement("3","3");
numberInGroup.addMenuElement("4","4");
DropdownMenu numberInTournamentGroup = new DropdownMenu("tournament_admin_number_in_tournament_group");
numberInTournamentGroup.addMenuElement("1","1");
numberInTournamentGroup.addMenuElement("2","2");
numberInTournamentGroup.addMenuElement("3","3");
numberInTournamentGroup.addMenuElement("4","4");
numberInTournamentGroup.setDisabled(true);
numberInTournamentGroup.setSelectedElement("2");
Iterator tIter = typeList.iterator();
while (tIter.hasNext()) {
TournamentType tt = (TournamentType) tIter.next();
if (tt.getUseGroups()) {
tournamentTypeDrop.setToEnableWhenSelected(numberInTournamentGroup, tt.getPrimaryKey().toString());
}
}
DropdownMenu interval = new DropdownMenu("tournament_admin_interval");
interval.addMenuElement("8","8");
interval.addMenuElement("10","10");
interval.addMenuElement("12","12");
TextInput maxHandicap = new TextInput("tournament_admin_max_handicap","24");
maxHandicap.setSize(3);
TextInput maxFemaleHandicap = new TextInput("tournament_admin_max_female_handicap","36");
maxFemaleHandicap.setSize(3);
TextArea extraText = new TextArea("tournament_admin_extra_text","");
extraText.setWidth(66);
extraText.setHeight(10);
SubmitButton submitButton = new SubmitButton("çfram");
HiddenInput hiddenAction = new HiddenInput("tournament_admin_createtournament_action","create_two");
// Window myWindow = new Window("Mtshpar",400,500,TournamentGroups.class);
GenericButton tournamentGroupButton = getButton(new GenericButton(iwrb.getLocalizedString("tournament.tournament_groups","Tournament Groups")));
tournamentGroupButton.setWindowToOpen(TournamentGroupsWindow.class);
// tournamentGroupButton.setWindowToOpen(TournamentGroups.class);
if (this.bIsUpdate) {
tournamentName.setContent(tournament.getName());
unions.setSelectedElement(tournament.getUnionId()+"");
fields.setSelectedElement(tournament.getFieldId()+"");
tournamentTypeDrop.setSelectedElement(tournament.getTournamentTypeId()+"");
openTournament.setSelected(tournament.getIfOpenTournament());
onlineRegistration.setSelected(tournament.getIfRegistrationOnline());
directRegistration.setSelected(tournament.isDirectRegistration());
tournamentFormDrop.setSelectedElement(tournament.getTournamentFormId()+"");
TournamentGroup[] tGroups = tournament.getTournamentGroups();
for (int i = 0 ; i < tGroups.length ; i ++ ) {
tournamentGroups.setSelectedElement(tGroups[i].getID()+"");
}
numberOfDays.setContent(tournament.getNumberOfDays()+"");
numberOfHoles.setContent(tournament.getNumberOfHoles()+"");
numberOfRounds.setContent(tournament.getNumberOfRounds()+"");
if (tournament.getNumberInTournamentGroup() > 0) {
numberInTournamentGroup.setSelectedElement(Integer.toString(tournament.getNumberInTournamentGroup()));
}
numberInTournamentGroup.setDisabled(!tournament.getTournamentType().getUseGroups());
maxHandicap.setContent(tournament.getMaxHandicap()+"");
maxFemaleHandicap.setContent(tournament.getFemaleMaxHandicap()+"");
if (tournament.getFirstRegistrationDate() != null) {
IWTimestamp firstRegDate = new IWTimestamp(tournament.getFirstRegistrationDate());
firstRegistartionDate.setYear(firstRegDate.getYear());
firstRegistartionDate.setMonth(firstRegDate.getMonth());
firstRegistartionDate.setDay(firstRegDate.getDay());
firstRegistartionDate.setHour(firstRegDate.getHour());
firstRegistartionDate.setMinute(firstRegDate.getMinute());
}
if (tournament.getLastRegistrationDate() != null) {
IWTimestamp lastRegDate = new IWTimestamp(tournament.getLastRegistrationDate());
lastRegistartionDate.setYear(lastRegDate.getYear());
lastRegistartionDate.setMonth(lastRegDate.getMonth());
lastRegistartionDate.setDay(lastRegDate.getDay());
lastRegistartionDate.setHour(lastRegDate.getHour());
lastRegistartionDate.setMinute(lastRegDate.getMinute());
}
if (tournament.getStartTime() != null) {
IWTimestamp iStartTime = new IWTimestamp(tournament.getStartTime());
startTime.setYear(iStartTime.getYear());
startTime.setMonth(iStartTime.getMonth());
startTime.setDay(iStartTime.getDay());
}
try {
StartingtimeFieldConfig[] fieldConf = (StartingtimeFieldConfig[])((StartingtimeFieldConfig) IDOLookup.instanciateEntity(StartingtimeFieldConfig.class)).findAllByColumnEquals("tournament_id",""+tournament.getID() );
if (fieldConf.length > 0) {
IWTimestamp endHour = new IWTimestamp(fieldConf[0].getCloseTime());
endTime.setYear(endHour.getYear());
endTime.setMonth(endHour.getMonth());
endTime.setDay(endHour.getDay());
}
else {
if (tournament.getStartTime() != null) {
IWTimestamp tempStamp = new IWTimestamp(tournament.getStartTime());
tempStamp.addDays(tournament.getNumberOfDays()-1);
endTime.setYear(tempStamp.getYear());
endTime.setMonth(tempStamp.getMonth());
endTime.setDay(tempStamp.getDay());
endTime.setDate(tempStamp.getSQLDate());
}
}
}
catch (Exception e){
e.printStackTrace(System.err);
}
extraText.setContent(tournament.getExtraText());
numberInGroup.setSelectedElement(tournament.getNumberInGroup()+"");
interval.setSelectedElement(tournament.getInterval()+"");
}
else {
firstRegistartionDate.setDate(IWTimestamp.RightNow().getSQLDate());
firstRegistartionDate.setHour(8);
firstRegistartionDate.setMinute(0);
lastRegistartionDate.setDate(IWTimestamp.RightNow().getSQLDate());
lastRegistartionDate.setHour(8);
lastRegistartionDate.setMinute(0);
startTime.setDate(IWTimestamp.RightNow().getSQLDate());
//startTime.setHour(8);
//startTime.setMinute(0);
endTime.setDate(IWTimestamp.RightNow().getSQLDate());
//endTime.setHour(20);
//endTime.setMinute(59);
directRegistration.setSelected(true);
numberInGroup.setSelectedElement("4");
interval.setSelectedElement("10");
}
// DONE CREATING INPUT FIELDS
table.add(iwrb.getLocalizedString("tournament.name","Name") ,1,row);
table.add(tournamentName,2,row);
table.mergeCells(2,row,4,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
table.setAlignment(5,row,"right");
if (bIsUpdate && AccessControl.isAdmin(modinfo)) {
if(AccessControl.isAdmin(modinfo) || AccessControl.isClubAdmin(modinfo)){
GenericButton deleteLink = getButton(new GenericButton());
deleteLink.setContent(localize("tournament.delete_tournament","Delete Tournament"));
deleteLink.setWindowToOpen(TournamentDeleteWindow.class);
deleteLink.addParameterToWindow("tournament_id",sTournamentIdToUpdate);
table.add(deleteLink,5,row);
}
}
++row;
table.add(iwrb.getLocalizedString("tournament.held_by","Held by"),1,row);
table.add(unions,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
table.mergeCells(2,row,5,row);
++row;
table.add(iwrb.getLocalizedString("tournament.field","Field"),1,row);
table.add(fields,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
table.mergeCells(2,row,5,row);
++row;
++row;
table.add(iwrb.getLocalizedString("tournament.arrangement","Arrangement"),1,row);
table.add(tournamentTypeDrop,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
table.add(iwrb.getLocalizedString("tournament.groups","Groups"),4,row);
table.setAlignment(1,row,"left");
table.setAlignment(4,row,"left");
table.setAlignment(5,row,"right");
table.add(tournamentGroupButton,5,row);
++row;
table.add(iwrb.getLocalizedString("tournament.type","Type"),1,row);
table.add(tournamentFormDrop,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
table.setAlignment(4,row,"left");
table.mergeCells(4,row,5,row+8);
table.setVerticalAlignment(4,row,"top");
table.add(tournamentGroups,4,row);
++row;
table.add(iwrb.getLocalizedString("tournament.open","Open"),1,row);
table.add(openTournament,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.allow_online_registration","Allow online registration"),1,row);
table.add(onlineRegistration,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.startingtime_registration","Register on tee time") ,1,row);
table.add(directRegistration,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.number_of_days","Number of days") ,1,row);
table.add(numberOfDays,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.number_of_rounds","Number of rounds") ,1,row);
table.add(numberOfRounds,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.number_of_holes_per_round","Holes per round"),1,row);
table.add(numberOfHoles,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.number_in_starting_group","Number in group"),1,row);
table.add(numberInGroup,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.number_in_tournament_group","Number in tournament group"),1,row);
table.add(numberInTournamentGroup,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.interval","Inteval"),1,row);
table.add(interval,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.male_maximum_handicap","Male maximum handicap"),1,row);
table.add(maxHandicap,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.female_maximum_handicap","Female maximum handicap"),1,row);
table.add(maxFemaleHandicap,2,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
++row;
table.add(iwrb.getLocalizedString("tournament.first_registration_date","First registration date"),1,row);
table.add(firstRegistartionDate,2,row);
table.mergeCells(2,row,5,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.last_registration_date","Last registration date"),1,row);
table.add(lastRegistartionDate,2,row);
table.mergeCells(2,row,5,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.tournament_begins","Tournament begins"),1,row);
table.add(startTime,2,row);
table.mergeCells(2,row,5,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
table.add(iwrb.getLocalizedString("tournament.tournament_ends","Tournament ends") ,1,row);
table.add(endTime,2,row);
table.mergeCells(2,row,5,row);
table.setAlignment(1,row,"left");
table.setAlignment(2,row,"left");
++row;
++row;
table.add(iwrb.getLocalizedString("tournament.other_information","Other information")+"<br>",1,row);
table.add(extraText,1,row);
table.setAlignment(1,row,"center");
table.mergeCells(1,row,5,row);
++row;
table.setAlignment(1,row,"left");
table.setAlignment(4,row,"right");
table.mergeCells(1,row,2,row);
table.mergeCells(4,row,5,row);
table.add(this.aframButton,4,row);
// table.add(submitButton,1,row);
table.add(hiddenAction,1,row);
table.add(getButton(getTournamentBusiness(modinfo).getBackLink(modinfo)),1,row);
}
else {
add("Ekkert mót valið eða mót ekki til");
}
}
public void createTournament2(IWContext modinfo, IWResourceBundle iwrb)throws SQLException, RemoteException{
String[] tournament_groups = modinfo.getParameterValues("tournament_group");
if (tournament_groups == null) {
add(iwrb.getLocalizedString("tournament.you_must_pick_groups","You must pick at least one tournament group")+ "<br><br>");
add(getButton(getTournamentBusiness(modinfo).getBackLink(modinfo)));
}
else {
try {
Form theForm = new Form();
//theForm.maintainParameter("tournament_group");
String name = modinfo.getParameter("tournament_admin_tournment_name");
String union_id = modinfo.getParameter("union_");
String field_id = modinfo.getParameter("tournament_admin_field_id");
String tournament_type_id = modinfo.getParameter("tournament_type");
String tournament_form_id = modinfo.getParameter("tournament_form");
String open_tournament = modinfo.getParameter("tournament_admin_open_tournament");
boolean isOpenTournament = true;
if (open_tournament.equalsIgnoreCase("N")) isOpenTournament = false;
String online_registration = modinfo.getParameter("tournament_admin_online_registration");
boolean isOnlineRegistration = false;
if (online_registration.equalsIgnoreCase("Y")) isOnlineRegistration = true;
String number_of_days = modinfo.getParameter("tournament_admin_number_of_days");
String number_of_rounds = modinfo.getParameter("tournament_admin_number_of_rounds");
int iNumberOfRounds = Integer.parseInt(number_of_rounds);
String number_of_holes = modinfo.getParameter("tournament_admin_number_of_holes");
String first_registration_date = modinfo.getParameter("tournament_admin_first_registartion_date");
IWTimestamp firstRegistrationDate = new IWTimestamp(first_registration_date);
String last_registration_date = modinfo.getParameter("tournament_admin_last_registartion_date");
IWTimestamp lastRegistrationDate = new IWTimestamp(last_registration_date);
String start_time = modinfo.getParameter("tournament_admin_start_time");
IWTimestamp startTime = new IWTimestamp(start_time);
String end_time = modinfo.getParameter("tournament_admin_end_time");
IWTimestamp endTime = new IWTimestamp(end_time);
String extra_text = modinfo.getParameter("tournament_admin_extra_text");
String direct_registration = modinfo.getParameter("tournament_admin_direct_registration");
boolean isDirectRegistration = true;
if (direct_registration.equalsIgnoreCase("N")) isDirectRegistration = false;
String number_in_group = modinfo.getParameter("tournament_admin_number_in_group");
String interval = modinfo.getParameter("tournament_admin_interval");
String maxHandicap = modinfo.getParameter("tournament_admin_max_handicap");
if (maxHandicap.equals("")) maxHandicap = "36";
String maxFemaleHandicap = modinfo.getParameter("tournament_admin_max_female_handicap");
if (maxFemaleHandicap.equals("")) maxFemaleHandicap = "36";
String sNumInTourGroup = modinfo.getParameter("tournament_admin_number_in_tournament_group");
int numInTourGroup = -1;
if (sNumInTourGroup != null && !sNumInTourGroup.equals("")) {
numInTourGroup = Integer.parseInt(sNumInTourGroup);
}
if ( maxHandicap.indexOf(",") != -1 ) {
maxHandicap = maxHandicap.replace(',','.');
}
if ( maxFemaleHandicap.indexOf(",") != -1 ) {
maxFemaleHandicap = maxFemaleHandicap.replace(',','.');
}
Tournament tournament = (Tournament) IDOLookup.createLegacy(Tournament.class);
if (bIsUpdate) {
tournament = ((TournamentHome) IDOLookup.getHomeLegacy(Tournament.class)).findByPrimaryKey(Integer.parseInt(sTournamentIdToUpdate));
}
tournament.setName(name);
tournament.setUnionId(Integer.parseInt(union_id));
tournament.setFieldId(new Integer(Integer.parseInt(field_id)));
tournament.setTournamentTypeID(Integer.parseInt(tournament_type_id));
tournament.setTournamentFormID(Integer.parseInt(tournament_form_id));
tournament.setOpenTournament(isOpenTournament);
tournament.setRegistrationOnline(isOnlineRegistration);
tournament.setIsDirectRegistration(isDirectRegistration);
tournament.setNumberOfDays(Integer.parseInt(number_of_days));
tournament.setNumberOfRounds(iNumberOfRounds);
tournament.setNumberOfHoles(Integer.parseInt(number_of_holes));
tournament.setNumberInGroup(Integer.parseInt(number_in_group));
tournament.setInterval(Integer.parseInt(interval));
if ( (tournament.getMaxHandicap() != Float.parseFloat(maxHandicap)) || (tournament.getFemaleMaxHandicap() != Float.parseFloat(maxFemaleHandicap)) ) {
theForm.add(new HiddenInput("update_handicap","true"));
}
tournament.setMaxHandicap(Float.parseFloat(maxHandicap));
tournament.setMaxFemaleHandicap(Float.parseFloat(maxFemaleHandicap));
tournament.setLastRegistrationDate(lastRegistrationDate.getTimestamp());
tournament.setFirstRegistrationDate(firstRegistrationDate.getTimestamp());
tournament.setStartTime(startTime.getTimestamp());
tournament.setExtraText(extra_text);
tournament.setGroupTournament(true);
tournament.setCreationDate(IWTimestamp.getTimestampRightNow());
tournament.setIsClosed(false);
tournament.setNumberInTournamentGroup(numInTourGroup);
modinfo.setSessionAttribute("tournament_admin_create_tournament",tournament);
/*
for (int i = 1; i <= tournament.getNumberOfRounds();i++){
TournamentRound round = new TournamentRound();
round.setRoundNumber(i);
round.setTournament(tournament);
round.setRoundDate(com.idega.util.idegaCalendar.getTimestampAfter(tournament.getStartTime(),i+1));
round.setIncreaseHandicap(true);
round.setDecreaseHandicap(true);
round.setRoundEndDate(com.idega.util.idegaCalendar.getTimestampAfter(tournament.getStartTime(),i+1));
round.insert();
}
*/
TournamentGroup tGroup;
Table groupTable = new Table();
groupTable.setWidth("85%");
groupTable.add(iwrb.getLocalizedString("tournament.group","Group") ,1,1);
groupTable.add(iwrb.getLocalizedString("tournament.fee","Fee"),2,1);
groupTable.add(iwrb.getLocalizedString("tournament.tee","Tee color"),3,1);
String sql = "select * from tee_color where tee_color_id in (select tee_color_id from tee where field_id = "+tournament.getFieldId()+") order by tee_color_name";
TeeColor[] tee_colors = (TeeColor[]) ((TeeColor) IDOLookup.instanciateEntity(TeeColor.class)).findAll(sql);
//TeeColor[] tee_colors = (TeeColor[]) ((TeeColor) IDOLookup.instanciateEntity(TeeColor.class)).findAllOrdered("TEE_COLOR_NAME");
int tableRow = 1;
TextInput feeText;
DropdownMenu teeColorDrop;
TournamentTournamentGroup[] tourTourGroup;
if (tournament_groups != null) {
for (int i = 0; i < tournament_groups.length; i++) {
tGroup = ((TournamentGroupHome) IDOLookup.getHomeLegacy(TournamentGroup.class)).findByPrimaryKey(Integer.parseInt(tournament_groups[i]));
++tableRow;
feeText = new TextInput("tournament_admin_fee_for_group"+tGroup.getID(),"0");
feeText.setSize(6);
teeColorDrop = new DropdownMenu("tournament_admin_tee_color_for_group"+tGroup.getID());
for (int j = 0 ; j < tee_colors.length ; j++) {
teeColorDrop.addMenuElement(tee_colors[j].getID(),tee_colors[j].getName());
}
teeColorDrop.setSelectedElement(tGroup.getTeeColor().getID()+"");
if (bIsUpdate) {
tourTourGroup = (TournamentTournamentGroup[]) ((TournamentTournamentGroup) IDOLookup.instanciateEntity(TournamentTournamentGroup.class)).findAll("Select * from tournament_tournament_group WHERE tournament_id ="+tournament.getID()+" AND tournament_group_id = "+tGroup.getID()+"");
if (tourTourGroup.length > 0) {
if (tourTourGroup[0].getRegistrationFee() != -1)
feeText.setContent(tourTourGroup[0].getRegistrationFee()+"");
try {
teeColorDrop.setSelectedElement(tourTourGroup[0].getTeeColorId()+"");
}
catch (Exception e) {}
}
}
groupTable.add(tGroup.getName(),1,tableRow);
groupTable.add(feeText,2,tableRow);
groupTable.add(new HiddenInput("tournament_group",tGroup.getID()+""),1,tableRow);
groupTable.add(teeColorDrop,3,tableRow);
}
}
// ++tableRow;
// ++tableRow;
tableRow = 1;
Table roundTable = new Table();
roundTable.setWidth("85%");
roundTable.add(iwrb.getLocalizedString("tournament.round","Round"),1,tableRow);
roundTable.add(iwrb.getLocalizedString("tournament.time","Time") ,2,tableRow);
roundTable.mergeCells(2,tableRow,3,tableRow);
roundTable.add(iwrb.getLocalizedString("tournament.plays_on_1_and_10_tee","Tee off on 1 and 10 tee"),4,tableRow);
++tableRow;
TimeInput tInput;
TimeInput toInput;
TournamentRound tRound;
TournamentRound[] tRounds = tournament.getTournamentRounds();
int tRoundsCounter = 0;
IWTimestamp temp = new IWTimestamp(endTime);
for ( int i = 0 ; i < tournament.getNumberOfRounds() ; i++) {
startTime = new IWTimestamp(start_time);
DropdownMenu availableDays = new DropdownMenu("round_date");
endTime.addDays(1);
while (endTime.isLaterThan(startTime) ) {
availableDays.addMenuElement(startTime.toSQLDateString(), startTime.getISLDate(".",true) );
startTime.addDays(1);
}
endTime = new IWTimestamp(temp);
DropdownMenu oneAndTen = new DropdownMenu("oneAndTen_"+i);
oneAndTen.addMenuElement("1","Nei");
oneAndTen.addMenuElement("2","Já");
oneAndTen.setSelectedElement("1");
if (bIsUpdate) {
try{
tRound = tRounds[i];
tInput = new TimeInput("tournament_admin_round_from_time_"+tRound.getID() );
toInput = new TimeInput("tournament_admin_round_to_time_"+tRound.getID() );
availableDays.setSelectedElement(new IWTimestamp(tRounds[tRoundsCounter].getRoundDate()).toSQLDateString() );
tInput.setTime(new java.sql.Time(tRounds[tRoundsCounter].getRoundDate().getTime()));
toInput.setTime(new java.sql.Time(tRounds[tRoundsCounter].getRoundEndDate().getTime()));
roundTable.add(new HiddenInput("tournament_round_id",""+tRound.getID()),1,tableRow);
oneAndTen.setName("oneAndTen_"+tRound.getID());
if (tRound.getStartingtees() == 2) {
oneAndTen.setSelectedElement("2");
}
++tRoundsCounter;
}
catch (Exception e) {
tInput = new TimeInput("tournament_admin_round_from_time_"+i);
toInput = new TimeInput("tournament_admin_round_to_time_"+i);
startTime.addDays(i);
tInput.setTime(new java.sql.Time(startTime.getSQLDate().getTime()));
toInput.setTime(new java.sql.Time(startTime.getSQLDate().getTime()));
startTime.addDays(-i);
}
}
else {
tInput = new TimeInput("tournament_admin_round_from_time_"+i);
toInput = new TimeInput("tournament_admin_round_to_time_"+i);
startTime.addDays(i);
tInput.setTime(new java.sql.Time(startTime.getSQLDate().getTime()));
toInput.setTime(new java.sql.Time(startTime.getSQLDate().getTime()));
startTime.addDays(-i);
}
roundTable.add(iwrb.getLocalizedString("tournament.round","Round")+" "+(i+1),1,tableRow);
roundTable.add(availableDays,2,tableRow);
roundTable.add(" frá ",2,tableRow);
roundTable.add(tInput,2,tableRow);
roundTable.add(" til ",2,tableRow);
roundTable.add(toInput,2,tableRow);
roundTable.mergeCells(2,tableRow,3,tableRow);
roundTable.add(oneAndTen,4,tableRow);
++tableRow;
}
Table buttonTable = new Table();
buttonTable.setWidth("85%");
GenericButton submitButton = getButton(new SubmitButton(localize("tournament.save","Save")));
HiddenInput hiddenInput = new HiddenInput("tournament_admin_createtournament_action","tournament_admin_save_tournament");
buttonTable.add(getButton(getTournamentBusiness(modinfo).getBackLink(modinfo)),1,1);
buttonTable.add(submitButton,3,1);
buttonTable.add(hiddenInput,3,1);
buttonTable.setAlignment(3,1,"right");
theForm.add(groupTable);
theForm.addBreak();
theForm.add(roundTable);
theForm.addBreak();
theForm.add(buttonTable);
add(theForm);
//dialog.add(dayTable);
}
catch (Exception e) {
add(iwrb.getLocalizedString("tournament.error","Error")+"<br>");
add(e.getMessage());
e.printStackTrace(System.out);
}
}
}
public void SaveTournament(IWContext modinfo, IWResourceBundle iwrb) throws Exception{
Tournament tournament = (Tournament) modinfo.getSession().getAttribute("tournament_admin_create_tournament");
TournamentRound[] tourRounds = tournament.getTournamentRounds();
int manyRounds = tourRounds.length;
if (tournament == null) {
add(iwrb.getLocalizedString("tournament.no_tournament_selected","No tournament selected"));
}
if (bIsUpdate) {
tournament.update();
TournamentGroup[] tempTournamentGroup = tournament.getTournamentGroups();
for (int i = 0; i < tempTournamentGroup.length; i++) {
tempTournamentGroup[i].removeFrom(tournament);
}
TeeColor[] tempTeeColor = tournament.getTeeColors();
for (int i = 0; i < tempTeeColor.length; i++) {
tempTeeColor[i].removeFrom(tournament);
}
StartingtimeFieldConfig[] sFieldConfig = (StartingtimeFieldConfig[]) ((StartingtimeFieldConfig) IDOLookup.instanciateEntity(StartingtimeFieldConfig.class)).findAllByColumnEquals("tournament_id",tournament.getID()+"") ;
for (int i = 0; i < sFieldConfig.length; i++) {
sFieldConfig[i].delete();
}
if (manyRounds == tournament.getNumberOfRounds() ) {
}else if (manyRounds < tournament.getNumberOfRounds() ) {
// BÆTA VIÐ TOURNAMENT_ROUNDs
String[] round_date = modinfo.getParameterValues("round_date");
String theFromTime;
String theToTime;
String fromString;
String toString;
IWTimestamp stampFrom;
IWTimestamp stampTo;
Member[] members = getTournamentBusiness(modinfo).getMembersInTournament(tournament);
Member member;
for (int i = (manyRounds +1) ; i <= tournament.getNumberOfRounds() ; i++){
theFromTime = modinfo.getParameter("tournament_admin_round_from_time_"+(i-1));
theToTime = modinfo.getParameter("tournament_admin_round_to_time_"+(i-1));
IWTimestamp tempStamp = new IWTimestamp(tournament.getStartTime());
fromString = round_date[i-1] + " "+ theFromTime;
toString = round_date[i-1] + " "+ theToTime;
stampFrom = new IWTimestamp(fromString);
stampTo = new IWTimestamp(toString);
TournamentRound round = (TournamentRound) IDOLookup.createLegacy(TournamentRound.class);
round.setRoundNumber(i);
round.setTournament(tournament);
if (tournament.isDirectRegistration()) {
round.setVisibleStartingtimes(true);
}
round.setRoundDate(stampFrom.getTimestamp());
round.setIncreaseHandicap(true);
round.setDecreaseHandicap(true);
round.setRoundEndDate(stampTo.getTimestamp());
round.insert();
}
}else if (manyRounds > tournament.getNumberOfRounds() ) {
// HENDA ÚT TOURNAMENT_ROUNDs
for (int i = (tournament.getNumberOfRounds()+1) ; i<= (manyRounds) ;i++) {
List tournamentRounds = EntityFinder.findAllByColumnEquals((TournamentRound) IDOLookup.instanciateEntity(TournamentRound.class),"tournament_id",""+tournament.getID(),"ROUND_NUMBER",""+i);
if (tournamentRounds != null) {
if (tournamentRounds.size() == 1) {
try {
TournamentRound tourRnd = (TournamentRound) tournamentRounds.get(0);
tourRnd.delete();
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
}
TournamentRound[] tournRounds = tournament.getTournamentRounds();
for (int u = 0; u < tournRounds.length; u++) {
getTournamentBusiness(modinfo).invalidateStartingTimeCache(modinfo, tournRounds[u].getTournamentID(), Integer.toString(tournRounds[u].getID()));
}
}
else {
try {
tournament.insert();
}
catch (Exception e) {
System.err.println("createTournament í insert()");
e.printStackTrace(System.err);
}
}
try {
String[] tournament_group_ids = modinfo.getParameterValues("tournament_group");
TournamentTournamentGroup tTGroup;
TournamentGroup tGroup = null;
String regFee = "";
String teeColorId = "";
if (tournament_group_ids != null) {
for (int i = 0; i < tournament_group_ids.length; i++) {
teeColorId = modinfo.getParameter("tournament_admin_tee_color_for_group"+tournament_group_ids[i]);
regFee = modinfo.getParameter("tournament_admin_fee_for_group"+tournament_group_ids[i]);
tTGroup = (TournamentTournamentGroup) IDOLookup.createLegacy(TournamentTournamentGroup.class);
tTGroup.setTournamentId(tournament.getID());
tTGroup.setTournamentGroupId(Integer.parseInt(tournament_group_ids[i]));
tTGroup.setRegistrationFee(Integer.parseInt(regFee));
tTGroup.setTeeColorId(Integer.parseInt(teeColorId));
tTGroup.insert();
}
}
}
catch (Exception e) {
add("villa í grúppum");
e.printStackTrace(System.err);
}
try {
String tournament_round_ids[] = modinfo.getParameterValues("tournament_round_id");
Scorecard[] scorecards;
if (tournament_round_ids != null) {
String[] round_date = modinfo.getParameterValues("round_date");
TournamentRound tRound;
String from_time;
String to_time;
String numberOfStartingtees;
IWTimestamp stampFrom;
IWTimestamp stampTo;
boolean updateScorecards = false;
String fromString = "";
String toString = "";
for (int i = 0; i < tournament_round_ids.length; i++) {
updateScorecards = false;
from_time = modinfo.getParameter("tournament_admin_round_from_time_"+tournament_round_ids[i]);
to_time = modinfo.getParameter("tournament_admin_round_to_time_"+tournament_round_ids[i]);
numberOfStartingtees = modinfo.getParameter("oneAndTen_"+tournament_round_ids[i]);
fromString = round_date[i] + " "+ from_time;
toString = round_date[i] + " "+ to_time;
tRound = ((TournamentRoundHome) IDOLookup.getHomeLegacy(TournamentRound.class)).findByPrimaryKey(Integer.parseInt(tournament_round_ids[i]));
stampFrom = new IWTimestamp(fromString);
stampTo = new IWTimestamp(toString);
if (tournament.isDirectRegistration()) {
tRound.setVisibleStartingtimes(true);
}
if ( (tRound.getRoundDate().getDay() != stampFrom.getTimestamp().getDay()) || (tRound.getRoundDate().getMonth() != stampFrom.getTimestamp().getMonth()) || (tRound.getRoundDate().getYear() != stampFrom.getTimestamp().getYear()) ) {
updateScorecards = true;
}
tRound.setRoundDate(stampFrom.getTimestamp());
tRound.setRoundEndDate(stampTo.getTimestamp());
tRound.setStartingtees(Integer.parseInt(numberOfStartingtees));
tRound.update();
if (updateScorecards) {
scorecards = (Scorecard[]) ((Scorecard) IDOLookup.instanciateEntity(Scorecard.class)).findAllByColumnEquals("tournament_round_id",tRound.getID());
for (int g = 0; g < scorecards.length; g++) {
scorecards[g].setScorecardDate(tRound.getRoundDate());
scorecards[g].update();
is.idega.idegaweb.golf.UpdateHandicap.update(scorecards[g].getMemberId(),new IWTimestamp(tournament.getStartTime()));
//System.out.println("Uppfaerdi skorkort fyrir "+scorecards[g].getMember().getName());
}
}
}
}
else {
String[] round_date = modinfo.getParameterValues("round_date");
TournamentRound tRound;
String from_time;
String to_time;
String numberOfStartingtees;
IWTimestamp stampFrom;
IWTimestamp stampTo;
boolean updateScorecards = false;
String fromString = "";
String toString = "";
TournamentRound[] tRounds = tournament.getTournamentRounds();
for (int i = 0; i < tRounds.length ; i++) {
updateScorecards = false;
from_time = modinfo.getParameter("tournament_admin_round_from_time_"+i);
to_time = modinfo.getParameter("tournament_admin_round_to_time_"+i);
numberOfStartingtees = modinfo.getParameter("oneAndTen_"+i);
fromString = round_date[i] + " "+ from_time;
toString = round_date[i] + " "+ to_time;
tRound = ((TournamentRoundHome) IDOLookup.getHomeLegacy(TournamentRound.class)).findByPrimaryKey(tRounds[i].getID());
stampFrom = new IWTimestamp(fromString);
stampTo = new IWTimestamp(toString);
if (tournament.isDirectRegistration()) {
tRound.setVisibleStartingtimes(true);
}
if ( (tRound.getRoundDate().getDay() != stampFrom.getTimestamp().getDay()) || (tRound.getRoundDate().getMonth() != stampFrom.getTimestamp().getMonth()) || (tRound.getRoundDate().getYear() != stampFrom.getTimestamp().getYear()) ) {
updateScorecards = true;
}
tRound.setRoundDate(stampFrom.getTimestamp());
tRound.setRoundEndDate(stampTo.getTimestamp());
tRound.setStartingtees(Integer.parseInt(numberOfStartingtees));
tRound.update();
if (updateScorecards) {
scorecards = (Scorecard[]) ((Scorecard) IDOLookup.instanciateEntity(Scorecard.class)).findAllByColumnEquals("tournament_round_id",tRound.getID());
for (int g = 0; g < scorecards.length; g++) {
scorecards[g].setScorecardDate(tRound.getRoundDate());
scorecards[g].update();
is.idega.idegaweb.golf.UpdateHandicap.update(scorecards[g].getMemberId(),new IWTimestamp(tournament.getStartTime()));
//System.out.println("Uppfaerdi skorkort fyrir "+scorecards[g].getMember().getName());
}
}
}
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
String isUpdateHandicap = modinfo.getParameter("update_handicap");
if (isUpdateHandicap != null) {
if (isUpdateHandicap.equalsIgnoreCase("true")) {
try { // updateHandicapForRegisteredMembers
Member[] members = getTournamentBusiness(modinfo).getMembersInTournament(tournament);
if (members != null) {
if (members.length > 0) {
for (int i = 0; i < members.length; i++) {
is.idega.idegaweb.golf.UpdateHandicap.update(members[i], new IWTimestamp(tournament.getStartTime()));
}
}
}
}catch (Exception e) {
System.err.println(this.getClassName()+" : saveTournament : updateHandicapForRegisteredMembers");
e.printStackTrace(System.err);
}
}
}
getTournamentBusiness(modinfo).removeTournamentTableApplicationAttribute(modinfo);
add(iwrb.getLocalizedString("tournament.tournament_saved","Tournament saved"));
}
public void selectTournament(String controlParameter,IWResourceBundle iwrb)throws SQLException{
GolfDialog dialog = new GolfDialog(iwrb.getLocalizedString("tournament.choose_tournament","Choose a tournament"));
add(dialog);
dialog.add(new DropdownMenu(((Tournament) IDOLookup.instanciateEntity(Tournament.class)).findAll()));
if (controlParameter.equals("startingtime")){
dialog.add(startingTimeB1);
}
}
public boolean isInEditMode(IWContext modinfo){
return bIsUpdate;
}
public Tournament getTournament(IWContext modinfo)throws Exception{
String tournament_par = modinfo.getParameter("tournament");
Tournament tournament=null;
if(tournament_par==null){
tournament = (Tournament)modinfo.getSessionAttribute("tournament_admin_tournament");
}
else{
tournament = ((TournamentHome) IDOLookup.getHomeLegacy(Tournament.class)).findByPrimaryKey(Integer.parseInt(tournament_par));
modinfo.setSessionAttribute("tournament_admin_tournament",tournament);
}
return tournament;
}
}
| gpl-3.0 |
Kjwon15/bluebirdradio | TwitterVoice/src/main/java/kai/twitter/voice/LoginActivity.java | 4663 | package kai.twitter.voice;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import kai.twitter.voice.util.CustomToast;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class LoginActivity extends AppCompatActivity {
private final static Uri CALLBACK_URL = Uri.parse("bluebird://callback");
private WebView webview;
private Twitter twitter;
private AccessToken acToken;
private RequestToken rqToken;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webview = (WebView) findViewById(R.id.login_webview);
webview.setWebViewClient(new WebViewClient() {
DbAdapter adapter = new DbAdapter(getApplicationContext());
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Uri uri = Uri.parse(url);
if (uri.getScheme().equals(CALLBACK_URL.getScheme()) &&
uri.getAuthority().equals(CALLBACK_URL.getAuthority())) {
String oauth_verifier = uri.getQueryParameter("oauth_verifier");
if (oauth_verifier != null && acToken == null) {
try {
acToken = new AsyncGetAccessToken().execute(oauth_verifier).get();
adapter.insertAccount(acToken);
} catch (Exception e) {
String errorMsg = getString(R.string.unable_get_oauth_token);
String msg = e.getMessage();
if (msg == null) {
msg = errorMsg;
}
Log.e("Twitter", msg);
CustomToast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
}
}
finish();
return;
}
}
});
new AsyncRequestTokenUrl(this).execute();
}
private class AsyncRequestTokenUrl extends AsyncTask<String, Void, Void> {
private Context context;
private ProgressDialog processDialog;
public AsyncRequestTokenUrl(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
processDialog = new ProgressDialog(context);
processDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
processDialog.show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if ((processDialog != null) && (processDialog.isShowing())) processDialog.dismiss();
if (rqToken != null) {
webview.loadUrl(rqToken.getAuthorizationURL());
} else {
CustomToast.makeText(context, getString(R.string.unable_get_oauth_token), Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
protected Void doInBackground(String... strings) {
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(getString(R.string.CONSUMER_KEY), getString(R.string.CONSUMER_SECRET));
rqToken = twitter.getOAuthRequestToken(CALLBACK_URL.toString());
} catch (TwitterException e) {
Log.e("Twitter", e.getMessage());
}
return null;
}
}
private class AsyncGetAccessToken extends AsyncTask<String, Void, AccessToken> {
@Override
protected AccessToken doInBackground(String... strings) {
try {
AccessToken token = twitter.getOAuthAccessToken(rqToken, strings[0]);
return token;
} catch (TwitterException e) {
Log.e("Twitter", e.getMessage());
}
return null;
}
}
}
| gpl-3.0 |
volmok/CPEE | Android/CPEE/app/src/main/java/ro/bfc/cpee/Controllers/MainActivityController.java | 3247 | package ro.bfc.cpee.Controllers;
import android.content.Intent;
import android.net.Uri;
import ro.bfc.cpee.models.CPEEDocument;
import ro.bfc.cpee.models.County;
import ro.bfc.cpee.models.NivelEnergie;
import ro.bfc.cpee.models.Price;
import ro.bfc.cpee.models.Total;
import ro.bfc.cpee.utils.CollectionUtils;
import ro.bfc.cpee.utils.FileUtils;
import ro.bfc.cpee.views.IMainActivityView;
/**
* Created by catalin on 1/5/15.
*/
public class MainActivityController {
CPEEDocument document;
IMainActivityView activity;
Total total;
public MainActivityController(IMainActivityView activity) {
this.activity = activity;
total = new Total();
if(document != null)
total.setGlobalPrices(document.Global);
}
public void init(Intent intent) {
if(intent != null && intent.getData() != null) {
try {
final Uri filePath = intent.getData();
loadModel(filePath);
}
catch (Exception e){
this.activity.showMessageLong(e.getMessage());
}
}else{
this.document = FileUtils.readFromInternalStorage(this.activity.getContext(), "valori.cpee");
}
if(this.document != null){
this.total.setGlobalPrices(document.Global);
this.activity.setDocument(this.document);
this.activity.updateCounties();
}
else
this.activity.showMessageLong("Nu exista valori definite. Incarcati un document CPEE.");
}
public void loadModel(Uri uri) {
try {
CPEEDocument doc = CPEEDocument.readJSON(FileUtils.getFileAsString(this.activity.getContext(), uri));
if(doc != null){
FileUtils.saveToInternalStorage(this.activity.getContext(), "valori.cpee", doc);
this.document = doc;
}
} catch (Exception e) {
this.activity.showMessageLong(e.getMessage());
e.printStackTrace();
}
}
public void onCountySelected(int position) {
final County county = CollectionUtils.getElementAt(this.document.Counties, position);
if(county != null) {
Price countyPrice = Price.getPrice(document.Prices, county.PriceId);
if(countyPrice != null){
total.setPrice(countyPrice);
this.activity.updateTotal(total);
this.activity.updateDistrib(countyPrice.Name);
}
else this.activity.showMessageShort(String.format("Pret invalid pentru judetul '%s'.", county.Name));
}
}
public void onNivelEnergeticSelected(int position) {
final NivelEnergie ne = NivelEnergie.forValue(position);
if(ne != null) {
total.setNivelEnergie(ne);
this.activity.updateTotal(total);
}
else this.activity.showMessageShort("Nivel selecat invalid");
}
public void setPretBaza(double pretBaza) {
total.setPretBaza(pretBaza);
if(pretBaza == 0){
this.activity.updateTotal(null);
}
else {
this.activity.updateTotal(total);
}
}
public void refreshTotal(){
this.activity.updateTotal(total);
}
}
| gpl-3.0 |
boudjaamaa/IslamicfinanceOntology | src/main/java/Fatw/fatwa.java | 3044 | /*
* 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 Fatw;
import Case.cas;
import java.io.Serializable;
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 static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* @author fathi
*/
@Entity
@Table(name = "fatwa")
public class fatwa implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;//il faaut yarja3 kima kan id
@Column(name = "hokm")
private String hokm;
@Column(name = "quren")
private String quren;
@Column(name = "suna")
private String suna;
@Column(name = "ijtihad")
private String ijtihad;
public fatwa(String hokm, String quren, String suna, String ijtihad) {
//this.id=id;
this.hokm = hokm;
this.quren = quren;
this.suna = suna;
this.ijtihad = ijtihad;
}
public fatwa(Integer id, String hokm, String quren, String suna, String ijtihad) {
this.id = id;
this.hokm = hokm;
this.quren = quren;
this.suna = suna;
this.ijtihad = ijtihad;
}
public fatwa() {
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the hokm
*/
public String getHokm() {
return hokm;
}
/**
* @param hokm the hokm to set
*/
public void setHokm(String hokm) {
this.hokm = hokm;
}
/**
* @return the quren
*/
public String getQuren() {
return quren;
}
/**
* @param quren the quren to set
*/
public void setQuren(String quren) {
this.quren = quren;
}
/**
* @return the suna
*/
public String getSuna() {
return suna;
}
/**
* @param suna the suna to set
*/
public void setSuna(String suna) {
this.suna = suna;
}
/**
* @return the ijtihad
*/
public String getIjtihad() {
return ijtihad;
}
/**
* @param ijtihad the ijtihad to set
*/
public void setIjtihad(String ijtihad) {
this.ijtihad = ijtihad;
}
@Override
public String toString() {
return " fatwa [ id=" + id + ", hokm=" + hokm + ", quren=" + quren + ", suna=" + suna + " , ijtihad=" + ijtihad + "]";
}
/**
* @return the cas
*/
/**
* @param cas the cas to set
*/
}
| gpl-3.0 |
robosoul/tmdb4j | src/main/java/com/soulware/tmdb4j/beans/model/MovieBean.java | 11690 | /**
* Copyright 2012 Luka Obradovic.
*/
/**
* This file is part of TMDb API support for JAVA - tmdb4j.
*
* TMDb API support for JAVA - tmdb4j 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.
*
* TMDb API support for JAVA - tmdb4j 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 TMDb API support for JAVA - tmdb4j. If not, see <http://www.gnu.org/licenses/>.
*/
package com.soulware.tmdb4j.beans.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.soulware.tmdb4j.beans.BaseBean;
/**
*
* @author Luka Obradovic, 2012
*
* Model: http://help.themoviedb.org/kb/api/movie-info
*/
public class MovieBean extends BaseBean {
private static final long serialVersionUID = 1L;
@JsonProperty("adult")
private boolean adult;
@JsonProperty("backdrop_path")
private String backdropPath;
@JsonProperty("belongs_to_collection")
private CollectionBean belongsToCollection;
@JsonProperty("budget")
private String budget;
@JsonProperty("genres")
private List<GenreBean> genres;
@JsonProperty("homepage")
private String homepage;
@JsonProperty("id")
private int id;
@JsonProperty("imdb_id")
private String imdbId;
@JsonProperty("original_title")
private String originalTitle;
@JsonProperty("overview")
private String overview;
@JsonProperty("popularity")
private float popularity;
@JsonProperty("poster_path")
private String posterPath;
@JsonProperty("production_companies")
private List<ProductionCompanyBean> productionCompanies;
@JsonProperty("production_countries")
private List<ProductionCountryBean> productionCountries;
@JsonProperty("release_date")
private String releaseDate;
@JsonProperty("revenue")
private long revenue;
@JsonProperty("runtime")
private int runtime;
@JsonProperty("spoken_languages")
private List<LanguageBean> spokenLanguages;
@JsonProperty("tagline")
private String tagline;
@JsonProperty("title")
private String title;
@JsonProperty("vote_average")
private float voteAverage;
@JsonProperty("vote_count")
private int voteCount;
@JsonProperty("status")
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
/**
* @return the adult
*/
public boolean isAdult() {
return adult;
}
/**
* @param adult the adult to set
*/
public void setAdult(boolean adult) {
this.adult = adult;
}
/**
* @return the backdropPath
*/
public String getBackdropPath() {
return backdropPath;
}
/**
* @param backdropPath the backdropPath to set
*/
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
/**
* @return the belongsToCollection
*/
public CollectionBean getBelongsToCollection() {
return belongsToCollection;
}
/**
* @param belongsToCollection the belongsToCollection to set
*/
public void setBelongsToCollection(CollectionBean belongsToCollection) {
this.belongsToCollection = belongsToCollection;
}
/**
* @return the budget
*/
public String getBudget() {
return budget;
}
/**
* @param budget the budget to set
*/
public void setBudget(String budget) {
this.budget = budget;
}
/**
* @return the genres
*/
public List<GenreBean> getGenres() {
return genres;
}
/**
* @param genres the genres to set
*/
public void setGenres(List<GenreBean> genres) {
this.genres = genres;
}
/**
* @return the homepage
*/
public String getHomepage() {
return homepage;
}
/**
* @param homepage the homepage to set
*/
public void setHomepage(String homepage) {
this.homepage = homepage;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the imdbId
*/
public String getImdbId() {
return imdbId;
}
/**
* @param imdbId the imdbId to set
*/
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
/**
* @return the originalTitle
*/
public String getOriginalTitle() {
return originalTitle;
}
/**
* @param originalTitle the originalTitle to set
*/
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
/**
* @return the overview
*/
public String getOverview() {
return overview;
}
/**
* @param overview the overview to set
*/
public void setOverview(String overview) {
this.overview = overview;
}
/**
* @return the popularity
*/
public float getPopularity() {
return popularity;
}
/**
* @param popularity the popularity to set
*/
public void setPopularity(float popularity) {
this.popularity = popularity;
}
/**
* @return the posterPath
*/
public String getPosterPath() {
return posterPath;
}
/**
* @param posterPath the posterPath to set
*/
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
/**
* @return the productionCompanies
*/
public List<ProductionCompanyBean> getProductionCompanies() {
return productionCompanies;
}
/**
* @param productionCompanies the productionCompanies to set
*/
public void setProductionCompanies(List<ProductionCompanyBean> productionCompanies) {
this.productionCompanies = productionCompanies;
}
/**
* @return the releaseDate
*/
public String getReleaseDate() {
return releaseDate;
}
/**
* @param releaseDate the releaseDate to set
*/
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
/**
* @return the revenue
*/
public long getRevenue() {
return revenue;
}
/**
* @param revenue the revenue to set
*/
public void setRevenue(long revenue) {
this.revenue = revenue;
}
/**
* @return the runtime
*/
public int getRuntime() {
return runtime;
}
/**
* @param runtime the runtime to set
*/
public void setRuntime(int runtime) {
this.runtime = runtime;
}
/**
* @return the spokenLanguages
*/
public List<LanguageBean> getSpokenLanguages() {
return spokenLanguages;
}
/**
* @param spokenLanguages the spokenLanguages to set
*/
public void setSpokenLanguages(List<LanguageBean> spokenLanguages) {
this.spokenLanguages = spokenLanguages;
}
/**
* @return the tagline
*/
public String getTagline() {
return tagline;
}
/**
* @param tagline the tagline to set
*/
public void setTagline(String tagline) {
this.tagline = tagline;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the voteAverage
*/
public float getVoteAverage() {
return voteAverage;
}
/**
* @param voteAverage the voteAverage to set
*/
public void setVoteAverage(float voteAverage) {
this.voteAverage = voteAverage;
}
/**
* @return the voteCount
*/
public int getVoteCount() {
return voteCount;
}
/**
* @param voteCount the voteCount to set
*/
public void setVoteCount(int voteCount) {
this.voteCount = voteCount;
}
/**
* @return the productionCountries
*/
public List<ProductionCountryBean> getProductionCountries() {
return productionCountries;
}
/**
* @param productionCountries the productionCountries to set
*/
public void setProductionCountries(List<ProductionCountryBean> productionCountries) {
this.productionCountries = productionCountries;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((imdbId == null) ? 0 : imdbId.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MovieBean)) {
return false;
}
final MovieBean other = (MovieBean) obj;
if (id != other.id) {
return false;
}
if (imdbId == null) {
if (other.imdbId != null) {
return false;
}
} else if (!imdbId.equals(other.imdbId)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Movie [adult=").append(adult);
builder.append(", backdropPath=").append(backdropPath);
builder.append(", belongsToCollection=").append(belongsToCollection);
builder.append(", budget=").append(budget);
builder.append(", genres=").append(genres);
builder.append(", homepage=").append(homepage);
builder.append(", id=").append(id);
builder.append(", imdbId=").append(imdbId);
builder.append(", originalTitle=").append(originalTitle);
builder.append(", overview=").append(overview);
builder.append(", popularity=").append(popularity);
builder.append(", posterPath=").append(posterPath);
builder.append(", productionCompanies=").append(productionCompanies);
builder.append(", productionCountries=").append(productionCountries);
builder.append(", releaseDate=").append(releaseDate);
builder.append(", revenue=").append(revenue);
builder.append(", runtime=").append(runtime);
builder.append(", spokenLanguages=").append(spokenLanguages);
builder.append(", tagline=").append(tagline);
builder.append(", title=").append(title);
builder.append(", voteAverage=").append(voteAverage);
builder.append(", voteCount=").append(voteCount);
builder.append("]");
return builder.toString();
}
}
| gpl-3.0 |
mediathekview/MediathekView | src/main/java/mediathek/tool/models/TModelFilm.java | 3944 | package mediathek.tool.models;
import mediathek.daten.DatenFilm;
import mediathek.tool.FilmSize;
import mediathek.tool.datum.DatumFilm;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.List;
public class TModelFilm extends AbstractTableModel {
private static final int COLUMN_COUNT = 15;
private final List<DatenFilm> dataList;
public TModelFilm() {
dataList = new ArrayList<>();
}
public TModelFilm(int capacity) {
dataList = new ArrayList<>(capacity);
}
@Override
public boolean isCellEditable(int i, int j) {
return false;
}
/**
* Get model row for a requested film nr.
*
* @param reqFilmNr the filmnr of the request
* @return the model row, otherwise -1
*/
public int getModelRowForFilmNumber(int reqFilmNr) {
int ret = 0;
for (var film : dataList) {
if (film.getFilmNr() == reqFilmNr)
return ret;
else
ret++;
}
return -1;
}
@Override
public int getRowCount() {
return dataList.size();
}
@Override
public int getColumnCount() {
return COLUMN_COUNT;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return switch (columnIndex) {
case DatenFilm.FILM_NR, DatenFilm.FILM_DAUER -> Integer.class;
case DatenFilm.FILM_DATUM -> DatumFilm.class;
case DatenFilm.FILM_GROESSE -> FilmSize.class;
case DatenFilm.FILM_HD, DatenFilm.FILM_UT -> Boolean.class;
case DatenFilm.FILM_DATUM_LONG -> Long.class;
default -> String.class;
};
}
@Override
public String getColumnName(int column) {
return switch (column) {
case DatenFilm.FILM_ABSPIELEN, DatenFilm.FILM_AUFZEICHNEN, DatenFilm.FILM_MERKEN -> "";
case DatenFilm.FILM_NR -> "Nr";
case DatenFilm.FILM_SENDER -> "Sender";
case DatenFilm.FILM_THEMA -> "Thema";
case DatenFilm.FILM_TITEL -> "Titel";
case DatenFilm.FILM_DATUM -> "Datum";
case DatenFilm.FILM_ZEIT -> "Zeit";
case DatenFilm.FILM_DAUER -> "Dauer";
case DatenFilm.FILM_GROESSE -> "Größe [MB]";
case DatenFilm.FILM_HD -> "HQ";
case DatenFilm.FILM_UT -> "UT";
case DatenFilm.FILM_GEO -> "Geo";
case DatenFilm.FILM_URL -> "URL";
default -> throw new IndexOutOfBoundsException("UNKNOWN COLUMN NAME: " + column);
};
}
@Override
public Object getValueAt(int row, int column) {
final var film = dataList.get(row);
return switch (column) {
case DatenFilm.FILM_NR -> film.getFilmNr();
case DatenFilm.FILM_SENDER -> film.getSender();
case DatenFilm.FILM_THEMA -> film.getThema();
case DatenFilm.FILM_TITEL -> film.getTitle();
case DatenFilm.FILM_ABSPIELEN, DatenFilm.FILM_AUFZEICHNEN, DatenFilm.FILM_MERKEN -> "";
case DatenFilm.FILM_DATUM -> film.getDatumFilm();
case DatenFilm.FILM_ZEIT -> film.getSendeZeit();
case DatenFilm.FILM_DAUER -> film.getDuration();
case DatenFilm.FILM_GROESSE -> film.getFilmSize();
case DatenFilm.FILM_HD -> film.isHighQuality();
case DatenFilm.FILM_UT -> film.hasSubtitle();
case DatenFilm.FILM_GEO -> film.getGeo().orElse("");
case DatenFilm.FILM_URL -> film.getUrl();
case DatenFilm.FILM_REF -> film;
default -> throw new IndexOutOfBoundsException("UNKNOWN COLUMN VALUE: " + column);
};
}
public void addAll(List<DatenFilm> listeFilme) {
final int oldRowCount = dataList.size();
dataList.addAll(listeFilme);
fireTableRowsInserted(oldRowCount, oldRowCount + dataList.size());
}
}
| gpl-3.0 |
Minecolonies/minecolonies | src/main/java/com/minecolonies/coremod/util/RecipeHandler.java | 704 | package com.minecolonies.coremod.util;
/**
* Recipe storage for minecolonies.
*/
public final class RecipeHandler
{
/**
* Private constructor to hide the implicit public one.
*/
private RecipeHandler()
{
}
/**
* Initialize all recipes for minecolonies.
*
* @param enableInDevelopmentFeatures if we want development recipes.
* @param supplyChests if we want supply chests or direct town hall crafting.
*/
public static void init(final boolean enableInDevelopmentFeatures, final boolean supplyChests)
{
// Register the hust
//todo disable indev features
//todo disable supplychest if config
}
}
| gpl-3.0 |
KuekenPartei/party-contracts | src/test/java/de/kueken/ethereum/party/publishing/ShortBlogTest.java | 4929 | package de.kueken.ethereum.party.publishing;
// Start of user code ShortBlogTest.customImports
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.CompletableFuture;
import org.adridadou.ethereum.propeller.keystore.AccountProvider;
import org.adridadou.ethereum.propeller.solidity.SolidityContractDetails;
import org.adridadou.ethereum.propeller.values.EthAddress;
import org.junit.Before;
import org.junit.Test;
import de.kueken.ethereum.party.basics.ManageableTest;
// End of user code
/**
* Test for the ShortBlog contract.
*
*/
public class ShortBlogTest extends ManageableTest{
private ShortBlog fixture;
// Start of user code ShortBlogTest.attributes
// private String senderAddressS = "5db10750e8caff27f906b41c71b3471057dd2004";
// End of user code
@Override
protected String getContractName() {
return "ShortBlog";
}
@Override
protected String getQuallifiedContractName() {
return "publishing.sol:ShortBlog";
}
/**
* Read the contract from the file and deploys the contract code.
* @throws Exception
*/
@Before
public void prepareTest() throws Exception {
//Start of user code prepareTest
createFixture();
//End of user code
}
/**
* Create a new fixture by deploying the contract source.
* @throws Exception
*/
protected void createFixture() throws Exception {
//Start of user code createFixture
SolidityContractDetails compiledContract = getCompiledContract("/mix/combine.json");
//TODO: set the constructor args
String _name = "_name";
CompletableFuture<EthAddress> address = ethereum.publishContract(compiledContract, sender
, _name);
fixtureAddress = address.get();
setFixture(ethereum.createContractProxy(compiledContract, fixtureAddress, sender, ShortBlog.class));
//End of user code
}
protected void setFixture(ShortBlog f) {
this.fixture = f;
super.setFixture(f);
}
/**
* Test method for sendMessage(String message,String hash,String er).
* see {@link ShortBlog#sendMessage( String, String, String)}
* @throws Exception
*/
@Test
public void testSendMessage_string_string_string() throws Exception {
//Start of user code testSendMessage_string_string_string
assertEquals(0, fixture.messageCount().intValue());
String message = "test1";
String hash = "h1";
String er = "er1";
fixture.sendMessage(message, hash, er).get();
assertEquals(1, fixture.messageCount().intValue());
Integer lastMessageDate = fixture.lastMessageDate();
System.out.println("-->" + lastMessageDate);
ShortBlogMessage messages = fixture.messages(0);
assertEquals(message, messages.getMessage());
assertEquals(hash, messages.getHashValue());
assertEquals(er, messages.getExternalResource());
// End of user code
}
//Start of user code customTests
/**
* Test method for sendMessage(String message,String hash,String er). see
* {@link ShortBlog#sendMessage( String, String, String)}
*
* @throws Exception
*/
@Test
public void testSendMessage_No_Manager() throws Exception {
assertEquals(0, fixture.messageCount().intValue());
fixture.sendMessage("test1", "h1", "er1").get();
assertEquals(1, fixture.messageCount().intValue());
fixture.addManager(AccountProvider.fromPrivateKey((java.math.BigInteger.valueOf(100002L))).getAddress()).get();
assertEquals(2, fixture.mangerCount().intValue());
fixture.removeManager(sender.getAddress()).get();
assertEquals(1, fixture.mangerCount().intValue());
try {
fixture.sendMessage("test1", "h1", "er1").get();
fail("Thow exception");
} catch (Exception e) {
}
assertEquals(1, fixture.messageCount().intValue());
}
/**
* Test method for sendMessage(String message,String hash,String er).
* see {@link ShortBlog#sendMessage( String, String, String)}
* @throws Exception
*/
@Test
public void testSendMessage_Often() throws Exception {
assertEquals(0, fixture.messageCount().intValue());
String message = "test1";
String hash = "h1";
String er = "er1";
fixture.sendMessage(message, hash, er).get();
assertEquals(1, fixture.messageCount().intValue());
ShortBlogMessage messages = fixture.messages(0);
assertEquals(message, messages.getMessage());
assertEquals(hash, messages.getHashValue());
assertEquals(er, messages.getExternalResource());
Integer lastMessageDate = fixture.lastMessageDate();
System.out.println("-->" + lastMessageDate);
message = "message1";
hash = "hash1";
er = "external resource 1";
fixture.sendMessage(message, hash, er).get();
assertEquals(2, fixture.messageCount().intValue());
messages = fixture.messages(1);
assertEquals(message, messages.getMessage());
assertEquals(hash, messages.getHashValue());
assertEquals(er, messages.getExternalResource());
assertTrue(lastMessageDate<fixture.lastMessageDate());
}
// End of user code
}
| gpl-3.0 |
Jude-Conroy/MinuteMediaPi | src/main/java/com/minutemedia/pi/resources/DataUpload.java | 504 | package com.minutemedia.pi.resources;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.annotation.JsonProperty;
@Path("update")
@Consumes(MediaType.APPLICATION_JSON)
public class DataUpload {
static class Entity {
@JsonProperty String name;
}
@POST
@Timed
public int updateRecord(List<Entity> entities) {
// Do something with entities...
return 0;
}
}
| gpl-3.0 |
netuh/DecodePlatformPlugin | br.ufpe.ines.decode/bundles/br.ufpe.ines.decode.model/src/br/ufpe/ines/decode/decode/artifacts/questionnaire/QuestionnairePackage.java | 38583 | /**
*/
package br.ufpe.ines.decode.decode.artifacts.questionnaire;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.QuestionnaireFactory
* @model kind="package"
* @generated
*/
public interface QuestionnairePackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "questionnaire";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "questionnaire";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "questionnaire";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
QuestionnairePackage eINSTANCE = br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl.init();
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.LabelableImpl <em>Labelable</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.LabelableImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getLabelable()
* @generated
*/
int LABELABLE = 11;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LABELABLE__CONTENT = 0;
/**
* The number of structural features of the '<em>Labelable</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LABELABLE_FEATURE_COUNT = 1;
/**
* The number of operations of the '<em>Labelable</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int LABELABLE_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ElementaryComponentImpl <em>Elementary Component</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ElementaryComponentImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getElementaryComponent()
* @generated
*/
int ELEMENTARY_COMPONENT = 0;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENTARY_COMPONENT__CONTENT = LABELABLE__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENTARY_COMPONENT__RESTRICTION = LABELABLE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Elementary Component</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENTARY_COMPONENT_FEATURE_COUNT = LABELABLE_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Elementary Component</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELEMENTARY_COMPONENT_OPERATION_COUNT = LABELABLE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.BlockImpl <em>Block</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.BlockImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getBlock()
* @generated
*/
int BLOCK = 1;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BLOCK__CONTENT = ELEMENTARY_COMPONENT__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BLOCK__RESTRICTION = ELEMENTARY_COMPONENT__RESTRICTION;
/**
* The feature id for the '<em><b>Chidren</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BLOCK__CHIDREN = ELEMENTARY_COMPONENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Block</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BLOCK_FEATURE_COUNT = ELEMENTARY_COMPONENT_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Block</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BLOCK_OPERATION_COUNT = ELEMENTARY_COMPONENT_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionImpl <em>Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getQuestion()
* @generated
*/
int QUESTION = 2;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION__CONTENT = ELEMENTARY_COMPONENT__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION__RESTRICTION = ELEMENTARY_COMPONENT__RESTRICTION;
/**
* The number of structural features of the '<em>Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_FEATURE_COUNT = ELEMENTARY_COMPONENT_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int QUESTION_OPERATION_COUNT = ELEMENTARY_COMPONENT_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.TextFieldImpl <em>Text Field</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.TextFieldImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getTextField()
* @generated
*/
int TEXT_FIELD = 3;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT_FIELD__CONTENT = QUESTION__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT_FIELD__RESTRICTION = QUESTION__RESTRICTION;
/**
* The number of structural features of the '<em>Text Field</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT_FIELD_FEATURE_COUNT = QUESTION_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Text Field</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TEXT_FIELD_OPERATION_COUNT = QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ComposedQuestionImpl <em>Composed Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ComposedQuestionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getComposedQuestion()
* @generated
*/
int COMPOSED_QUESTION = 4;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int COMPOSED_QUESTION__CONTENT = QUESTION__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int COMPOSED_QUESTION__RESTRICTION = QUESTION__RESTRICTION;
/**
* The feature id for the '<em><b>Choice</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int COMPOSED_QUESTION__CHOICE = QUESTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Composed Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int COMPOSED_QUESTION_FEATURE_COUNT = QUESTION_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Composed Question</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int COMPOSED_QUESTION_OPERATION_COUNT = QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ChoiceImpl <em>Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getChoice()
* @generated
*/
int CHOICE = 5;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CHOICE__CONTENT = LABELABLE__CONTENT;
/**
* The number of structural features of the '<em>Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CHOICE_FEATURE_COUNT = LABELABLE_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CHOICE_OPERATION_COUNT = LABELABLE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.SimpleChoiceImpl <em>Simple Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.SimpleChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getSimpleChoice()
* @generated
*/
int SIMPLE_CHOICE = 6;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SIMPLE_CHOICE__CONTENT = COMPOSED_QUESTION__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SIMPLE_CHOICE__RESTRICTION = COMPOSED_QUESTION__RESTRICTION;
/**
* The feature id for the '<em><b>Choice</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SIMPLE_CHOICE__CHOICE = COMPOSED_QUESTION__CHOICE;
/**
* The number of structural features of the '<em>Simple Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SIMPLE_CHOICE_FEATURE_COUNT = COMPOSED_QUESTION_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Simple Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SIMPLE_CHOICE_OPERATION_COUNT = COMPOSED_QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.MultiChoiceImpl <em>Multi Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.MultiChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getMultiChoice()
* @generated
*/
int MULTI_CHOICE = 7;
/**
* The feature id for the '<em><b>Content</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE__CONTENT = COMPOSED_QUESTION__CONTENT;
/**
* The feature id for the '<em><b>Restriction</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE__RESTRICTION = COMPOSED_QUESTION__RESTRICTION;
/**
* The feature id for the '<em><b>Choice</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE__CHOICE = COMPOSED_QUESTION__CHOICE;
/**
* The feature id for the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE__MIN = COMPOSED_QUESTION_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE__MAX = COMPOSED_QUESTION_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Multi Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE_FEATURE_COUNT = COMPOSED_QUESTION_FEATURE_COUNT + 2;
/**
* The number of operations of the '<em>Multi Choice</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int MULTI_CHOICE_OPERATION_COUNT = COMPOSED_QUESTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.RestrictionImpl <em>Restriction</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.RestrictionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getRestriction()
* @generated
*/
int RESTRICTION = 8;
/**
* The number of structural features of the '<em>Restriction</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESTRICTION_FEATURE_COUNT = 0;
/**
* The number of operations of the '<em>Restriction</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESTRICTION_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.AppendableElementImpl <em>Appendable Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.AppendableElementImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getAppendableElement()
* @generated
*/
int APPENDABLE_ELEMENT = 9;
/**
* The feature id for the '<em><b>Default Quantity</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPENDABLE_ELEMENT__DEFAULT_QUANTITY = RESTRICTION_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Appendable Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPENDABLE_ELEMENT_FEATURE_COUNT = RESTRICTION_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Appendable Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int APPENDABLE_ELEMENT_OPERATION_COUNT = RESTRICTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.DependentElementImpl <em>Dependent Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.DependentElementImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getDependentElement()
* @generated
*/
int DEPENDENT_ELEMENT = 10;
/**
* The feature id for the '<em><b>Question</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DEPENDENT_ELEMENT__QUESTION = RESTRICTION_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Expected Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DEPENDENT_ELEMENT__EXPECTED_VALUE = RESTRICTION_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Dependent Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DEPENDENT_ELEMENT_FEATURE_COUNT = RESTRICTION_FEATURE_COUNT + 2;
/**
* The number of operations of the '<em>Dependent Element</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DEPENDENT_ELEMENT_OPERATION_COUNT = RESTRICTION_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ContentImpl <em>Content</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ContentImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getContent()
* @generated
*/
int CONTENT = 12;
/**
* The feature id for the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONTENT__TEXT = 0;
/**
* The feature id for the '<em><b>Language</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONTENT__LANGUAGE = 1;
/**
* The number of structural features of the '<em>Content</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONTENT_FEATURE_COUNT = 2;
/**
* The number of operations of the '<em>Content</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONTENT_OPERATION_COUNT = 0;
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.ElementaryComponent <em>Elementary Component</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Elementary Component</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.ElementaryComponent
* @generated
*/
EClass getElementaryComponent();
/**
* Returns the meta object for the containment reference '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.ElementaryComponent#getRestriction <em>Restriction</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Restriction</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.ElementaryComponent#getRestriction()
* @see #getElementaryComponent()
* @generated
*/
EReference getElementaryComponent_Restriction();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Block <em>Block</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Block</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Block
* @generated
*/
EClass getBlock();
/**
* Returns the meta object for the containment reference list '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Block#getChidren <em>Chidren</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Chidren</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Block#getChidren()
* @see #getBlock()
* @generated
*/
EReference getBlock_Chidren();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Question <em>Question</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Question</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Question
* @generated
*/
EClass getQuestion();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.TextField <em>Text Field</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Text Field</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.TextField
* @generated
*/
EClass getTextField();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.ComposedQuestion <em>Composed Question</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Composed Question</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.ComposedQuestion
* @generated
*/
EClass getComposedQuestion();
/**
* Returns the meta object for the containment reference list '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.ComposedQuestion#getChoice <em>Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Choice</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.ComposedQuestion#getChoice()
* @see #getComposedQuestion()
* @generated
*/
EReference getComposedQuestion_Choice();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Choice <em>Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Choice</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Choice
* @generated
*/
EClass getChoice();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.SimpleChoice <em>Simple Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Simple Choice</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.SimpleChoice
* @generated
*/
EClass getSimpleChoice();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice <em>Multi Choice</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Multi Choice</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice
* @generated
*/
EClass getMultiChoice();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice#getMin <em>Min</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Min</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice#getMin()
* @see #getMultiChoice()
* @generated
*/
EAttribute getMultiChoice_Min();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice#getMax <em>Max</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Max</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.MultiChoice#getMax()
* @see #getMultiChoice()
* @generated
*/
EAttribute getMultiChoice_Max();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Restriction <em>Restriction</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Restriction</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Restriction
* @generated
*/
EClass getRestriction();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.AppendableElement <em>Appendable Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Appendable Element</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.AppendableElement
* @generated
*/
EClass getAppendableElement();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.AppendableElement#getDefaultQuantity <em>Default Quantity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Default Quantity</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.AppendableElement#getDefaultQuantity()
* @see #getAppendableElement()
* @generated
*/
EAttribute getAppendableElement_DefaultQuantity();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement <em>Dependent Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Dependent Element</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement
* @generated
*/
EClass getDependentElement();
/**
* Returns the meta object for the reference '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement#getQuestion <em>Question</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Question</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement#getQuestion()
* @see #getDependentElement()
* @generated
*/
EReference getDependentElement_Question();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement#getExpectedValue <em>Expected Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Expected Value</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.DependentElement#getExpectedValue()
* @see #getDependentElement()
* @generated
*/
EAttribute getDependentElement_ExpectedValue();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Labelable <em>Labelable</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Labelable</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Labelable
* @generated
*/
EClass getLabelable();
/**
* Returns the meta object for the containment reference list '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Labelable#getContent <em>Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Content</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Labelable#getContent()
* @see #getLabelable()
* @generated
*/
EReference getLabelable_Content();
/**
* Returns the meta object for class '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Content <em>Content</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Content</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Content
* @generated
*/
EClass getContent();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Content#getText <em>Text</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Text</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Content#getText()
* @see #getContent()
* @generated
*/
EAttribute getContent_Text();
/**
* Returns the meta object for the attribute '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.Content#getLanguage <em>Language</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Language</em>'.
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.Content#getLanguage()
* @see #getContent()
* @generated
*/
EAttribute getContent_Language();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
QuestionnaireFactory getQuestionnaireFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ElementaryComponentImpl <em>Elementary Component</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ElementaryComponentImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getElementaryComponent()
* @generated
*/
EClass ELEMENTARY_COMPONENT = eINSTANCE.getElementaryComponent();
/**
* The meta object literal for the '<em><b>Restriction</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ELEMENTARY_COMPONENT__RESTRICTION = eINSTANCE.getElementaryComponent_Restriction();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.BlockImpl <em>Block</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.BlockImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getBlock()
* @generated
*/
EClass BLOCK = eINSTANCE.getBlock();
/**
* The meta object literal for the '<em><b>Chidren</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference BLOCK__CHIDREN = eINSTANCE.getBlock_Chidren();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionImpl <em>Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getQuestion()
* @generated
*/
EClass QUESTION = eINSTANCE.getQuestion();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.TextFieldImpl <em>Text Field</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.TextFieldImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getTextField()
* @generated
*/
EClass TEXT_FIELD = eINSTANCE.getTextField();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ComposedQuestionImpl <em>Composed Question</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ComposedQuestionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getComposedQuestion()
* @generated
*/
EClass COMPOSED_QUESTION = eINSTANCE.getComposedQuestion();
/**
* The meta object literal for the '<em><b>Choice</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference COMPOSED_QUESTION__CHOICE = eINSTANCE.getComposedQuestion_Choice();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ChoiceImpl <em>Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getChoice()
* @generated
*/
EClass CHOICE = eINSTANCE.getChoice();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.SimpleChoiceImpl <em>Simple Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.SimpleChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getSimpleChoice()
* @generated
*/
EClass SIMPLE_CHOICE = eINSTANCE.getSimpleChoice();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.MultiChoiceImpl <em>Multi Choice</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.MultiChoiceImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getMultiChoice()
* @generated
*/
EClass MULTI_CHOICE = eINSTANCE.getMultiChoice();
/**
* The meta object literal for the '<em><b>Min</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute MULTI_CHOICE__MIN = eINSTANCE.getMultiChoice_Min();
/**
* The meta object literal for the '<em><b>Max</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute MULTI_CHOICE__MAX = eINSTANCE.getMultiChoice_Max();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.RestrictionImpl <em>Restriction</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.RestrictionImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getRestriction()
* @generated
*/
EClass RESTRICTION = eINSTANCE.getRestriction();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.AppendableElementImpl <em>Appendable Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.AppendableElementImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getAppendableElement()
* @generated
*/
EClass APPENDABLE_ELEMENT = eINSTANCE.getAppendableElement();
/**
* The meta object literal for the '<em><b>Default Quantity</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute APPENDABLE_ELEMENT__DEFAULT_QUANTITY = eINSTANCE.getAppendableElement_DefaultQuantity();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.DependentElementImpl <em>Dependent Element</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.DependentElementImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getDependentElement()
* @generated
*/
EClass DEPENDENT_ELEMENT = eINSTANCE.getDependentElement();
/**
* The meta object literal for the '<em><b>Question</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DEPENDENT_ELEMENT__QUESTION = eINSTANCE.getDependentElement_Question();
/**
* The meta object literal for the '<em><b>Expected Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute DEPENDENT_ELEMENT__EXPECTED_VALUE = eINSTANCE.getDependentElement_ExpectedValue();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.LabelableImpl <em>Labelable</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.LabelableImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getLabelable()
* @generated
*/
EClass LABELABLE = eINSTANCE.getLabelable();
/**
* The meta object literal for the '<em><b>Content</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference LABELABLE__CONTENT = eINSTANCE.getLabelable_Content();
/**
* The meta object literal for the '{@link br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ContentImpl <em>Content</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.ContentImpl
* @see br.ufpe.ines.decode.decode.artifacts.questionnaire.impl.QuestionnairePackageImpl#getContent()
* @generated
*/
EClass CONTENT = eINSTANCE.getContent();
/**
* The meta object literal for the '<em><b>Text</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute CONTENT__TEXT = eINSTANCE.getContent_Text();
/**
* The meta object literal for the '<em><b>Language</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute CONTENT__LANGUAGE = eINSTANCE.getContent_Language();
}
} //QuestionnairePackage
| gpl-3.0 |
kshade2001/Subspace-Mobile | build/source/r/debug/com/subspace/redemption/R.java | 2943 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.subspace.redemption;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
public static final int icon_original=0x7f020001;
public static final int icon_play=0x7f020002;
public static final int icon_play_selected=0x7f020003;
public static final int icon_play_unselected=0x7f020004;
public static final int icon_settings=0x7f020005;
public static final int icon_settings_selected=0x7f020006;
public static final int icon_settings_unselected=0x7f020007;
public static final int icon_zone=0x7f020008;
public static final int icon_zone_selected=0x7f020009;
public static final int icon_zone_unselected=0x7f02000a;
public static final int over1=0x7f02000b;
public static final int over2=0x7f02000c;
public static final int over3=0x7f02000d;
public static final int over4=0x7f02000e;
public static final int over5=0x7f02000f;
public static final int tiles=0x7f020010;
}
public static final class id {
public static final int LastRefreshTextView=0x7f060007;
public static final int RefreshButton=0x7f060008;
public static final int ViewArenaButton=0x7f060000;
public static final int adView=0x7f060004;
public static final int bottomtext=0x7f060006;
public static final int chatBox=0x7f060003;
public static final int messageView=0x7f060002;
public static final int scroller=0x7f060001;
public static final int toptext=0x7f060005;
}
public static final class layout {
public static final int connect_activity=0x7f030000;
public static final int game_activity=0x7f030001;
public static final int main_menu_activity=0x7f030002;
public static final int play_activity=0x7f030003;
public static final int splash_activity=0x7f030004;
public static final int zone_item=0x7f030005;
public static final int zones_activity=0x7f030006;
}
public static final class string {
public static final int about_text=0x7f050000;
public static final int app_name=0x7f050001;
public static final int main_menu_btn_settings=0x7f050002;
public static final int main_menu_btn_zones=0x7f050003;
public static final int network_service_started=0x7f050004;
public static final int network_service_stopped=0x7f050005;
public static final int tbl_Settings=0x7f050006;
public static final int tbl_Zone=0x7f050007;
}
public static final class xml {
public static final int application_preferences_screen=0x7f040000;
}
}
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/nianticproject/ingress/i/a.java | 4031 | package com.nianticproject.ingress.i;
import com.google.a.a.ak;
import com.google.a.a.an;
import com.google.a.a.br;
import com.google.a.c.dc;
import com.google.a.c.dh;
import com.nianticproject.ingress.gameentity.components.portal.PhotoStreamInfo;
import com.nianticproject.ingress.shared.portal.PlayerPortalImage;
import com.nianticproject.ingress.shared.portal.PortalImagePage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public final class a
{
private final String a;
private final PhotoStreamInfo b;
private final HashSet<String> c = new HashSet();
private final ArrayList<PortalImagePage> d = new ArrayList();
private final HashMap<String, ak<Boolean, Integer>> e = new HashMap();
private boolean f;
public a(String paramString, PhotoStreamInfo paramPhotoStreamInfo)
{
if (!br.b(paramString));
for (boolean bool = true; ; bool = false)
{
an.a(bool);
this.a = paramString;
this.b = ((PhotoStreamInfo)an.a(paramPhotoStreamInfo));
this.f = false;
return;
}
}
public static boolean a(String paramString)
{
if (br.b(paramString))
return false;
return paramString.startsWith("this_is_not_a_true_URL_its_that_fuzzy_image");
}
public final boolean a()
{
return this.f;
}
public final boolean a(PortalImagePage paramPortalImagePage, int paramInt, HashMap<String, com.nianticproject.ingress.shared.portal.a> paramHashMap, String paramString)
{
if (paramString != null);
while (this.c.contains(paramString))
{
return this.f;
paramString = "";
}
this.c.add(paramString);
Iterator localIterator = paramPortalImagePage.portalImages.iterator();
while (localIterator.hasNext())
{
PlayerPortalImage localPlayerPortalImage2 = (PlayerPortalImage)localIterator.next();
this.e.put(localPlayerPortalImage2.c(), ak.a(Boolean.valueOf(localPlayerPortalImage2.f()), Integer.valueOf(localPlayerPortalImage2.e())));
}
this.d.add(paramPortalImagePage);
int i = paramPortalImagePage.portalImages.size();
if ((i < paramInt) || ((i == paramInt) && (paramPortalImagePage.cursor == null)))
{
this.f = true;
if ((this.d.size() == 1) && (paramPortalImagePage.portalImages.size() == 0))
{
PlayerPortalImage localPlayerPortalImage1 = new PlayerPortalImage("this_is_not_a_true_GUID_its_that_fuzzy_image", "this_is_not_a_true_URL_its_that_fuzzy_image", null, 0);
this.d.add(new PortalImagePage(Arrays.asList(new PlayerPortalImage[] { localPlayerPortalImage1 })));
this.e.put("this_is_not_a_true_GUID_its_that_fuzzy_image", ak.a(Boolean.FALSE, Integer.valueOf(0)));
paramHashMap.put("this_is_not_a_true_GUID_its_that_fuzzy_image", localPlayerPortalImage1);
}
}
return this.f;
}
public final boolean a(String paramString, boolean paramBoolean)
{
ak localak = (ak)this.e.get(paramString);
Boolean localBoolean = (Boolean)localak.a;
if (localBoolean == null)
return false;
if (paramBoolean == localBoolean.booleanValue())
return false;
int i = ((Integer)localak.b).intValue();
if (paramBoolean);
for (int j = i + 1; ; j = i - 1)
{
this.e.put(paramString, ak.a(Boolean.valueOf(paramBoolean), Integer.valueOf(j)));
return true;
}
}
public final PhotoStreamInfo b()
{
return this.b;
}
public final List<PortalImagePage> c()
{
return dc.a(this.d);
}
public final Map<String, ak<Boolean, Integer>> d()
{
return dh.a(this.e);
}
public final void e()
{
this.d.clear();
this.e.clear();
}
public final String toString()
{
return "ImageStream [portalGuid=" + this.a + ", info=" + this.b + ", pages=" + this.d + ", complete=" + this.f + "]";
}
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.nianticproject.ingress.i.a
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
cgd/gwt-client-util | src/java/org/jax/gwtutil/client/MessageType.java | 3358 | /*
* Copyright (c) 2010 The Jackson Laboratory
*
* This 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jax.gwtutil.client;
import com.google.gwt.user.client.ui.Image;
/**
* An enum which allows for different types of messages to the user
* @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A>
*/
public enum MessageType
{
/**
* To give the user important information that we want to emphasize
*/
ALERT
{
@Override
public String getIconUrl()
{
return "images/alert-16x16.png";
}
@Override
public String getStyle()
{
return "jax-PlainMessage";
}
},
/**
* To give the user normal info... no emphasis needed
*/
PLAIN
{
@Override
public String getIconUrl()
{
return null;
}
@Override
public String getStyle()
{
return "jax-PlainMessage";
}
},
/**
* tells the user an error ocurred
*/
ERROR
{
@Override
public String getIconUrl()
{
return "images/error-16x16.png";
}
@Override
public String getStyle()
{
return "jax-ErrorMessage";
}
},
/**
* tells the user processing is OK
*/
OK
{
@Override
public String getIconUrl()
{
return "images/ok-16x16.png";
}
@Override
public String getStyle()
{
return "jax-PlainMessage";
}
},
/**
* to tell the user that we're working on something
*/
WORKING
{
@Override
public String getIconUrl()
{
return "images/spinner-16x16.gif";
}
@Override
public String getStyle()
{
return "jax-PlainMessage";
}
};
/**
* Get the icon for this message
* @return
* the icon or null
*/
public abstract String getIconUrl();
/**
* Get the style for this message
* @return
* the style (can't be null)
*/
public abstract String getStyle();
/**
* Prefetch the icon for this message type (if there's no icon
* then do nothing)
*/
public void prefetchIcon()
{
if(this.getIconUrl() != null)
{
Image.prefetch(this.getIconUrl());
}
}
/**
* A convenience method for prefetching all icons
*/
public static void prefetchIcons()
{
for(MessageType messageType: MessageType.values())
{
messageType.prefetchIcon();
}
}
}
| gpl-3.0 |
idega/is.idega.idegaweb.egov.bpm | src/java/is/idega/idegaweb/egov/bpm/cases/CasesBPMProcessView.java | 15748 | package is.idega.idegaweb.egov.bpm.cases;
import is.idega.idegaweb.egov.cases.business.CasesBusiness;
import is.idega.idegaweb.egov.cases.data.GeneralCase;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.jbpm.JbpmContext;
import org.jbpm.JbpmException;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.idega.block.process.business.CaseManagersProvider;
import com.idega.block.process.business.CasesRetrievalManager;
import com.idega.block.process.business.ProcessConstants;
import com.idega.block.process.data.Case;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.business.IBORuntimeException;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.egov.bpm.data.CaseProcInstBind;
import com.idega.idegaweb.egov.bpm.data.dao.CasesBPMDAO;
import com.idega.jbpm.BPMContext;
import com.idega.jbpm.JbpmCallback;
import com.idega.jbpm.exe.BPMFactory;
import com.idega.jbpm.exe.ProcessManager;
import com.idega.jbpm.exe.TaskInstanceW;
import com.idega.jbpm.identity.BPMAccessControlException;
import com.idega.jbpm.identity.BPMUser;
import com.idega.jbpm.identity.RolesManager;
import com.idega.presentation.IWContext;
import com.idega.user.business.UserBusiness;
import com.idega.util.CoreConstants;
import com.idega.util.CoreUtil;
import com.idega.util.IWTimestamp;
/**
* @author <a href="mailto:civilis@idega.com">Vytautas Čivilis</a>
* @version $Revision: 1.24 $ Last modified: $Date: 2009/03/17 20:53:23 $ by $Author: civilis $
*/
@Scope("singleton")
@Service(CasesBPMProcessView.BEAN_IDENTIFIER)
public class CasesBPMProcessView {
public static final String BEAN_IDENTIFIER = "casesBPMProcessView";
private BPMContext idegaJbpmContext;
private BPMFactory BPMFactory;
private CasesBPMDAO casesBPMDAO;
private CaseManagersProvider caseManagersProvider;
@Transactional(readOnly = true)
public CasesBPMTaskViewBean getTaskView(final long taskInstanceId) {
return getIdegaJbpmContext().execute(new JbpmCallback() {
@Override
public Object doInJbpm(JbpmContext context) throws JbpmException {
// ProcessInstanceW processInstanceW = getBPMFactory()
// .getProcessManagerByProcessInstanceId(processInstanceId)
// .getProcessInstance(processInstanceId);
//
// Collection<TaskInstanceW> taskInstances = processInstanceW
// .getAllTaskInstances();
//
// TaskInstanceW ti = null;
// for (TaskInstanceW task : taskInstances) {
// if (task.getTaskInstanceId() == taskInstanceId) {
// ti = task;
// }
// }
// TODO: changed the way tiw is resolved, test if it works!
TaskInstanceW tiw = getBPMFactory()
.getProcessManagerByTaskInstanceId(taskInstanceId)
.getTaskInstance(taskInstanceId);
if (tiw == null) {
Logger.getLogger(getClass().getName()).log(
Level.WARNING,
"No task instance found for task instance id provided: "
+ taskInstanceId);
return new CasesBPMTaskViewBean();
}
TaskInstance ti = tiw.getTaskInstance();
IWContext iwc = IWContext.getInstance();
IWTimestamp createTime = new IWTimestamp(ti.getCreate());
String taskStatus = getTaskStatus(ti);
String assignedTo = getTaskAssignedTo(ti);
CasesBPMTaskViewBean bean = new CasesBPMTaskViewBean();
bean.setTaskName(tiw.getName(iwc.getCurrentLocale()));
bean.setTaskStatus(taskStatus);
bean.setAssignedTo(assignedTo);
bean.setCreatedDate(createTime.getLocaleDateAndTime(iwc
.getLocale(), IWTimestamp.SHORT, IWTimestamp.SHORT));
return bean;
}
});
}
protected String getTaskStatus(TaskInstance taskInstance) {
if (taskInstance.hasEnded())
return "Ended";
if (taskInstance.getStart() != null)
return "In progress";
return "Not started";
}
@Transactional(readOnly = true)
protected String getTaskAssignedTo(TaskInstance taskInstance) {
String actorId = taskInstance.getActorId();
if (actorId != null) {
try {
int assignedTo = Integer.parseInt(actorId);
return getUserBusiness().getUser(assignedTo).getName();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(
Level.SEVERE,
"Exception while resolving assigned user name for actor id: "
+ actorId, e);
}
}
return "No one";
}
@Transactional(readOnly = false)
public void startTask(long taskInstanceId, int actorUserId) {
ProcessManager processManager = getBPMFactory()
.getProcessManagerByTaskInstanceId(taskInstanceId);
processManager.getTaskInstance(taskInstanceId).start(actorUserId);
}
@Transactional(readOnly = false)
public void assignTask(long taskInstanceId, int actorUserId) {
ProcessManager processManager = getBPMFactory()
.getProcessManagerByTaskInstanceId(taskInstanceId);
processManager.getTaskInstance(taskInstanceId).assign(actorUserId);
}
/**
* @param taskInstanceId
* @param userId
* @return null if task can be started, err message otherwise
*/
@Transactional(readOnly = true)
public String getCanStartTask(long taskInstanceId, int userId) {
try {
RolesManager rolesManager = getBPMFactory().getRolesManager();
rolesManager.hasRightsToStartTask(taskInstanceId, userId);
} catch (BPMAccessControlException e) {
return e.getUserFriendlyMessage();
}
return null;
}
@Transactional(readOnly = true)
public String getCanTakeTask(long taskInstanceId, int userId) {
try {
RolesManager rolesManager = getBPMFactory().getRolesManager();
rolesManager.hasRightsToAssignTask(taskInstanceId, userId);
} catch (BPMAccessControlException e) {
return e.getUserFriendlyMessage();
}
return null;
}
@Transactional(readOnly = true)
public CasesBPMProcessViewBean getProcessView(final long processInstanceId, final int caseId) {
return getIdegaJbpmContext().execute(new JbpmCallback() {
@Override
public Object doInJbpm(JbpmContext context) throws JbpmException {
ProcessInstance pi = context.getProcessInstance(processInstanceId);
if (pi == null) {
Logger.getLogger(getClass().getName()).log(Level.WARNING, "No process instance found for process instance id provided: "
+ processInstanceId);
return new CasesBPMProcessViewBean();
}
ContextInstance ci = pi.getContextInstance();
String ownerFirstName = (String) ci.getVariable(CasesBPMProcessConstants.caseOwnerFirstNameVariableName);
String ownerLastName = (String) ci.getVariable(CasesBPMProcessConstants.caseOwnerLastNameVariableName);
String ownerName = new StringBuffer(ownerFirstName == null ? CoreConstants.EMPTY : ownerFirstName).append(
ownerFirstName != null && ownerLastName != null ? CoreConstants.SPACE : CoreConstants.EMPTY).append(
ownerLastName == null ? CoreConstants.EMPTY : ownerLastName).toString();
IWContext iwc = IWContext.getIWContext(FacesContext.getCurrentInstance());
String processStatus = pi.hasEnded() ? "Ended" : "In progress";
IWTimestamp time = new IWTimestamp(pi.getStart());
String createDate = time.getLocaleDate(iwc.getLocale());
String caseIdentifier = (String) ci.getVariable(ProcessConstants.CASE_IDENTIFIER);
String caseCategory;
String caseType;
try {
GeneralCase genCase = getCaseBusiness(iwc).getGeneralCase(Integer.valueOf(caseId));
caseCategory = genCase.getCaseCategory().getLocalizedCategoryName(iwc.getLocale());
caseType = genCase.getCaseType().getName();
} catch (Exception e) {
caseCategory = null;
caseType = null;
}
CasesBPMProcessViewBean bean = new CasesBPMProcessViewBean();
bean.setProcessName(pi.getProcessDefinition().getName());
bean.setProcessStatus(processStatus);
bean.setEnded(pi.hasEnded());
bean.setProcessOwner(ownerName);
bean.setProcessCreateDate(createDate);
bean.setCaseCategory(caseCategory);
bean.setCaseType(caseType);
bean.setCaseIdentifier(caseIdentifier);
return bean;
}
});
}
public BPMUser getCurrentBPMUser() {
return getBPMFactory().getBpmUserFactory().getCurrentBPMUser();
}
@Transactional(readOnly = true)
public Long getProcessInstanceId(Object casePK) {
if (casePK != null) {
Integer caseId;
if (casePK instanceof Integer)
caseId = (Integer) casePK;
else
caseId = new Integer(String.valueOf(casePK));
CaseProcInstBind cpi = getCPIBind(caseId, null);
if (cpi != null)
return cpi.getProcInstId();
}
return null;
}
@Transactional(readOnly = true)
public Integer getCaseId(Long processInstanceId) {
CaseProcInstBind cpi = getCPIBind(null, processInstanceId);
if (cpi != null)
return cpi.getCaseId();
return null;
}
/**
* either of parameters should be not null
*
* @param processInstanceId
* @param caseId
* @return
*/
@Transactional(readOnly = true)
public UIComponent getCaseManagerView(IWContext iwc,
Long processInstanceId, Integer caseId, String caseProcessorType) {
if (iwc == null)
iwc = IWContext.getInstance();
if (processInstanceId == null && caseId == null)
throw new IllegalArgumentException(
"Neither processInstanceId, nor caseId provided");
caseId = caseId != null ? caseId : getCaseId(processInstanceId);
try {
Case theCase = getCasesBusiness(iwc).getCase(caseId);
CasesRetrievalManager caseManager;
if (theCase.getCaseManagerType() != null)
caseManager = getCaseManagersProvider().getCaseManager();
else
caseManager = null;
if (caseManager != null) {
UIComponent caseAssets = caseManager.getView(iwc, caseId,
caseProcessorType, theCase.getCaseManagerType());
if (caseAssets != null)
return caseAssets;
else
Logger.getLogger(getClass().getName()).log(
Level.WARNING,
"No case assets component resolved from case manager: "
+ caseManager.getType() + " by case pk: "
+ theCase.getPrimaryKey().toString());
} else
Logger.getLogger(getClass().getName()).log(
Level.WARNING,
"No case manager resolved by type="
+ theCase.getCaseManagerType());
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE,
"Exception while resolving case manager view", e);
}
return null;
}
@Transactional(readOnly = true)
protected CaseProcInstBind getCPIBind(Integer caseId, Long processInstanceId) {
if (caseId != null) {
CaseProcInstBind bind = getCasesBPMDAO()
.getCaseProcInstBindByCaseId(caseId);
if (bind != null) {
return bind;
} else {
Logger.getLogger(getClass().getName()).log(
Level.SEVERE,
"No case process instance bind found for caseId provided: "
+ caseId);
}
} else if (processInstanceId != null) {
CaseProcInstBind bind;
try {
bind = getCasesBPMDAO().find(CaseProcInstBind.class,
processInstanceId);
} catch (Exception e) {
bind = null;
}
if (bind != null) {
return bind;
} else {
Logger.getLogger(getClass().getName()).log(
Level.SEVERE,
"No case process instance bind found for process instanceid provided: "
+ processInstanceId);
}
}
return null;
}
public class CasesBPMProcessViewBean implements Serializable {
private static final long serialVersionUID = -1209671586005809408L;
private Boolean ended;
private String processName;
private String processStatus;
private String processOwner;
private String processCreateDate;
private String caseCategory;
private String caseType;
private String caseIdentifier;
public String getProcessOwner() {
return processOwner;
}
public void setProcessOwner(String processOwner) {
this.processOwner = processOwner;
}
public String getProcessCreateDate() {
return processCreateDate;
}
public void setProcessCreateDate(String processCreateDate) {
this.processCreateDate = processCreateDate;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public String getProcessStatus() {
return processStatus;
}
public void setProcessStatus(String processStatus) {
this.processStatus = processStatus;
}
public String getCaseCategory() {
return caseCategory;
}
public void setCaseCategory(String caseCategory) {
this.caseCategory = caseCategory;
}
public String getCaseType() {
return caseType;
}
public void setCaseType(String caseType) {
this.caseType = caseType;
}
public String getCaseIdentifier() {
return caseIdentifier;
}
public void setCaseIdentifier(String caseIdentifier) {
this.caseIdentifier = caseIdentifier;
}
public Boolean getEnded() {
return ended == null ? false : ended;
}
public void setEnded(Boolean ended) {
this.ended = ended;
}
}
public class CasesBPMTaskViewBean implements Serializable {
private static final long serialVersionUID = -6402627297789228878L;
private String taskName;
private String taskStatus;
private String assignedTo;
private String createdDate;
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
public String getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(String assignedTo) {
this.assignedTo = assignedTo;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
}
public BPMContext getIdegaJbpmContext() {
return idegaJbpmContext;
}
@Autowired
public void setIdegaJbpmContext(BPMContext idegaJbpmContext) {
this.idegaJbpmContext = idegaJbpmContext;
}
protected CasesBusiness getCaseBusiness(IWContext iwc) {
try {
return (CasesBusiness) IBOLookup.getServiceInstance(iwc,
CasesBusiness.class);
} catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
protected UserBusiness getUserBusiness() {
try {
return (UserBusiness) IBOLookup.getServiceInstance(CoreUtil
.getIWContext(), UserBusiness.class);
} catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
public BPMFactory getBPMFactory() {
return BPMFactory;
}
@Autowired
public void setBPMFactory(BPMFactory factory) {
BPMFactory = factory;
}
public CasesBPMDAO getCasesBPMDAO() {
return casesBPMDAO;
}
@Autowired
public void setCasesBPMDAO(CasesBPMDAO casesBPMDAO) {
this.casesBPMDAO = casesBPMDAO;
}
protected CasesBusiness getCasesBusiness(IWApplicationContext iwac) {
try {
return (CasesBusiness) IBOLookup.getServiceInstance(iwac,
CasesBusiness.class);
} catch (IBOLookupException ile) {
throw new IBORuntimeException(ile);
}
}
public CaseManagersProvider getCaseManagersProvider() {
return caseManagersProvider;
}
@Autowired
public void setCaseManagersProvider(
CaseManagersProvider caseManagersProvider) {
this.caseManagersProvider = caseManagersProvider;
}
} | gpl-3.0 |
Jardo-51/user_module | core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java | 1501 | /*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule.containers;
/**
* @since 0.2.0
*/
public class SocialAccountDetails {
private final String accountType;
private final String userId;
private final String userName;
private final String email;
public SocialAccountDetails(String accountType, String userId, String userName, String email) {
this.accountType = accountType;
this.userId = userId;
this.userName = userName;
this.email = email;
}
public String getAccountType() {
return accountType;
}
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getEmail() {
return email;
}
}
| gpl-3.0 |